Skip to content

Commit

Permalink
Fixed loop inside loop issue.
Browse files Browse the repository at this point in the history
  • Loading branch information
orizi committed Apr 18, 2024
1 parent cb4bf08 commit 609cb7f
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
10 changes: 6 additions & 4 deletions crates/cairo-lang-lowering/src/lower/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ pub fn lower_loop_function(
loop_expr_id: semantic::ExprId,
) -> Maybe<FlatLowered> {
let mut ctx = LoweringContext::new(encapsulating_ctx, function_id, loop_signature.clone())?;
ctx.current_loop_expr_id = Some(loop_expr_id);
let old = std::mem::replace(&mut ctx.current_loop_expr_id, Some(loop_expr_id));

// Initialize builder.
let root_block_id = alloc_empty_block(&mut ctx);
Expand Down Expand Up @@ -370,6 +370,7 @@ pub fn lower_loop_function(

Ok(root_block_id)
})();
ctx.current_loop_expr_id = old;

let blocks = root_ok
.map(|_| ctx.blocks.build().expect("Root block must exist."))
Expand Down Expand Up @@ -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 = 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;
call
}

/// Adds a call to an inner loop-generated function.
Expand Down
27 changes: 27 additions & 0 deletions tests/bug_samples/issue5438.cairo
Original file line number Diff line number Diff line change
@@ -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)
}
1 change: 1 addition & 0 deletions tests/bug_samples/lib.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 609cb7f

Please sign in to comment.