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.

196 lines
7.5 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. self.line = line
  97. self.column = column
  98. self.pos_in_stream = lex_pos
  99. self.state = state
  100. self.allowed = allowed
  101. self.considered_tokens = considered_tokens
  102. if isinstance(seq, bytes):
  103. _s = seq[lex_pos:lex_pos+1].decode("ascii", "backslashreplace")
  104. else:
  105. _s = seq[lex_pos]
  106. message = "No terminal defined for %r at line %d col %d" % (_s, line, column)
  107. message += '\n\n' + self.get_context(seq)
  108. if allowed:
  109. message += '\nExpecting: %s\n' % allowed
  110. if token_history:
  111. message += '\nPrevious tokens: %s\n' % ', '.join(repr(t) for t in token_history)
  112. super(UnexpectedCharacters, self).__init__(message)
  113. class UnexpectedToken(ParseError, UnexpectedInput):
  114. """When the parser throws UnexpectedToken, it instantiates a puppet
  115. with its internal state. Users can then interactively set the puppet to
  116. the desired puppet state, and resume regular parsing.
  117. see: :ref:`ParserPuppet`.
  118. """
  119. def __init__(self, token, expected, considered_rules=None, state=None, puppet=None, token_history=None):
  120. self.line = getattr(token, 'line', '?')
  121. self.column = getattr(token, 'column', '?')
  122. self.pos_in_stream = getattr(token, 'pos_in_stream', None)
  123. self.state = state
  124. self.token = token
  125. self.expected = expected # XXX deprecate? `accepts` is better
  126. self.considered_rules = considered_rules
  127. self.puppet = puppet
  128. self.token_history = token_history
  129. # TODO Only calculate `accepts()` when we need to display it to the user
  130. # This will improve performance when doing automatic error handling
  131. self.accepts = puppet and puppet.accepts()
  132. message = ("Unexpected token %r at line %s, column %s.\n"
  133. "Expected one of: \n\t* %s\n"
  134. % (token, self.line, self.column, '\n\t* '.join(self.accepts or self.expected)))
  135. if self.token_history:
  136. message += "Previous tokens: %r\n" % token_history
  137. super(UnexpectedToken, self).__init__(message)
  138. class VisitError(LarkError):
  139. """VisitError is raised when visitors are interrupted by an exception
  140. It provides the following attributes for inspection:
  141. - obj: the tree node or token it was processing when the exception was raised
  142. - orig_exc: the exception that cause it to fail
  143. """
  144. def __init__(self, rule, obj, orig_exc):
  145. self.obj = obj
  146. self.orig_exc = orig_exc
  147. message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc)
  148. super(VisitError, self).__init__(message)
  149. ###}