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.

209 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. t = []
  91. for name in names:
  92. try:
  93. t.append(next(t.nice_print for t in self._all_terminals if t.name == name))
  94. except StopIteration:
  95. # If we don't find the corresponding Terminal (which *should* never happen), don't error.
  96. # Broken __str__ for Exception are some of the worst bugs
  97. t.append(t.display_name)
  98. else:
  99. t = names
  100. return "Expected one of: \n\t* %s\n" % '\n\t* '.join(t)
  101. class UnexpectedCharacters(LexError, UnexpectedInput):
  102. def __init__(self, seq, lex_pos, line, column, allowed=None, considered_tokens=None, state=None, token_history=None, _all_terminals=None):
  103. self.line = line
  104. self.column = column
  105. self.pos_in_stream = lex_pos
  106. self.state = state
  107. self._all_terminals = _all_terminals
  108. self.allowed = allowed
  109. self.considered_tokens = considered_tokens
  110. self.token_history = token_history
  111. if isinstance(seq, bytes):
  112. self._s = seq[lex_pos:lex_pos+1].decode("ascii", "backslashreplace")
  113. else:
  114. self._s = seq[lex_pos]
  115. self._context = self.get_context(seq)
  116. super(UnexpectedCharacters, self).__init__()
  117. def __str__(self):
  118. # Be aware: Broken __str__ for Exceptions are terrible to debug. Make sure there is as little room as possible for errors
  119. # You will get just `UnexpectedCharacters: <str() failed>` or something like that
  120. # If you run into this, add an `except Exception as e: print(e); raise e` or similar.
  121. message = "No terminal defined for '%s' at line %d col %d" % (self._s, self.line, self.column)
  122. message += '\n\n' + self._context
  123. if self.allowed:
  124. message += self._format_terminals(self.allowed)
  125. if self.token_history:
  126. message += '\nPrevious tokens: %s\n' % ', '.join(repr(t) for t in self.token_history)
  127. return message
  128. class UnexpectedToken(ParseError, UnexpectedInput):
  129. """When the parser throws UnexpectedToken, it instantiates a puppet
  130. with its internal state. Users can then interactively set the puppet to
  131. the desired puppet state, and resume regular parsing.
  132. see: :ref:`ParserPuppet`.
  133. """
  134. def __init__(self, token, expected, considered_rules=None, state=None, puppet=None, all_terminals=None):
  135. self.line = getattr(token, 'line', '?')
  136. self.column = getattr(token, 'column', '?')
  137. self.pos_in_stream = getattr(token, 'pos_in_stream', None)
  138. self.state = state
  139. self.token = token
  140. self.expected = expected # XXX deprecate? `accepts` is better
  141. self.considered_rules = considered_rules
  142. self.puppet = puppet
  143. self._all_terminals = all_terminals
  144. super(UnexpectedToken, self).__init__()
  145. @property
  146. def accepts(self):
  147. return self.puppet and self.puppet.accepts()
  148. def __str__(self):
  149. # Be aware: Broken __str__ for Exceptions are terrible to debug. Make sure there is as little room as possible for errors
  150. message = ("Unexpected token %r at line %s, column %s.\n%s"
  151. % (self.token, self.line, self.column, self._format_terminals(self.accepts or self.expected)))
  152. return message
  153. class VisitError(LarkError):
  154. """VisitError is raised when visitors are interrupted by an exception
  155. It provides the following attributes for inspection:
  156. - obj: the tree node or token it was processing when the exception was raised
  157. - orig_exc: the exception that cause it to fail
  158. """
  159. def __init__(self, rule, obj, orig_exc):
  160. self.obj = obj
  161. self.orig_exc = orig_exc
  162. message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc)
  163. super(VisitError, self).__init__(message)
  164. ###}