Skip to content

Commit fd3fbcc

Browse files
Fix: Raise SemanticError for unsupported inline class instantiation #2826
1 parent a9a4698 commit fd3fbcc

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8488,6 +8488,32 @@ we will have to use something else.
84888488
void visit_Call(const AST::Call_t &x) {
84898489
std::string call_name = "";
84908490
Vec<ASR::call_arg_t> args;
8491+
for (size_t i = 0; i < x.n_args; i++) {
8492+
AST::expr_t *arg_expr = x.m_args[i];
8493+
8494+
if (arg_expr->type == AST::exprType::Call) {
8495+
AST::Call_t *call_node = (AST::Call_t*)arg_expr;
8496+
8497+
if (call_node->m_func->type == AST::exprType::Name) {
8498+
AST::Name_t *func_name = (AST::Name_t*)call_node->m_func;
8499+
std::string name = std::string(func_name->m_id);
8500+
8501+
// Resolve symbol
8502+
ASR::symbol_t *sym = current_scope->resolve_symbol(name);
8503+
8504+
if (sym) {
8505+
sym = ASRUtils::symbol_get_past_external(sym);
8506+
8507+
// FIX: Only check for Struct (Python classes are Structs in ASR)
8508+
if (sym->type == ASR::symbolType::Struct) {
8509+
throw SemanticError("Inline class instantiation (e.g. print(Foo(10))) is not yet supported. "
8510+
"Please assign it to a variable first.",
8511+
arg_expr->base.loc);
8512+
}
8513+
}
8514+
}
8515+
}
8516+
}
84918517
if (AST::is_a<AST::Name_t>(*x.m_func)) {
84928518
AST::Name_t *n = AST::down_cast<AST::Name_t>(x.m_func);
84938519
call_name = n->m_id;
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Foo:
2+
def __init__(self: "Foo", x: i32):
3+
self.x: i32 = x
4+
5+
def my_func(f: Foo):
6+
pass
7+
8+
def main():
9+
# This should trigger the SemanticError immediately
10+
print(Foo(10))
11+
12+
# This checks the other case (function params)
13+
my_func(Foo(20))
14+
15+
main()
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Foo:
2+
def __init__(self: "Foo", x: i32):
3+
self.x: i32 = x
4+
5+
def main():
6+
a: Foo = Foo(10)
7+
print(a)
8+
9+
main()

0 commit comments

Comments
 (0)