Skip to content

Commit

Permalink
fix: let derive(Eq) work for empty structs (#5965)
Browse files Browse the repository at this point in the history
# Description

## Problem

While playing around with the derive attribute I noticed `derive(Eq)`
fails to compile for an empty struct.

## Summary

Fixes the above.

## Additional Context



## 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 Sep 6, 2024
1 parent b9a072d commit ff8e8b5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 7 additions & 1 deletion noir_stdlib/src/cmp.nr
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ trait Eq {
comptime fn derive_eq(s: StructDefinition) -> Quoted {
let signature = quote { fn eq(_self: Self, _other: Self) -> bool };
let for_each_field = |name| quote { (_self.$name == _other.$name) };
let body = |fields| fields;
let body = |fields| {
if s.fields().len() == 0 {
quote { true }
} else {
fields
}
};
crate::meta::make_trait_impl(s, quote { Eq }, signature, for_each_field, quote { & }, body)
}
// docs:end:derive_eq
Expand Down
6 changes: 6 additions & 0 deletions test_programs/execution_success/derive/src/main.nr
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ struct MyOtherOtherStruct<T> {
x: T,
}

#[derive(Eq, Default, Hash, Ord)]
struct EmptyStruct { }

fn main() {
let s = MyStruct { my_field: 1 };
s.do_nothing();
Expand All @@ -53,6 +56,9 @@ fn main() {
let mut hasher = TestHasher { result: 0 };
o1.hash(&mut hasher);
assert_eq(hasher.finish(), 12 + 24 + 54);

let empty = EmptyStruct {};
assert_eq(empty, empty);
}

struct TestHasher {
Expand Down

0 comments on commit ff8e8b5

Please sign in to comment.