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.

249 lines
8.5 KiB

  1. ###{standalone
  2. #
  3. #
  4. # Lark Stand-alone Generator Tool
  5. # ----------------------------------
  6. # Generates a stand-alone LALR(1) parser with a standard lexer
  7. #
  8. # Git: https://github.com/erezsh/lark
  9. # Author: Erez Shinan (erezshin@gmail.com)
  10. #
  11. #
  12. # >>> LICENSE
  13. #
  14. # This tool and its generated code use a separate license from Lark.
  15. #
  16. # It is licensed under GPLv2 or above.
  17. #
  18. # If you wish to purchase a commercial license for this tool and its
  19. # generated code, contact me via email.
  20. #
  21. # This program is free software: you can redistribute it and/or modify
  22. # it under the terms of the GNU General Public License as published by
  23. # the Free Software Foundation, either version 2 of the License, or
  24. # (at your option) any later version.
  25. #
  26. # This program is distributed in the hope that it will be useful,
  27. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. # GNU General Public License for more details.
  30. #
  31. # See <http://www.gnu.org/licenses/>.
  32. #
  33. #
  34. ###}
  35. import codecs
  36. import sys
  37. import os
  38. from pprint import pprint
  39. from os import path
  40. from collections import defaultdict
  41. import lark
  42. from lark import Lark
  43. from lark.parsers.lalr_analysis import Shift, Reduce
  44. from ..grammar import Rule
  45. _dir = path.dirname(__file__)
  46. _larkdir = path.join(_dir, path.pardir)
  47. EXTRACT_STANDALONE_FILES = [
  48. 'tools/standalone.py',
  49. 'exceptions.py',
  50. 'utils.py',
  51. 'tree.py',
  52. 'visitors.py',
  53. 'indenter.py',
  54. 'lexer.py',
  55. 'parse_tree_builder.py',
  56. 'parsers/lalr_parser.py',
  57. ]
  58. def extract_sections(lines):
  59. section = None
  60. text = []
  61. sections = defaultdict(list)
  62. for l in lines:
  63. if l.startswith('###'):
  64. if l[3] == '{':
  65. section = l[4:].strip()
  66. elif l[3] == '}':
  67. sections[section] += text
  68. section = None
  69. text = []
  70. else:
  71. raise ValueError(l)
  72. elif section:
  73. text.append(l)
  74. return {name:''.join(text) for name, text in sections.items()}
  75. def _prepare_mres(mres):
  76. return [(p.pattern,{i: t for i, t in d.items()}) for p,d in mres]
  77. class TraditionalLexerAtoms:
  78. def __init__(self, lexer):
  79. self.mres = _prepare_mres(lexer.mres)
  80. self.newline_types = lexer.newline_types
  81. self.ignore_types = lexer.ignore_types
  82. self.callback = {name:_prepare_mres(c.mres)
  83. for name, c in lexer.callback.items()}
  84. def print_python(self):
  85. print('import re')
  86. print('class LexerRegexps: pass')
  87. print('NEWLINE_TYPES = %s' % self.newline_types)
  88. print('IGNORE_TYPES = %s' % self.ignore_types)
  89. self._print_python('lexer')
  90. def _print_python(self, var_name):
  91. print('MRES = (')
  92. pprint(self.mres)
  93. print(')')
  94. print('LEXER_CALLBACK = (')
  95. pprint(self.callback)
  96. print(')')
  97. print('lexer_regexps = LexerRegexps()')
  98. print('lexer_regexps.mres = [(re.compile(p), d) for p, d in MRES]')
  99. print('lexer_regexps.callback = {n: UnlessCallback([(re.compile(p), d) for p, d in mres])')
  100. print(' for n, mres in LEXER_CALLBACK.items()}')
  101. print('%s = (lexer_regexps)' % var_name)
  102. class ContextualLexerAtoms:
  103. def __init__(self, lexer):
  104. self.lexer_atoms = {state: TraditionalLexerAtoms(lexer) for state, lexer in lexer.lexers.items()}
  105. self.root_lexer_atoms = TraditionalLexerAtoms(lexer.root_lexer)
  106. def print_python(self):
  107. print('import re')
  108. print('class LexerRegexps: pass')
  109. print('NEWLINE_TYPES = %s' % self.root_lexer_atoms.newline_types)
  110. print('IGNORE_TYPES = %s' % self.root_lexer_atoms.ignore_types)
  111. print('LEXERS = {}')
  112. for state, lexer_atoms in self.lexer_atoms.items():
  113. lexer_atoms._print_python('LEXERS[%d]' % state)
  114. print('class ContextualLexer:')
  115. print(' def __init__(self):')
  116. print(' self.lexers = LEXERS')
  117. print(' self.set_parser_state(None)')
  118. print(' def set_parser_state(self, state):')
  119. print(' self.parser_state = state')
  120. print(' def lex(self, stream):')
  121. print(' newline_types = NEWLINE_TYPES')
  122. print(' ignore_types = IGNORE_TYPES')
  123. print(' lexers = LEXERS')
  124. print(' l = _Lex(lexers[self.parser_state], self.parser_state)')
  125. print(' for x in l.lex(stream, newline_types, ignore_types):')
  126. print(' yield x')
  127. print(' l.lexer = lexers[self.parser_state]')
  128. print(' l.state = self.parser_state')
  129. print('CON_LEXER = ContextualLexer()')
  130. print('def lex(stream):')
  131. print(' return CON_LEXER.lex(stream)')
  132. class GetRule:
  133. def __init__(self, rule_id):
  134. self.rule_id = rule_id
  135. def __repr__(self):
  136. return 'RULES[%d]' % self.rule_id
  137. rule_ids = {}
  138. token_types = {}
  139. def _get_token_type(token_type):
  140. if token_type not in token_types:
  141. token_types[token_type] = len(token_types)
  142. return token_types[token_type]
  143. class ParserAtoms:
  144. def __init__(self, parser):
  145. self.parse_table = parser._parse_table
  146. def print_python(self):
  147. print('class ParseTable: pass')
  148. print('parse_table = ParseTable()')
  149. print('STATES = {')
  150. for state, actions in self.parse_table.states.items():
  151. print(' %r: %r,' % (state, {_get_token_type(token): ((1, rule_ids[arg]) if action is Reduce else (0, arg))
  152. for token, (action, arg) in actions.items()}))
  153. print('}')
  154. print('TOKEN_TYPES = (')
  155. pprint({v:k for k, v in token_types.items()})
  156. print(')')
  157. print('parse_table.states = {s: {TOKEN_TYPES[t]: (a, RULES[x] if a is Reduce else x) for t, (a, x) in acts.items()}')
  158. print(' for s, acts in STATES.items()}')
  159. print('parse_table.start_state = %s' % self.parse_table.start_state)
  160. print('parse_table.end_state = %s' % self.parse_table.end_state)
  161. print('class Lark_StandAlone:')
  162. print(' def __init__(self, transformer=None, postlex=None):')
  163. print(' callback = parse_tree_builder.create_callback(transformer=transformer)')
  164. print(' callbacks = {rule: getattr(callback, rule.alias or rule.origin, None) for rule in RULES.values()}')
  165. print(' self.parser = _Parser(parse_table, callbacks)')
  166. print(' self.postlex = postlex')
  167. print(' def parse(self, stream):')
  168. print(' tokens = lex(stream)')
  169. print(' sps = CON_LEXER.set_parser_state')
  170. print(' if self.postlex: tokens = self.postlex.process(tokens)')
  171. print(' return self.parser.parse(tokens, sps)')
  172. class TreeBuilderAtoms:
  173. def __init__(self, lark):
  174. self.rules = lark.rules
  175. self.ptb = lark._parse_tree_builder
  176. def print_python(self):
  177. # print('class InlineTransformer: pass')
  178. print('RULES = {')
  179. for i, r in enumerate(self.rules):
  180. rule_ids[r] = i
  181. print(' %d: Rule(%r, [%s], %r, %r),' % (i, r.origin, ', '.join(s.fullrepr for s in r.expansion), self.ptb.user_aliases[r], r.options ))
  182. print('}')
  183. print('parse_tree_builder = ParseTreeBuilder(RULES.values(), Tree)')
  184. def main(fobj, start):
  185. lark_inst = Lark(fobj, parser="lalr", lexer="contextual", start=start)
  186. lexer_atoms = ContextualLexerAtoms(lark_inst.parser.lexer)
  187. parser_atoms = ParserAtoms(lark_inst.parser.parser)
  188. tree_builder_atoms = TreeBuilderAtoms(lark_inst)
  189. print('# The file was automatically generated by Lark v%s' % lark.__version__)
  190. for pyfile in EXTRACT_STANDALONE_FILES:
  191. with open(os.path.join(_larkdir, pyfile)) as f:
  192. print (extract_sections(f)['standalone'])
  193. with open(os.path.join(_larkdir, 'grammar.py')) as grammar_py:
  194. print(grammar_py.read())
  195. print('Shift = 0')
  196. print('Reduce = 1')
  197. lexer_atoms.print_python()
  198. tree_builder_atoms.print_python()
  199. parser_atoms.print_python()
  200. if __name__ == '__main__':
  201. if len(sys.argv) < 2:
  202. print("Lark Stand-alone Generator Tool")
  203. print("Usage: python -m lark.tools.standalone <grammar-file> [<start>]")
  204. sys.exit(1)
  205. if len(sys.argv) == 3:
  206. fn, start = sys.argv[1:]
  207. elif len(sys.argv) == 2:
  208. fn, start = sys.argv[1], 'start'
  209. else:
  210. assert False, sys.argv
  211. with codecs.open(fn, encoding='utf8') as f:
  212. main(f, start)