agtest/gen.py

54 lines
1.2 KiB
Python
Raw Normal View History

2021-06-09 00:56:30 +00:00
import textwrap
import os
2021-06-09 07:44:52 +00:00
import importlib
2021-06-09 00:56:30 +00:00
from lark import Lark
from agast import *
from agtypeck import *
2021-06-09 05:10:45 +00:00
p = Lark(open("grammar.lark").read(), start="program", parser="lalr")
2021-06-09 00:56:30 +00:00
if __name__ == "__main__":
with open("arith.ag") as f:
data = f.read()
cst = p.parse(data)
# print("cst", cst)
trans = Parser()
ast = trans.transform(cst)
print("ast", ast)
2021-06-09 06:48:34 +00:00
res = typecheck(ast)
2021-06-09 00:56:30 +00:00
if not os.path.exists("gen"):
os.makedirs("gen")
with open("gen/arith.py", "w") as f:
2021-06-09 07:44:52 +00:00
fmt_str = textwrap.dedent("""
__all__ = ["parse"]
2021-06-09 06:48:34 +00:00
from typing import Generic, TypeVar, Optional, Callable
from lark import Lark, Transformer
2021-06-09 00:56:30 +00:00
T = TypeVar('T')
class Thunk(Generic[T]):
2021-06-09 06:48:34 +00:00
''' A thunk represents a value that may be computed lazily. '''
value: Optional[T]
def __init__(self, func: Callable[[], T]):
self.func = func
self.value = None
def get(self) -> T:
if self.value is None:
self.value = self.func()
return self.value
2021-06-09 07:44:52 +00:00
parser = Lark('''start:
{pd}''')
2021-06-09 06:48:34 +00:00
class Trans(Transformer[None]):
2021-06-09 00:56:30 +00:00
pass
2021-06-09 07:44:52 +00:00
{ex}
def parse(input: str) -> None:
print(input)
""")
f.write(fmt_str.format(pd=res.parser_data, ex=res.extra))
mod = importlib.import_module("gen.arith")
mod.parse("1 + 2 * 3") # type: ignore