Skip to content

Commit

Permalink
fixed modifying closure mutable params
Browse files Browse the repository at this point in the history
  • Loading branch information
TomerStarkware committed Jan 14, 2025
1 parent 872a69f commit 122cfdf
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 0 deletions.
5 changes: 5 additions & 0 deletions crates/cairo-lang-semantic/src/expr/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1663,6 +1663,11 @@ fn compute_expr_closure_semantic(
} else {
vec![]
};

new_ctx
.semantic_defs
.extend(new_ctx.environment.variables.iter().map(|(_, var)| (var.id(), var.clone())));

let return_type = match syntax.ret_ty(syntax_db) {
OptionReturnTypeClause::ReturnTypeClause(ty_syntax) => resolve_type_with_environment(
new_ctx.db,
Expand Down
25 changes: 25 additions & 0 deletions crates/cairo-lang-semantic/src/expr/test_data/closure
Original file line number Diff line number Diff line change
Expand Up @@ -718,3 +718,28 @@ error: Trait `core::ops::function::FnOnce` should not be re-implemented.
--> lib.cairo:1:16
impl MyImpl of core::ops::FnOnce<u32, ()> {
^^^^^^^^^^^^^^^^^^^^^^^^^^

//! > ==========================================================================

//! > Mutating non mutable closure param.

//! > test_runner_name
test_function_diagnostics(expect_diagnostics: true)

//! > function
fn foo() {
let _ = |a| {
a = a + 2
};
}

//! > function_name
foo

//! > module_code

//! > expected_diagnostics
error: Cannot assign to an immutable variable.
--> lib.cairo:3:9
a = a + 2
^^^^^^^^^
8 changes: 8 additions & 0 deletions crates/cairo-lang-utils/src/unordered_hash_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,11 @@ impl<Key: Hash + Eq, Value, const N: usize, BH: BuildHasher + Default> From<[(Ke
Self(HashMap::from_iter(items))
}
}

impl<Key: Hash + Eq, Value, BH: BuildHasher> Extend<(Key, Value)>
for UnorderedHashMap<Key, Value, BH>
{
fn extend<T: IntoIterator<Item = (Key, Value)>>(&mut self, iter: T) {
self.0.extend(iter)
}
}
17 changes: 17 additions & 0 deletions tests/bug_samples/issue7071.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
fn call_with<F, +Drop<F>, +core::ops::Fn<F, (A,)>[Output: usize]>(func: F) -> usize {
func(A { inner: array![] })
}


#[derive(Drop)]
struct A {
inner: Array<usize>,
}

fn main() {
let aclosure = |mut a: A| {
a.inner.append(3);
*a.inner[0]
};
call_with(aclosure);
}
1 change: 1 addition & 0 deletions tests/bug_samples/lib.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ mod issue6968;
mod issue7031;
mod issue7038;
mod issue7060;
mod issue7071;
mod loop_break_in_match;
mod loop_only_change;
mod partial_param_local;
Expand Down

0 comments on commit 122cfdf

Please sign in to comment.