7 from .util import col, line, lineno, _collapse_string_to_ranges
8 from .unicode import pyparsing_unicode as ppu
11 class ExceptionWordUnicode(ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic):
15 _extract_alphanums = _collapse_string_to_ranges(ExceptionWordUnicode.alphanums)
16 _exception_word_extractor = re.compile("([" + _extract_alphanums + "]{1,16})|.")
19 class ParseBaseException(Exception):
20 """base exception class for all parsing runtime exceptions"""
22 # Performance tuning: we construct a *lot* of these, so keep this
23 # constructor as small and fast as possible
28 msg: typing.Optional[str] = None,
38 self.parser_element = self.parserElement = elem
39 self.args = (pstr, loc, msg)
42 def explain_exception(exc, depth=16):
44 Method to take an exception and translate the Python internal traceback into a list
45 of the pyparsing expressions that caused the exception to be raised.
49 - exc - exception raised during parsing (need not be a ParseException, in support
50 of Python exceptions that might be raised in a parse action)
51 - depth (default=16) - number of levels back in the stack trace to list expression
52 and function names; if None, the full stack trace names will be listed; if 0, only
53 the failing input line, marker, and exception string will be shown
55 Returns a multi-line string listing the ParserElements and/or function names in the
56 exception's stack trace.
59 from .core import ParserElement
62 depth = sys.getrecursionlimit()
64 if isinstance(exc, ParseBaseException):
66 ret.append(" " * (exc.column - 1) + "^")
67 ret.append("{}: {}".format(type(exc).__name__, exc))
70 callers = inspect.getinnerframes(exc.__traceback__, context=depth)
72 for i, ff in enumerate(callers[-depth:]):
75 f_self = frm.f_locals.get("self", None)
76 if isinstance(f_self, ParserElement):
77 if frm.f_code.co_name not in ("parseImpl", "_parseNoCache"):
79 if id(f_self) in seen:
83 self_type = type(f_self)
86 self_type.__module__, self_type.__name__, f_self
90 elif f_self is not None:
91 self_type = type(f_self)
92 ret.append("{}.{}".format(self_type.__module__, self_type.__name__))
96 if code.co_name in ("wrapper", "<module>"):
99 ret.append("{}".format(code.co_name))
105 return "\n".join(ret)
108 def _from_exception(cls, pe):
110 internal factory method to simplify creating one type of ParseException
111 from another - avoids having __init__ signature conflicts among subclasses
113 return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
116 def line(self) -> str:
118 Return the line of text where the exception occurred.
120 return line(self.loc, self.pstr)
123 def lineno(self) -> int:
125 Return the 1-based line number of text where the exception occurred.
127 return lineno(self.loc, self.pstr)
130 def col(self) -> int:
132 Return the 1-based column on the line of text where the exception occurred.
134 return col(self.loc, self.pstr)
137 def column(self) -> int:
139 Return the 1-based column on the line of text where the exception occurred.
141 return col(self.loc, self.pstr)
143 def __str__(self) -> str:
145 if self.loc >= len(self.pstr):
146 foundstr = ", found end of text"
148 # pull out next word at error location
149 found_match = _exception_word_extractor.match(self.pstr, self.loc)
150 if found_match is not None:
151 found = found_match.group(0)
153 found = self.pstr[self.loc : self.loc + 1]
154 foundstr = (", found %r" % found).replace(r"\\", "\\")
157 return "{}{} (at char {}), (line:{}, col:{})".format(
158 self.msg, foundstr, self.loc, self.lineno, self.column
164 def mark_input_line(self, marker_string: str = None, *, markerString=">!<") -> str:
166 Extracts the exception line from the input string, and marks
167 the location of the exception with a special symbol.
169 markerString = marker_string if marker_string is not None else markerString
171 line_column = self.column - 1
174 (line_str[:line_column], markerString, line_str[line_column:])
176 return line_str.strip()
178 def explain(self, depth=16) -> str:
180 Method to translate the Python internal traceback into a list
181 of the pyparsing expressions that caused the exception to be raised.
185 - depth (default=16) - number of levels back in the stack trace to list expression
186 and function names; if None, the full stack trace names will be listed; if 0, only
187 the failing input line, marker, and exception string will be shown
189 Returns a multi-line string listing the ParserElements and/or function names in the
190 exception's stack trace.
194 expr = pp.Word(pp.nums) * 3
196 expr.parse_string("123 456 A789")
197 except pp.ParseException as pe:
198 print(pe.explain(depth=0))
204 ParseException: Expected W:(0-9), found 'A' (at char 8), (line:1, col:9)
206 Note: the diagnostic output will include string representations of the expressions
207 that failed to parse. These representations will be more helpful if you use `set_name` to
208 give identifiable names to your expressions. Otherwise they will use the default string
209 forms, which may be cryptic to read.
211 Note: pyparsing's default truncation of exception tracebacks may also truncate the
212 stack of expressions that are displayed in the ``explain`` output. To get the full listing
213 of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True``
215 return self.explain_exception(self, depth)
217 markInputline = mark_input_line
220 class ParseException(ParseBaseException):
222 Exception thrown when a parse expression doesn't match the input string
227 Word(nums).set_name("integer").parse_string("ABC")
228 except ParseException as pe:
230 print("column: {}".format(pe.column))
234 Expected integer (at char 0), (line:1, col:1)
240 class ParseFatalException(ParseBaseException):
242 User-throwable exception thrown when inconsistent parse content
243 is found; stops all parsing immediately
247 class ParseSyntaxException(ParseFatalException):
249 Just like :class:`ParseFatalException`, but thrown internally
250 when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates
251 that parsing is to stop immediately because an unbacktrackable
252 syntax error has been found.
256 class RecursiveGrammarException(Exception):
258 Exception thrown by :class:`ParserElement.validate` if the
259 grammar could be left-recursive; parser may need to enable
260 left recursion using :class:`ParserElement.enable_left_recursion<ParserElement.enable_left_recursion>`
263 def __init__(self, parseElementList):
264 self.parseElementTrace = parseElementList
266 def __str__(self) -> str:
267 return "RecursiveGrammarException: {}".format(self.parseElementTrace)