The expiration time for new job artifacts in CI/CD pipelines is now 30 days (GitLab default). Previously generated artifacts in already completed jobs will not be affected by the change. The latest artifacts for all jobs in the latest successful pipelines will be kept. More information: https://gitlab.lrz.de/help/user/admin_area/settings/continuous_integration.html#default-artifacts-expiration

error.py 4.9 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
20
21
import bisect
import functools

22
from DHParser.stringview import StringView
di68kap's avatar
di68kap committed
23
24
25
from DHParser.toolkit import typing
from typing import Hashable, Iterable, Iterator, Union, Tuple, List

26
27
28
29
30
31
32

__all__ = ('Error',
           'is_error',
           'is_warning',
           'has_errors',
           'only_errors',
           'linebreaks',
33
           'line_col')
34
35
36
37
38


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

39
40
    # error levels

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

45
46
47
48
    # error codes

    MANDATORY_CONTINUATION = 1001

eckhart's avatar
eckhart committed
49
    def __init__(self, message: str, level: int = ERROR, code: int = 0,
50
                 pos: int = -1, line: int = -1, column: int = -1) -> None:
51
52
53
54
        self.message = message
        assert level >= 0
        self.level = level or Error.ERROR
        self.code = code
55
56
57
        self.pos = pos
        self.line = line
        self.column = column
58
59
60
61
62
63
64

    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)

65
66
67
68
    def __repr__(self):
        return 'Error("%s", %i, %s, %i, %i, %i)' \
               % (self.message, self.level, repr(self.code), self.pos, self.line, self.column)

69
70
    @property
    def level_str(self):
eckhart's avatar
eckhart committed
71
72
        """Returns a string representation of the error level, e.g. "warning".
        """
73
74
75
76
        return "Warning" if is_warning(self.level) else "Error"


def is_warning(level: int) -> bool:
eckhart's avatar
eckhart committed
77
    """Returns True, if error is merely a warning."""
78
79
80
    return level < Error.ERROR


eckhart's avatar
eckhart committed
81
82
def is_error(level: int) -> bool:
    """Returns True, if error is an error, not just a warning."""
83
84
85
    return level >= Error.ERROR


eckhart's avatar
eckhart committed
86
def has_errors(messages: Iterable[Error], level: int = Error.ERROR) -> bool:
87
88
89
90
91
92
93
94
95
96
    """
    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


eckhart's avatar
eckhart committed
97
def only_errors(messages: Iterable[Error], level: int = Error.ERROR) -> Iterator[Error]:
98
99
100
101
102
103
104
105
    """
    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]):
eckhart's avatar
eckhart committed
106
107
108
109
    """
    Returns a list of indices all line breaks in the text.
    """
    lbr = [-1]
110
111
    i = text.find('\n', 0)
    while i >= 0:
eckhart's avatar
eckhart committed
112
        lbr.append(i)
113
        i = text.find('\n', i + 1)
eckhart's avatar
eckhart committed
114
115
    lbr.append(len(text))
    return lbr
116
117
118
119


@functools.singledispatch
def line_col(text: Union[StringView, str], pos: int) -> Tuple[int, int]:
eckhart's avatar
eckhart committed
120
121
    """
    Returns the position within a text as (line, column)-tuple.
122
123
124
125
126
127
128
129
130
131
    """
    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


@line_col.register(list)
def _line_col(lbreaks: List[int], pos: int) -> Tuple[int, int]:
eckhart's avatar
eckhart committed
132
133
    """
    Returns the position within a text as (line, column)-tuple based
134
135
136
137
138
139
140
141
    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

142

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# def error_messages(source_text:str, errors: List[Error]) -> List[str]:
#     """Adds line, column information for error messages, if the position
#     is given.
#
#     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:
#         The same list of error messages, which now contain line and
#         column numbers.
#     """
#     for err in errors:
#         if err.pos >= 0 and err.line <= 0:
#             err.line, err.column = line_col(source_text, err.pos)
#     return errors