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.

235 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. d = self._terminals_by_name
  92. expected = [d[t_name].user_repr() if t_name in d else t_name for t_name in expected]
  93. return "Expected one of: \n\t* %s\n" % '\n\t* '.join(expected)
  94. class UnexpectedEOF(ParseError, UnexpectedInput):
  95. def __init__(self, expected, state=None, terminals_by_name=None):
  96. self.expected = expected
  97. self.state = state
  98. from .lexer import Token
  99. self.token = Token("<EOF>", "") # , line=-1, column=-1, pos_in_stream=-1)
  100. self.pos_in_stream = -1
  101. self.line = -1
  102. self.column = -1
  103. self._terminals_by_name = terminals_by_name
  104. super(UnexpectedEOF, self).__init__()
  105. def __str__(self):
  106. message = "Unexpected end-of-input. "
  107. message += self._format_expected(self.expected)
  108. return message
  109. class UnexpectedCharacters(LexError, UnexpectedInput):
  110. def __init__(self, seq, lex_pos, line, column, allowed=None, considered_tokens=None, state=None, token_history=None,
  111. terminals_by_name=None):
  112. # TODO considered_tokens and allowed can be figured out using state
  113. self.line = line
  114. self.column = column
  115. self.pos_in_stream = lex_pos
  116. self.state = state
  117. self._terminals_by_name = terminals_by_name
  118. self.allowed = allowed
  119. self.considered_tokens = considered_tokens
  120. self.token_history = token_history
  121. if isinstance(seq, bytes):
  122. self.char = seq[lex_pos:lex_pos + 1].decode("ascii", "backslashreplace")
  123. else:
  124. self.char = seq[lex_pos]
  125. self._context = self.get_context(seq)
  126. super(UnexpectedCharacters, self).__init__()
  127. def __str__(self):
  128. message = "No terminal defined for '%s' at line %d col %d" % (self.char, self.line, self.column)
  129. message += '\n\n' + self._context
  130. if self.allowed:
  131. message += self._format_expected(self.allowed)
  132. if self.token_history:
  133. message += '\nPrevious tokens: %s\n' % ', '.join(repr(t) for t in self.token_history)
  134. return message
  135. class UnexpectedToken(ParseError, UnexpectedInput):
  136. """When the parser throws UnexpectedToken, it instantiates a puppet
  137. with its internal state. Users can then interactively set the puppet to
  138. the desired puppet state, and resume regular parsing.
  139. see: :ref:`ParserPuppet`.
  140. """
  141. def __init__(self, token, expected, considered_rules=None, state=None, puppet=None, terminals_by_name=None, token_history=None):
  142. # TODO considered_rules and expected can be figured out using state
  143. self.line = getattr(token, 'line', '?')
  144. self.column = getattr(token, 'column', '?')
  145. self.pos_in_stream = getattr(token, 'pos_in_stream', None)
  146. self.state = state
  147. self.token = token
  148. self.expected = expected # XXX deprecate? `accepts` is better
  149. self._accepts = NO_VALUE
  150. self.considered_rules = considered_rules
  151. self.puppet = puppet
  152. self._terminals_by_name = terminals_by_name
  153. self.token_history = token_history
  154. super(UnexpectedToken, self).__init__()
  155. @property
  156. def accepts(self):
  157. if self._accepts is NO_VALUE:
  158. self._accepts = self.puppet and self.puppet.accepts()
  159. return self._accepts
  160. def __str__(self):
  161. message = ("Unexpected token %r at line %s, column %s.\n%s"
  162. % (self.token, self.line, self.column, self._format_expected(self.accepts or self.expected)))
  163. if self.token_history:
  164. message += "Previous tokens: %r\n" % self.token_history
  165. return message
  166. class VisitError(LarkError):
  167. """VisitError is raised when visitors are interrupted by an exception
  168. It provides the following attributes for inspection:
  169. - obj: the tree node or token it was processing when the exception was raised
  170. - orig_exc: the exception that cause it to fail
  171. """
  172. def __init__(self, rule, obj, orig_exc):
  173. self.obj = obj
  174. self.orig_exc = orig_exc
  175. message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc)
  176. super(VisitError, self).__init__(message)
  177. ###}