This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

211 lines
8.3 KiB

  1. from .utils import STRING_TYPE, logger
  2. ###{standalone
  3. class LarkError(Exception):
  4. pass
  5. class GrammarError(LarkError):
  6. pass
  7. class ParseError(LarkError):
  8. pass
  9. class LexError(LarkError):
  10. pass
  11. class UnexpectedEOF(ParseError):
  12. def __init__(self, expected):
  13. self.expected = expected
  14. message = ("Unexpected end-of-input. Expected one of: \n\t* %s\n" % '\n\t* '.join(x.name for x in self.expected))
  15. super(UnexpectedEOF, self).__init__(message)
  16. class UnexpectedInput(LarkError):
  17. """UnexpectedInput Error.
  18. Used as a base class for the following exceptions:
  19. - ``UnexpectedToken``: The parser received an unexpected token
  20. - ``UnexpectedCharacters``: The lexer encountered an unexpected string
  21. After catching one of these exceptions, you may call the following helper methods to create a nicer error message.
  22. """
  23. pos_in_stream = None
  24. _all_terminals = None
  25. def get_context(self, text, span=40):
  26. """Returns a pretty string pinpointing the error in the text,
  27. with span amount of context characters around it.
  28. Note:
  29. The parser doesn't hold a copy of the text it has to parse,
  30. so you have to provide it again
  31. """
  32. pos = self.pos_in_stream
  33. start = max(pos - span, 0)
  34. end = pos + span
  35. if not isinstance(text, bytes):
  36. before = text[start:pos].rsplit('\n', 1)[-1]
  37. after = text[pos:end].split('\n', 1)[0]
  38. return before + after + '\n' + ' ' * len(before.expandtabs()) + '^\n'
  39. else:
  40. before = text[start:pos].rsplit(b'\n', 1)[-1]
  41. after = text[pos:end].split(b'\n', 1)[0]
  42. return (before + after + b'\n' + b' ' * len(before.expandtabs()) + b'^\n').decode("ascii", "backslashreplace")
  43. def match_examples(self, parse_fn, examples, token_type_match_fallback=False, use_accepts=False):
  44. """Allows you to detect what's wrong in the input text by matching
  45. against example errors.
  46. Given a parser instance and a dictionary mapping some label with
  47. some malformed syntax examples, it'll return the label for the
  48. example that bests matches the current error. The function will
  49. iterate the dictionary until it finds a matching error, and
  50. return the corresponding value.
  51. For an example usage, see `examples/error_reporting_lalr.py`
  52. Parameters:
  53. parse_fn: parse function (usually ``lark_instance.parse``)
  54. examples: dictionary of ``{'example_string': value}``.
  55. use_accepts: Recommended to call this with ``use_accepts=True``.
  56. The default is ``False`` for backwards compatibility.
  57. """
  58. assert self.state is not None, "Not supported for this exception"
  59. if isinstance(examples, dict):
  60. examples = examples.items()
  61. candidate = (None, False)
  62. for i, (label, example) in enumerate(examples):
  63. assert not isinstance(example, STRING_TYPE)
  64. for j, malformed in enumerate(example):
  65. try:
  66. parse_fn(malformed)
  67. except UnexpectedInput as ut:
  68. if ut.state == self.state:
  69. if use_accepts and ut.accepts != self.accepts:
  70. logger.debug("Different accepts with same state[%d]: %s != %s at example [%s][%s]" %
  71. (self.state, self.accepts, ut.accepts, i, j))
  72. continue
  73. try:
  74. if ut.token == self.token: # Try exact match first
  75. logger.debug("Exact Match at example [%s][%s]" % (i, j))
  76. return label
  77. if token_type_match_fallback:
  78. # Fallback to token types match
  79. if (ut.token.type == self.token.type) and not candidate[-1]:
  80. logger.debug("Token Type Fallback at example [%s][%s]" % (i, j))
  81. candidate = label, True
  82. except AttributeError:
  83. pass
  84. if not candidate[0]:
  85. logger.debug("Same State match at example [%s][%s]" % (i, j))
  86. candidate = label, False
  87. return candidate[0]
  88. def _format_terminals(self, names):
  89. if self._all_terminals:
  90. if isinstance(self._all_terminals, list):
  91. self._all_terminals = {t.name: t for t in self._all_terminals}
  92. ts = []
  93. for name in names:
  94. try:
  95. ts.append(self._all_terminals[name].user_repr)
  96. except StopIteration:
  97. # If we don't find the corresponding Terminal (which *should* never happen), don't error.
  98. # Broken __str__ for Exception are some of the worst bugs
  99. ts.append(name)
  100. else:
  101. ts = names
  102. return "Expected one of: \n\t* %s\n" % '\n\t* '.join(ts)
  103. class UnexpectedCharacters(LexError, UnexpectedInput):
  104. def __init__(self, seq, lex_pos, line, column, allowed=None, considered_tokens=None, state=None, token_history=None, _all_terminals=None):
  105. self.line = line
  106. self.column = column
  107. self.pos_in_stream = lex_pos
  108. self.state = state
  109. self._all_terminals = _all_terminals
  110. self.allowed = allowed
  111. self.considered_tokens = considered_tokens
  112. self.token_history = token_history
  113. if isinstance(seq, bytes):
  114. self._s = seq[lex_pos:lex_pos+1].decode("ascii", "backslashreplace")
  115. else:
  116. self._s = seq[lex_pos]
  117. self._context = self.get_context(seq)
  118. super(UnexpectedCharacters, self).__init__()
  119. def __str__(self):
  120. # Be aware: Broken __str__ for Exceptions are terrible to debug. Make sure there is as little room as possible for errors
  121. # You will get just `UnexpectedCharacters: <str() failed>` or something like that
  122. # If you run into this, add an `except Exception as e: print(e); raise e` or similar.
  123. message = "No terminal defined for '%s' at line %d col %d" % (self._s, self.line, self.column)
  124. message += '\n\n' + self._context
  125. if self.allowed:
  126. message += self._format_terminals(self.allowed)
  127. if self.token_history:
  128. message += '\nPrevious tokens: %s\n' % ', '.join(repr(t) for t in self.token_history)
  129. return message
  130. class UnexpectedToken(ParseError, UnexpectedInput):
  131. """When the parser throws UnexpectedToken, it instantiates a puppet
  132. with its internal state. Users can then interactively set the puppet to
  133. the desired puppet state, and resume regular parsing.
  134. see: :ref:`ParserPuppet`.
  135. """
  136. def __init__(self, token, expected, considered_rules=None, state=None, puppet=None, all_terminals=None):
  137. self.line = getattr(token, 'line', '?')
  138. self.column = getattr(token, 'column', '?')
  139. self.pos_in_stream = getattr(token, 'pos_in_stream', None)
  140. self.state = state
  141. self.token = token
  142. self.expected = expected # XXX deprecate? `accepts` is better
  143. self.considered_rules = considered_rules
  144. self.puppet = puppet
  145. self._all_terminals = all_terminals
  146. super(UnexpectedToken, self).__init__()
  147. @property
  148. def accepts(self):
  149. return self.puppet and self.puppet.accepts()
  150. def __str__(self):
  151. # Be aware: Broken __str__ for Exceptions are terrible to debug. Make sure there is as little room as possible for errors
  152. message = ("Unexpected token %r at line %s, column %s.\n%s"
  153. % (self.token, self.line, self.column, self._format_terminals(self.accepts or self.expected)))
  154. return message
  155. class VisitError(LarkError):
  156. """VisitError is raised when visitors are interrupted by an exception
  157. It provides the following attributes for inspection:
  158. - obj: the tree node or token it was processing when the exception was raised
  159. - orig_exc: the exception that cause it to fail
  160. """
  161. def __init__(self, rule, obj, orig_exc):
  162. self.obj = obj
  163. self.orig_exc = orig_exc
  164. message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc)
  165. super(VisitError, self).__init__(message)
  166. ###}