parser_frontends.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. from typing import Any, Callable, Dict, Optional, Collection, Union, TYPE_CHECKING
  2. from .exceptions import ConfigurationError, GrammarError, assert_config
  3. from .utils import get_regexp_width, Serialize, TextOrSlice, TextSlice, LarkInput
  4. from .lexer import LexerThread, BasicLexer, ContextualLexer, Lexer
  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, _ParserArgType, _LexerArgType
  9. if TYPE_CHECKING:
  10. from .parsers.lalr_analysis import ParseTableBase
  11. ###{standalone
  12. def _wrap_lexer(lexer_class):
  13. future_interface = getattr(lexer_class, '__future_interface__', 0)
  14. if future_interface == 2:
  15. return lexer_class
  16. elif future_interface == 1:
  17. class CustomLexerWrapper1(Lexer):
  18. def __init__(self, lexer_conf):
  19. self.lexer = lexer_class(lexer_conf)
  20. def lex(self, lexer_state, parser_state):
  21. if isinstance(lexer_state.text, TextSlice) and not lexer_state.text.is_complete_text():
  22. raise TypeError("Interface=1 Custom Lexer don't support TextSlice")
  23. lexer_state.text = lexer_state.text
  24. return self.lexer.lex(lexer_state, parser_state)
  25. return CustomLexerWrapper1
  26. elif future_interface == 0:
  27. class CustomLexerWrapper0(Lexer):
  28. def __init__(self, lexer_conf):
  29. self.lexer = lexer_class(lexer_conf)
  30. def lex(self, lexer_state, parser_state):
  31. if isinstance(lexer_state.text, TextSlice):
  32. if not lexer_state.text.is_complete_text():
  33. raise TypeError("Interface=0 Custom Lexer don't support TextSlice")
  34. return self.lexer.lex(lexer_state.text.text)
  35. return self.lexer.lex(lexer_state.text)
  36. return CustomLexerWrapper0
  37. else:
  38. raise ValueError(f"Unknown __future_interface__ value {future_interface}, integer 0-2 expected")
  39. def _deserialize_parsing_frontend(data, memo, lexer_conf, callbacks, options):
  40. parser_conf = ParserConf.deserialize(data['parser_conf'], memo)
  41. cls = (options and options._plugins.get('LALR_Parser')) or LALR_Parser
  42. parser = cls.deserialize(data['parser'], memo, callbacks, options.debug)
  43. parser_conf.callbacks = callbacks
  44. return ParsingFrontend(lexer_conf, parser_conf, options, parser=parser)
  45. _parser_creators: 'Dict[str, Callable[[LexerConf, Any, Any], Any]]' = {}
  46. class ParsingFrontend(Serialize):
  47. __serialize_fields__ = 'lexer_conf', 'parser_conf', 'parser'
  48. lexer_conf: LexerConf
  49. parser_conf: ParserConf
  50. options: Any
  51. def __init__(self, lexer_conf: LexerConf, parser_conf: ParserConf, options, parser=None):
  52. self.parser_conf = parser_conf
  53. self.lexer_conf = lexer_conf
  54. self.options = options
  55. # Set-up parser
  56. if parser: # From cache
  57. self.parser = parser
  58. else:
  59. create_parser = _parser_creators.get(parser_conf.parser_type)
  60. assert create_parser is not None, "{} is not supported in standalone mode".format(
  61. parser_conf.parser_type
  62. )
  63. self.parser = create_parser(lexer_conf, parser_conf, options)
  64. # Set-up lexer
  65. lexer_type = lexer_conf.lexer_type
  66. self.skip_lexer = False
  67. if lexer_type in ('dynamic', 'dynamic_complete'):
  68. assert lexer_conf.postlex is None
  69. self.skip_lexer = True
  70. return
  71. if isinstance(lexer_type, type):
  72. assert issubclass(lexer_type, Lexer)
  73. self.lexer = _wrap_lexer(lexer_type)(lexer_conf)
  74. elif isinstance(lexer_type, str):
  75. create_lexer = {
  76. 'basic': create_basic_lexer,
  77. 'contextual': create_contextual_lexer,
  78. }[lexer_type]
  79. self.lexer = create_lexer(lexer_conf, self.parser, lexer_conf.postlex, options)
  80. else:
  81. raise TypeError("Bad value for lexer_type: {lexer_type}")
  82. if lexer_conf.postlex:
  83. self.lexer = PostLexConnector(self.lexer, lexer_conf.postlex)
  84. def _verify_start(self, start=None):
  85. if start is None:
  86. start_decls = self.parser_conf.start
  87. if len(start_decls) > 1:
  88. raise ConfigurationError("Lark initialized with more than 1 possible start rule. Must specify which start rule to parse", start_decls)
  89. start ,= start_decls
  90. elif start not in self.parser_conf.start:
  91. raise ConfigurationError("Unknown start rule %s. Must be one of %r" % (start, self.parser_conf.start))
  92. return start
  93. def _make_lexer_thread(self, text: Optional[LarkInput]) -> Union[LarkInput, LexerThread, None]:
  94. cls = (self.options and self.options._plugins.get('LexerThread')) or LexerThread
  95. if self.skip_lexer:
  96. return text
  97. if text is None:
  98. return cls(self.lexer, None)
  99. if isinstance(text, (str, bytes, TextSlice)):
  100. return cls.from_text(self.lexer, text)
  101. return cls.from_custom_input(self.lexer, text)
  102. def parse(self, text: Optional[LarkInput], start=None, on_error=None):
  103. if self.lexer_conf.lexer_type in ("dynamic", "dynamic_complete"):
  104. if isinstance(text, TextSlice) and not text.is_complete_text():
  105. raise TypeError(f"Lexer {self.lexer_conf.lexer_type} does not support text slices.")
  106. chosen_start = self._verify_start(start)
  107. kw = {} if on_error is None else {'on_error': on_error}
  108. stream = self._make_lexer_thread(text)
  109. return self.parser.parse(stream, chosen_start, **kw)
  110. def parse_interactive(self, text: Optional[TextOrSlice]=None, start=None):
  111. # TODO BREAK - Change text from Optional[str] to text: str = ''.
  112. # Would break behavior of exhaust_lexer(), which currently raises TypeError, and after the change would just return []
  113. chosen_start = self._verify_start(start)
  114. if self.parser_conf.parser_type != 'lalr':
  115. raise ConfigurationError("parse_interactive() currently only works with parser='lalr' ")
  116. stream = self._make_lexer_thread(text)
  117. return self.parser.parse_interactive(stream, chosen_start)
  118. def _validate_frontend_args(parser, lexer) -> None:
  119. assert_config(parser, ('lalr', 'earley', 'cyk'))
  120. if not isinstance(lexer, type): # not custom lexer?
  121. expected = {
  122. 'lalr': ('basic', 'contextual'),
  123. 'earley': ('basic', 'dynamic', 'dynamic_complete'),
  124. 'cyk': ('basic', ),
  125. }[parser]
  126. assert_config(lexer, expected, 'Parser %r does not support lexer %%r, expected one of %%s' % parser)
  127. def _get_lexer_callbacks(transformer, terminals):
  128. result = {}
  129. for terminal in terminals:
  130. callback = getattr(transformer, terminal.name, None)
  131. if callback is not None:
  132. result[terminal.name] = callback
  133. return result
  134. class PostLexConnector:
  135. def __init__(self, lexer, postlexer):
  136. self.lexer = lexer
  137. self.postlexer = postlexer
  138. def lex(self, lexer_state, parser_state):
  139. i = self.lexer.lex(lexer_state, parser_state)
  140. return self.postlexer.process(i)
  141. def create_basic_lexer(lexer_conf, parser, postlex, options) -> BasicLexer:
  142. cls = (options and options._plugins.get('BasicLexer')) or BasicLexer
  143. return cls(lexer_conf)
  144. def create_contextual_lexer(lexer_conf: LexerConf, parser, postlex, options) -> ContextualLexer:
  145. cls = (options and options._plugins.get('ContextualLexer')) or ContextualLexer
  146. parse_table: ParseTableBase[int] = parser._parse_table
  147. states: Dict[int, Collection[str]] = {idx:list(t.keys()) for idx, t in parse_table.states.items()}
  148. always_accept: Collection[str] = postlex.always_accept if postlex else ()
  149. return cls(lexer_conf, states, always_accept=always_accept)
  150. def create_lalr_parser(lexer_conf: LexerConf, parser_conf: ParserConf, options=None) -> LALR_Parser:
  151. debug = options.debug if options else False
  152. strict = options.strict if options else False
  153. cls = (options and options._plugins.get('LALR_Parser')) or LALR_Parser
  154. return cls(parser_conf, debug=debug, strict=strict)
  155. _parser_creators['lalr'] = create_lalr_parser
  156. ###}
  157. class EarleyRegexpMatcher:
  158. def __init__(self, lexer_conf):
  159. self.regexps = {}
  160. for t in lexer_conf.terminals:
  161. regexp = t.pattern.to_regexp()
  162. try:
  163. width = get_regexp_width(regexp)[0]
  164. except ValueError:
  165. raise GrammarError("Bad regexp in token %s: %s" % (t.name, regexp))
  166. else:
  167. if width == 0:
  168. raise GrammarError("Dynamic Earley doesn't allow zero-width regexps", t)
  169. if lexer_conf.use_bytes:
  170. regexp = regexp.encode('utf-8')
  171. self.regexps[t.name] = lexer_conf.re_module.compile(regexp, lexer_conf.g_regex_flags)
  172. def match(self, term, text, index=0):
  173. return self.regexps[term.name].match(text, index)
  174. def create_earley_parser__dynamic(lexer_conf: LexerConf, parser_conf: ParserConf, **kw):
  175. if lexer_conf.callbacks:
  176. raise GrammarError("Earley's dynamic lexer doesn't support lexer_callbacks.")
  177. earley_matcher = EarleyRegexpMatcher(lexer_conf)
  178. return xearley.Parser(lexer_conf, parser_conf, earley_matcher.match, **kw)
  179. def _match_earley_basic(term, token):
  180. return term.name == token.type
  181. def create_earley_parser__basic(lexer_conf: LexerConf, parser_conf: ParserConf, **kw):
  182. return earley.Parser(lexer_conf, parser_conf, _match_earley_basic, **kw)
  183. def create_earley_parser(lexer_conf: LexerConf, parser_conf: ParserConf, options) -> earley.Parser:
  184. resolve_ambiguity = options.ambiguity == 'resolve'
  185. debug = options.debug if options else False
  186. tree_class = options.tree_class or Tree if options.ambiguity != 'forest' else None
  187. extra = {}
  188. if lexer_conf.lexer_type == 'dynamic':
  189. f = create_earley_parser__dynamic
  190. elif lexer_conf.lexer_type == 'dynamic_complete':
  191. extra['complete_lex'] = True
  192. f = create_earley_parser__dynamic
  193. else:
  194. f = create_earley_parser__basic
  195. return f(lexer_conf, parser_conf, resolve_ambiguity=resolve_ambiguity,
  196. debug=debug, tree_class=tree_class, ordered_sets=options.ordered_sets, **extra)
  197. class CYK_FrontEnd:
  198. def __init__(self, lexer_conf, parser_conf, options=None):
  199. self.parser = cyk.Parser(parser_conf.rules)
  200. self.callbacks = parser_conf.callbacks
  201. def parse(self, lexer_thread, start):
  202. tokens = list(lexer_thread.lex(None))
  203. tree = self.parser.parse(tokens, start)
  204. return self._transform(tree)
  205. def _transform(self, tree):
  206. subtrees = list(tree.iter_subtrees())
  207. for subtree in subtrees:
  208. subtree.children = [self._apply_callback(c) if isinstance(c, Tree) else c for c in subtree.children]
  209. return self._apply_callback(tree)
  210. def _apply_callback(self, tree):
  211. return self.callbacks[tree.rule](tree.children)
  212. _parser_creators['earley'] = create_earley_parser
  213. _parser_creators['cyk'] = CYK_FrontEnd
  214. def _construct_parsing_frontend(
  215. parser_type: _ParserArgType,
  216. lexer_type: _LexerArgType,
  217. lexer_conf,
  218. parser_conf,
  219. options
  220. ):
  221. assert isinstance(lexer_conf, LexerConf)
  222. assert isinstance(parser_conf, ParserConf)
  223. parser_conf.parser_type = parser_type
  224. lexer_conf.lexer_type = lexer_type
  225. return ParsingFrontend(lexer_conf, parser_conf, options)