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.

168 lines
4.3 KiB

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