Skip to content

Commit 6999c42

Browse files
authored
allow eagerly eval global attr (#278)
I know this has been annoying. See the test for an example. I think this should be considered a bug, although it still worth discussion on how far do we allow eagerly evaluation on expressions involves global value access, e.g `glob[1]` does not make sense in this case?
1 parent 815ffec commit 6999c42

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/kirin/dialects/py/attr.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,19 @@ class Lowering(lowering.FromPythonAST):
4040
def lower_Attribute(
4141
self, state: lowering.LoweringState, node: ast.Attribute
4242
) -> lowering.Result:
43+
from kirin.dialects.py import Constant
44+
4345
if not isinstance(node.ctx, ast.Load):
4446
raise exceptions.DialectLoweringError(
4547
f"unsupported attribute context {node.ctx}"
4648
)
49+
50+
# NOTE: eagerly load global variables
51+
value = state.get_global_nothrow(node)
52+
if value is not None:
53+
stmt = state.append_stmt(Constant(value.unwrap()))
54+
return lowering.Result(stmt)
55+
4756
value = state.visit(node.value).expect_one()
4857
stmt = GetAttr(obj=value, attrname=node.attr)
4958
state.append_stmt(stmt)

test/program/py/test_glob_pi.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import math
2+
3+
from kirin.prelude import basic_no_opt
4+
from kirin.dialects import py
5+
6+
7+
def test_math_pi():
8+
@basic_no_opt
9+
def main():
10+
return math.pi
11+
12+
stmt = main.callable_region.blocks[0].stmts.at(0)
13+
assert isinstance(stmt, py.Constant)
14+
assert stmt.value == math.pi

0 commit comments

Comments
 (0)