agtest/agmain.py
2021-09-30 21:57:57 -05:00

43 lines
985 B
Python

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