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

fix: let unary traits work at comptime #5507

Merged
merged 6 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@
}
} else {
let name = self.interner.function_name(&function);
unreachable!("Non-builtin, lowlevel or oracle builtin fn '{name}'")

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lowlevel)
}
}

Expand Down Expand Up @@ -593,6 +593,11 @@

fn evaluate_prefix(&mut self, prefix: HirPrefixExpression, id: ExprId) -> IResult<Value> {
let rhs = self.evaluate(prefix.rhs)?;

if self.interner.get_selected_impl_for_expression(id).is_some() {
return self.evaluate_overloaded_prefix(prefix, rhs, id);
}

self.evaluate_prefix_with_value(rhs, prefix.operator, id)
asterite marked this conversation as resolved.
Show resolved Hide resolved
}

Expand Down Expand Up @@ -925,6 +930,25 @@
}
}

fn evaluate_overloaded_prefix(
&mut self,
prefix: HirPrefixExpression,
rhs: Value,
id: ExprId,
) -> IResult<Value> {
let method =
prefix.trait_method_id.expect("ice: expected prefix operator trait at this point");
let operator = prefix.operator;

let method_id = resolve_trait_method(self.interner, method, id)?;
let type_bindings = self.interner.get_instantiation_bindings(id).clone();

let rhs = (rhs, self.interner.expr_location(&prefix.rhs));

let location = self.interner.expr_location(&id);
self.call_function(method_id, vec![rhs], type_bindings, location)
}

/// Given the result of a `cmp` operation, convert it into the boolean result of the given operator.
/// - `<`: `ordering == Ordering::Less`
/// - `<=`: `ordering != Ordering::Greater`
Expand Down
21 changes: 21 additions & 0 deletions test_programs/compile_success_empty/comptime_traits/src/main.nr
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::ops::Neg;

fn main() {
comptime
{
Expand All @@ -13,3 +15,22 @@ fn main() {
assert([1, 2] != array);
}
}

struct MyType {
value: i32,
}

impl Neg for MyType {
comptime fn neg(self) -> Self {
self
}
}

fn neg_at_comptime() {
comptime
{
let value = MyType { value: 1 };
let _result = -value;
}
}

Loading