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.

188 lines
5.2 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. from io import open
  28. from abc import ABC, abstractmethod
  29. ###}
  30. import sys
  31. import token, tokenize
  32. import os
  33. from os import path
  34. from collections import defaultdict
  35. from functools import partial
  36. from argparse import ArgumentParser, SUPPRESS
  37. import lark
  38. from lark import Lark
  39. from lark.tools import lalr_argparser, build_lalr, make_warnings_comments
  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. '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. 'indenter.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 gen_standalone(lark_inst, output=None, out=sys.stdout, compress=False):
  104. if output is None:
  105. output = partial(print, file=out)
  106. import pickle, zlib, base64
  107. def compressed_output(obj):
  108. s = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
  109. c = zlib.compress(s)
  110. output(repr(base64.b64encode(c)))
  111. def output_decompress(name):
  112. output('%(name)s = pickle.loads(zlib.decompress(base64.b64decode(%(name)s)))' % locals())
  113. output('# The file was automatically generated by Lark v%s' % lark.__version__)
  114. output('__version__ = "%s"' % lark.__version__)
  115. output()
  116. for i, pyfile in enumerate(EXTRACT_STANDALONE_FILES):
  117. with open(os.path.join(_larkdir, pyfile)) as f:
  118. code = extract_sections(f)['standalone']
  119. if i: # if not this file
  120. code = strip_docstrings(partial(next, iter(code.splitlines(True))))
  121. output(code)
  122. data, m = lark_inst.memo_serialize([TerminalDef, Rule])
  123. output('import pickle, zlib, base64')
  124. if compress:
  125. output('DATA = (')
  126. compressed_output(data)
  127. output(')')
  128. output_decompress('DATA')
  129. output('MEMO = (')
  130. compressed_output(m)
  131. output(')')
  132. output_decompress('MEMO')
  133. else:
  134. output('DATA = (')
  135. output(data)
  136. output(')')
  137. output('MEMO = (')
  138. output(m)
  139. output(')')
  140. output('Shift = 0')
  141. output('Reduce = 1')
  142. output("def Lark_StandAlone(**kwargs):")
  143. output(" return Lark._load_from_dict(DATA, MEMO, **kwargs)")
  144. def main():
  145. make_warnings_comments()
  146. parser = ArgumentParser(prog="prog='python -m lark.tools.standalone'", description="Lark Stand-alone Generator Tool",
  147. parents=[lalr_argparser], epilog='Look at the Lark documentation for more info on the options')
  148. parser.add_argument("old_start", nargs='?', help=SUPPRESS)
  149. parser.add_argument('-c', '--compress', action='store_true', default=0, help="Enable compression")
  150. if len(sys.argv)==1:
  151. parser.print_help(sys.stderr)
  152. sys.exit(1)
  153. ns = parser.parse_args()
  154. lark_inst, out = build_lalr(ns)
  155. gen_standalone(lark_inst, out=out, compress=ns.compress)
  156. if __name__ == '__main__':
  157. main()