This commit is contained in:
Michael Zhang 2021-09-30 21:58:18 -05:00
parent 8f51231f5b
commit 30644c5db7
Signed by: michael
GPG key ID: BDA47A31A3C8EE6B
2 changed files with 27 additions and 11 deletions

View file

@ -47,13 +47,15 @@ class GenResult:
for name, rules in self.parse_rules.items():
n = name.lstrip("?")
for equation in rules:
code = textwrap.dedent(f"""
code = textwrap.dedent(
f"""
def {equation.name}(self, items: Any) -> Thunk[{equation.ty}]:
def inner() -> {equation.ty}:
res = {equation.ty}()
return res
return Thunk(inner)
""")
"""
)
s.append(code)
if not s:
s = ["pass"]

View file

@ -6,33 +6,47 @@ 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)
}}
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. '''
"""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('''
parser = Lark(
"""
{pd}
''', parser='lalr', start={starts}, debug=True)
""",
parser="lalr",
start={starts},
debug=True,
)
{ex}
class Trans(Transformer[None]): {transdef}
class Trans(Transformer[None]):
{transdef}
__agNonterminals = {ntmap}
def parse(input: str, start: Optional[str] = None) -> Any:
if start is not None: start = __agNonterminals[start]
if start is not None:
start = __agNonterminals[start]
tree = parser.parse(input, start)
trans = Trans()
res = trans.transform(tree)