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.

202 lines
7.7 KiB

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