Skip to content

Commit

Permalink
fix: Improve member access error (noir-lang#940)
Browse files Browse the repository at this point in the history
* Improve member access error

* Fix broken error

* cargo fmt

* Feedback
  • Loading branch information
jfecher authored Mar 10, 2023
1 parent 2ee0119 commit 9b5b5f6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
7 changes: 7 additions & 0 deletions crates/noirc_frontend/src/hir/type_check/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ pub enum TypeCheckError {
second_type: String,
second_index: usize,
},
#[error("Cannot infer type of expression, type annotations needed before this point")]
TypeAnnotationsNeeded { span: Span },
}

impl TypeCheckError {
Expand Down Expand Up @@ -96,6 +98,11 @@ impl From<TypeCheckError> for Diagnostic {
format!("return type is {typ}"),
span,
),
TypeCheckError::TypeAnnotationsNeeded { span } => Diagnostic::simple_error(
"Expression type is ambiguous".to_string(),
"Type must be known at this point".to_string(),
span,
),
}
}
}
9 changes: 7 additions & 2 deletions crates/noirc_frontend/src/hir/type_check/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ pub fn check_member_access(
expr_id: ExprId,
errors: &mut Vec<TypeCheckError>,
) -> Type {
let lhs_type = type_check_expression(interner, &access.lhs, errors);
let lhs_type = type_check_expression(interner, &access.lhs, errors).follow_bindings();

if let Type::Struct(s, args) = &lhs_type {
let s = s.borrow();
Expand All @@ -712,7 +712,12 @@ pub fn check_member_access(
}
}

if lhs_type != Type::Error {
// If we get here the type has no field named 'access.rhs'.
// Now we specialize the error message based on whether we know the object type in question yet.
if let Type::TypeVariable(..) = &lhs_type {
errors
.push(TypeCheckError::TypeAnnotationsNeeded { span: interner.expr_span(&access.lhs) });
} else if lhs_type != Type::Error {
errors.push(TypeCheckError::Unstructured {
msg: format!("Type {lhs_type} has no member named {}", access.rhs),
span: interner.expr_span(&access.lhs),
Expand Down

0 comments on commit 9b5b5f6

Please sign in to comment.