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.

267 lines
9.6 KiB

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