Skip to content

Commit

Permalink
fix: let trait calls work in globals (noir-lang#5602)
Browse files Browse the repository at this point in the history
# Description

## Problem

Resolves noir-lang#5029

## Summary

Trait constraints weren't checked after elaborating a global.

## Additional Context

I couldn't just call `check_and_pop_function_context()` because that
also defaults type variables... and if we do that the usage of a global
will not have an effect on its type. I guess this is one scenario:

```rust
global x = 1; // What's the type of x?
```

We don't know. I guess it ends up being `Field` later on (where?) But if
we have this:

```rust
global x = 1;

fn main() {
  let y: i32 = 0;
  assert_eq(x, y);
}
```

now x's type will be `i32` because of that comparison. So if we eagerly
bind `1` to its default type, this will break.

All of this to say: in Rust a global's type (well, for a `const`) must
be explicitly specified. I guess that if we also did that in Noir then
this wouldn't be a problem. And given that globals are, well, global, it
might be strange to have `global x = 1` expecting that to be a Field,
used as a Field in many places, but you accidentally compare it to an
`i32` and the type changes under the hood. But that's a bigger
discussion, so maybe the fix in this PR is good for now?

## Documentation\*

Check one:
- [x] No documentation needed.
- [ ] Documentation included in this PR.
- [ ] **[For Experimental Features]** Documentation to be submitted in a
separate PR.

# PR Checklist\*

- [x] I have tested the changes locally.
- [x] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.
  • Loading branch information
asterite authored Jul 25, 2024
1 parent fd7002c commit c02a6f6
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
1 change: 1 addition & 0 deletions compiler/noirc_frontend/src/elaborator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ impl<'context> Elaborator<'context> {
let (comptime_items, runtime_items) = Self::filter_comptime_items(items);
this.elaborate_items(comptime_items);
this.elaborate_items(runtime_items);
this.check_and_pop_function_context();
this
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "trait_call_in_global"
type = "bin"
authors = [""]

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
global s: BoundedVec<Field, 2> = From::from([0]);

fn main() {
let _ = s;
}

0 comments on commit c02a6f6

Please sign in to comment.