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.

165 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. import lark
  37. from lark import Lark
  38. from lark.parsers.lalr_analysis import Reduce
  39. from lark.grammar import RuleOptions, Rule
  40. from lark.lexer import TerminalDef
  41. _dir = path.dirname(__file__)
  42. _larkdir = path.join(_dir, path.pardir)
  43. EXTRACT_STANDALONE_FILES = [
  44. 'tools/standalone.py',
  45. 'exceptions.py',
  46. 'utils.py',
  47. 'tree.py',
  48. 'visitors.py',
  49. 'indenter.py',
  50. 'grammar.py',
  51. 'lexer.py',
  52. 'common.py',
  53. 'parse_tree_builder.py',
  54. 'parsers/lalr_parser.py',
  55. 'parsers/lalr_analysis.py',
  56. 'parser_frontends.py',
  57. 'lark.py',
  58. ]
  59. def extract_sections(lines):
  60. section = None
  61. text = []
  62. sections = defaultdict(list)
  63. for l in lines:
  64. if l.startswith('###'):
  65. if l[3] == '{':
  66. section = l[4:].strip()
  67. elif l[3] == '}':
  68. sections[section] += text
  69. section = None
  70. text = []
  71. else:
  72. raise ValueError(l)
  73. elif section:
  74. text.append(l)
  75. return {name:''.join(text) for name, text in sections.items()}
  76. def strip_docstrings(line_gen):
  77. """ Strip comments and docstrings from a file.
  78. Based on code from: https://stackoverflow.com/questions/1769332/script-to-remove-python-comments-docstrings
  79. """
  80. res = []
  81. prev_toktype = token.INDENT
  82. last_lineno = -1
  83. last_col = 0
  84. tokgen = tokenize.generate_tokens(line_gen)
  85. for toktype, ttext, (slineno, scol), (elineno, ecol), ltext in tokgen:
  86. if slineno > last_lineno:
  87. last_col = 0
  88. if scol > last_col:
  89. res.append(" " * (scol - last_col))
  90. if toktype == token.STRING and prev_toktype == token.INDENT:
  91. # Docstring
  92. res.append("#--")
  93. elif toktype == tokenize.COMMENT:
  94. # Comment
  95. res.append("##\n")
  96. else:
  97. res.append(ttext)
  98. prev_toktype = toktype
  99. last_col = ecol
  100. last_lineno = elineno
  101. return ''.join(res)
  102. def main(fobj, start):
  103. lark_inst = Lark(fobj, parser="lalr", lexer="contextual", start=start)
  104. print('# The file was automatically generated by Lark v%s' % lark.__version__)
  105. print('__version__ = "%s"' % lark.__version__)
  106. print()
  107. for i, pyfile in enumerate(EXTRACT_STANDALONE_FILES):
  108. with open(os.path.join(_larkdir, pyfile)) as f:
  109. code = extract_sections(f)['standalone']
  110. if i: # if not this file
  111. code = strip_docstrings(iter(code.splitlines(True)).__next__)
  112. print(code)
  113. data, m = lark_inst.memo_serialize([TerminalDef, Rule])
  114. print( 'DATA = (' )
  115. # pprint(data, width=160)
  116. print(data)
  117. print(')')
  118. print( 'MEMO = (')
  119. print(m)
  120. print(')')
  121. print('Shift = 0')
  122. print('Reduce = 1')
  123. print("def Lark_StandAlone(transformer=None, postlex=None):")
  124. print(" return Lark._load_from_dict(DATA, MEMO, transformer=transformer, postlex=postlex)")
  125. if __name__ == '__main__':
  126. if len(sys.argv) < 2:
  127. print("Lark Stand-alone Generator Tool")
  128. print("Usage: python -m lark.tools.standalone <grammar-file> [<start>]")
  129. sys.exit(1)
  130. if len(sys.argv) == 3:
  131. fn, start = sys.argv[1:]
  132. elif len(sys.argv) == 2:
  133. fn, start = sys.argv[1], 'start'
  134. else:
  135. assert False, sys.argv
  136. with codecs.open(fn, encoding='utf8') as f:
  137. main(f, start)