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.

282 rivejä
10 KiB

  1. from .utils import logger, NO_VALUE
  2. ###{standalone
  3. from typing import Dict, Iterable, Callable, Union, TypeVar, Tuple, Any, List, Set, Optional, TYPE_CHECKING
  4. if TYPE_CHECKING:
  5. from .lexer import Token
  6. from .parsers.lalr_interactive_parser import InteractiveParser
  7. from .tree import Tree
  8. class LarkError(Exception):
  9. pass
  10. class ConfigurationError(LarkError, ValueError):
  11. pass
  12. def assert_config(value, options, msg='Got %r, expected one of %s'):
  13. if value not in options:
  14. raise ConfigurationError(msg % (value, options))
  15. class GrammarError(LarkError):
  16. pass
  17. class ParseError(LarkError):
  18. pass
  19. class LexError(LarkError):
  20. pass
  21. T = TypeVar('T')
  22. class UnexpectedInput(LarkError):
  23. """UnexpectedInput Error.
  24. Used as a base class for the following exceptions:
  25. - ``UnexpectedCharacters``: The lexer encountered an unexpected string
  26. - ``UnexpectedToken``: The parser received an unexpected token
  27. - ``UnexpectedEOF``: The parser expected a token, but the input ended
  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. """An exception that is raised by the parser, when the input ends while it still expects a token.
  106. """
  107. expected: 'List[Token]'
  108. def __init__(self, expected, state=None, terminals_by_name=None):
  109. super(UnexpectedEOF, self).__init__()
  110. self.expected = expected
  111. self.state = state
  112. from .lexer import Token
  113. self.token = Token("<EOF>", "") # , line=-1, column=-1, pos_in_stream=-1)
  114. self.pos_in_stream = -1
  115. self.line = -1
  116. self.column = -1
  117. self._terminals_by_name = terminals_by_name
  118. def __str__(self):
  119. message = "Unexpected end-of-input. "
  120. message += self._format_expected(self.expected)
  121. return message
  122. class UnexpectedCharacters(LexError, UnexpectedInput):
  123. """An exception that is raised by the lexer, when it cannot match the next
  124. string of characters to any of its terminals.
  125. """
  126. allowed: Set[str]
  127. considered_tokens: Set[Any]
  128. def __init__(self, seq, lex_pos, line, column, allowed=None, considered_tokens=None, state=None, token_history=None,
  129. terminals_by_name=None, considered_rules=None):
  130. super(UnexpectedCharacters, self).__init__()
  131. # TODO considered_tokens and allowed can be figured out using state
  132. self.line = line
  133. self.column = column
  134. self.pos_in_stream = lex_pos
  135. self.state = state
  136. self._terminals_by_name = terminals_by_name
  137. self.allowed = allowed
  138. self.considered_tokens = considered_tokens
  139. self.considered_rules = considered_rules
  140. self.token_history = token_history
  141. if isinstance(seq, bytes):
  142. self.char = seq[lex_pos:lex_pos + 1].decode("ascii", "backslashreplace")
  143. else:
  144. self.char = seq[lex_pos]
  145. self._context = self.get_context(seq)
  146. def __str__(self):
  147. message = "No terminal matches '%s' in the current parser context, at line %d col %d" % (self.char, self.line, self.column)
  148. message += '\n\n' + self._context
  149. if self.allowed:
  150. message += self._format_expected(self.allowed)
  151. if self.token_history:
  152. message += '\nPrevious tokens: %s\n' % ', '.join(repr(t) for t in self.token_history)
  153. return message
  154. class UnexpectedToken(ParseError, UnexpectedInput):
  155. """An exception that is raised by the parser, when the token it received
  156. doesn't match any valid step forward.
  157. Parameters:
  158. token: The mismatched token
  159. expected: The set of expected tokens
  160. considered_rules: Which rules were considered, to deduce the expected tokens
  161. state: A value representing the parser state. Do not rely on its value or type.
  162. interactive_parser: An instance of ``InteractiveParser``, that is initialized to the point of failture,
  163. and can be used for debugging and error handling.
  164. Note: These parameters are available as attributes of the instance.
  165. """
  166. expected: Set[str]
  167. considered_rules: Set[str]
  168. interactive_parser: 'InteractiveParser'
  169. def __init__(self, token, expected, considered_rules=None, state=None, interactive_parser=None, terminals_by_name=None, token_history=None):
  170. super(UnexpectedToken, self).__init__()
  171. # TODO considered_rules and expected can be figured out using state
  172. self.line = getattr(token, 'line', '?')
  173. self.column = getattr(token, 'column', '?')
  174. self.pos_in_stream = getattr(token, 'start_pos', None)
  175. self.state = state
  176. self.token = token
  177. self.expected = expected # XXX deprecate? `accepts` is better
  178. self._accepts = NO_VALUE
  179. self.considered_rules = considered_rules
  180. self.interactive_parser = interactive_parser
  181. self._terminals_by_name = terminals_by_name
  182. self.token_history = token_history
  183. @property
  184. def accepts(self) -> Set[str]:
  185. if self._accepts is NO_VALUE:
  186. self._accepts = self.interactive_parser and self.interactive_parser.accepts()
  187. return self._accepts
  188. def __str__(self):
  189. message = ("Unexpected token %r at line %s, column %s.\n%s"
  190. % (self.token, self.line, self.column, self._format_expected(self.accepts or self.expected)))
  191. if self.token_history:
  192. message += "Previous tokens: %r\n" % self.token_history
  193. return message
  194. class VisitError(LarkError):
  195. """VisitError is raised when visitors are interrupted by an exception
  196. It provides the following attributes for inspection:
  197. Parameters:
  198. rule: the name of the visit rule that failed
  199. obj: the tree-node or token that was being processed
  200. orig_exc: the exception that cause it to fail
  201. Note: These parameters are available as attributes
  202. """
  203. obj: 'Union[Tree, Token]'
  204. orig_exc: Exception
  205. def __init__(self, rule, obj, orig_exc):
  206. message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc)
  207. super(VisitError, self).__init__(message)
  208. self.rule = rule
  209. self.obj = obj
  210. self.orig_exc = orig_exc
  211. ###}