Skip to content
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
26 changes: 25 additions & 1 deletion compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,12 @@ impl<'a> Interpreter<'a> {
UnaryOp::MutableReference => self.evaluate_no_dereference(prefix.rhs)?,
_ => self.evaluate(prefix.rhs)?,
};
self.evaluate_prefix_with_value(rhs, prefix.operator, id)

if self.interner.get_selected_impl_for_expression(id).is_some() {
self.evaluate_overloaded_prefix(prefix, rhs, id)
} else {
self.evaluate_prefix_with_value(rhs, prefix.operator, id)
}
}

fn evaluate_prefix_with_value(
Expand Down Expand Up @@ -953,6 +958,25 @@ impl<'a> Interpreter<'a> {
}
}

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,
}

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

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