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.

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