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.

151 lines
6.7 KiB

  1. """This module implements an experimental Earley parser with a dynamic lexer
  2. The core Earley algorithm used here is based on Elizabeth Scott's implementation, here:
  3. https://www.sciencedirect.com/science/article/pii/S1571066108001497
  4. That is probably the best reference for understanding the algorithm here.
  5. The Earley parser outputs an SPPF-tree as per that document. The SPPF tree format
  6. is better documented here:
  7. http://www.bramvandersanden.com/post/2014/06/shared-packed-parse-forest/
  8. Instead of running a lexer beforehand, or using a costy char-by-char method, this parser
  9. uses regular expressions by necessity, achieving high-performance while maintaining all of
  10. Earley's power in parsing any CFG.
  11. """
  12. from collections import defaultdict
  13. from ..exceptions import UnexpectedCharacters
  14. from ..lexer import Token
  15. from ..grammar import Terminal
  16. from .earley import Parser as BaseParser
  17. from .earley_forest import SymbolNode
  18. class Parser(BaseParser):
  19. def __init__(self, parser_conf, term_matcher, resolve_ambiguity=True, ignore = (), complete_lex = False, debug=False):
  20. BaseParser.__init__(self, parser_conf, term_matcher, resolve_ambiguity, debug)
  21. self.ignore = [Terminal(t) for t in ignore]
  22. self.complete_lex = complete_lex
  23. def _parse(self, stream, columns, to_scan, start_symbol=None):
  24. def scan(i, to_scan):
  25. """The core Earley Scanner.
  26. This is a custom implementation of the scanner that uses the
  27. Lark lexer to match tokens. The scan list is built by the
  28. Earley predictor, based on the previously completed tokens.
  29. This ensures that at each phase of the parse we have a custom
  30. lexer context, allowing for more complex ambiguities."""
  31. node_cache = {}
  32. # 1) Loop the expectations and ask the lexer to match.
  33. # Since regexp is forward looking on the input stream, and we only
  34. # want to process tokens when we hit the point in the stream at which
  35. # they complete, we push all tokens into a buffer (delayed_matches), to
  36. # be held possibly for a later parse step when we reach the point in the
  37. # input stream at which they complete.
  38. for item in set(to_scan):
  39. m = match(item.expect, stream, i)
  40. if m:
  41. t = Token(item.expect.name, m.group(0), i, text_line, text_column)
  42. delayed_matches[m.end()].append( (item, i, t) )
  43. if self.complete_lex:
  44. s = m.group(0)
  45. for j in range(1, len(s)):
  46. m = match(item.expect, s[:-j])
  47. if m:
  48. t = Token(item.expect.name, m.group(0), i, text_line, text_column)
  49. delayed_matches[i+m.end()].append( (item, i, t) )
  50. # Remove any items that successfully matched in this pass from the to_scan buffer.
  51. # This ensures we don't carry over tokens that already matched, if we're ignoring below.
  52. to_scan.remove(item)
  53. # 3) Process any ignores. This is typically used for e.g. whitespace.
  54. # We carry over any unmatched items from the to_scan buffer to be matched again after
  55. # the ignore. This should allow us to use ignored symbols in non-terminals to implement
  56. # e.g. mandatory spacing.
  57. for x in self.ignore:
  58. m = match(x, stream, i)
  59. if m:
  60. # Carry over any items still in the scan buffer, to past the end of the ignored items.
  61. delayed_matches[m.end()].extend([(item, i, None) for item in to_scan ])
  62. # If we're ignoring up to the end of the file, # carry over the start symbol if it already completed.
  63. delayed_matches[m.end()].extend([(item, i, None) for item in columns[i] if item.is_complete and item.s == start_symbol])
  64. next_to_scan = set()
  65. next_set = set()
  66. columns.append(next_set)
  67. transitives.append({})
  68. ## 4) Process Tokens from delayed_matches.
  69. # This is the core of the Earley scanner. Create an SPPF node for each Token,
  70. # and create the symbol node in the SPPF tree. Advance the item that completed,
  71. # and add the resulting new item to either the Earley set (for processing by the
  72. # completer/predictor) or the to_scan buffer for the next parse step.
  73. for item, start, token in delayed_matches[i+1]:
  74. if token is not None:
  75. token.end_line = text_line
  76. token.end_column = text_column + 1
  77. token.end_pos = i + 1
  78. new_item = item.advance()
  79. label = (new_item.s, new_item.start, i)
  80. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  81. new_item.node.add_family(new_item.s, item.rule, new_item.start, item.node, token)
  82. else:
  83. new_item = item
  84. if new_item.expect in self.TERMINALS:
  85. # add (B ::= Aai+1.B, h, y) to Q'
  86. next_to_scan.add(new_item)
  87. else:
  88. # add (B ::= Aa+1.B, h, y) to Ei+1
  89. next_set.add(new_item)
  90. del delayed_matches[i+1] # No longer needed, so unburden memory
  91. if not next_set and not delayed_matches and not next_to_scan:
  92. raise UnexpectedCharacters(stream, i, text_line, text_column, {item.expect.name for item in to_scan}, set(to_scan))
  93. return next_to_scan
  94. delayed_matches = defaultdict(list)
  95. match = self.term_matcher
  96. # Cache for nodes & tokens created in a particular parse step.
  97. transitives = [{}]
  98. text_line = 1
  99. text_column = 1
  100. ## The main Earley loop.
  101. # Run the Prediction/Completion cycle for any Items in the current Earley set.
  102. # Completions will be added to the SPPF tree, and predictions will be recursively
  103. # processed down to terminals/empty nodes to be added to the scanner for the next
  104. # step.
  105. i = 0
  106. for token in stream:
  107. self.predict_and_complete(i, to_scan, columns, transitives)
  108. to_scan = scan(i, to_scan)
  109. if token == '\n':
  110. text_line += 1
  111. text_column = 1
  112. else:
  113. text_column += 1
  114. i += 1
  115. self.predict_and_complete(i, to_scan, columns, transitives)
  116. ## Column is now the final column in the parse.
  117. assert i == len(columns)-1
  118. return to_scan