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.

234 lines
8.6 KiB

  1. from .utils import STRING_TYPE, logger, NO_VALUE
  2. ###{standalone
  3. class LarkError(Exception):
  4. pass
  5. class ConfigurationError(LarkError, ValueError):
  6. pass
  7. def assert_config(value, options, msg='Got %r, expected one of %s'):
  8. if value not in options:
  9. raise ConfigurationError(msg % (value, options))
  10. class GrammarError(LarkError):
  11. pass
  12. class ParseError(LarkError):
  13. pass
  14. class LexError(LarkError):
  15. pass
  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. _terminals_by_name = 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. assert self.pos_in_stream is not None, self
  33. pos = self.pos_in_stream
  34. start = max(pos - span, 0)
  35. end = pos + span
  36. if not isinstance(text, bytes):
  37. before = text[start:pos].rsplit('\n', 1)[-1]
  38. after = text[pos:end].split('\n', 1)[0]
  39. return before + after + '\n' + ' ' * len(before.expandtabs()) + '^\n'
  40. else:
  41. before = text[start:pos].rsplit(b'\n', 1)[-1]
  42. after = text[pos:end].split(b'\n', 1)[0]
  43. return (before + after + b'\n' + b' ' * len(before.expandtabs()) + b'^\n').decode("ascii", "backslashreplace")
  44. def match_examples(self, parse_fn, examples, token_type_match_fallback=False, use_accepts=False):
  45. """Allows you to detect what's wrong in the input text by matching
  46. against example errors.
  47. Given a parser instance and a dictionary mapping some label with
  48. some malformed syntax examples, it'll return the label for the
  49. example that bests matches the current error. The function will
  50. iterate the dictionary until it finds a matching error, and
  51. return the corresponding value.
  52. For an example usage, see `examples/error_reporting_lalr.py`
  53. Parameters:
  54. parse_fn: parse function (usually ``lark_instance.parse``)
  55. examples: dictionary of ``{'example_string': value}``.
  56. use_accepts: Recommended to call this with ``use_accepts=True``.
  57. The default is ``False`` for backwards compatibility.
  58. """
  59. assert self.state is not None, "Not supported for this exception"
  60. if isinstance(examples, dict):
  61. examples = examples.items()
  62. candidate = (None, False)
  63. for i, (label, example) in enumerate(examples):
  64. assert not isinstance(example, STRING_TYPE)
  65. for j, malformed in enumerate(example):
  66. try:
  67. parse_fn(malformed)
  68. except UnexpectedInput as ut:
  69. if ut.state == self.state:
  70. if use_accepts and hasattr(self, 'accepts') and ut.accepts != self.accepts:
  71. logger.debug("Different accepts with same state[%d]: %s != %s at example [%s][%s]" %
  72. (self.state, self.accepts, ut.accepts, i, j))
  73. continue
  74. try:
  75. if ut.token == self.token: # Try exact match first
  76. logger.debug("Exact Match at example [%s][%s]" % (i, j))
  77. return label
  78. if token_type_match_fallback:
  79. # Fallback to token types match
  80. if (ut.token.type == self.token.type) and not candidate[-1]:
  81. logger.debug("Token Type Fallback at example [%s][%s]" % (i, j))
  82. candidate = label, True
  83. except AttributeError:
  84. pass
  85. if candidate[0] is None:
  86. logger.debug("Same State match at example [%s][%s]" % (i, j))
  87. candidate = label, False
  88. return candidate[0]
  89. def _format_expected(self, expected):
  90. if self._terminals_by_name:
  91. expected = [self._terminals_by_name[t_name].user_repr() for t_name in expected]
  92. return "Expected one of: \n\t* %s\n" % '\n\t* '.join(expected)
  93. class UnexpectedEOF(ParseError, UnexpectedInput):
  94. def __init__(self, expected, state=None, terminals_by_name=None):
  95. self.expected = expected
  96. self.state = state
  97. from .lexer import Token
  98. self.token = Token("<EOF>", "") # , line=-1, column=-1, pos_in_stream=-1)
  99. self.pos_in_stream = -1
  100. self.line = -1
  101. self.column = -1
  102. self._terminals_by_name = terminals_by_name
  103. super(UnexpectedEOF, self).__init__()
  104. def __str__(self):
  105. message = "Unexpected end-of-input. "
  106. message += self._format_expected(self.expected)
  107. return message
  108. class UnexpectedCharacters(LexError, UnexpectedInput):
  109. def __init__(self, seq, lex_pos, line, column, allowed=None, considered_tokens=None, state=None, token_history=None,
  110. terminals_by_name=None):
  111. # TODO considered_tokens and allowed can be figured out using state
  112. self.line = line
  113. self.column = column
  114. self.pos_in_stream = lex_pos
  115. self.state = state
  116. self._terminals_by_name = terminals_by_name
  117. self.allowed = allowed
  118. self.considered_tokens = considered_tokens
  119. self.token_history = token_history
  120. if isinstance(seq, bytes):
  121. self.char = seq[lex_pos:lex_pos + 1].decode("ascii", "backslashreplace")
  122. else:
  123. self.char = seq[lex_pos]
  124. self._context = self.get_context(seq)
  125. super(UnexpectedCharacters, self).__init__()
  126. def __str__(self):
  127. message = "No terminal defined for '%s' at line %d col %d" % (self.char, self.line, self.column)
  128. message += '\n\n' + self._context
  129. if self.allowed:
  130. message += self._format_expected(self.allowed)
  131. if self.token_history:
  132. message += '\nPrevious tokens: %s\n' % ', '.join(repr(t) for t in self.token_history)
  133. return message
  134. class UnexpectedToken(ParseError, UnexpectedInput):
  135. """When the parser throws UnexpectedToken, it instantiates a puppet
  136. with its internal state. Users can then interactively set the puppet to
  137. the desired puppet state, and resume regular parsing.
  138. see: :ref:`ParserPuppet`.
  139. """
  140. def __init__(self, token, expected, considered_rules=None, state=None, puppet=None, terminals_by_name=None, token_history=None):
  141. # TODO considered_rules and expected can be figured out using state
  142. self.line = getattr(token, 'line', '?')
  143. self.column = getattr(token, 'column', '?')
  144. self.pos_in_stream = getattr(token, 'pos_in_stream', None)
  145. self.state = state
  146. self.token = token
  147. self.expected = expected # XXX deprecate? `accepts` is better
  148. self._accepts = NO_VALUE
  149. self.considered_rules = considered_rules
  150. self.puppet = puppet
  151. self._terminals_by_name = terminals_by_name
  152. self.token_history = token_history
  153. super(UnexpectedToken, self).__init__()
  154. @property
  155. def accepts(self):
  156. if self._accepts is NO_VALUE:
  157. self._accepts = self.puppet and self.puppet.accepts()
  158. return self._accepts
  159. def __str__(self):
  160. message = ("Unexpected token %r at line %s, column %s.\n%s"
  161. % (self.token, self.line, self.column, self._format_expected(self.accepts or self.expected)))
  162. if self.token_history:
  163. message += "Previous tokens: %r\n" % self.token_history
  164. return message
  165. class VisitError(LarkError):
  166. """VisitError is raised when visitors are interrupted by an exception
  167. It provides the following attributes for inspection:
  168. - obj: the tree node or token it was processing when the exception was raised
  169. - orig_exc: the exception that cause it to fail
  170. """
  171. def __init__(self, rule, obj, orig_exc):
  172. self.obj = obj
  173. self.orig_exc = orig_exc
  174. message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc)
  175. super(VisitError, self).__init__(message)
  176. ###}