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.

209 lines
7.8 KiB

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