This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

158 righe
7.2 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 ..tree import Tree
  14. from ..exceptions import UnexpectedCharacters
  15. from ..lexer import Token
  16. from ..grammar import Terminal
  17. from .earley import Parser as BaseParser
  18. from .earley_forest import SymbolNode
  19. class Parser(BaseParser):
  20. def __init__(self, parser_conf, term_matcher, resolve_ambiguity=True, ignore = (), complete_lex = False, debug=False, tree_class=Tree):
  21. BaseParser.__init__(self, parser_conf, term_matcher, resolve_ambiguity, debug, tree_class)
  22. self.ignore = [Terminal(t) for t in ignore]
  23. self.complete_lex = complete_lex
  24. def _parse(self, stream, columns, to_scan, start_symbol=None):
  25. def scan(i, to_scan):
  26. """The core Earley Scanner.
  27. This is a custom implementation of the scanner that uses the
  28. Lark lexer to match tokens. The scan list is built by the
  29. Earley predictor, based on the previously completed tokens.
  30. This ensures that at each phase of the parse we have a custom
  31. lexer context, allowing for more complex ambiguities."""
  32. node_cache = {}
  33. # 1) Loop the expectations and ask the lexer to match.
  34. # Since regexp is forward looking on the input stream, and we only
  35. # want to process tokens when we hit the point in the stream at which
  36. # they complete, we push all tokens into a buffer (delayed_matches), to
  37. # be held possibly for a later parse step when we reach the point in the
  38. # input stream at which they complete.
  39. for item in set(to_scan):
  40. m = match(item.expect, stream, i)
  41. if m:
  42. t = Token(item.expect.name, m.group(0), i, text_line, text_column)
  43. delayed_matches[m.end()].append( (item, i, t) )
  44. if self.complete_lex:
  45. s = m.group(0)
  46. for j in range(1, len(s)):
  47. m = match(item.expect, s[:-j])
  48. if m:
  49. t = Token(item.expect.name, m.group(0), i, text_line, text_column)
  50. delayed_matches[i+m.end()].append( (item, i, t) )
  51. # XXX The following 3 lines were commented out for causing a bug. See issue #768
  52. # # Remove any items that successfully matched in this pass from the to_scan buffer.
  53. # # This ensures we don't carry over tokens that already matched, if we're ignoring below.
  54. # to_scan.remove(item)
  55. # 3) Process any ignores. This is typically used for e.g. whitespace.
  56. # We carry over any unmatched items from the to_scan buffer to be matched again after
  57. # the ignore. This should allow us to use ignored symbols in non-terminals to implement
  58. # e.g. mandatory spacing.
  59. for x in self.ignore:
  60. m = match(x, stream, i)
  61. if m:
  62. # Carry over any items still in the scan buffer, to past the end of the ignored items.
  63. delayed_matches[m.end()].extend([(item, i, None) for item in to_scan ])
  64. # If we're ignoring up to the end of the file, # carry over the start symbol if it already completed.
  65. delayed_matches[m.end()].extend([(item, i, None) for item in columns[i] if item.is_complete and item.s == start_symbol])
  66. next_to_scan = set()
  67. next_set = set()
  68. columns.append(next_set)
  69. transitives.append({})
  70. ## 4) Process Tokens from delayed_matches.
  71. # This is the core of the Earley scanner. Create an SPPF node for each Token,
  72. # and create the symbol node in the SPPF tree. Advance the item that completed,
  73. # and add the resulting new item to either the Earley set (for processing by the
  74. # completer/predictor) or the to_scan buffer for the next parse step.
  75. for item, start, token in delayed_matches[i+1]:
  76. if token is not None:
  77. token.end_line = text_line
  78. token.end_column = text_column + 1
  79. token.end_pos = i + 1
  80. new_item = item.advance()
  81. label = (new_item.s, new_item.start, i)
  82. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  83. new_item.node.add_family(new_item.s, item.rule, new_item.start, item.node, token)
  84. else:
  85. new_item = item
  86. if new_item.expect in self.TERMINALS:
  87. # add (B ::= Aai+1.B, h, y) to Q'
  88. next_to_scan.add(new_item)
  89. else:
  90. # add (B ::= Aa+1.B, h, y) to Ei+1
  91. next_set.add(new_item)
  92. del delayed_matches[i+1] # No longer needed, so unburden memory
  93. if not next_set and not delayed_matches and not next_to_scan:
  94. considered_rules = list(sorted(to_scan, key=lambda key: key.rule.origin.name))
  95. raise UnexpectedCharacters(stream, i, text_line, text_column, {item.expect.name for item in to_scan},
  96. set(to_scan), state=frozenset(i.s for i in to_scan),
  97. considered_rules=considered_rules
  98. )
  99. return next_to_scan
  100. delayed_matches = defaultdict(list)
  101. match = self.term_matcher
  102. # Cache for nodes & tokens created in a particular parse step.
  103. transitives = [{}]
  104. text_line = 1
  105. text_column = 1
  106. ## The main Earley loop.
  107. # Run the Prediction/Completion cycle for any Items in the current Earley set.
  108. # Completions will be added to the SPPF tree, and predictions will be recursively
  109. # processed down to terminals/empty nodes to be added to the scanner for the next
  110. # step.
  111. i = 0
  112. for token in stream:
  113. self.predict_and_complete(i, to_scan, columns, transitives)
  114. to_scan = scan(i, to_scan)
  115. if token == '\n':
  116. text_line += 1
  117. text_column = 1
  118. else:
  119. text_column += 1
  120. i += 1
  121. self.predict_and_complete(i, to_scan, columns, transitives)
  122. ## Column is now the final column in the parse.
  123. assert i == len(columns)-1
  124. return to_scan