From e43c38a9f5ef165b35ad127149145c31a9bc1fe9 Mon Sep 17 00:00:00 2001 From: Ori Ziv Date: Tue, 31 Mar 2026 18:07:40 +0300 Subject: [PATCH] fix: handle missing return type context in loop body instead of panicking Fixes starkware-libs/cairo#9787 --- .../cairo-lang-semantic/src/expr/compute.rs | 7 ++++- .../src/expr/test_data/fixed_size_array | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/cairo-lang-semantic/src/expr/compute.rs b/crates/cairo-lang-semantic/src/expr/compute.rs index fc4b97bf5d2..0f361753147 100644 --- a/crates/cairo-lang-semantic/src/expr/compute.rs +++ b/crates/cairo-lang-semantic/src/expr/compute.rs @@ -2329,7 +2329,12 @@ fn compute_loop_body_semantic<'db>( ) -> (ExprId, InnerContext<'db>) { let db: &dyn Database = ctx.db; ctx.run_in_subscope(|new_ctx| { - let return_type = new_ctx.get_return_type().unwrap(); + // `None` means we're outside a function/loop context (e.g. a loop in array size position). + // The invalid usage will be caught by the caller; use `missing` to suppress cascading + // errors. + let return_type = new_ctx + .get_return_type() + .unwrap_or_else(|| TypeId::missing(new_ctx.db, skip_diagnostic())); let old_inner_ctx = new_ctx.inner_ctx.replace(InnerContext { return_type, kind }); let (statements, tail) = statements_and_tail(ctx.db, syntax.statements(db)); let mut statements_semantic = vec![]; diff --git a/crates/cairo-lang-semantic/src/expr/test_data/fixed_size_array b/crates/cairo-lang-semantic/src/expr/test_data/fixed_size_array index 4b60f9d19c9..33114555f7e 100644 --- a/crates/cairo-lang-semantic/src/expr/test_data/fixed_size_array +++ b/crates/cairo-lang-semantic/src/expr/test_data/fixed_size_array @@ -299,3 +299,32 @@ fn foo() { foo //! > expected_diagnostics + +//! > ========================================================================== + +//! > Loop expression in fixed-size array size position. + +//! > test_runner_name +test_function_diagnostics(expect_diagnostics: true) + +//! > function_code +fn foo() {} + +//! > function_name +foo + +//! > module_code +fn f() -> [felt252; for _ in 0..1_u32 {}] { + [0] +} + +//! > expected_diagnostics +error[E2302]: Type mismatch: `()` and `core::integer::u32`. + --> lib.cairo:1:21 +fn f() -> [felt252; for _ in 0..1_u32 {}] { + ^^^^^^^^^^^^^^^^^^^^ + +error[E2172]: Fixed size array type must have a positive integer size. + --> lib.cairo:1:11 +fn f() -> [felt252; for _ in 0..1_u32 {}] { + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^