agtest/agast.py

65 lines
1.9 KiB
Python
Raw Normal View History

2021-06-09 05:10:45 +00:00
from typing import *
from lark import Transformer, Tree
class Interface: pass
class Node: pass
class NodeRef: pass
class Sym: pass
class SymRename(Sym):
def __init__(self, name: str, node_ref: NodeRef):
self.name = name
self.node_ref = node_ref
def __repr__(self) -> str: return f"SymRename({self.name} : {self.node_ref})"
class Equation: pass
class Variant:
def __init__(self, prod: List[Sym], equations: List[Equation]):
self.prod = prod
self.equations = equations
def __repr__(self) -> str: return f"Variant({self.prod}, {self.equations})"
class Expr: pass
class ExprDot(Expr):
def __init__(self, left: Expr, right: Expr):
self.left = left
self.right = right
def __repr__(self) -> str: return f"{self.left}.{self.right}"
class ExprAdd(Expr):
def __init__(self, left: Expr, right: Expr):
self.left = left
self.right = right
def __repr__(self) -> str: return f"{self.left} + {self.right}"
class ExprMul(Expr):
def __init__(self, left: Expr, right: Expr):
self.left = left
self.right = right
def __repr__(self) -> str: return f"{self.left} * {self.right}"
class ExprCall(Expr):
def __init__(self, func: Expr, args: List[Expr]):
self.func = func
self.args = args
def __repr__(self) -> str: return f"{self.func}({self.args})"
class Parser(Transformer[None]):
def variant(self, items: List[Any]) -> Variant:
[prod, equations] = items
return Variant(prod, equations)
def prod(self, items: List[Sym]) -> List[Sym]: return items
def sym_rename(self, items: List[Any]) -> Sym: return SymRename(items[0], items[1])
def expr_dot(self, items: List[Expr]) -> Expr:
[left, _, right] = items
return ExprDot(left, right)
def expr_add(self, items: List[Expr]) -> Expr:
[left, _, right] = items
return ExprAdd(left, right)
def expr_mul(self, items: List[Expr]) -> Expr:
[left, _, right] = items
return ExprMul(left, right)
def expr_call(self, items: List[Expr]) -> Expr:
[func, _, args, _] = items
return ExprMul(func, args)