diff --git a/crates/cairo-lang-lowering/src/lower/mod.rs b/crates/cairo-lang-lowering/src/lower/mod.rs index 051c11d8241..0dfd199ae6a 100644 --- a/crates/cairo-lang-lowering/src/lower/mod.rs +++ b/crates/cairo-lang-lowering/src/lower/mod.rs @@ -315,7 +315,7 @@ pub fn lower_loop_function( loop_expr_id: semantic::ExprId, ) -> Maybe { let mut ctx = LoweringContext::new(encapsulating_ctx, function_id, loop_signature.clone())?; - ctx.current_loop_expr_id = Some(loop_expr_id); + let old_loop_expr_id = std::mem::replace(&mut ctx.current_loop_expr_id, Some(loop_expr_id)); // Initialize builder. let root_block_id = alloc_empty_block(&mut ctx); @@ -369,6 +369,7 @@ pub fn lower_loop_function( Ok(root_block_id) })(); + ctx.current_loop_expr_id = old_loop_expr_id; let blocks = root_ok .map(|_| ctx.blocks.build().expect("Root block must exist.")) @@ -1252,9 +1253,10 @@ fn lower_expr_loop( encapsulating_ctx.lowerings.insert(loop_expr_id, lowered); ctx.encapsulating_ctx = Some(encapsulating_ctx); - ctx.current_loop_expr_id = Some(loop_expr_id); - - call_loop_func(ctx, loop_signature, builder, loop_expr_id, stable_ptr.untyped()) + let old_loop_expr_id = std::mem::replace(&mut ctx.current_loop_expr_id, Some(loop_expr_id)); + let call = call_loop_func(ctx, loop_signature, builder, loop_expr_id, stable_ptr.untyped()); + ctx.current_loop_expr_id = old_loop_expr_id; + call } /// Adds a call to an inner loop-generated function. diff --git a/tests/bug_samples/issue5438.cairo b/tests/bug_samples/issue5438.cairo new file mode 100644 index 00000000000..7e268b87bbb --- /dev/null +++ b/tests/bug_samples/issue5438.cairo @@ -0,0 +1,27 @@ +#[inline(never)] +fn foo(mut x: i8, mut y: i8) -> i8 { + loop { + match x { + 0 => { + // A loop before continue - bug would cause the continue to call this loop. + while y < 100 { + y += 1; + }; + x += 1; + }, + 1 => { + x -= 2; + continue; + }, + _ => { x -= 2; }, + } + if x < 0 { + break y; + } + } +} + +#[test] +fn loop_of_loop() -> i8 { + foo(10, 10) +} diff --git a/tests/bug_samples/lib.cairo b/tests/bug_samples/lib.cairo index 3a3501b4e54..a8ea11ac6cf 100644 --- a/tests/bug_samples/lib.cairo +++ b/tests/bug_samples/lib.cairo @@ -41,6 +41,7 @@ mod issue4380; mod issue4897; mod issue4937; mod issue5411; +mod issue5438; mod loop_break_in_match; mod loop_only_change; mod partial_param_local;