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.

268 lines
12 KiB

  1. from __future__ import absolute_import
  2. import os
  3. import time
  4. from collections import defaultdict
  5. from io import open
  6. from .utils import STRING_TYPE
  7. from .load_grammar import load_grammar
  8. from .tree import Tree
  9. from .common import LexerConf, ParserConf
  10. from .lexer import Lexer, TraditionalLexer
  11. from .parse_tree_builder import ParseTreeBuilder
  12. from .parser_frontends import get_frontend
  13. class LarkOptions(object):
  14. """Specifies the options for Lark
  15. """
  16. OPTIONS_DOC = """
  17. parser - Decides which parser engine to use, "earley" or "lalr". (Default: "earley")
  18. Note: "lalr" requires a lexer
  19. lexer - Decides whether or not to use a lexer stage
  20. "standard": Use a standard lexer
  21. "contextual": Stronger lexer (only works with parser="lalr")
  22. "dynamic": Flexible and powerful (only with parser="earley")
  23. "dynamic_complete": Same as dynamic, but tries *every* variation
  24. of tokenizing possible. (only with parser="earley")
  25. "auto" (default): Choose for me based on grammar and parser
  26. ambiguity - Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
  27. "resolve": The parser will automatically choose the simplest derivation
  28. (it chooses consistently: greedy for tokens, non-greedy for rules)
  29. "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
  30. transformer - Applies the transformer to every parse tree
  31. debug - Affects verbosity (default: False)
  32. keep_all_tokens - Don't automagically remove "punctuation" tokens (default: False)
  33. cache_grammar - Cache the Lark grammar (Default: False)
  34. postlex - Lexer post-processing (Default: None) Only works with the standard and contextual lexers.
  35. start - The start symbol (Default: start)
  36. <<<<<<< HEAD
  37. profile - Measure run-time usage in Lark. Read results from the profiler proprety (Default: False)
  38. priority - How priorities should be evaluated - auto, none, normal, invert (Default: auto)
  39. =======
  40. profile - Measure run-time usage in Lark. Read results from the profiler property (Default: False)
  41. >>>>>>> master
  42. propagate_positions - Propagates [line, column, end_line, end_column] attributes into all tree branches.
  43. lexer_callbacks - Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
  44. maybe_placeholders - Experimental feature. Instead of omitting optional rules (i.e. rule?), replace them with None
  45. """
  46. if __doc__:
  47. __doc__ += OPTIONS_DOC
  48. def __init__(self, options_dict):
  49. o = dict(options_dict)
  50. self.debug = bool(o.pop('debug', False))
  51. self.keep_all_tokens = bool(o.pop('keep_all_tokens', False))
  52. self.tree_class = o.pop('tree_class', Tree)
  53. self.cache_grammar = o.pop('cache_grammar', False)
  54. self.postlex = o.pop('postlex', None)
  55. self.parser = o.pop('parser', 'earley')
  56. self.lexer = o.pop('lexer', 'auto')
  57. self.transformer = o.pop('transformer', None)
  58. self.start = o.pop('start', 'start')
  59. self.profile = o.pop('profile', False)
  60. self.priority = o.pop('priority', 'auto')
  61. self.ambiguity = o.pop('ambiguity', 'auto')
  62. self.propagate_positions = o.pop('propagate_positions', False)
  63. self.lexer_callbacks = o.pop('lexer_callbacks', {})
  64. self.maybe_placeholders = o.pop('maybe_placeholders', False)
  65. assert self.parser in ('earley', 'lalr', 'cyk', None)
  66. if self.ambiguity == 'explicit' and self.transformer:
  67. raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm for explicit ambiguity.'
  68. 'Please use your transformer on the resulting Forest, or use a different algorithm (i.e. LALR)')
  69. if o:
  70. raise ValueError("Unknown options: %s" % o.keys())
  71. class Profiler:
  72. def __init__(self):
  73. self.total_time = defaultdict(float)
  74. self.cur_section = '__init__'
  75. self.last_enter_time = time.time()
  76. def enter_section(self, name):
  77. cur_time = time.time()
  78. self.total_time[self.cur_section] += cur_time - self.last_enter_time
  79. self.last_enter_time = cur_time
  80. self.cur_section = name
  81. def make_wrapper(self, name, f):
  82. def wrapper(*args, **kwargs):
  83. last_section = self.cur_section
  84. self.enter_section(name)
  85. try:
  86. return f(*args, **kwargs)
  87. finally:
  88. self.enter_section(last_section)
  89. return wrapper
  90. class Lark:
  91. def __init__(self, grammar, **options):
  92. """
  93. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  94. options : a dictionary controlling various aspects of Lark.
  95. """
  96. self.options = LarkOptions(options)
  97. # Some, but not all file-like objects have a 'name' attribute
  98. try:
  99. self.source = grammar.name
  100. except AttributeError:
  101. self.source = '<string>'
  102. cache_file = "larkcache_%s" % str(hash(grammar)%(2**32))
  103. else:
  104. cache_file = "larkcache_%s" % os.path.basename(self.source)
  105. # Drain file-like objects to get their contents
  106. try:
  107. read = grammar.read
  108. except AttributeError:
  109. pass
  110. else:
  111. grammar = read()
  112. assert isinstance(grammar, STRING_TYPE)
  113. if self.options.cache_grammar:
  114. raise NotImplementedError("Not available yet")
  115. assert not self.options.profile, "Feature temporarily disabled"
  116. self.profiler = Profiler() if self.options.profile else None
  117. if self.options.lexer == 'auto':
  118. if self.options.parser == 'lalr':
  119. self.options.lexer = 'contextual'
  120. elif self.options.parser == 'earley':
  121. self.options.lexer = 'dynamic'
  122. elif self.options.parser == 'cyk':
  123. self.options.lexer = 'standard'
  124. else:
  125. assert False, self.options.parser
  126. lexer = self.options.lexer
  127. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  128. if self.options.ambiguity == 'auto':
  129. if self.options.parser == 'earley':
  130. self.options.ambiguity = 'resolve'
  131. else:
  132. disambig_parsers = ['earley', 'cyk']
  133. assert self.options.parser in disambig_parsers, (
  134. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  135. assert self.options.priority in ('auto', 'none', 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority)
  136. if self.options.priority == 'auto':
  137. if self.options.parser in ('earley', 'cyk', ):
  138. self.options.priority = 'normal'
  139. elif self.options.parser in ('lalr', ):
  140. self.options.priority = 'none'
  141. if self.options.priority in ('invert', 'normal'):
  142. assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time"
  143. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  144. assert self.options.ambiguity in ('resolve', 'explicit', 'auto', )
  145. # Parse the grammar file and compose the grammars (TODO)
  146. self.grammar = load_grammar(grammar, self.source)
  147. # Compile the EBNF grammar into BNF
  148. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile()
  149. # If the user asked to invert the priorities, negate them all here.
  150. # This replaces the old 'resolve__antiscore_sum' option.
  151. if self.options.priority == 'invert':
  152. for rule in self.rules:
  153. if rule.options and rule.options.priority is not None:
  154. rule.options.priority = -rule.options.priority
  155. # Else, if the user asked to disable priorities, strip them from the
  156. # rules. This allows the Earley parsers to skip an extra forest walk
  157. # for improved performance, if you don't need them (or didn't specify any).
  158. elif self.options.priority == 'none':
  159. for rule in self.rules:
  160. if rule.options and rule.options.priority is not None:
  161. rule.options.priority = None
  162. self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, self.options.lexer_callbacks)
  163. if self.options.parser:
  164. self.parser = self._build_parser()
  165. elif lexer:
  166. self.lexer = self._build_lexer()
  167. if self.profiler: self.profiler.enter_section('outside_lark')
  168. if __init__.__doc__:
  169. __init__.__doc__ += "\nOPTIONS:" + LarkOptions.OPTIONS_DOC
  170. def _build_lexer(self):
  171. return TraditionalLexer(self.lexer_conf.tokens, ignore=self.lexer_conf.ignore, user_callbacks=self.lexer_conf.callbacks)
  172. def _build_parser(self):
  173. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  174. self._parse_tree_builder = ParseTreeBuilder(self.rules, self.options.tree_class, self.options.propagate_positions, self.options.keep_all_tokens, self.options.parser!='lalr' and self.options.ambiguity=='explicit', self.options.maybe_placeholders)
  175. callback = self._parse_tree_builder.create_callback(self.options.transformer)
  176. if self.profiler:
  177. for f in dir(callback):
  178. if not (f.startswith('__') and f.endswith('__')):
  179. setattr(callback, f, self.profiler.make_wrapper('transformer', getattr(callback, f)))
  180. parser_conf = ParserConf(self.rules, callback, self.options.start)
  181. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  182. @classmethod
  183. def open(cls, grammar_filename, rel_to=None, **options):
  184. """Create an instance of Lark with the grammar given by its filename
  185. If rel_to is provided, the function will find the grammar filename in relation to it.
  186. Example:
  187. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  188. Lark(...)
  189. """
  190. if rel_to:
  191. basepath = os.path.dirname(rel_to)
  192. grammar_filename = os.path.join(basepath, grammar_filename)
  193. with open(grammar_filename, encoding='utf8') as f:
  194. return cls(f, **options)
  195. def __repr__(self):
  196. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  197. def lex(self, text):
  198. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  199. if not hasattr(self, 'lexer'):
  200. self.lexer = self._build_lexer()
  201. stream = self.lexer.lex(text)
  202. if self.options.postlex:
  203. return self.options.postlex.process(stream)
  204. return stream
  205. def parse(self, text):
  206. "Parse the given text, according to the options provided. Returns a tree, unless specified otherwise."
  207. return self.parser.parse(text)
  208. # if self.profiler:
  209. # self.profiler.enter_section('lex')
  210. # l = list(self.lex(text))
  211. # self.profiler.enter_section('parse')
  212. # try:
  213. # return self.parser.parse(l)
  214. # finally:
  215. # self.profiler.enter_section('outside_lark')
  216. # else:
  217. # l = list(self.lex(text))
  218. # return self.parser.parse(l)