move the template to another file

This commit is contained in:
Michael Zhang 2021-09-30 17:53:47 -05:00
parent 9dbb557d00
commit 744496e32e
Signed by: michael
GPG key ID: BDA47A31A3C8EE6B
3 changed files with 49 additions and 51 deletions

View file

@ -4,7 +4,6 @@ import re
import copy import copy
import json import json
from collections import defaultdict from collections import defaultdict
from re import Pattern
from agast import * from agast import *
@ -113,13 +112,13 @@ def gen(program: List[Decl]) -> GenResult:
print("what_ifaces:", what_ifaces) print("what_ifaces:", what_ifaces)
print("what_fields:", what_fields) print("what_fields:", what_fields)
# a high-level dictionary of productions; this has sub-productions # a high-level dictionary of productions; this has sub-productions that
# that should be further expanded at a later step before converting # should be further expanded at a later step before converting into lark
# into lark code # code
productions_hi: Dict[str, Union[str, List[str]]] = dict() productions_hi: Dict[str, Union[str, List[str]]] = dict()
# TODO: this should probably not be inlined here, but i'll move it # TODO: this should probably not be inlined here, but i'll move it out once
# out once i get more info into the 'env' # i get more info into the 'env'
def collect_required_thunks( def collect_required_thunks(
env: List[Tuple[str, NodeRef]], expr: Expr env: List[Tuple[str, NodeRef]], expr: Expr
) -> Dict[str, str]: ) -> Dict[str, str]:
@ -210,17 +209,16 @@ def gen(program: List[Decl]) -> GenResult:
ParseEquation(prod_name, seq, v_class_name) ParseEquation(prod_name, seq, v_class_name)
) )
# create an environment for checking the equations based on # create an environment for checking the equations based on the
# the production # production
env: List[Tuple[str, NodeRef]] = list() env: List[Tuple[str, NodeRef]] = list()
for sym in variant.prod: for sym in variant.prod:
if isinstance(sym, SymRename): if isinstance(sym, SymRename):
env.append((sym.name, sym.ty)) env.append((sym.name, sym.ty))
print(env) print(env)
# for each of the equations, find out what the equation is # for each of the equations, find out what the equation is trying
# trying to compute, and generate a thunk corresponding to # to compute, and generate a thunk corresponding to that value.
# that value.
for eq in variant.equations: for eq in variant.equations:
eq_name = gensym(f"eq_{node_desc.name}") eq_name = gensym(f"eq_{node_desc.name}")
thunk_name = gensym(f"thunk_{node_desc.name}") thunk_name = gensym(f"thunk_{node_desc.name}")

View file

@ -25,46 +25,7 @@ if __name__ == "__main__":
if not os.path.exists("gen"): if not os.path.exists("gen"):
os.makedirs("gen") os.makedirs("gen")
with open("gen/arith.py", "w") as f: with open("gen/arith.py", "w") as f:
fmt_str = textwrap.dedent( fmt_str = open("agruntime.tmpl.py", "r").read()
"""
# This document is generated by agtest.
__all__ = ["parse"]
from typing import Generic, TypeVar, Optional, Callable, Dict, Any
from lark import Lark, Transformer
T = TypeVar('T')
builtins: Dict[str, Any] = {{
"parseInt": lambda s: int(s)
}}
class Thunk(Generic[T]):
''' 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
parser = Lark('''
{pd}
''', parser='lalr', start={starts}, debug=True)
{ex}
class Trans(Transformer[None]): {transdef}
__agNonterminals = {ntmap}
def parse(input: str, start: Optional[str] = None) -> Any:
if start is not None: start = __agNonterminals[start]
tree = parser.parse(input, start)
trans = Trans()
res = trans.transform(tree)
return res
"""
)
f.write( f.write(
fmt_str.format( fmt_str.format(
pd=res.parser_data, pd=res.parser_data,

39
agruntime.tmpl.py Normal file
View file

@ -0,0 +1,39 @@
# This document is generated by agtest.
# type: ignore
__all__ = ["parse"]
import re
from typing import Generic, TypeVar, Optional, Callable, Dict, Any
from lark import Lark, Transformer
T = TypeVar('T')
builtins: Dict[str, Any] = {{
"parseInt": lambda s: int(s)
}}
class Thunk(Generic[T]):
''' 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
parser = Lark('''
{pd}
''', parser='lalr', start={starts}, debug=True)
{ex}
class Trans(Transformer[None]): {transdef}
__agNonterminals = {ntmap}
def parse(input: str, start: Optional[str] = None) -> Any:
if start is not None: start = __agNonterminals[start]
tree = parser.parse(input, start)
trans = Trans()
res = trans.transform(tree)
return res