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 unbound generics in structs #5619

Merged
merged 5 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
130 changes: 123 additions & 7 deletions compiler/noirc_frontend/src/monomorphization/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,8 +383,8 @@ impl<'interner> Monomorphizer<'interner> {
self.parameter(field, &typ, new_params)?;
}
}
HirPattern::Struct(_, fields, _) => {
let struct_field_types = unwrap_struct_type(typ);
HirPattern::Struct(_, fields, location) => {
let struct_field_types = unwrap_struct_type(typ, *location)?;
assert_eq!(struct_field_types.len(), fields.len());

let mut fields =
Expand Down Expand Up @@ -663,8 +663,10 @@ impl<'interner> Monomorphizer<'interner> {
constructor: HirConstructorExpression,
id: node_interner::ExprId,
) -> Result<ast::Expression, MonomorphizationError> {
let location = self.interner.expr_location(&id);

let typ = self.interner.id_type(id);
let field_types = unwrap_struct_type(&typ);
let field_types = unwrap_struct_type(&typ, location)?;

let field_type_map = btree_map(&field_types, |x| x.clone());

Expand Down Expand Up @@ -740,8 +742,8 @@ impl<'interner> Monomorphizer<'interner> {
let fields = unwrap_tuple_type(typ);
self.unpack_tuple_pattern(value, patterns.into_iter().zip(fields))
}
HirPattern::Struct(_, patterns, _) => {
let fields = unwrap_struct_type(typ);
HirPattern::Struct(_, patterns, location) => {
let fields = unwrap_struct_type(typ, location)?;
assert_eq!(patterns.len(), fields.len());

let mut patterns =
Expand Down Expand Up @@ -975,12 +977,37 @@ impl<'interner> Monomorphizer<'interner> {
}

HirType::Struct(def, args) => {
// Even though we later call `convert_type` on `fields`, it might be the types
// in `args` end up not being part of fields. For example:
//
// struct Foo<let N: u32> {}
//
// fn main() {
// let _ = Foo {};
// }
//
// In the above case args is `[N]` but fields is `[]`, so T will never be checked.
// However, we want the above program to not compile.
asterite marked this conversation as resolved.
Show resolved Hide resolved
for arg in args {
if let Some(error) = Self::check_type(arg, location) {
return Err(error);
}
asterite marked this conversation as resolved.
Show resolved Hide resolved
}

let fields = def.borrow().get_fields(args);
let fields = try_vecmap(fields, |(_, field)| Self::convert_type(&field, location))?;
ast::Type::Tuple(fields)
}

HirType::Alias(def, args) => {
// Similar to the struct case above: generics of an alias might not end up being
// used in the type that is aliased.
for arg in args {
if let Some(error) = Self::check_type(arg, location) {
return Err(error);
}
}

Self::convert_type(&def.borrow().get_type(args), location)?
}

Expand Down Expand Up @@ -1019,6 +1046,83 @@ impl<'interner> Monomorphizer<'interner> {
})
}

// Similar to `convert_type` but returns an error if any type variable can't be defaulted.
fn check_type(typ: &HirType, location: Location) -> Option<MonomorphizationError> {
jfecher marked this conversation as resolved.
Show resolved Hide resolved
match typ {
HirType::FieldElement
| HirType::Integer(..)
| HirType::Bool
| HirType::String(..)
| HirType::Unit
| HirType::TraitAsType(..)
| HirType::Forall(_, _)
| HirType::Constant(_)
| HirType::Error
| HirType::Quoted(_) => None,
HirType::FmtString(_size, fields) => Self::check_type(fields.as_ref(), location),
HirType::Array(_length, element) => Self::check_type(element.as_ref(), location),
HirType::Slice(element) => Self::check_type(element.as_ref(), location),
HirType::NamedGeneric(binding, _, _) => {
if let TypeBinding::Bound(binding) = &*binding.borrow() {
return Self::check_type(binding, location);
}

None
}

HirType::TypeVariable(binding, kind) => {
if let TypeBinding::Bound(binding) = &*binding.borrow() {
return Self::check_type(binding, location);
}

// Default any remaining unbound type variables.
// This should only happen if the variable in question is unused
// and within a larger generic type.
let default = match kind.default_type() {
Some(typ) => typ,
None => return Some(MonomorphizationError::TypeAnnotationsNeeded { location }),
};

Self::check_type(&default, location)
}

HirType::Struct(_def, args) => {
for arg in args {
Self::check_type(arg, location)?;
}

None
}

HirType::Alias(_def, args) => {
for arg in args {
Self::check_type(arg, location)?;
}

None
}

HirType::Tuple(fields) => {
for field in fields {
Self::check_type(field, location)?;
}

None
}

HirType::Function(args, ret, env) => {
for arg in args {
Self::check_type(arg, location)?;
}

Self::check_type(ret, location)?;
Self::check_type(env, location)
}

HirType::MutableReference(element) => Self::check_type(element, location),
}
}

fn is_function_closure(&self, t: ast::Type) -> bool {
if self.is_function_closure_type(&t) {
true
Expand Down Expand Up @@ -1753,9 +1857,21 @@ fn unwrap_tuple_type(typ: &HirType) -> Vec<HirType> {
}
}

fn unwrap_struct_type(typ: &HirType) -> Vec<(String, HirType)> {
fn unwrap_struct_type(
typ: &HirType,
location: Location,
) -> Result<Vec<(String, HirType)>, MonomorphizationError> {
match typ.follow_bindings() {
HirType::Struct(def, args) => def.borrow().get_fields(&args),
HirType::Struct(def, args) => {
// Some of args might not be mentioned in fields, so we need to check that they aren't unbound.
for arg in &args {
if let Some(error) = Monomorphizer::check_type(arg, location) {
return Err(error);
}
}

Ok(def.borrow().get_fields(&args))
}
other => unreachable!("unwrap_struct_type: expected struct, found {:?}", other),
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "type_annotation_needed_on_struct_constructor"
type = "bin"
authors = [""]
compiler_version = ">=0.31.0"

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
struct Foo<T> {
}

fn main() {
let foo = Foo {};
}
asterite marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "type_annotation_needed_on_struct_new"
type = "bin"
authors = [""]
compiler_version = ">=0.31.0"

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
struct Foo<T> {
}

impl <T> Foo<T> {
fn new() -> Foo<T> {
Foo {}
}
}

fn main() {
let foo = Foo::new();
}
Loading