import textwrap import os import json import importlib from lark import Lark from agast import * from aggen import * p = Lark(open("grammar.lark").read(), start="program", parser="lalr") if __name__ == "__main__": with open("test/arith.ag") as f: data = f.read() cst = p.parse(data) trans = Parser() ast = trans.transform(cst) res = gen(ast) print("Grammar:") print(res.parser_data) if not os.path.exists("gen"): os.makedirs("gen") with open("agruntime.tmpl.py", "r") as f: fmt_str = f.read() with open("gen/arith.py", "w") as f: f.write( fmt_str.format( pd=res.parser_data, ex=res.extra, starts=list(res.starts), transdef=res.transdef, ntmap=json.dumps(res.nonterminal_map), ) ) mod = importlib.import_module("gen.arith") print(mod.parse("1 + 2 * 3", start="Expr")) # type: ignore