1# exceptions.py
2from __future__ import annotations
3
4import copy
5import re
6import sys
7import typing
8import warnings
9from functools import cached_property
10
11from .unicode import pyparsing_unicode as ppu
12from .util import (
13 _collapse_string_to_ranges,
14 col,
15 deprecate_argument,
16 line,
17 lineno,
18 replaced_by_pep8,
19)
20
21
22class _ExceptionWordUnicodeSet(
23 ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic
24):
25 pass
26
27
28_extract_alphanums = _collapse_string_to_ranges(_ExceptionWordUnicodeSet.alphanums)
29_exception_word_extractor = re.compile("([" + _extract_alphanums + "]{1,16})|.")
30
31
32class ParseBaseException(Exception):
33 """base exception class for all parsing runtime exceptions"""
34
35 loc: int
36 msg: str
37 pstr: str
38 parser_element: typing.Any # "ParserElement"
39 args: tuple[str, int, typing.Optional[str]]
40
41 __slots__ = (
42 "loc",
43 "msg",
44 "pstr",
45 "parser_element",
46 "args",
47 )
48
49 # Performance tuning: we construct a *lot* of these, so keep this
50 # constructor as small and fast as possible
51 def __init__(
52 self,
53 pstr: str,
54 loc: int = 0,
55 msg: typing.Optional[str] = None,
56 elem=None,
57 ) -> None:
58 if msg is None:
59 msg, pstr = pstr, ""
60
61 self.loc = loc
62 self.msg = msg
63 self.pstr = pstr
64 self.parser_element = elem
65 self.args = (pstr, loc, msg)
66
67 @staticmethod
68 def explain_exception(exc: Exception, depth: int = 16) -> str:
69 """
70 Method to take an exception and translate the Python internal traceback into a list
71 of the pyparsing expressions that caused the exception to be raised.
72
73 Parameters:
74
75 - exc - exception raised during parsing (need not be a ParseException, in support
76 of Python exceptions that might be raised in a parse action)
77 - depth (default=16) - number of levels back in the stack trace to list expression
78 and function names; if None, the full stack trace names will be listed; if 0, only
79 the failing input line, marker, and exception string will be shown
80
81 Returns a multi-line string listing the ParserElements and/or function names in the
82 exception's stack trace.
83 """
84 import inspect
85 from .core import ParserElement
86
87 if depth is None:
88 depth = sys.getrecursionlimit()
89 ret: list[str] = []
90 if isinstance(exc, ParseBaseException):
91 ret.append(exc.line)
92 ret.append(f"{'^':>{exc.column}}")
93 ret.append(f"{type(exc).__name__}: {exc}")
94
95 if depth <= 0 or exc.__traceback__ is None:
96 return "\n".join(ret)
97
98 callers = inspect.getinnerframes(exc.__traceback__, context=depth)
99 seen: set[int] = set()
100 for ff in callers[-depth:]:
101 frm = ff[0]
102
103 f_self = frm.f_locals.get("self", None)
104 if isinstance(f_self, ParserElement):
105 if not frm.f_code.co_name.startswith(("parseImpl", "_parseNoCache")):
106 continue
107 if id(f_self) in seen:
108 continue
109 seen.add(id(f_self))
110
111 self_type = type(f_self)
112 ret.append(f"{self_type.__module__}.{self_type.__name__} - {f_self}")
113
114 elif f_self is not None:
115 self_type = type(f_self)
116 ret.append(f"{self_type.__module__}.{self_type.__name__}")
117
118 else:
119 code = frm.f_code
120 if code.co_name in ("wrapper", "<module>"):
121 continue
122
123 ret.append(code.co_name)
124
125 depth -= 1
126 if not depth:
127 break
128
129 return "\n".join(ret)
130
131 @classmethod
132 def _from_exception(cls, pe) -> ParseBaseException:
133 """
134 internal factory method to simplify creating one type of ParseException
135 from another - avoids having __init__ signature conflicts among subclasses
136 """
137 return cls(pe.pstr, pe.loc, pe.msg, pe.parser_element)
138
139 @cached_property
140 def line(self) -> str:
141 """
142 Return the line of text where the exception occurred.
143 """
144 return line(self.loc, self.pstr)
145
146 @cached_property
147 def lineno(self) -> int:
148 """
149 Return the 1-based line number of text where the exception occurred.
150 """
151 return lineno(self.loc, self.pstr)
152
153 @cached_property
154 def col(self) -> int:
155 """
156 Return the 1-based column on the line of text where the exception occurred.
157 """
158 return col(self.loc, self.pstr)
159
160 @cached_property
161 def column(self) -> int:
162 """
163 Return the 1-based column on the line of text where the exception occurred.
164 """
165 return col(self.loc, self.pstr)
166
167 @cached_property
168 def found(self) -> str:
169 if not self.pstr:
170 return ""
171
172 if self.loc >= len(self.pstr):
173 return "end of text"
174
175 # pull out next word at error location
176 found_match = _exception_word_extractor.match(self.pstr, self.loc)
177 if found_match is not None:
178 found_text = found_match.group(0)
179 else:
180 found_text = self.pstr[self.loc : self.loc + 1]
181
182 return repr(found_text).replace(r"\\", "\\")
183
184 # pre-PEP8 compatibility
185 @property
186 def parserElement(self):
187 warnings.warn(
188 "parserElement is deprecated, use parser_element",
189 DeprecationWarning,
190 stacklevel=2,
191 )
192 return self.parser_element
193
194 @parserElement.setter
195 def parserElement(self, elem):
196 warnings.warn(
197 "parserElement is deprecated, use parser_element",
198 DeprecationWarning,
199 stacklevel=2,
200 )
201 self.parser_element = elem
202
203 def copy(self):
204 return copy.copy(self)
205
206 def formatted_message(self) -> str:
207 """
208 Output the formatted exception message.
209 Can be overridden to customize the message formatting or contents.
210
211 .. versionadded:: 3.2.0
212 """
213 found_phrase = f", found {self.found}" if self.found else ""
214 return f"{self.msg}{found_phrase} (at char {self.loc}), (line:{self.lineno}, col:{self.column})"
215
216 def __str__(self) -> str:
217 """
218 .. versionchanged:: 3.2.0
219 Now uses :meth:`formatted_message` to format message.
220 """
221 try:
222 return self.formatted_message()
223 except Exception as ex:
224 return (
225 f"{type(self).__name__}: {self.msg}"
226 f" ({type(ex).__name__}: {ex} while formatting message)"
227 )
228
229 def __repr__(self):
230 return str(self)
231
232 def mark_input_line(
233 self, marker_string: typing.Optional[str] = None, **kwargs
234 ) -> str:
235 """
236 Extracts the exception line from the input string, and marks
237 the location of the exception with a special symbol.
238 """
239 markerString: str = deprecate_argument(kwargs, "markerString", ">!<")
240
241 markerString = marker_string if marker_string is not None else markerString
242 line_str = self.line
243 line_column = self.column - 1
244 if markerString:
245 line_str = f"{line_str[:line_column]}{markerString}{line_str[line_column:]}"
246 return line_str.strip()
247
248 def explain(self, depth: int = 16) -> str:
249 """
250 Method to translate the Python internal traceback into a list
251 of the pyparsing expressions that caused the exception to be raised.
252
253 Parameters:
254
255 - depth (default=16) - number of levels back in the stack trace to list expression
256 and function names; if None, the full stack trace names will be listed; if 0, only
257 the failing input line, marker, and exception string will be shown
258
259 Returns a multi-line string listing the ParserElements and/or function names in the
260 exception's stack trace.
261
262 Example:
263
264 .. testcode::
265
266 # an expression to parse 3 integers
267 expr = pp.Word(pp.nums) * 3
268 try:
269 # a failing parse - the third integer is prefixed with "A"
270 expr.parse_string("123 456 A789")
271 except pp.ParseException as pe:
272 print(pe.explain(depth=0))
273
274 prints:
275
276 .. testoutput::
277
278 123 456 A789
279 ^
280 ParseException: Expected W:(0-9), found 'A789' (at char 8), (line:1, col:9)
281
282 Note: the diagnostic output will include string representations of the expressions
283 that failed to parse. These representations will be more helpful if you use `set_name` to
284 give identifiable names to your expressions. Otherwise they will use the default string
285 forms, which may be cryptic to read.
286
287 Note: pyparsing's default truncation of exception tracebacks may also truncate the
288 stack of expressions that are displayed in the ``explain`` output. To get the full listing
289 of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True``
290 """
291 return self.explain_exception(self, depth)
292
293 # Compatibility synonyms
294 # fmt: off
295 markInputline = replaced_by_pep8("markInputline", mark_input_line)
296 # fmt: on
297
298
299class ParseException(ParseBaseException):
300 """
301 Exception thrown when a parse expression doesn't match the input string
302
303 Example:
304
305 .. testcode::
306
307 integer = Word(nums).set_name("integer")
308 try:
309 integer.parse_string("ABC")
310 except ParseException as pe:
311 print(pe, f"column: {pe.column}")
312
313 prints:
314
315 .. testoutput::
316
317 Expected integer, found 'ABC' (at char 0), (line:1, col:1) column: 1
318
319 """
320
321
322class ParseFatalException(ParseBaseException):
323 """
324 User-throwable exception thrown when inconsistent parse content
325 is found; stops all parsing immediately
326 """
327
328
329class ParseSyntaxException(ParseFatalException):
330 """
331 Just like :class:`ParseFatalException`, but thrown internally
332 when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates
333 that parsing is to stop immediately because an unbacktrackable
334 syntax error has been found.
335 """
336
337
338class RecursiveGrammarException(Exception):
339 """
340 .. deprecated:: 3.0.0
341 Only used by the deprecated :meth:`ParserElement.validate`.
342
343 Exception thrown by :class:`ParserElement.validate` if the
344 grammar could be left-recursive; parser may need to enable
345 left recursion using :class:`ParserElement.enable_left_recursion<ParserElement.enable_left_recursion>`
346 """
347
348 def __init__(self, parseElementList) -> None:
349 self.parseElementTrace = parseElementList
350
351 def __str__(self) -> str:
352 return f"RecursiveGrammarException: {self.parseElementTrace}"