Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement closures in the comptime interpreter #5682

Merged
merged 1 commit into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,15 +219,14 @@
}
} else {
let name = self.elaborator.interner.function_name(&function);
unreachable!("Non-builtin, lowlevel or oracle builtin fn '{name}'")

Check warning on line 222 in compiler/noirc_frontend/src/hir/comptime/interpreter.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lowlevel)
}
}

fn call_closure(
&mut self,
closure: HirLambda,
// TODO: How to define environment here?
_environment: Vec<Value>,
environment: Vec<Value>,
arguments: Vec<(Value, Location)>,
call_location: Location,
) -> IResult<Value> {
Expand All @@ -246,6 +245,10 @@
self.define_pattern(parameter, typ, argument, arg_location)?;
}

for (param, arg) in closure.captures.into_iter().zip(environment) {
self.define(param.ident.id, arg);
}

let result = self.evaluate(closure.body)?;

self.exit_function(previous_state);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "comptime_closures"
type = "bin"
authors = [""]
compiler_version = ">=0.32.0"

[dependencies]
39 changes: 39 additions & 0 deletions test_programs/compile_success_empty/comptime_closures/src/main.nr
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
fn main() {
comptime
{
closure_test(0);
}
}

fn closure_test(mut x: Field) {
let one = 1;
let add1 = |z| {
(|| {
*z += one;
})()
};

let two = 2;
let add2 = |z| {
*z = *z + two;
};

add1(&mut x);
assert(x == 1);

add2(&mut x);
assert(x == 3);

issue_2120();
}

fn issue_2120() {
let x1 = &mut 42;
let set_x1 = |y| { *x1 = y; };

assert(*x1 == 42);
set_x1(44);
assert(*x1 == 44);
set_x1(*x1);
assert(*x1 == 44);
}
Loading