fix: improve error message of mismatched type

This commit is contained in:
Araozu 2024-11-03 11:25:22 -05:00
parent 469a9eaf5e
commit 6f56ab0b4d

View File

@ -4,7 +4,7 @@ use crate::{
impls::SemanticCheck, impls::SemanticCheck,
types::{Type, Typed}, types::{Type, Typed},
}, },
syntax::ast::var_binding::VariableBinding, syntax::ast::{var_binding::VariableBinding, Positionable},
}; };
impl SemanticCheck for VariableBinding<'_> { impl SemanticCheck for VariableBinding<'_> {
@ -46,18 +46,26 @@ impl SemanticCheck for VariableBinding<'_> {
// Both the declared & actual datatypes must be the same // Both the declared & actual datatypes must be the same
if datatype != expression_datatype { if datatype != expression_datatype {
let label = ErrorLabel { // This can only happen if the binding has an annotated type,
message: format!( // so its safe to unwrap here
"The variable `{}` was declared as `{:?}` but its expression has type `{:?}`", let datatype_token = self.datatype.unwrap();
binding_name, datatype, expression_datatype
), let label1 = ErrorLabel {
start: self.identifier.position, message: format!("The variable is declared as {:?} here", datatype),
end: self.identifier.get_end_position(), start: datatype_token.position,
end: datatype_token.get_end_position(),
}; };
let (expr_start, expr_end) = self.expression.get_position();
let label2 = ErrorLabel {
message: format!("But this expression has type {:?}", expression_datatype),
start: expr_start,
end: expr_end,
};
let econtainer = ErrorContainer { let econtainer = ErrorContainer {
error_code: SEMANTIC_DUPLICATED_REFERENCE, error_code: SEMANTIC_DUPLICATED_REFERENCE,
error_offset: self.identifier.position, error_offset: self.identifier.position,
labels: vec![label], labels: vec![label1, label2],
note: None, note: None,
help: None, help: None,
}; };