Skip to content

Commit 412ad84

Browse files
committed
Introduce ASTBuilder mixin to simplify and reduce verbosity in AST construction, refactor language_generation.py to leverage the new mixin, and consolidate feature creation logic.
1 parent 900aa87 commit 412ad84

2 files changed

Lines changed: 193 additions & 240 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import ast
2+
3+
class ASTBuilder:
4+
"""Helper mixin to reduce ast verbosity."""
5+
6+
def name(self, id: str, ctx=None) -> ast.Name:
7+
return ast.Name(id=id, ctx=ctx or ast.Load())
8+
9+
def const(self, value) -> ast.Constant:
10+
return ast.Constant(value=value)
11+
12+
def attr(self, value, attr: str, ctx=None) -> ast.Attribute:
13+
# value can be a string (implies a Name node) or an AST node
14+
if isinstance(value, str):
15+
value = self.name(value)
16+
return ast.Attribute(value=value, attr=attr, ctx=ctx or ast.Load())
17+
18+
def call(self, func, args=None, keywords=None) -> ast.Call:
19+
"""Creates a function call.
20+
'func' can be a string (function name) or an AST node.
21+
'keywords' is a dict of {arg_name: ast_node}.
22+
"""
23+
if isinstance(func, str):
24+
func = self.name(func)
25+
26+
ast_keywords = []
27+
if keywords:
28+
for k, v in keywords.items():
29+
if v is None: continue # Skip None values
30+
ast_keywords.append(ast.keyword(arg=k, value=v))
31+
32+
return ast.Call(func=func, args=args or [], keywords=ast_keywords)
33+
34+
def assign(self, target_id: str, value) -> ast.Assign:
35+
return ast.Assign(
36+
targets=[self.name(target_id, ctx=ast.Store())],
37+
value=value
38+
)

0 commit comments

Comments
 (0)