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.

369 lines
14 KiB

  1. from __future__ import absolute_import
  2. import sys, os, pickle, hashlib, logging
  3. from io import open
  4. from .utils import STRING_TYPE, Serialize, SerializeMemoizer, FS
  5. from .load_grammar import load_grammar
  6. from .tree import Tree
  7. from .common import LexerConf, ParserConf
  8. from .lexer import Lexer, TraditionalLexer, TerminalDef
  9. from .parse_tree_builder import ParseTreeBuilder
  10. from .parser_frontends import get_frontend
  11. from .grammar import Rule
  12. ###{standalone
  13. class LarkOptions(Serialize):
  14. """Specifies the options for Lark
  15. """
  16. OPTIONS_DOC = """
  17. # General
  18. start - The start symbol. Either a string, or a list of strings for
  19. multiple possible starts (Default: "start")
  20. debug - Display debug information, such as warnings (default: False)
  21. transformer - Applies the transformer to every parse tree (equivlent to
  22. applying it after the parse, but faster)
  23. propagate_positions - Propagates (line, column, end_line, end_column)
  24. attributes into all tree branches.
  25. maybe_placeholders - When True, the `[]` operator returns `None` when not matched.
  26. When `False`, `[]` behaves like the `?` operator,
  27. and returns no value at all.
  28. (default=`False`. Recommended to set to `True`)
  29. cache - Cache the results of the Lark grammar analysis, for x2 to x3 faster loading.
  30. LALR only for now.
  31. When `False`, does nothing (default)
  32. When `True`, caches to a temporary file in the local directory
  33. When given a string, caches to the path pointed by the string
  34. g_regex_flags - Flags that are applied to all terminals
  35. (both regex and strings)
  36. keep_all_tokens - Prevent the tree builder from automagically
  37. removing "punctuation" tokens (default: False)
  38. # Algorithm
  39. parser - Decides which parser engine to use
  40. Accepts "earley" or "lalr". (Default: "earley")
  41. (there is also a "cyk" option for legacy)
  42. lexer - Decides whether or not to use a lexer stage
  43. "auto" (default): Choose for me based on the parser
  44. "standard": Use a standard lexer
  45. "contextual": Stronger lexer (only works with parser="lalr")
  46. "dynamic": Flexible and powerful (only with parser="earley")
  47. "dynamic_complete": Same as dynamic, but tries *every* variation
  48. of tokenizing possible.
  49. ambiguity - Decides how to handle ambiguity in the parse.
  50. Only relevant if parser="earley"
  51. "resolve": The parser will automatically choose the simplest
  52. derivation (it chooses consistently: greedy for
  53. tokens, non-greedy for rules)
  54. "explicit": The parser will return all derivations wrapped
  55. in "_ambig" tree nodes (i.e. a forest).
  56. # Domain Specific
  57. postlex - Lexer post-processing (Default: None) Only works with the
  58. standard and contextual lexers.
  59. priority - How priorities should be evaluated - auto, none, normal,
  60. invert (Default: auto)
  61. lexer_callbacks - Dictionary of callbacks for the lexer. May alter
  62. tokens during lexing. Use with caution.
  63. edit_terminals - A callback
  64. """
  65. if __doc__:
  66. __doc__ += OPTIONS_DOC
  67. _defaults = {
  68. 'debug': False,
  69. 'keep_all_tokens': False,
  70. 'tree_class': None,
  71. 'cache': False,
  72. 'postlex': None,
  73. 'parser': 'earley',
  74. 'lexer': 'auto',
  75. 'transformer': None,
  76. 'start': 'start',
  77. 'priority': 'auto',
  78. 'ambiguity': 'auto',
  79. 'propagate_positions': False,
  80. 'lexer_callbacks': {},
  81. 'maybe_placeholders': False,
  82. 'edit_terminals': None,
  83. 'g_regex_flags': 0,
  84. }
  85. def __init__(self, options_dict):
  86. o = dict(options_dict)
  87. options = {}
  88. for name, default in self._defaults.items():
  89. if name in o:
  90. value = o.pop(name)
  91. if isinstance(default, bool) and name != 'cache':
  92. value = bool(value)
  93. else:
  94. value = default
  95. options[name] = value
  96. if isinstance(options['start'], STRING_TYPE):
  97. options['start'] = [options['start']]
  98. self.__dict__['options'] = options
  99. assert self.parser in ('earley', 'lalr', 'cyk', None)
  100. if self.parser == 'earley' and self.transformer:
  101. raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm.'
  102. 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
  103. if o:
  104. raise ValueError("Unknown options: %s" % o.keys())
  105. def __getattr__(self, name):
  106. try:
  107. return self.options[name]
  108. except KeyError as e:
  109. raise AttributeError(e)
  110. def __setattr__(self, name, value):
  111. assert name in self.options
  112. self.options[name] = value
  113. def serialize(self, memo):
  114. return self.options
  115. @classmethod
  116. def deserialize(cls, data, memo):
  117. return cls(data)
  118. class Lark(Serialize):
  119. def __init__(self, grammar, **options):
  120. """
  121. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  122. options : a dictionary controlling various aspects of Lark.
  123. """
  124. self.options = LarkOptions(options)
  125. # Some, but not all file-like objects have a 'name' attribute
  126. try:
  127. self.source = grammar.name
  128. except AttributeError:
  129. self.source = '<string>'
  130. # Drain file-like objects to get their contents
  131. try:
  132. read = grammar.read
  133. except AttributeError:
  134. pass
  135. else:
  136. grammar = read()
  137. assert isinstance(grammar, STRING_TYPE)
  138. cache_fn = None
  139. if self.options.cache:
  140. if isinstance(self.options.cache, STRING_TYPE):
  141. cache_fn = self.options.cache
  142. else:
  143. if self.options.cache is not True:
  144. raise ValueError("cache must be bool or str")
  145. unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals')
  146. options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
  147. s = grammar + options_str
  148. md5 = hashlib.md5(s.encode()).hexdigest()
  149. cache_fn = '.lark_cache_%s.tmp' % md5
  150. if FS.exists(cache_fn):
  151. logging.debug('Loading grammar from cache: %s', cache_fn)
  152. with FS.open(cache_fn, 'rb') as f:
  153. self._load(f, self.options.transformer, self.options.postlex)
  154. return
  155. if self.options.lexer == 'auto':
  156. if self.options.parser == 'lalr':
  157. self.options.lexer = 'contextual'
  158. elif self.options.parser == 'earley':
  159. self.options.lexer = 'dynamic'
  160. elif self.options.parser == 'cyk':
  161. self.options.lexer = 'standard'
  162. else:
  163. assert False, self.options.parser
  164. lexer = self.options.lexer
  165. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  166. if self.options.ambiguity == 'auto':
  167. if self.options.parser == 'earley':
  168. self.options.ambiguity = 'resolve'
  169. else:
  170. disambig_parsers = ['earley', 'cyk']
  171. assert self.options.parser in disambig_parsers, (
  172. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  173. if self.options.priority == 'auto':
  174. if self.options.parser in ('earley', 'cyk', ):
  175. self.options.priority = 'normal'
  176. elif self.options.parser in ('lalr', ):
  177. self.options.priority = None
  178. elif self.options.priority in ('invert', 'normal'):
  179. assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time"
  180. assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority)
  181. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  182. assert self.options.ambiguity in ('resolve', 'explicit', 'auto', )
  183. # Parse the grammar file and compose the grammars (TODO)
  184. self.grammar = load_grammar(grammar, self.source)
  185. # Compile the EBNF grammar into BNF
  186. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start)
  187. if self.options.edit_terminals:
  188. for t in self.terminals:
  189. self.options.edit_terminals(t)
  190. self._terminals_dict = {t.name:t for t in self.terminals}
  191. # If the user asked to invert the priorities, negate them all here.
  192. # This replaces the old 'resolve__antiscore_sum' option.
  193. if self.options.priority == 'invert':
  194. for rule in self.rules:
  195. if rule.options.priority is not None:
  196. rule.options.priority = -rule.options.priority
  197. # Else, if the user asked to disable priorities, strip them from the
  198. # rules. This allows the Earley parsers to skip an extra forest walk
  199. # for improved performance, if you don't need them (or didn't specify any).
  200. elif self.options.priority == None:
  201. for rule in self.rules:
  202. if rule.options.priority is not None:
  203. rule.options.priority = None
  204. # TODO Deprecate lexer_callbacks?
  205. lexer_callbacks = dict(self.options.lexer_callbacks)
  206. if self.options.transformer:
  207. t = self.options.transformer
  208. for term in self.terminals:
  209. if hasattr(t, term.name):
  210. lexer_callbacks[term.name] = getattr(t, term.name)
  211. self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, lexer_callbacks, self.options.g_regex_flags)
  212. if self.options.parser:
  213. self.parser = self._build_parser()
  214. elif lexer:
  215. self.lexer = self._build_lexer()
  216. if cache_fn:
  217. logging.debug('Saving grammar to cache: %s', cache_fn)
  218. with FS.open(cache_fn, 'wb') as f:
  219. self.save(f)
  220. if __init__.__doc__:
  221. __init__.__doc__ += "\nOptions:\n" + LarkOptions.OPTIONS_DOC
  222. __serialize_fields__ = 'parser', 'rules', 'options'
  223. def _build_lexer(self):
  224. return TraditionalLexer(self.lexer_conf.tokens, ignore=self.lexer_conf.ignore, user_callbacks=self.lexer_conf.callbacks, g_regex_flags=self.lexer_conf.g_regex_flags)
  225. def _prepare_callbacks(self):
  226. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  227. self._parse_tree_builder = ParseTreeBuilder(self.rules, self.options.tree_class or Tree, self.options.propagate_positions, self.options.keep_all_tokens, self.options.parser!='lalr' and self.options.ambiguity=='explicit', self.options.maybe_placeholders)
  228. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  229. def _build_parser(self):
  230. self._prepare_callbacks()
  231. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  232. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  233. def save(self, f):
  234. data, m = self.memo_serialize([TerminalDef, Rule])
  235. pickle.dump({'data': data, 'memo': m}, f)
  236. @classmethod
  237. def load(cls, f):
  238. inst = cls.__new__(cls)
  239. return inst._load(f)
  240. def _load(self, f, transformer=None, postlex=None):
  241. if isinstance(f, dict):
  242. d = f
  243. else:
  244. d = pickle.load(f)
  245. memo = d['memo']
  246. data = d['data']
  247. assert memo
  248. memo = SerializeMemoizer.deserialize(memo, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
  249. options = dict(data['options'])
  250. if transformer is not None:
  251. options['transformer'] = transformer
  252. if postlex is not None:
  253. options['postlex'] = postlex
  254. self.options = LarkOptions.deserialize(options, memo)
  255. self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  256. self.source = '<deserialized>'
  257. self._prepare_callbacks()
  258. self.parser = self.parser_class.deserialize(data['parser'], memo, self._callbacks, self.options.postlex)
  259. return self
  260. @classmethod
  261. def _load_from_dict(cls, data, memo, transformer=None, postlex=None):
  262. inst = cls.__new__(cls)
  263. return inst._load({'data': data, 'memo': memo}, transformer, postlex)
  264. @classmethod
  265. def open(cls, grammar_filename, rel_to=None, **options):
  266. """Create an instance of Lark with the grammar given by its filename
  267. If rel_to is provided, the function will find the grammar filename in relation to it.
  268. Example:
  269. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  270. Lark(...)
  271. """
  272. if rel_to:
  273. basepath = os.path.dirname(rel_to)
  274. grammar_filename = os.path.join(basepath, grammar_filename)
  275. with open(grammar_filename, encoding='utf8') as f:
  276. return cls(f, **options)
  277. def __repr__(self):
  278. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  279. def lex(self, text):
  280. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  281. if not hasattr(self, 'lexer'):
  282. self.lexer = self._build_lexer()
  283. stream = self.lexer.lex(text)
  284. if self.options.postlex:
  285. return self.options.postlex.process(stream)
  286. return stream
  287. def get_terminal(self, name):
  288. "Get information about a terminal"
  289. return self._terminals_dict[name]
  290. def parse(self, text, start=None):
  291. """Parse the given text, according to the options provided.
  292. The 'start' parameter is required if Lark was given multiple possible start symbols (using the start option).
  293. Returns a tree, unless specified otherwise.
  294. """
  295. return self.parser.parse(text, start=start)
  296. ###}