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.

248 lines
8.6 KiB

  1. from .exceptions import ConfigurationError, GrammarError
  2. from .utils import get_regexp_width, Serialize
  3. from .parsers.grammar_analysis import GrammarAnalyzer
  4. from .lexer import LexerThread, TraditionalLexer, ContextualLexer, Lexer, Token, TerminalDef
  5. from .parsers import earley, xearley, cyk
  6. from .parsers.lalr_parser import LALR_Parser
  7. from .tree import Tree
  8. from .common import LexerConf, ParserConf
  9. try:
  10. import regex
  11. except ImportError:
  12. regex = None
  13. import re
  14. ###{standalone
  15. def _wrap_lexer(lexer_class):
  16. future_interface = getattr(lexer_class, '__future_interface__', False)
  17. if future_interface:
  18. return lexer_class
  19. else:
  20. class CustomLexerWrapper(Lexer):
  21. def __init__(self, lexer_conf):
  22. self.lexer = lexer_class(lexer_conf)
  23. def lex(self, lexer_state, parser_state):
  24. return self.lexer.lex(lexer_state.text)
  25. return CustomLexerWrapper
  26. class MakeParsingFrontend:
  27. def __init__(self, parser, lexer):
  28. self.parser = parser
  29. self.lexer = lexer
  30. def __call__(self, lexer_conf, parser_conf, options):
  31. assert isinstance(lexer_conf, LexerConf)
  32. assert isinstance(parser_conf, ParserConf)
  33. parser_conf.name = self.parser
  34. lexer_conf.name = self.lexer
  35. return ParsingFrontend(lexer_conf, parser_conf, options)
  36. @classmethod
  37. def deserialize(cls, data, memo, callbacks, options):
  38. lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo)
  39. parser_conf = ParserConf.deserialize(data['parser_conf'], memo)
  40. parser = LALR_Parser.deserialize(data['parser'], memo, callbacks, options.debug)
  41. parser_conf.callbacks = callbacks
  42. terminals = [item for item in memo.values() if isinstance(item, TerminalDef)]
  43. lexer_conf.callbacks = _get_lexer_callbacks(options.transformer, terminals)
  44. lexer_conf.re_module = regex if options.regex else re
  45. lexer_conf.use_bytes = options.use_bytes
  46. lexer_conf.g_regex_flags = options.g_regex_flags
  47. lexer_conf.skip_validation = True
  48. lexer_conf.postlex = options.postlex
  49. return ParsingFrontend(lexer_conf, parser_conf, options, parser=parser)
  50. class ParsingFrontend(Serialize):
  51. __serialize_fields__ = 'lexer_conf', 'parser_conf', 'parser', 'options'
  52. def __init__(self, lexer_conf, parser_conf, options, parser=None):
  53. self.parser_conf = parser_conf
  54. self.lexer_conf = lexer_conf
  55. self.options = options
  56. # Set-up parser
  57. if parser: # From cache
  58. self.parser = parser
  59. else:
  60. create_parser = {
  61. 'lalr': create_lalr_parser,
  62. 'earley': make_early,
  63. 'cyk': CYK_FrontEnd,
  64. }[parser_conf.name]
  65. self.parser = create_parser(lexer_conf, parser_conf, options)
  66. # Set-up lexer
  67. self.skip_lexer = False
  68. if lexer_conf.name in ('dynamic', 'dynamic_complete'):
  69. self.skip_lexer = True
  70. return
  71. try:
  72. create_lexer = {
  73. 'standard': create_traditional_lexer,
  74. 'contextual': create_contextual_lexer,
  75. }[lexer_conf.name]
  76. except KeyError:
  77. assert issubclass(lexer_conf.name, Lexer), lexer_conf.name
  78. self.lexer = _wrap_lexer(lexer_conf.name)(lexer_conf)
  79. else:
  80. self.lexer = create_lexer(lexer_conf, self.parser, lexer_conf.postlex)
  81. if lexer_conf.postlex:
  82. self.lexer = PostLexConnector(self.lexer, lexer_conf.postlex)
  83. def _parse(self, start, input, *args):
  84. if start is None:
  85. start = self.parser_conf.start
  86. if len(start) > 1:
  87. raise ConfigurationError("Lark initialized with more than 1 possible start rule. Must specify which start rule to parse", start)
  88. start ,= start
  89. return self.parser.parse(input, start, *args)
  90. def parse(self, text, start=None):
  91. if self.skip_lexer:
  92. return self._parse(start, text)
  93. lexer = LexerThread(self.lexer, text)
  94. return self._parse(start, lexer)
  95. def get_frontend(parser, lexer):
  96. if parser=='lalr':
  97. if lexer is None:
  98. raise ConfigurationError('The LALR parser requires use of a lexer')
  99. if lexer not in ('standard' ,'contextual') and not issubclass(lexer, Lexer):
  100. raise ConfigurationError('Unknown lexer: %s' % lexer)
  101. elif parser=='earley':
  102. if lexer=='contextual':
  103. raise ConfigurationError('The Earley parser does not support the contextual parser')
  104. elif parser == 'cyk':
  105. if lexer != 'standard':
  106. raise ConfigurationError('CYK parser requires using standard parser.')
  107. else:
  108. raise ConfigurationError('Unknown parser: %s' % parser)
  109. return MakeParsingFrontend(parser, lexer)
  110. def _get_lexer_callbacks(transformer, terminals):
  111. result = {}
  112. for terminal in terminals:
  113. callback = getattr(transformer, terminal.name, None)
  114. if callback is not None:
  115. result[terminal.name] = callback
  116. return result
  117. class PostLexConnector:
  118. def __init__(self, lexer, postlexer):
  119. self.lexer = lexer
  120. self.postlexer = postlexer
  121. def make_lexer_state(self, text):
  122. return self.lexer.make_lexer_state(text)
  123. def lex(self, lexer_state, parser_state):
  124. i = self.lexer.lex(lexer_state, parser_state)
  125. return self.postlexer.process(i)
  126. def create_traditional_lexer(lexer_conf, parser, postlex):
  127. return TraditionalLexer(lexer_conf)
  128. def create_contextual_lexer(lexer_conf, parser, postlex):
  129. states = {idx:list(t.keys()) for idx, t in parser._parse_table.states.items()}
  130. always_accept = postlex.always_accept if postlex else ()
  131. return ContextualLexer(lexer_conf, states, always_accept=always_accept)
  132. def create_lalr_parser(lexer_conf, parser_conf, options=None):
  133. debug = options.debug if options else False
  134. return LALR_Parser(parser_conf, debug=debug)
  135. make_early = NotImplemented
  136. CYK_FrontEnd = NotImplemented
  137. ###}
  138. class EarleyRegexpMatcher:
  139. def __init__(self, lexer_conf):
  140. self.regexps = {}
  141. for t in lexer_conf.tokens:
  142. if t.priority != 1:
  143. raise GrammarError("Dynamic Earley doesn't support weights on terminals", t, t.priority)
  144. regexp = t.pattern.to_regexp()
  145. try:
  146. width = get_regexp_width(regexp)[0]
  147. except ValueError:
  148. raise GrammarError("Bad regexp in token %s: %s" % (t.name, regexp))
  149. else:
  150. if width == 0:
  151. raise GrammarError("Dynamic Earley doesn't allow zero-width regexps", t)
  152. if lexer_conf.use_bytes:
  153. regexp = regexp.encode('utf-8')
  154. self.regexps[t.name] = lexer_conf.re_module.compile(regexp, lexer_conf.g_regex_flags)
  155. def match(self, term, text, index=0):
  156. return self.regexps[term.name].match(text, index)
  157. def make_xearley(lexer_conf, parser_conf, options=None, **kw):
  158. earley_matcher = EarleyRegexpMatcher(lexer_conf)
  159. return xearley.Parser(parser_conf, earley_matcher.match, ignore=lexer_conf.ignore, **kw)
  160. def _match_earley_basic(term, token):
  161. return term.name == token.type
  162. def make_early_basic(lexer_conf, parser_conf, options, **kw):
  163. return earley.Parser(parser_conf, _match_earley_basic, **kw)
  164. def make_early(lexer_conf, parser_conf, options):
  165. resolve_ambiguity = options.ambiguity == 'resolve'
  166. debug = options.debug if options else False
  167. tree_class = options.tree_class or Tree if options.ambiguity != 'forest' else None
  168. extra = {}
  169. if lexer_conf.name == 'dynamic':
  170. f = make_xearley
  171. elif lexer_conf.name == 'dynamic_complete':
  172. extra['complete_lex'] =True
  173. f = make_xearley
  174. else:
  175. f = make_early_basic
  176. return f(lexer_conf, parser_conf, options, resolve_ambiguity=resolve_ambiguity, debug=debug, tree_class=tree_class, **extra)
  177. class CYK_FrontEnd:
  178. def __init__(self, lexer_conf, parser_conf, options=None):
  179. self._analysis = GrammarAnalyzer(parser_conf)
  180. self.parser = cyk.Parser(parser_conf.rules)
  181. self.callbacks = parser_conf.callbacks
  182. def parse(self, lexer, start):
  183. tokens = list(lexer.lex(None))
  184. tree = self.parser.parse(tokens, start)
  185. return self._transform(tree)
  186. def _transform(self, tree):
  187. subtrees = list(tree.iter_subtrees())
  188. for subtree in subtrees:
  189. subtree.children = [self._apply_callback(c) if isinstance(c, Tree) else c for c in subtree.children]
  190. return self._apply_callback(tree)
  191. def _apply_callback(self, tree):
  192. return self.callbacks[tree.rule](tree.children)