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.

166 lines
4.3 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. # and are subject to the terms of the Mozilla Public License, v. 2.0.
  16. # If a copy of the MPL was not distributed with this
  17. # file, You can obtain one at https://mozilla.org/MPL/2.0/.
  18. #
  19. # If you wish to purchase a commercial license for this tool and its
  20. # generated code, you may contact me via email or otherwise.
  21. #
  22. # If MPL2 is incompatible with your free or open-source project,
  23. # contact me and we'll work it out.
  24. #
  25. #
  26. import os
  27. from io import open
  28. ###}
  29. import codecs
  30. import sys
  31. import token, tokenize
  32. import os
  33. from pprint import pprint
  34. from os import path
  35. from collections import defaultdict
  36. from functools import partial
  37. import lark
  38. from lark import Lark
  39. from lark.parsers.lalr_analysis import Reduce
  40. from lark.grammar import RuleOptions, Rule
  41. from lark.lexer import TerminalDef
  42. _dir = path.dirname(__file__)
  43. _larkdir = path.join(_dir, path.pardir)
  44. EXTRACT_STANDALONE_FILES = [
  45. 'tools/standalone.py',
  46. 'exceptions.py',
  47. 'utils.py',
  48. 'tree.py',
  49. 'visitors.py',
  50. 'indenter.py',
  51. 'grammar.py',
  52. 'lexer.py',
  53. 'common.py',
  54. 'parse_tree_builder.py',
  55. 'parsers/lalr_parser.py',
  56. 'parsers/lalr_analysis.py',
  57. 'parser_frontends.py',
  58. 'lark.py',
  59. ]
  60. def extract_sections(lines):
  61. section = None
  62. text = []
  63. sections = defaultdict(list)
  64. for l in lines:
  65. if l.startswith('###'):
  66. if l[3] == '{':
  67. section = l[4:].strip()
  68. elif l[3] == '}':
  69. sections[section] += text
  70. section = None
  71. text = []
  72. else:
  73. raise ValueError(l)
  74. elif section:
  75. text.append(l)
  76. return {name:''.join(text) for name, text in sections.items()}
  77. def strip_docstrings(line_gen):
  78. """ Strip comments and docstrings from a file.
  79. Based on code from: https://stackoverflow.com/questions/1769332/script-to-remove-python-comments-docstrings
  80. """
  81. res = []
  82. prev_toktype = token.INDENT
  83. last_lineno = -1
  84. last_col = 0
  85. tokgen = tokenize.generate_tokens(line_gen)
  86. for toktype, ttext, (slineno, scol), (elineno, ecol), ltext in tokgen:
  87. if slineno > last_lineno:
  88. last_col = 0
  89. if scol > last_col:
  90. res.append(" " * (scol - last_col))
  91. if toktype == token.STRING and prev_toktype == token.INDENT:
  92. # Docstring
  93. res.append("#--")
  94. elif toktype == tokenize.COMMENT:
  95. # Comment
  96. res.append("##\n")
  97. else:
  98. res.append(ttext)
  99. prev_toktype = toktype
  100. last_col = ecol
  101. last_lineno = elineno
  102. return ''.join(res)
  103. def main(fobj, start):
  104. lark_inst = Lark(fobj, parser="lalr", lexer="contextual", start=start)
  105. print('# The file was automatically generated by Lark v%s' % lark.__version__)
  106. print('__version__ = "%s"' % lark.__version__)
  107. print()
  108. for i, pyfile in enumerate(EXTRACT_STANDALONE_FILES):
  109. with open(os.path.join(_larkdir, pyfile)) as f:
  110. code = extract_sections(f)['standalone']
  111. if i: # if not this file
  112. code = strip_docstrings(partial(next, iter(code.splitlines(True))))
  113. print(code)
  114. data, m = lark_inst.memo_serialize([TerminalDef, Rule])
  115. print( 'DATA = (' )
  116. # pprint(data, width=160)
  117. print(data)
  118. print(')')
  119. print( 'MEMO = (')
  120. print(m)
  121. print(')')
  122. print('Shift = 0')
  123. print('Reduce = 1')
  124. print("def Lark_StandAlone(transformer=None, postlex=None):")
  125. print(" return Lark._load_from_dict(DATA, MEMO, transformer=transformer, postlex=postlex)")
  126. if __name__ == '__main__':
  127. if len(sys.argv) < 2:
  128. print("Lark Stand-alone Generator Tool")
  129. print("Usage: python -m lark.tools.standalone <grammar-file> [<start>]")
  130. sys.exit(1)
  131. if len(sys.argv) == 3:
  132. fn, start = sys.argv[1:]
  133. elif len(sys.argv) == 2:
  134. fn, start = sys.argv[1], 'start'
  135. else:
  136. assert False, sys.argv
  137. with codecs.open(fn, encoding='utf8') as f:
  138. main(f, start)