standalone.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. ###{standalone
  2. #
  3. #
  4. # Lark Stand-alone Generator Tool
  5. # ----------------------------------
  6. # Generates a stand-alone LALR(1) parser
  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. from copy import deepcopy
  27. from abc import ABC, abstractmethod
  28. from types import ModuleType
  29. from typing import (
  30. TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
  31. Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
  32. Pattern as REPattern, ClassVar, Set, Mapping
  33. )
  34. ###}
  35. import sys
  36. import token, tokenize
  37. import os
  38. from os import path
  39. from collections import defaultdict
  40. from functools import partial
  41. from argparse import ArgumentParser
  42. import lark
  43. from lark.tools import lalr_argparser, build_lalr, make_warnings_comments
  44. from lark.grammar import Rule
  45. from lark.lexer import TerminalDef
  46. _dir = path.dirname(__file__)
  47. _larkdir = path.join(_dir, path.pardir)
  48. EXTRACT_STANDALONE_FILES = [
  49. 'tools/standalone.py',
  50. 'exceptions.py',
  51. 'utils.py',
  52. 'tree.py',
  53. 'visitors.py',
  54. 'grammar.py',
  55. 'lexer.py',
  56. 'common.py',
  57. 'parse_tree_builder.py',
  58. 'parsers/lalr_analysis.py',
  59. 'parsers/lalr_parser_state.py',
  60. 'parsers/lalr_parser.py',
  61. 'parsers/lalr_interactive_parser.py',
  62. 'parser_frontends.py',
  63. 'lark.py',
  64. 'indenter.py',
  65. ]
  66. def extract_sections(lines):
  67. section = None
  68. text = []
  69. sections = defaultdict(list)
  70. for line in lines:
  71. if line.startswith('###'):
  72. if line[3] == '{':
  73. section = line[4:].strip()
  74. elif line[3] == '}':
  75. sections[section] += text
  76. section = None
  77. text = []
  78. else:
  79. raise ValueError(line)
  80. elif section:
  81. text.append(line)
  82. return {name: ''.join(text) for name, text in sections.items()}
  83. def strip_docstrings(line_gen):
  84. """ Strip comments and docstrings from a file.
  85. Based on code from: https://stackoverflow.com/questions/1769332/script-to-remove-python-comments-docstrings
  86. """
  87. res = []
  88. prev_toktype = token.INDENT
  89. last_lineno = -1
  90. last_col = 0
  91. tokgen = tokenize.generate_tokens(line_gen)
  92. for toktype, ttext, (slineno, scol), (elineno, ecol), ltext in tokgen:
  93. if slineno > last_lineno:
  94. last_col = 0
  95. if scol > last_col:
  96. res.append(" " * (scol - last_col))
  97. if toktype == token.STRING and prev_toktype == token.INDENT:
  98. # Docstring
  99. res.append("#--")
  100. elif toktype == tokenize.COMMENT:
  101. # Comment
  102. res.append("##\n")
  103. else:
  104. res.append(ttext)
  105. prev_toktype = toktype
  106. last_col = ecol
  107. last_lineno = elineno
  108. return ''.join(res)
  109. def gen_standalone(lark_inst, output=None, out=sys.stdout, compress=False):
  110. if output is None:
  111. output = partial(print, file=out)
  112. import pickle, zlib, base64
  113. def compressed_output(obj):
  114. s = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
  115. c = zlib.compress(s)
  116. output(repr(base64.b64encode(c)))
  117. def output_decompress(name):
  118. output('%(name)s = pickle.loads(zlib.decompress(base64.b64decode(%(name)s)))' % locals())
  119. output('# The file was automatically generated by Lark v%s' % lark.__version__)
  120. output('__version__ = "%s"' % lark.__version__)
  121. output()
  122. for i, pyfile in enumerate(EXTRACT_STANDALONE_FILES):
  123. with open(os.path.join(_larkdir, pyfile)) as f:
  124. code = extract_sections(f)['standalone']
  125. if i: # if not this file
  126. code = strip_docstrings(partial(next, iter(code.splitlines(True))))
  127. output(code)
  128. data, m = lark_inst.memo_serialize([TerminalDef, Rule])
  129. output('import pickle, zlib, base64')
  130. if compress:
  131. output('DATA = (')
  132. compressed_output(data)
  133. output(')')
  134. output_decompress('DATA')
  135. output('MEMO = (')
  136. compressed_output(m)
  137. output(')')
  138. output_decompress('MEMO')
  139. else:
  140. output('DATA = (')
  141. output(data)
  142. output(')')
  143. output('MEMO = (')
  144. output(m)
  145. output(')')
  146. output('Shift = 0')
  147. output('Reduce = 1')
  148. output("def Lark_StandAlone(**kwargs):")
  149. output(" return Lark._load_from_dict(DATA, MEMO, **kwargs)")
  150. def main():
  151. make_warnings_comments()
  152. parser = ArgumentParser(prog="prog='python -m lark.tools.standalone'", description="Lark Stand-alone Generator Tool",
  153. parents=[lalr_argparser], epilog='Look at the Lark documentation for more info on the options')
  154. parser.add_argument('-c', '--compress', action='store_true', default=0, help="Enable compression")
  155. if len(sys.argv) == 1:
  156. parser.print_help(sys.stderr)
  157. sys.exit(1)
  158. ns = parser.parse_args()
  159. lark_inst, out = build_lalr(ns)
  160. gen_standalone(lark_inst, out=out, compress=ns.compress)
  161. ns.out.close()
  162. ns.grammar_file.close()
  163. if __name__ == '__main__':
  164. main()