Fix: Raise SemanticError for unsupported inline class instantiation #2826 by amritamishra01 · Pull Request #2873 · lcompilers/lpython
Summary
Hi @swamishiju Fixes #2826 where the compiler hangs (infinite loop) when encountering inline class instantiation, such as print(Foo(10)).
The Issue
Currently, the compiler attempts to lower temporary class objects created inline but fails to handle the lifecycle correctly in python_ast_to_asr.cpp, resulting in infinite recursion/hanging during the lowering phase.
The Fix
I implemented a check in the semantic analysis phase (visit_Call) to detect this unsupported pattern before it reaches the lowering stage.
- File:
src/lpython/semantics/python_ast_to_asr.cpp - Logic: The visitor now checks if a function call argument is a direct
Callto aStruct(Class) symbol. - Action: If detected, it raises a clear
SemanticErroradvising the user to assign the object to a variable first.
Verification
I added two new test cases to ensure the fix works and is safe:
-
Error Case:
tests/errors/test_inline_class_error.py- Contains
print(Foo(10))andmy_func(Foo(20)). - Verified that it now raises a
SemanticErrorimmediately instead of hanging.
- Contains
-
Regression Test:
tests/reference/pass_inline_class_safe.py- Contains
a = Foo(10); print(a). - Verified that valid usage (assigning to a variable first) still compiles and produces correct ASR.
- Contains
Future Work
This is a safeguard fix. Full support for inline class instantiation will require implementing proper lowering logic for temporary class objects, likely by separating symbol registration from body lowering to handle recursive resolution.