This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

249 rader
9.1 KiB

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