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.

139 lines
4.7 KiB

  1. from __future__ import absolute_import
  2. import os
  3. from .utils import STRING_TYPE, inline_args
  4. from .load_grammar import load_grammar
  5. from .tree import Tree, Transformer
  6. from .common import GrammarError
  7. from .lexer import Lexer
  8. from .parse_tree_builder import ParseTreeBuilder
  9. from .parser_frontends import ENGINE_DICT
  10. class LarkOptions(object):
  11. """Specifies the options for Lark
  12. """
  13. OPTIONS_DOC = """
  14. parser - Which parser engine to use ("earley" or "lalr". Default: "earley")
  15. Note: Both will use Lark's lexer.
  16. transformer - Applies the transformer to every parse tree
  17. debug - Affects verbosity (default: False)
  18. only_lex - Don't build a parser. Useful for debugging (default: False)
  19. keep_all_tokens - Don't automagically remove "punctuation" tokens (default: True)
  20. cache_grammar - Cache the Lark grammar (Default: False)
  21. postlex - Lexer post-processing (Default: None)
  22. start - The start symbol (Default: start)
  23. """
  24. __doc__ += OPTIONS_DOC
  25. def __init__(self, options_dict):
  26. o = dict(options_dict)
  27. self.debug = bool(o.pop('debug', False))
  28. self.only_lex = bool(o.pop('only_lex', False))
  29. self.keep_all_tokens = bool(o.pop('keep_all_tokens', False))
  30. self.tree_class = o.pop('tree_class', Tree)
  31. self.cache_grammar = o.pop('cache_grammar', False)
  32. self.postlex = o.pop('postlex', None)
  33. self.parser = o.pop('parser', 'earley')
  34. self.transformer = o.pop('transformer', None)
  35. self.start = o.pop('start', 'start')
  36. assert self.parser in ENGINE_DICT
  37. if self.parser == 'earley' and self.transformer:
  38. raise ValueError('Cannot specify an auto-transformer when using the Earley algorithm. Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. lalr)')
  39. if self.keep_all_tokens:
  40. raise NotImplementedError("Not implemented yet!")
  41. if o:
  42. raise ValueError("Unknown options: %s" % o.keys())
  43. class Lark:
  44. def __init__(self, grammar, **options):
  45. """
  46. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  47. options : a dictionary controlling various aspects of Lark.
  48. """
  49. self.options = LarkOptions(options)
  50. # Some, but not all file-like objects have a 'name' attribute
  51. try:
  52. source = grammar.name
  53. except AttributeError:
  54. source = '<string>'
  55. cache_file = "larkcache_%s" % str(hash(grammar)%(2**32))
  56. else:
  57. cache_file = "larkcache_%s" % os.path.basename(source)
  58. # Drain file-like objects to get their contents
  59. try:
  60. read = grammar.read
  61. except AttributeError:
  62. pass
  63. else:
  64. grammar = read()
  65. assert isinstance(grammar, STRING_TYPE)
  66. if self.options.cache_grammar:
  67. raise NotImplementedError("Not available yet")
  68. self.tokens, self.rules = load_grammar(grammar)
  69. self.lexer = self._build_lexer()
  70. if not self.options.only_lex:
  71. self.parser_engine = ENGINE_DICT[self.options.parser]()
  72. self.parse_tree_builder = ParseTreeBuilder(self.options.tree_class)
  73. self.parser = self._build_parser()
  74. def _create_unless_callback(self, strs):
  75. def f(t):
  76. if t in strs:
  77. t.type = strs[t]
  78. return t
  79. return f
  80. def _build_lexer(self):
  81. ignore_tokens = []
  82. tokens = []
  83. callbacks = {}
  84. for name, value, flags in self.tokens:
  85. for flag in flags:
  86. if flag == 'ignore':
  87. ignore_tokens.append(name)
  88. elif flag == 'newline':
  89. pass # TODO
  90. elif isinstance(flag, tuple) and flag[0] == 'unless':
  91. _, strs = flag
  92. callbacks[name] = self._create_unless_callback(strs)
  93. else:
  94. raise GrammarError("No such flag: %s" % flag)
  95. tokens.append((name, value))
  96. return Lexer(tokens, callbacks, ignore=ignore_tokens)
  97. def _build_parser(self):
  98. rules, callback = self.parse_tree_builder.create_tree_builder(self.rules, self.options.transformer)
  99. return self.parser_engine.build_parser(rules, callback, self.options.start)
  100. __init__.__doc__ += "\nOPTIONS:" + LarkOptions.OPTIONS_DOC
  101. def lex(self, text):
  102. stream = self.lexer.lex(text)
  103. if self.options.postlex:
  104. return self.options.postlex.process(stream)
  105. else:
  106. return stream
  107. def parse(self, text):
  108. assert not self.options.only_lex
  109. l = list(self.lex(text))
  110. return self.parser.parse(l)