noir-lang / noir

Noir is a domain specific language for zero knowledge proofs
https://noir-lang.org
Apache License 2.0
821 stars 177 forks source link

comptime interpreter handles scopes incorrectly when calling builtin/foreign/oracle functions #5274

Closed TomAFrench closed 2 weeks ago

TomAFrench commented 2 weeks ago

The below program compiles just fine

fn main() {
    comptime {
        let ws: [Field; 1] = [1];
        let ws_as_slice: [Field] = ws.as_slice();

        assert_eq(ws_as_slice[0], 1);
    }
}

however if I change the assertion to act on ws rather than ws_as_slice then the program fails to compile with the error message below.

fn main() {
    comptime {
        let ws: [Field; 1] = [1];
        let ws_as_slice: [Field] = ws.as_slice();

        assert_eq(ws[0], 1);
    }
}
$ nargo compile
warning: unused variable ws_as_slice
  ┌─ /home/tom/Programming/aztec/noir/test_programs/compile_success_empty/comptime_as_slice/src/main.nr:4:13
  │
4 │         let ws_as_slice: [Field] = ws.as_slice();
  │             ----------- unused variable 
  │

error: Non-comptime variable `ws` referenced in comptime code
  ┌─ /home/tom/Programming/aztec/noir/test_programs/compile_success_empty/comptime_as_slice/src/main.nr:6:19
  │
6 │         assert_eq(ws[0], 1);
  │                   -- Non-comptime variables can't be used in comptime code
  │
TomAFrench commented 2 weeks ago

Actually, this seems to be specific to as_slice.

jfecher commented 2 weeks ago

@TomAFrench It is also because of the fact that any time a variable is not in scope the interpreter assumes the variable is not comptime. I'm not sure why it'd be happening here but we should probably make that error more general.

TomAFrench commented 2 weeks ago

I've fixed this issue in https://github.com/noir-lang/noir/pull/5276. We were performing an early return in the situation where we hit a builtin/foreign/oracle function so we missed the call to exit_function

jfecher commented 2 weeks ago

@TomAFrench Thanks, I was about to say I had this fixed as well yesterday but it looks like I never made the PR. We found the same issue though.