In January 2021 we will introduce a 10 GB quota for project repositories. Higher limits for individual projects will be available on request. Please see https://doku.lrz.de/display/PUBLIC/GitLab for more information.

Commit e9b10f1f authored by Eckhart Arnold's avatar Eckhart Arnold

Refactorings: base.py removed in favor of erroy.py

parent 8229e7f3
......@@ -18,7 +18,7 @@ implied. See the License for the specific language governing
permissions and limitations under the License.
"""
from .base import *
from .error import *
from .dsl import *
from .ebnf import *
from .parser import *
......@@ -26,9 +26,10 @@ from .syntaxtree import *
# Flat namespace for the DHParser Package. Is this a good idea...?
from .toolkit import *
from .transform import *
# from .testing import *
from .testing import *
from .versionnumber import __version__
__author__ = "Eckhart Arnold <arnold@badw.de>"
__copyright__ = "http://www.apache.org/licenses/LICENSE-2.0"
# __all__ = ['toolkit', 'base', 'syntaxtree', 'parser', 'transform', 'ebnf', 'dsl', 'testing', 'versionnumber'] # flat namespace
# __all__ = ['toolkit', 'error', 'syntaxtree', 'parser', 'transform', 'ebnf', 'dsl', 'testing',
# 'versionnumber'] # flat namespace
This diff is collapsed.
......@@ -36,7 +36,7 @@ from DHParser.ebnf import EBNFCompiler, grammar_changed, \
from DHParser.toolkit import logging, load_if_file, is_python_code, compile_python_object
from DHParser.parser import Grammar, Compiler, compile_source, nil_preprocessor, PreprocessorFunc
from DHParser.syntaxtree import Node, TransformationFunc
from DHParser.base import Error, is_error, has_errors, only_errors
from DHParser.error import Error, is_error, has_errors, only_errors
__all__ = ('GrammarError',
'CompilationError',
......
......@@ -33,8 +33,8 @@ from DHParser.toolkit import load_if_file, escape_re, md5, sane_parser_name
from DHParser.parser import Grammar, mixin_comment, nil_preprocessor, Forward, RE, NegativeLookahead, \
Alternative, Series, Option, Required, OneOrMore, ZeroOrMore, Token, Compiler, \
PreprocessorFunc
from DHParser.syntaxtree import Node, TransformationFunc
from DHParser.base import WHITESPACE_PTYPE, TOKEN_PTYPE, Error
from DHParser.syntaxtree import Node, TransformationFunc, WHITESPACE_PTYPE, TOKEN_PTYPE
from DHParser.error import Error
from DHParser.transform import TransformationDict, traverse, remove_brackets, \
reduce_single_child, replace_by_single_child, remove_expendables, \
remove_tokens, flatten, forbid, assert_content, remove_infix_operator
......
"""error.py - error handling for DHParser
Copyright 2016 by Eckhart Arnold (arnold@badw.de)
Bavarian Academy of Sciences an Humanities (badw.de)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
"""
import bisect
import functools
from typing import Hashable, Iterable, Iterator, Union, Tuple, List
from DHParser.toolkit import StringView
__all__ = ('Error',
'is_error',
'is_warning',
'has_errors',
'only_errors',
'linebreaks',
'line_col',
'error_messages')
class Error:
__slots__ = ['message', 'level', 'code', 'pos', 'line', 'column']
WARNING = 1
ERROR = 1000
HIGHEST = ERROR
def __init__(self, message: str, level: int=ERROR, code: Hashable=0):
self.message = message
assert level >= 0
self.level = level or Error.ERROR
self.code = code
self.pos = -1
self.line = -1
self.column = -1
def __str__(self):
prefix = ''
if self.line > 0:
prefix = "line: %3i, column: %2i, " % (self.line, self.column)
return prefix + "%s: %s" % (self.level_str, self.message)
@property
def level_str(self):
return "Warning" if is_warning(self.level) else "Error"
def is_warning(level: int) -> bool:
return level < Error.ERROR
def is_error(level: int) -> bool:
return level >= Error.ERROR
def has_errors(messages: Iterable[Error], level: int=Error.ERROR) -> bool:
"""
Returns True, if at least one entry in `messages` has at
least the given error `level`.
"""
for err_obj in messages:
if err_obj.level >= level:
return True
return False
def only_errors(messages: Iterable[Error], level: int=Error.ERROR) -> Iterator[Error]:
"""
Returns an Iterator that yields only those messages that have
at least the given error level.
"""
return (err for err in messages if err.level >= level)
def linebreaks(text: Union[StringView, str]):
lb = [-1]
i = text.find('\n', 0)
while i >= 0:
lb.append(i)
i = text.find('\n', i + 1)
lb.append(len(text))
return lb
@functools.singledispatch
def line_col(text: Union[StringView, str], pos: int) -> Tuple[int, int]:
"""Returns the position within a text as (line, column)-tuple.
"""
if pos < 0 or pos > len(text): # one character behind EOF is still an allowed position!
raise ValueError('Position %i outside text of length %s !' % (pos, len(text)))
# assert pos <= len(text), str(pos) + " > " + str(len(text))
line = text.count("\n", 0, pos) + 1
column = pos - text.rfind("\n", 0, pos)
return line, column
@line_col.register(list)
def _line_col(lbreaks: List[int], pos: int) -> Tuple[int, int]:
"""Returns the position within a text as (line, column)-tuple based
on a list of all line breaks, including -1 and EOF.
"""
if pos < 0 or pos > lbreaks[-1]: # one character behind EOF is still an allowed position!
raise ValueError('Position %i outside text of length %s !' % (pos, lbreaks[-1]))
line = bisect.bisect_left(lbreaks, pos)
column = pos - lbreaks[line - 1]
return line, column
def error_messages(source_text, errors) -> List[str]:
"""Returns the sequence or iterator of error objects as an intertor
of error messages with line and column numbers at the beginning.
Args:
source_text (str): The source text on which the errors occurred.
(Needed in order to determine the line and column numbers.)
errors (list): The list of errors as returned by the method
``collect_errors()`` of a Node object
Returns:
a list that contains all error messages in string form. Each
string starts with "line: [Line-No], column: [Column-No]
"""
for err in errors:
if err.pos >= 0 and err.line <= 0:
err.line, err.column = line_col(source_text, err.pos)
return [str(err) for err in sorted(errors, key=lambda err: err.pos)]
......@@ -74,11 +74,12 @@ try:
except ImportError:
from .typing34 import Any, Callable, cast, Dict, Iterator, List, Set, Tuple, Union, Optional
from DHParser.toolkit import is_logging, log_dir, logfile_basename, escape_re, sane_parser_name
from DHParser.syntaxtree import Node, TransformationFunc
from DHParser.base import ParserBase, WHITESPACE_PTYPE, TOKEN_PTYPE, ZOMBIE_PARSER, Error, is_error, has_errors, \
from DHParser.toolkit import is_logging, log_dir, logfile_basename, escape_re, sane_parser_name, \
StringView, EMPTY_STRING_VIEW
from DHParser.toolkit import load_if_file, error_messages, line_col
from DHParser.syntaxtree import Node, TransformationFunc, ParserBase, WHITESPACE_PTYPE, TOKEN_PTYPE, \
ZOMBIE_PARSER
from DHParser.error import Error, is_error, has_errors, line_col, error_messages
from DHParser.toolkit import load_if_file
__all__ = ('PreprocessorFunc',
'HistoryRecord',
......
......@@ -32,14 +32,112 @@ except ImportError:
from .typing34 import AbstractSet, Any, ByteString, Callable, cast, Container, Dict, \
Iterator, Iterable, List, NamedTuple, Sequence, Union, Text, Tuple, Hashable
from DHParser.toolkit import is_logging, log_dir, linebreaks, line_col, identity
from DHParser.base import MockParser, ZOMBIE_PARSER, Error, StringView
__all__ = ('Node',
from DHParser.toolkit import is_logging, log_dir, identity, StringView
from DHParser.error import Error, linebreaks, line_col
__all__ = ('ParserBase',
'WHITESPACE_PTYPE',
'TOKEN_PTYPE',
'MockParser',
'ZombieParser',
'ZOMBIE_PARSER',
'Node',
'mock_syntax_tree',
'TransformationFunc')
#######################################################################
#
# parser base and mock parsers
#
#######################################################################
class ParserBase:
"""
ParserBase is the base class for all real and mock parser classes.
It is defined here, because Node objects require a parser object
for instantiation.
"""
def __init__(self, name=''): # , pbases=frozenset()):
self.name = name # type: str
self._ptype = ':' + self.__class__.__name__ # type: str
def __repr__(self):
return self.name + self.ptype
def __str__(self):
return self.name + (' = ' if self.name else '') + repr(self)
@property
def ptype(self) -> str:
return self._ptype
@property
def repr(self) -> str:
return self.name if self.name else repr(self)
WHITESPACE_PTYPE = ':Whitespace'
TOKEN_PTYPE = ':Token'
class MockParser(ParserBase):
"""
MockParser objects can be used to reconstruct syntax trees from a
serialized form like S-expressions or XML. Mock objects can mimic
different parser types by assigning them a ptype on initialization.
Mock objects should not be used for anything other than
syntax tree (re-)construction. In all other cases where a parser
object substitute is needed, chose the singleton ZOMBIE_PARSER.
"""
def __init__(self, name='', ptype=''): # , pbases=frozenset()):
assert not ptype or ptype[0] == ':'
super(MockParser, self).__init__(name)
self.name = name
self._ptype = ptype or ':' + self.__class__.__name__
class ZombieParser(MockParser):
"""
Serves as a substitute for a Parser instance.
``ZombieParser`` is the class of the singelton object
``ZOMBIE_PARSER``. The ``ZOMBIE_PARSER`` has a name and can be
called, but it never matches. It serves as a substitute where only
these (or one of these properties) is needed, but no real Parser-
object is instantiated.
"""
alive = False
def __init__(self):
super(ZombieParser, self).__init__("__ZOMBIE__")
assert not self.__class__.alive, "There can be only one!"
assert self.__class__ == ZombieParser, "No derivatives, please!"
self.__class__.alive = True
def __copy__(self):
return self
def __deepcopy__(self, memo):
return self
def __call__(self, text):
"""Better call Saul ;-)"""
return None, text
ZOMBIE_PARSER = ZombieParser()
#######################################################################
#
# syntaxtree nodes
#
#######################################################################
ChildrenType = Tuple['Node', ...]
StrictResultType = Union[ChildrenType, StringView, str]
ResultType = Union[ChildrenType, 'Node', StringView, str, None]
......
......@@ -27,9 +27,9 @@ try:
except ImportError:
import re
from DHParser.toolkit import is_logging, clear_logs, error_messages
from DHParser.toolkit import is_logging, clear_logs
from DHParser.syntaxtree import mock_syntax_tree, flatten_sxpr
from DHParser.base import is_error
from DHParser.error import is_error, error_messages
__all__ = ('unit_from_configfile',
'unit_from_json',
......
This diff is collapsed.
......@@ -20,8 +20,7 @@ permissions and limitations under the License.
import inspect
from functools import partial, reduce, singledispatch
from DHParser.syntaxtree import Node
from DHParser.base import WHITESPACE_PTYPE, TOKEN_PTYPE, MockParser
from DHParser.syntaxtree import Node, WHITESPACE_PTYPE, TOKEN_PTYPE, MockParser
try:
import regex as re
......
# LaTeX-Grammar for DHParser
@ whitespace = /[ \t]*(?:\n(?![ \t]*\n)[ \t]*)?/ # optional whitespace, including at most one linefeed
@ comment = /%.*/
......
......@@ -49,7 +49,6 @@ class LaTeXGrammar(Grammar):
# LaTeX-Grammar for DHParser
@ whitespace = /[ \t]*(?:\n(?![ \t]*\n)[ \t]*)?/ # optional whitespace, including at most one linefeed
@ comment = /%.*/
......@@ -229,7 +228,7 @@ class LaTeXGrammar(Grammar):
paragraph = Forward()
tabular_config = Forward()
text_element = Forward()
source_hash__ = "2438244cc4ad969a9d12e946b8218eb6"
source_hash__ = "37585004123d6b80ecf8f67217b43479"
parser_initialization__ = "upon instantiation"
COMMENT__ = r'%.*'
WHITESPACE__ = r'[ \t]*(?:\n(?![ \t]*\n)[ \t]*)?'
......
......@@ -24,6 +24,8 @@ import os
import pstats
import sys
import DHParser.error
sys.path.extend(['../../', '../', './'])
import DHParser.dsl
......@@ -44,7 +46,7 @@ transformer = get_transformer()
def fail_on_error(src, result):
if result.error_flag:
print(result.as_sxpr())
for e in toolkit.error_messages(src, result.collect_errors()):
for e in DHParser.error.error_messages(src, result.collect_errors()):
print(e)
sys.exit(1)
......
#!/usr/bin/python3
"""test_base.py - tests of the base-module of DHParser
Author: Eckhart Arnold <arnold@badw.de>
Copyright 2017 Bavarian Academy of Sciences and Humanities
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
try:
import regex as re
except ImportError:
import re
from DHParser import StringView, EMPTY_STRING_VIEW
class TestStringView:
def test_real_indices(self):
assert StringView.real_indices(3, 5, 10) == (3, 5)
assert StringView.real_indices(None, None, 10) == (0, 10)
assert StringView.real_indices(-2, -1, 10) == (8, 9)
assert StringView.real_indices(-3, 11, 10) == (7, 10)
assert StringView.real_indices(-5, -12, 10) == (5, 0)
assert StringView.real_indices(-12, -5, 10) == (0, 5)
assert StringView.real_indices(7, 6, 10) == (7, 6)
assert StringView.real_indices(None, 0, 10) == (0, 0)
def test_creation(self):
s = "0123456789"
assert str(StringView(s)) == s
assert str(StringView(s, 3, 4)) == '3'
assert str(StringView(s, -4)) == '6789'
def test_equality(self):
s = "0123456789"
assert StringView(s) == s
assert StringView(s, 3, 4) == '3'
assert StringView(s, -4) == '6789'
def test_slicing(self):
s = " 0123456789 "
sv = StringView(s, 1, -1)
assert sv == '0123456789'
assert sv[3:4] == '3'
assert sv[-3:-1] == '78'
assert sv[4:3] == ''
assert sv[:4] == '0123'
assert sv[4:] == '456789'
assert sv[-2:] == '89'
assert sv[:-5] == '01234'
assert isinstance(sv[3:5], StringView)
def test_len(self):
s = " 0123456789 "
sv = StringView(s, 1, -1)
assert len(sv) == 10
assert sv.len == 10
assert len(sv[5:5]) == 0
assert len(sv[7:4]) == 0
assert len(sv[-12:-2]) == 8
assert len(sv[-12:12]) == 10
def test_bool(self):
assert not StringView('')
assert StringView('x')
s = " 0123456789 "
sv = StringView(s, 1, -1)
assert not sv[5:4]
assert sv[4:5], str(sv[4:5])
assert not sv[3:3]
assert not sv[12:13]
assert sv[0:20]
def test_sv_match(self):
s = " 0123456789 "
sv = StringView(s, 1, -1)
assert sv.match(re.compile(r'\d'))
assert sv.match(re.compile(r'\d+'))
assert not sv.match(re.compile(r' '))
assert sv[4:].match(re.compile(r'45'))
def test_sv_search(self):
s = " 0123456789 "
sv = StringView(s, 1, -1)
assert sv.search(re.compile(r'5'))
assert not sv.search(re.compile(r' '))
assert sv[5:].search(re.compile(r'5'))
assert not sv[:9].search(re.compile(r'9'))
def test_find(self):
s = " 0123456789 "
sv = StringView(s, 1, -1)
assert sv.find('5') == 5
assert sv.find(' ') < 0
assert sv.find('0', 1) < 0
assert sv.find('9', 0, 8) < 0
assert sv.find('45', 1, 8) == 4
def test_startswith(self):
s = " 0123456789 "
sv = StringView(s, 1, -1)
assert sv.startswith('012')
assert sv.startswith('123', 1)
assert not sv.startswith('123', 1, 3)
def test_EMPTY_STRING_VIEW(self):
assert len(EMPTY_STRING_VIEW) == 0
assert EMPTY_STRING_VIEW.find('x') < 0
assert not EMPTY_STRING_VIEW.match(re.compile(r'x'))
assert EMPTY_STRING_VIEW.match(re.compile(r'.*'))
assert len(EMPTY_STRING_VIEW[0:1]) == 0
if __name__ == "__main__":
from DHParser.testing import runner
runner("", globals())
......@@ -25,7 +25,7 @@ import sys
sys.path.extend(['../', './'])
from DHParser.parser import Grammar, Compiler
from DHParser.base import is_error
from DHParser.error import is_error
from DHParser.dsl import compile_on_disk, run_compiler, compileEBNF, grammar_provider, \
load_compiler_suite
......
......@@ -31,7 +31,8 @@ sys.path.extend(['../', './'])
from DHParser.toolkit import compile_python_object
from DHParser.parser import compile_source, nil_preprocessor
from DHParser.base import WHITESPACE_PTYPE, has_errors
from DHParser.error import has_errors
from DHParser.syntaxtree import WHITESPACE_PTYPE
from DHParser.ebnf import get_ebnf_grammar, get_ebnf_transformer, EBNFTransform, get_ebnf_compiler
from DHParser.dsl import CompilationError, compileDSL, DHPARSER_IMPORTS, grammar_provider
......
#!/usr/bin/python3
"""test_error.py - tests of the error-handling-module of DHParser
Author: Eckhart Arnold <arnold@badw.de>
Copyright 2017 Bavarian Academy of Sciences and Humanities
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
try:
import regex as re
except ImportError:
import re
from DHParser.error import linebreaks, line_col
class TestErrorSupport:
def mini_suite(self, s, data, offset):
l, c = line_col(data, 0)
assert (l, c) == (1, 1), str((l, c))
l, c = line_col(data, 0 + offset)
assert (l, c) == (1 + offset, 1), str((l, c))
l, c = line_col(data, 1 + offset)
assert (l, c) == (1 + offset, 2), str((l, c))
l, c = line_col(data, 9 + offset)
assert (l, c) == (1 + offset, 10), str((l, c))
l, c = line_col(data, 10 + offset)
assert (l, c) == (2 + offset, 1), str((l, c))
l, c = line_col(data, 18 + offset)
assert (l, c) == (2 + offset, 9), str((l, c))
l, c = line_col(data, 19 + offset)
assert (l, c) == (2 + offset, 10), str((l, c))
try:
l, c = line_col(data, -1)
assert False, "ValueError expected for negative position."
except ValueError:
pass
try:
l, c = line_col(data, len(s) + 1)
assert False, "ValueError expected for postion > pos(EOF)+1."
except ValueError:
pass
def test_line_col(self):
s = "123456789\n123456789"
self.mini_suite(s, s, 0)
s = "\n123456789\n123456789"
self.mini_suite(s, s, 1)
s = "123456789\n123456789\n"
self.mini_suite(s, s, 0)
s = "\n123456789\n123456789\n"
self.mini_suite(s, s, 1)
def test_line_col_bisect(self):
s = "123456789\n123456789"
self.mini_suite(s, linebreaks(s), 0)
s = "\n123456789\n123456789"
self.mini_suite(s, linebreaks(s), 1)
s = "123456789\n123456789\n"
self.mini_suite(s, linebreaks(s), 0)
s = "\n123456789\n123456789\n"
self.mini_suite(s, linebreaks(s), 1)
if __name__ == "__main__":
from DHParser.testing import runner
runner("", globals())
......@@ -24,8 +24,7 @@ from functools import partial
sys.path.extend(['../', './'])
from DHParser.toolkit import is_logging, logging, compile_python_object
from DHParser.base import StringView
from DHParser.toolkit import is_logging, logging, compile_python_object, StringView
from DHParser.parser import compile_source, Retrieve, Grammar, Forward, Token, ZeroOrMore, RE, \
RegExp, Lookbehind, NegativeLookahead, OneOrMore, Series
from DHParser.ebnf import get_ebnf_grammar, get_ebnf_transformer, get_ebnf_compiler
......
......@@ -23,8 +23,7 @@ import copy
import sys
sys.path.extend(['../', './'])