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.

198 lines
7.6 KiB

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