This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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