L4.parse
1from collections.abc import Sequence 2from pathlib import Path 3from typing import Literal, cast 4 5from lark import Lark, Token, Transformer 6from lark.visitors import v_args # pyright: ignore[reportUnknownVariableType] 7 8from .syntax import ( 9 Abstraction, 10 And, 11 Application, 12 Arrow, 13 Bool, 14 Boolean, 15 Box, 16 BoxRead, 17 BoxWrite, 18 Branch, 19 Identifier, 20 If, 21 Immediate, 22 Int, 23 Join, 24 Primitive, 25 Product, 26 Program, 27 Project, 28 Reference, 29 Sole, 30 Term, 31 Trivial, 32 Tuple, 33 TupleGet, 34 Type, 35) 36 37 38class AstTransformer(Transformer[Token, Program | Term]): 39 @v_args(inline=True) 40 def program( 41 self, 42 _program: Token, 43 parameters: Sequence[Identifier], 44 body: Term, 45 ) -> Program: 46 return Program(parameters=parameters, body=body) 47 48 def parameters(self, parameters: Sequence[Token]) -> Sequence[Identifier]: 49 return [str(parameter) for parameter in parameters] 50 51 @v_args(inline=True) 52 def term(self, term: Term) -> Term: 53 return term 54 55 # --- Types --- 56 57 @v_args(inline=True) 58 def int_type(self) -> Type: 59 return Int() 60 61 @v_args(inline=True) 62 def bool_type(self) -> Type: 63 return Bool() 64 65 @v_args(inline=True) 66 def trivial_type(self) -> Type: 67 return Trivial() 68 69 @v_args(inline=True) 70 def arrow_type(self, domain: Type, codomain: Type) -> Type: 71 return Arrow(domain=domain, codomain=codomain) 72 73 def product_type(self, args: Sequence[Type]) -> Type: 74 return Product(components=[component for component in args]) 75 76 @v_args(inline=True) 77 def box_type(self, content: Type) -> Type: 78 return Box(content=content) 79 80 # --- Terms --- 81 82 @v_args(inline=True) 83 def let(self, _let: Token, bindings: Sequence[tuple[Identifier, Term]], body: Term) -> Term: 84 from .syntax import Let 85 86 return Let(bindings=bindings, body=body) 87 88 def bindings(self, bindings: Sequence[tuple[Identifier, Term]]) -> Sequence[tuple[Identifier, Term]]: 89 return bindings 90 91 @v_args(inline=True) 92 def binding(self, name: Token, value: Term) -> tuple[Identifier, Term]: 93 return str(name), value 94 95 @v_args(inline=True) 96 def reference(self, name: Token) -> Term: 97 return Reference(name=str(name)) 98 99 @v_args(inline=False) 100 def abstract(self, args) -> Term: 101 # Grammar: abstract : "(" LAMBDA "(" parameters ")" term ")" 102 # args will contain processed children after Lark filters anonymous tokens 103 from .syntax import Int 104 105 # Filter args into parameters and body 106 parameters = None 107 body = None 108 109 for arg in args: 110 if isinstance(arg, (list, tuple)) and parameters is None: 111 parameters = arg 112 elif arg is not None and parameters is not None: # Body comes after parameters 113 body = arg 114 115 if parameters is None or body is None: 116 raise ValueError(f"abstract requires parameters and body, got args: {args}") 117 118 if not parameters: 119 raise ValueError("abstract requires at least one parameter") 120 121 # Build nested Abstraction for multiple parameters 122 result = body 123 for param in reversed(parameters): 124 result = Abstraction(parameter=param, domain=Int(), body=result) 125 126 return result 127 128 def apply(self, args: Sequence[Term]) -> Term: 129 terms = list(args) 130 if len(terms) == 0: 131 raise ValueError("application requires at least one term") 132 133 target = terms[0] 134 for argument in terms[1:]: 135 target = Application(target=target, argument=argument) 136 137 return target 138 139 @v_args(inline=True) 140 def immediate(self, value: Token) -> Term: 141 return Immediate(value=int(value)) 142 143 @v_args(inline=True) 144 def boolean(self, value: Token) -> Term: 145 # Lark gives us the token "true" or "false" as a string 146 return Boolean(value=str(value) == "true") 147 148 @v_args(inline=True) 149 def primitive(self, operator: Token, left: Term, right: Term) -> Term: 150 op = cast(Literal["+", "-", "*"], str(operator)) 151 return Primitive(operator=op, left=left, right=right) 152 153 @v_args(inline=True) 154 def branch( 155 self, 156 _if: Token, 157 operator: Token, 158 left: Term, 159 right: Term, 160 motive: Type, 161 consequent: Term, 162 otherwise: Term, 163 ) -> Term: 164 # Branch: (if (< left right) motive consequent otherwise) 165 op = cast(Literal["<", "=="], str(operator)) 166 return Branch( 167 operator=op, 168 left=left, 169 right=right, 170 motive=motive, 171 consequent=consequent, 172 otherwise=otherwise, 173 ) 174 175 @v_args(inline=True) 176 def if_expr(self, _if: Token, test: Term, consequent: Term, otherwise: Term) -> Term: 177 return If(test=test, consequent=consequent, otherwise=otherwise) 178 179 @v_args(inline=True) 180 def and_expr(self, _and: Token, left: Term, right: Term) -> Term: 181 return And(left=left, right=right) 182 183 @v_args(inline=True) 184 def sole_expr(self, _sole: Token) -> Term: 185 return Sole() 186 187 def tuple_expr(self, components: Sequence[Term]) -> Term: 188 return Tuple(components=components) 189 190 @v_args(inline=True) 191 def tuple_get_expr(self, _tuple_get: Token, target: Term, index: Immediate) -> Term: 192 return TupleGet(target=target, index=index.value) 193 194 def join_expr(self, components: Sequence[Term]) -> Term: 195 return Join(components=components) 196 197 @v_args(inline=True) 198 def project_expr(self, _project: Token, target: Term, index: Immediate) -> Term: 199 return Project(target=target, index=index.value) 200 201 @v_args(inline=True) 202 def box_write_expr(self, _box_write: Token, target: Term, value: Term) -> Term: 203 return BoxWrite(target=target, value=value) 204 205 @v_args(inline=True) 206 def box_read_expr(self, _box_read: Token, target: Term) -> Term: 207 return BoxRead(target=target) 208 209 210def parse_term(source: str) -> Term: 211 grammar = Path(__file__).with_name("L4.lark").read_text() 212 parser = Lark(grammar, start="term") 213 tree = parser.parse(source) # pyright: ignore[reportUnknownMemberType] 214 return AstTransformer().transform(tree) # pyright: ignore[reportReturnType] 215 216 217def parse_program(source: str) -> Program: 218 grammar = Path(__file__).with_name("L4.lark").read_text() 219 parser = Lark(grammar, start="program") 220 tree = parser.parse(source) # pyright: ignore[reportUnknownMemberType] 221 return AstTransformer().transform(tree) # pyright: ignore[reportReturnType]
39class AstTransformer(Transformer[Token, Program | Term]): 40 @v_args(inline=True) 41 def program( 42 self, 43 _program: Token, 44 parameters: Sequence[Identifier], 45 body: Term, 46 ) -> Program: 47 return Program(parameters=parameters, body=body) 48 49 def parameters(self, parameters: Sequence[Token]) -> Sequence[Identifier]: 50 return [str(parameter) for parameter in parameters] 51 52 @v_args(inline=True) 53 def term(self, term: Term) -> Term: 54 return term 55 56 # --- Types --- 57 58 @v_args(inline=True) 59 def int_type(self) -> Type: 60 return Int() 61 62 @v_args(inline=True) 63 def bool_type(self) -> Type: 64 return Bool() 65 66 @v_args(inline=True) 67 def trivial_type(self) -> Type: 68 return Trivial() 69 70 @v_args(inline=True) 71 def arrow_type(self, domain: Type, codomain: Type) -> Type: 72 return Arrow(domain=domain, codomain=codomain) 73 74 def product_type(self, args: Sequence[Type]) -> Type: 75 return Product(components=[component for component in args]) 76 77 @v_args(inline=True) 78 def box_type(self, content: Type) -> Type: 79 return Box(content=content) 80 81 # --- Terms --- 82 83 @v_args(inline=True) 84 def let(self, _let: Token, bindings: Sequence[tuple[Identifier, Term]], body: Term) -> Term: 85 from .syntax import Let 86 87 return Let(bindings=bindings, body=body) 88 89 def bindings(self, bindings: Sequence[tuple[Identifier, Term]]) -> Sequence[tuple[Identifier, Term]]: 90 return bindings 91 92 @v_args(inline=True) 93 def binding(self, name: Token, value: Term) -> tuple[Identifier, Term]: 94 return str(name), value 95 96 @v_args(inline=True) 97 def reference(self, name: Token) -> Term: 98 return Reference(name=str(name)) 99 100 @v_args(inline=False) 101 def abstract(self, args) -> Term: 102 # Grammar: abstract : "(" LAMBDA "(" parameters ")" term ")" 103 # args will contain processed children after Lark filters anonymous tokens 104 from .syntax import Int 105 106 # Filter args into parameters and body 107 parameters = None 108 body = None 109 110 for arg in args: 111 if isinstance(arg, (list, tuple)) and parameters is None: 112 parameters = arg 113 elif arg is not None and parameters is not None: # Body comes after parameters 114 body = arg 115 116 if parameters is None or body is None: 117 raise ValueError(f"abstract requires parameters and body, got args: {args}") 118 119 if not parameters: 120 raise ValueError("abstract requires at least one parameter") 121 122 # Build nested Abstraction for multiple parameters 123 result = body 124 for param in reversed(parameters): 125 result = Abstraction(parameter=param, domain=Int(), body=result) 126 127 return result 128 129 def apply(self, args: Sequence[Term]) -> Term: 130 terms = list(args) 131 if len(terms) == 0: 132 raise ValueError("application requires at least one term") 133 134 target = terms[0] 135 for argument in terms[1:]: 136 target = Application(target=target, argument=argument) 137 138 return target 139 140 @v_args(inline=True) 141 def immediate(self, value: Token) -> Term: 142 return Immediate(value=int(value)) 143 144 @v_args(inline=True) 145 def boolean(self, value: Token) -> Term: 146 # Lark gives us the token "true" or "false" as a string 147 return Boolean(value=str(value) == "true") 148 149 @v_args(inline=True) 150 def primitive(self, operator: Token, left: Term, right: Term) -> Term: 151 op = cast(Literal["+", "-", "*"], str(operator)) 152 return Primitive(operator=op, left=left, right=right) 153 154 @v_args(inline=True) 155 def branch( 156 self, 157 _if: Token, 158 operator: Token, 159 left: Term, 160 right: Term, 161 motive: Type, 162 consequent: Term, 163 otherwise: Term, 164 ) -> Term: 165 # Branch: (if (< left right) motive consequent otherwise) 166 op = cast(Literal["<", "=="], str(operator)) 167 return Branch( 168 operator=op, 169 left=left, 170 right=right, 171 motive=motive, 172 consequent=consequent, 173 otherwise=otherwise, 174 ) 175 176 @v_args(inline=True) 177 def if_expr(self, _if: Token, test: Term, consequent: Term, otherwise: Term) -> Term: 178 return If(test=test, consequent=consequent, otherwise=otherwise) 179 180 @v_args(inline=True) 181 def and_expr(self, _and: Token, left: Term, right: Term) -> Term: 182 return And(left=left, right=right) 183 184 @v_args(inline=True) 185 def sole_expr(self, _sole: Token) -> Term: 186 return Sole() 187 188 def tuple_expr(self, components: Sequence[Term]) -> Term: 189 return Tuple(components=components) 190 191 @v_args(inline=True) 192 def tuple_get_expr(self, _tuple_get: Token, target: Term, index: Immediate) -> Term: 193 return TupleGet(target=target, index=index.value) 194 195 def join_expr(self, components: Sequence[Term]) -> Term: 196 return Join(components=components) 197 198 @v_args(inline=True) 199 def project_expr(self, _project: Token, target: Term, index: Immediate) -> Term: 200 return Project(target=target, index=index.value) 201 202 @v_args(inline=True) 203 def box_write_expr(self, _box_write: Token, target: Term, value: Term) -> Term: 204 return BoxWrite(target=target, value=value) 205 206 @v_args(inline=True) 207 def box_read_expr(self, _box_read: Token, target: Term) -> Term: 208 return BoxRead(target=target)
Transformers work bottom-up (or depth-first), starting with visiting the leaves and working their way up until ending at the root of the tree.
For each node visited, the transformer will call the appropriate method (callbacks), according to the
node's data, and use the returned value to replace the node, thereby creating a new tree structure.
Transformers can be used to implement map & reduce patterns. Because nodes are reduced from leaf to root, at any point the callbacks may assume the children have already been transformed (if applicable).
If the transformer cannot find a method with the right name, it will instead call __default__, which by
default creates a copy of the node.
To discard a node, return Discard (lark.visitors.Discard).
Transformer can do anything Visitor can do, but because it reconstructs the tree,
it is slightly less efficient.
A transformer without methods essentially performs a non-memoized partial deepcopy.
All these classes implement the transformer interface:
Transformer- Recursively transforms the tree. This is the one you probably want.Transformer_InPlace- Non-recursive. Changes the tree in-place instead of returning new instancesTransformer_InPlaceRecursive- Recursive. Changes the tree in-place instead of returning new instances
Parameters:
visit_tokens (bool, optional): Should the transformer visit tokens in addition to rules.
Setting this to False is slightly faster. Defaults to True.
(For processing ignored tokens, use the lexer_callbacks options)
100 @v_args(inline=False) 101 def abstract(self, args) -> Term: 102 # Grammar: abstract : "(" LAMBDA "(" parameters ")" term ")" 103 # args will contain processed children after Lark filters anonymous tokens 104 from .syntax import Int 105 106 # Filter args into parameters and body 107 parameters = None 108 body = None 109 110 for arg in args: 111 if isinstance(arg, (list, tuple)) and parameters is None: 112 parameters = arg 113 elif arg is not None and parameters is not None: # Body comes after parameters 114 body = arg 115 116 if parameters is None or body is None: 117 raise ValueError(f"abstract requires parameters and body, got args: {args}") 118 119 if not parameters: 120 raise ValueError("abstract requires at least one parameter") 121 122 # Build nested Abstraction for multiple parameters 123 result = body 124 for param in reversed(parameters): 125 result = Abstraction(parameter=param, domain=Int(), body=result) 126 127 return result
154 @v_args(inline=True) 155 def branch( 156 self, 157 _if: Token, 158 operator: Token, 159 left: Term, 160 right: Term, 161 motive: Type, 162 consequent: Term, 163 otherwise: Term, 164 ) -> Term: 165 # Branch: (if (< left right) motive consequent otherwise) 166 op = cast(Literal["<", "=="], str(operator)) 167 return Branch( 168 operator=op, 169 left=left, 170 right=right, 171 motive=motive, 172 consequent=consequent, 173 otherwise=otherwise, 174 )
218def parse_program(source: str) -> Program: 219 grammar = Path(__file__).with_name("L4.lark").read_text() 220 parser = Lark(grammar, start="program") 221 tree = parser.parse(source) # pyright: ignore[reportUnknownMemberType] 222 return AstTransformer().transform(tree) # pyright: ignore[reportReturnType]