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: error on duplicate struct field #5585

Merged
merged 6 commits into from
Jul 23, 2024
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
28 changes: 27 additions & 1 deletion compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,8 @@
}

/// Collect any struct definitions declared within the ast.
/// Returns a vector of errors if any structs were already defined.
/// Returns a vector of errors if any structs were already defined,
/// or if a struct has duplicate fields in it.
fn collect_structs(
&mut self,
context: &mut Context,
Expand All @@ -271,6 +272,8 @@
) -> Vec<(CompilationError, FileId)> {
let mut definition_errors = vec![];
for struct_definition in types {
self.check_duplicate_field_names(&struct_definition, &mut definition_errors);

let name = struct_definition.name.clone();

let unresolved = UnresolvedStruct {
Expand Down Expand Up @@ -330,6 +333,29 @@
definition_errors
}

fn check_duplicate_field_names(
&self,
struct_definition: &NoirStruct,
definition_errors: &mut Vec<(CompilationError, FileId)>,
) {
let mut seen_field_names = std::collections::HashSet::new();
for (field_name, _) in &struct_definition.fields {
if seen_field_names.insert(field_name) {
continue;
}

let previous_field_name = *seen_field_names.get(field_name).unwrap();
definition_errors.push((
DefCollectorErrorKind::DuplicateField {
first_def: previous_field_name.clone(),
second_def: field_name.clone(),
}
.into(),
self.file_id,
));
}
}

/// Collect any type aliases definitions declared within the ast.
/// Returns a vector of errors if any type aliases were already defined.
fn collect_type_aliases(
Expand Down Expand Up @@ -514,7 +540,7 @@
}
}
TraitItem::Type { name } => {
// TODO(nickysn or alexvitkov): implement context.def_interner.push_empty_type_alias and get an id, instead of using TypeAliasId::dummy_id()

Check warning on line 543 in compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (nickysn)

Check warning on line 543 in compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (alexvitkov)
if let Err((first_def, second_def)) = self.def_collector.def_map.modules
[trait_id.0.local_id.0]
.declare_type_alias(name.clone(), TypeAliasId::dummy_id())
Expand Down Expand Up @@ -700,7 +726,7 @@
// if it's an inline module, or the first char of a the file if it's an external module.
// - `location` will always point to the token "foo" in `mod foo` regardless of whether
// it's inline or external.
// Eventually the location put in `ModuleData` is used for codelenses about `contract`s,

Check warning on line 729 in compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (codelenses)
// so we keep using `location` so that it continues to work as usual.
let location = Location::new(mod_name.span(), mod_location.file);
let new_module = ModuleData::new(parent, location, is_contract);
Expand Down
19 changes: 19 additions & 0 deletions compiler/noirc_frontend/src/hir/def_collector/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub enum DuplicateType {
pub enum DefCollectorErrorKind {
#[error("duplicate {typ} found in namespace")]
Duplicate { typ: DuplicateType, first_def: Ident, second_def: Ident },
#[error("duplicate struct field {first_def}")]
DuplicateField { first_def: Ident, second_def: Ident },
#[error("unresolved import")]
UnresolvedModuleDecl { mod_name: Ident, expected_path: String, alternative_path: String },
#[error("overlapping imports")]
Expand Down Expand Up @@ -132,6 +134,23 @@ impl<'a> From<&'a DefCollectorErrorKind> for Diagnostic {
diag
}
}
DefCollectorErrorKind::DuplicateField { first_def, second_def } => {
let primary_message = format!(
"Duplicate definitions of struct field with name {} found",
&first_def.0.contents
);
{
let first_span = first_def.0.span();
let second_span = second_def.0.span();
let mut diag = Diagnostic::simple_error(
primary_message,
"First definition found here".to_string(),
first_span,
);
diag.add_secondary("Second definition found here".to_string(), second_span);
diag
}
}
DefCollectorErrorKind::UnresolvedModuleDecl { mod_name, expected_path, alternative_path } => {
let span = mod_name.0.span();
let mod_name = &mod_name.0.contents;
Expand Down
28 changes: 28 additions & 0 deletions compiler/noirc_frontend/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2309,7 +2309,7 @@
}

#[test]
fn underflowing_u8() {

Check warning on line 2312 in compiler/noirc_frontend/src/tests.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (underflowing)
let src = r#"
fn main() {
let _: u8 = -1;
Expand Down Expand Up @@ -2347,7 +2347,7 @@
}

#[test]
fn underflowing_i8() {

Check warning on line 2350 in compiler/noirc_frontend/src/tests.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (underflowing)
let src = r#"
fn main() {
let _: i8 = -129;
Expand Down Expand Up @@ -2494,3 +2494,31 @@
"#;
assert_no_errors(src);
}

#[test]
fn duplicate_struct_field() {
let src = r#"
struct Foo {
x: i32,
x: i32,
}

fn main() {}
"#;
let errors = get_program_errors(src);
assert_eq!(errors.len(), 1);

let CompilationError::DefinitionError(DefCollectorErrorKind::DuplicateField {
first_def,
second_def,
}) = &errors[0].0
else {
panic!("Expected a duplicate field error, got {:?}", errors[0].0);
};

assert_eq!(first_def.to_string(), "x");
assert_eq!(second_def.to_string(), "x");

assert_eq!(first_def.span().start(), 26);
assert_eq!(second_def.span().start(), 42);
}
Loading