error.py 6.03 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""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.
"""
di68kap's avatar
di68kap committed
18

19
import bisect
20
from typing import Iterable, Iterator, Union, Tuple, List
21

22
from DHParser.preprocess import SourceMapFunc
23
from DHParser.stringview import StringView
24
25
26
27
28
29
30

__all__ = ('Error',
           'is_error',
           'is_warning',
           'has_errors',
           'only_errors',
           'linebreaks',
31
           'line_col',
eckhart's avatar
eckhart committed
32
           'adjust_error_locations')
33
34
35


class Error:
36
    __slots__ = ['message', 'level', 'code', 'pos', 'orig_pos', 'line', 'column']
37

38
39
    # error levels

40
41
42
43
    WARNING   = 1
    ERROR     = 1000
    HIGHEST   = ERROR

44
45
46
    # warning codes

    REDEFINED_DIRECTIVE_WARNING = 101
47
    REDECLARED_TOKEN_WARNING = 102
48

49
50
51
52
    # error codes

    MANDATORY_CONTINUATION = 1001

53
54
    def __init__(self, message: str, code: int = ERROR, pos: int = -1,
                 orig_pos: int = -1, line: int = -1, column: int = -1) -> None:
55
        self.message = message
56
        assert code >= 0
57
        self.code = code
58
        self.pos = pos
59
        self.orig_pos = orig_pos
60
61
        self.line = line
        self.column = column
62
63
64
65

    def __str__(self):
        prefix = ''
        if self.line > 0:
eckhart's avatar
eckhart committed
66
67
68
            prefix = "line: %s, column: %s, " % \
                     ("%4i" % self.line if self.line >= 0 else ' ???',
                      "%3i" % self.column if self.column >= 0 else '???')
69
70
        return prefix + "%s: %s" % (self.level_str, self.message)

71
    def __repr__(self):
72
73
        return 'Error("%s", %s, %i, %i, %i, %i)' \
               % (self.message, repr(self.code), self.pos, self.orig_pos, self.line, self.column)
74

75
76
    @property
    def level_str(self):
77
        """Returns a string representation of the error level, e.g. "warning"."""
78
        return "Warning" if is_warning(self.code) else "Error"
79

80
81
82
83
84
85
86
    def visualize(self, document: str) -> str:
        """Shows the line of the document and the position where the error
        occurred."""
        start = document.rfind('\n', 0, self.pos) + 1
        stop = document.find('\n', self.pos)
        return document[start:stop] + '\n' + ' ' * (self.pos - start) + '^\n'

87

88
def is_warning(code: int) -> bool:
eckhart's avatar
eckhart committed
89
    """Returns True, if error is merely a warning."""
90
    return code < Error.ERROR
91
92


93
def is_error(code: int) -> bool:
eckhart's avatar
eckhart committed
94
    """Returns True, if error is an error, not just a warning."""
95
    return code >= Error.ERROR
96
97


eckhart's avatar
eckhart committed
98
def has_errors(messages: Iterable[Error], level: int = Error.ERROR) -> bool:
99
100
101
102
103
    """
    Returns True, if at least one entry in `messages` has at
    least the given error `level`.
    """
    for err_obj in messages:
104
        if err_obj.code >= level:
105
106
107
108
            return True
    return False


eckhart's avatar
eckhart committed
109
def only_errors(messages: Iterable[Error], level: int = Error.ERROR) -> Iterator[Error]:
110
111
112
113
    """
    Returns an Iterator that yields only those messages that have
    at least the given error level.
    """
114
    return (err for err in messages if err.code >= level)
115
116


117
118
119
120
121
122
123
#######################################################################
#
# Setting of line, column and position properties of error messages.
#
#######################################################################


eckhart's avatar
eckhart committed
124
def linebreaks(text: Union[StringView, str]) -> List[int]:
eckhart's avatar
eckhart committed
125
126
127
128
    """
    Returns a list of indices all line breaks in the text.
    """
    lbr = [-1]
129
130
    i = text.find('\n', 0)
    while i >= 0:
eckhart's avatar
eckhart committed
131
        lbr.append(i)
132
        i = text.find('\n', i + 1)
eckhart's avatar
eckhart committed
133
134
    lbr.append(len(text))
    return lbr
135
136


137
def line_col(lbreaks: List[int], pos: int) -> Tuple[int, int]:
eckhart's avatar
eckhart committed
138
139
    """
    Returns the position within a text as (line, column)-tuple based
140
141
    on a list of all line breaks, including -1 and EOF.
    """
142
143
    if not lbreaks and pos >= 0:
        return 0, pos
144
145
146
147
148
149
    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

150

151
152
153
# def line_col(text: Union[StringView, str], pos: int) -> Tuple[int, int]:
#     """
#     Returns the position within a text as (line, column)-tuple.
154
#     """
155
156
157
158
159
160
161
#     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)))
#     line = text.count("\n", 0, pos) + 1
#     column = pos - text.rfind("\n", 0, pos)
#     return line, column


eckhart's avatar
eckhart committed
162
163
164
def adjust_error_locations(errors: List[Error],
                           original_text: Union[StringView, str],
                           source_mapping: SourceMapFunc=lambda i: i) -> List[Error]:
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    """Adds (or adjusts) line and column numbers of error messages in place.

    Args:
        errors:  The list of errors as returned by the method
            ``collect_errors()`` of a Node object
        original_text:  The source text on which the errors occurred.
            (Needed in order to determine the line and column numbers.)
        source_mapping:  A function that maps error positions to their
            positions in the original source file.
    Returns:
        The list of errors. (Returning the list of errors is just syntactical
        sugar. Be aware that the line, col and orig_pos attributes have been
        changed in place.)
    """
    line_breaks = linebreaks(original_text)
    for err in errors:
        assert err.pos >= 0
        err.orig_pos = source_mapping(err.pos)
        err.line, err.column = line_col(line_breaks, err.orig_pos)
    return errors