From 09906381f47a7ef20f04a58530ca3c2c532775f1 Mon Sep 17 00:00:00 2001 From: Tim Fennis Date: Sun, 29 Nov 2026 21:17:33 +0100 Subject: [PATCH] =?UTF-8?q?feat(analyser):=20point=20a=20write=20that=20do?= =?UTF-8?q?esn't=20fit=20at=20its=20declaration=20=F0=9F=93=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An assignment, an annotated let or a return that doesn't fit names the variable or function, labels the value, and notes where its type is declared. The help that explained the rule is gone or cut to one line. Co-Authored-By: Claude Opus 5.5 --- manual/src/reference/types.md | 2 +- manual/src/reference/types/function.md | 2 +- manual/src/reference/types/number.md | 2 +- manual/src/reference/variables-and-scopes.md | 4 +- ndc_analyser/src/analyser/assignments.rs | 91 +++++++++++++------ ndc_analyser/src/analyser/declarations.rs | 19 ++-- ndc_analyser/src/analyser/mod.rs | 21 +++-- ndc_analyser/src/analyser/solver.rs | 2 +- ndc_analyser/src/analyser/tests.rs | 79 +++++++++++++--- ndc_analyser/src/error.rs | 79 +++++++++++++++- ndc_lsp/src/document.rs | 6 +- ndc_resolver/src/name_resolution.rs | 13 ++- .../047_annotated_let_type_mismatch.ndc | 2 +- .../049_annotated_let_type_mismatch_list.ndc | 2 +- .../050_annotated_let_type_mismatch_tuple.ndc | 2 +- .../052_annotated_let_rejects_supertype.ndc | 2 +- ...54_annotated_let_reassignment_rejected.ndc | 2 +- .../070_a_variable_keeps_its_type.ndc | 2 +- .../071_some_has_the_type_of_its_value.ndc | 2 +- .../086_a_placeholder_is_an_option.ndc | 2 +- .../087_a_variable_holds_one_type.ndc | 4 +- .../038_return_type_annotation_mismatch.ndc | 2 +- ...otated_return_type_checks_every_return.ndc | 2 +- ...h_a_lambda_is_blamed_at_the_assignment.ndc | 2 +- ...a_loop_variable_keeps_the_element_type.ndc | 2 +- .../015_let_annotation_mismatch.ndc | 2 +- .../015_struct/016_nominal_annotation.ndc | 2 +- .../002_an_annotated_let_takes_no_any.ndc | 2 +- .../003_an_assignment_takes_no_any.ndc | 2 +- .../004_a_destructuring_takes_no_any.ndc | 2 +- ...terals_of_different_types_are_an_error.ndc | 2 +- ...12_a_list_of_ints_is_not_a_list_of_any.ndc | 2 +- ...ecome_a_float_to_reach_an_any_overload.ndc | 2 +- ...e_no_type_stored_as_an_any_take_a_cast.ndc | 2 +- ...on_returning_any_gives_no_typed_values.ndc | 2 +- ...ng_an_int_is_not_a_function_taking_any.ndc | 2 +- ..._callback_returning_a_tuple_is_checked.ndc | 2 +- .../003_an_element_has_its_own_type.ndc | 2 +- ...onto_a_tuple_variable_changes_its_type.ndc | 2 +- ..._destructuring_assignment_checks_types.ndc | 2 +- ...0044_if_joined_after_fallbacks_in_list.ndc | 2 +- 41 files changed, 287 insertions(+), 93 deletions(-) diff --git a/manual/src/reference/types.md b/manual/src/reference/types.md index 51307275..fa8ad923 100644 --- a/manual/src/reference/types.md +++ b/manual/src/reference/types.md @@ -104,7 +104,7 @@ Anything can go into an `Any`, but to get a value back out you need a [cast](../ ```ndc,fails let a: Any = 5; -let n: Int = a; // error: mismatched types: found Any but expected Int +let n: Int = a; // error: can't assign an Any to `n`, which holds an Int ``` ```ndc diff --git a/manual/src/reference/types/function.md b/manual/src/reference/types/function.md index 91b73e7b..f5379116 100644 --- a/manual/src/reference/types/function.md +++ b/manual/src/reference/types/function.md @@ -147,7 +147,7 @@ print(count([1, 2])); // 2 If the body returns a value that doesn't fit the return type, you get an error before the program runs: ```ndc,fails -fn bad() -> Int { "hello" } // error: mismatched types +fn bad() -> Int { "hello" } // error: can't return a String from `bad`, which returns an Int ``` A function that returns values of different types, like a String in one place and an Int in another, has to say that it returns `Any`: diff --git a/manual/src/reference/types/number.md b/manual/src/reference/types/number.md index 521d900f..b2fe131d 100644 --- a/manual/src/reference/types/number.md +++ b/manual/src/reference/types/number.md @@ -61,7 +61,7 @@ A variable keeps the type it starts with, so one that starts at `0` stays an `In let total = 0.0; total += 2.5; // fine: total is a Float let count = 0; -count += 2.5; // error: mismatched types: found Float but expected Int +count += 2.5; // error: can't assign a Float to `count`, which holds an Int ``` Arbitrary-radix literals such as `16r2a` remain `Int` literals and do not accept `n`. The `i` and `j` suffixes create complex `Number` values: diff --git a/manual/src/reference/variables-and-scopes.md b/manual/src/reference/variables-and-scopes.md index 0d26198c..3e69c072 100644 --- a/manual/src/reference/variables-and-scopes.md +++ b/manual/src/reference/variables-and-scopes.md @@ -47,7 +47,7 @@ The `=` operator assigns a new value to an existing variable. A variable keeps t ```ndc,fails let n = 1; // n is an Int n = 2; // fine -n = 3.14; // error: mismatched types: found Float but expected Int +n = 3.14; // error: can't assign a Float to `n`, which holds an Int ``` So to keep a running total of Floats, start it at `0.0` rather than `0`. The same goes for [augmented assignment](../features/augmented-assignment.md), like `n += 0.5`. @@ -88,7 +88,7 @@ print(count, name, xs); // 0 world [1,2,3] ``` ```ndc,fails -let x: Int = "hello"; // ERROR: mismatched types: found String but expected Int +let x: Int = "hello"; // ERROR: can't assign a String to `x`, which holds an Int ``` An annotation is the way to say what an empty list or map will hold: diff --git a/ndc_analyser/src/analyser/assignments.rs b/ndc_analyser/src/analyser/assignments.rs index 3cc11b33..ee3dee90 100644 --- a/ndc_analyser/src/analyser/assignments.rs +++ b/ndc_analyser/src/analyser/assignments.rs @@ -148,7 +148,7 @@ impl Analyser { span: Span, ) { if !self.accepts_write(stored_type, value_type) { - self.emit_rejected_write(stored_type, value_type, span, false); + self.emit_rejected_write(stored_type, value_type, span, None); } } @@ -157,14 +157,15 @@ impl Analyser { /// of `if c { 1 } else { "a" }`, are reported as such once they're /// settled, unless a later use makes them `Any`s, as `let v: Any = …` /// does, so their write is checked again then. - /// `into_variable` says it's an assignment to a variable, which the help - /// then explains. + /// `target` is what's written, if it's a variable or what a function + /// returns, which the error names and points back to the declaration + /// of. pub(super) fn emit_rejected_write( &mut self, stored_type: &StaticType, value_type: &StaticType, span: Span, - into_variable: bool, + target: Option, ) { if let StaticType::Var(var) = self.vars.resolve(value_type) && self.vars.is_literal(var) @@ -174,38 +175,45 @@ impl Analyser { stored_type: stored_type.clone(), value_type: value_type.clone(), span, + target, recording: self.recording, copied_through: self.copied_through.clone(), }); return; } - let mut error = AnalysisError::mismatched_types( - &self.vars.shown(value_type), - &self.vars.shown(stored_type), - span, - ); + let found = self.vars.shown(value_type); + let expected = self.vars.shown(stored_type); + let into_variable = matches!(target, Some(WriteTarget::Variable(_))); + let mut error = match target { + Some(WriteTarget::Variable(variable)) => AnalysisError::assigned_to_variable( + self.resolver.symbol_name(variable), + &found, + &expected, + span, + self.resolver.declared_at(variable), + ), + Some(WriteTarget::Return { + function, + annotation, + }) => AnalysisError::returned_from_function( + function.as_deref(), + &found, + &expected, + span, + annotation, + ), + None => AnalysisError::mismatched_types(&found, &expected, span), + }; let value_is_a_number = matches!( - self.vars.shown(value_type), + found, StaticType::Int | StaticType::Float | StaticType::Number ); - let stored = self.vars.resolve(stored_type); if self.vars.has_number_literal(stored_type) && value_is_a_number { + error = error + .with_help("A number written without a `.` is an Int, as `0`; `0.0` is a Float"); + } else if into_variable && self.vars.resolve(stored_type) == StaticType::unit() { error = error.with_help( - "A number written without a `.` is an Int, and a variable holds what it's \ - given first: write it as a Float, as in `let total = 0.0`, or annotate the \ - variable, as in `let total: Float = 0`", - ); - } else if into_variable && stored == StaticType::unit() { - error = error.with_help( - "`()` holds nothing, and a variable holds what it's given first. A value that \ - only comes later is an `Option`: start with `None` and write `Some(…)`, as in \ - `let best = None;` and `best = Some(x)`", - ); - } else if into_variable { - error = error.with_help( - "A variable holds one type, the type of what it's given first. Use a new name \ - for a value of another type, or annotate the variable with `Any` to hold values \ - of different types, as in `let x: Any = 1`", + "For a value that only comes later, start with `None` and assign `Some(…)`", ); } self.emit(error); @@ -231,7 +239,14 @@ impl Analyser { } let recording = std::mem::replace(&mut self.recording, write.recording); let copied_through = std::mem::replace(&mut self.copied_through, write.copied_through); - self.check_write(&write.stored_type, &write.value_type, write.span); + if !self.accepts_write(&write.stored_type, &write.value_type) { + self.emit_rejected_write( + &write.stored_type, + &write.value_type, + write.span, + write.target, + ); + } self.recording = recording; self.copied_through = copied_through; } @@ -250,10 +265,12 @@ impl Analyser { ) { self.solve_waiting(); match &lvalue.target { - // A variable's error says how its type is decided. + // A variable's error names it and points at its declaration. AssignmentTarget::Identifier { .. } => { if !self.accepts_write(stored_type, value_type) { - self.emit_rejected_write(stored_type, value_type, span, true); + let variable = self.resolver.assigned_symbol(lvalue.id); + let target = Some(WriteTarget::Variable(variable)); + self.emit_rejected_write(stored_type, value_type, span, target); } } AssignmentTarget::Member { .. } | AssignmentTarget::Index { .. } => { @@ -273,12 +290,28 @@ impl Analyser { } } +/// What a write that doesn't fit stores into, when its error names it and +/// points back to where its type is declared. +#[derive(Debug, Clone)] +pub(super) enum WriteTarget { + /// A variable a `let` or an assignment writes, as `x` in `x = "a"`. + Variable(SymbolId), + /// What a function returns, as annotated at `annotation`: `-> Int` in + /// `fn f() -> Int { "a" }`. `function` is its name, if it has one. + Return { + function: Option, + annotation: Span, + }, +} + /// A write of values that share no type, put off until they're settled. #[derive(Debug)] pub(super) struct DeferredWrite { stored_type: StaticType, value_type: StaticType, span: Span, + /// What's written, if the error names it. + target: Option, recording: Option, copied_through: Option, } diff --git a/ndc_analyser/src/analyser/declarations.rs b/ndc_analyser/src/analyser/declarations.rs index 079ffde9..aa25e30d 100644 --- a/ndc_analyser/src/analyser/declarations.rs +++ b/ndc_analyser/src/analyser/declarations.rs @@ -1,3 +1,4 @@ +use super::assignments::WriteTarget; use super::generics::{BodyStart, Generalizing}; use super::solver::Constraint; use super::{Analyser, Returns}; @@ -175,7 +176,10 @@ impl Analyser { } self.return_type_stack.push(Returns { - annotated: annotated_return.clone(), + function: name.map(str::to_string), + annotated: annotated_return + .clone() + .zip(return_annotation.map(TypeExpr::span)), joined: None, }); // A function body starts outside of any loop: `break` can't @@ -218,7 +222,7 @@ impl Analyser { )); self.vars.unify(returns, &StaticType::Error); } else { - self.emit_rejected_write(returns, &inferred_return, span, false); + self.emit_rejected_write(returns, &inferred_return, span, None); } } @@ -491,16 +495,19 @@ impl Analyser { span: Span, ) { match &lvalue.pattern { - BindingPattern::Identifier { span, .. } => { + BindingPattern::Identifier { .. } => { // The value is checked like an assignment to the annotated // variable, so `let o: Option = None` settles `None`. - if let Some(expected_type) = &expected_type { - self.check_write(expected_type, &found_type, *span); + let symbol = self.resolver.declared_symbol(lvalue.id); + if let Some(expected_type) = &expected_type + && !self.accepts_write(expected_type, &found_type) + { + let target = Some(WriteTarget::Variable(symbol)); + self.emit_rejected_write(expected_type, &found_type, span, target); } // An annotation decides the type, or else the value does. let typ = expected_type.unwrap_or(found_type); - let symbol = self.resolver.declared_symbol(lvalue.id); self.types.declare(symbol, typ.clone()); self.picks.variables.insert(lvalue.id, symbol); self.result.analysis.variable_types.insert(lvalue.id, typ); diff --git a/ndc_analyser/src/analyser/mod.rs b/ndc_analyser/src/analyser/mod.rs index c67aade8..bb439957 100644 --- a/ndc_analyser/src/analyser/mod.rs +++ b/ndc_analyser/src/analyser/mod.rs @@ -21,7 +21,7 @@ pub(crate) mod generics; mod instances; mod solver; -use assignments::DeferredWrite; +use assignments::{DeferredWrite, WriteTarget}; use declarations::FunctionDeclaration; pub use generics::tied_natives; use instances::{Cast, GenericUse, Pending, Scheme}; @@ -176,8 +176,10 @@ pub struct Analyser { /// What a function returns. #[derive(Debug)] pub(super) struct Returns { - /// Its annotated return type. - annotated: Option, + /// Its name, if it has one. + function: Option, + /// Its annotated return type, with where the annotation is. + annotated: Option<(StaticType, Span)>, /// The type its values have in common, without an annotation, with /// where the first of them is. joined: Option<(StaticType, Span)>, @@ -698,7 +700,8 @@ impl Analyser { Expression::Assignment { l_value, r_value } => { let old_type = self.analyse_assignment_target(l_value, *span); let new_type = self.analyse_expr(r_value); - self.validate_assignment_write(l_value, &old_type, &new_type, *span); + // A write that doesn't fit is the value's error. + self.validate_assignment_write(l_value, &old_type, &new_type, r_value.span); StaticType::unit() } @@ -1105,8 +1108,14 @@ impl Analyser { /// type, and each value it returns has to fit it. Without one, it /// returns the type its values join as, as with [`Self::join`]. fn add_return(&mut self, returns: &mut Returns, value: &ExpressionLocation, typ: StaticType) { - if let Some(annotated) = &returns.annotated { - self.check_write(annotated, &typ, value.span); + if let Some((annotated, annotation)) = &returns.annotated { + if !self.accepts_write(annotated, &typ) { + let target = WriteTarget::Return { + function: returns.function.clone(), + annotation: *annotation, + }; + self.emit_rejected_write(annotated, &typ, value_span(value), Some(target)); + } return; } returns.joined = Some(match returns.joined.take() { diff --git a/ndc_analyser/src/analyser/solver.rs b/ndc_analyser/src/analyser/solver.rs index 093bee3b..2aa6da56 100644 --- a/ndc_analyser/src/analyser/solver.rs +++ b/ndc_analyser/src/analyser/solver.rs @@ -1240,7 +1240,7 @@ impl Analyser { // that doesn't fit. The write fails the same way and // isn't reported again. CallSite::Getter(id) if !self.accepts_write(&result, &typ) => { - self.emit_rejected_write(&typ, &result, call.span, false); + self.emit_rejected_write(&typ, &result, call.span, None); self.failed_reads.insert(id); } CallSite::Getter(_) => {} diff --git a/ndc_analyser/src/analyser/tests.rs b/ndc_analyser/src/analyser/tests.rs index 4a6fb430..0b50e1ca 100644 --- a/ndc_analyser/src/analyser/tests.rs +++ b/ndc_analyser/src/analyser/tests.rs @@ -101,7 +101,7 @@ fn destructuring_assignment_checks_each_target() { assert_analysis_error( "let a: Int = 1; let b = 2; (a, b) = (\"s\", 2);", vec![], - "mismatched types", + "can't assign a String to `a`, which holds an Int", ); assert_analysis_error( "let a = 1; let b = 2; (a, b) = (1, 2, 3);", @@ -187,7 +187,7 @@ fn annotated_identifier_augmented_assignment_rejects_widening() { assert_analysis_error( "let x: Int = 3; x += 0.5;", vec![("+".to_string(), add)], - "mismatched types: found Float but expected Int", + "can't assign a Float to `x`, which holds an Int", ); } @@ -253,7 +253,7 @@ fn annotated_declaration_rejects_a_mismatched_container_literal() { assert_analysis_error( "let x: %{Int: Int} = %{\"a\": 1};", vec![], - "mismatched types: found %{String: Int} but expected %{Int: Int}", + "can't assign a %{String: Int} to `x`, which holds a %{Int: Int}", ); } @@ -469,14 +469,15 @@ fn a_variable_keeps_its_inferred_type() { .concat(); let scalar = "mismatched types: found Float but expected Int"; let list = "mismatched types: found [Float] but expected [Int]"; + let variable = |name| format!("can't assign a Float to `{name}`, which holds an Int"); for (source, expected) in [ - ("let x = one(); x = 0.5;", scalar), - ("let x = one(); x += 0.5;", scalar), + ("let x = one(); x = 0.5;", &*variable("x")), + ("let x = one(); x += 0.5;", &variable("x")), ( "let a = one(); let b = one(); (a, b) = (0.5, one());", - scalar, + &variable("a"), ), - ("for x in [one()] { x = 0.5; }", scalar), + ("for x in [one()] { x = 0.5; }", &variable("x")), ("let values = [one()]; values[0] = 0.5;", scalar), ("let values = [one()]; values[0..1] = [0.5];", list), ("let values = [one()]; values[0] += 0.5;", scalar), @@ -500,7 +501,7 @@ fn an_any_value_takes_a_cast_to_be_stored_in_a_typed_variable() { )]; assert_eq!( errors("let x = 3; x = anything(); x", any_value.clone()), - vec!["mismatched types: found Any but expected Int"] + vec!["can't assign an Any to `x`, which holds an Int"] ); assert_eq!( analyse_last_type_with_globals( @@ -667,7 +668,7 @@ fn a_function_annotation_types_a_variable() { ); assert_eq!( errors("let f: fn(Int) -> Int = fn(x: String) => x;", vec![]), - vec!["mismatched types: found fn(String) -> String but expected fn(Int) -> Int"] + vec!["can't assign a fn(String) -> String to `f`, which holds a fn(Int) -> Int"] ); } @@ -1089,7 +1090,7 @@ fn a_field_write_settles_the_receiver_like_a_field_read() { fn an_error_shows_what_isnt_known_yet_as_unknown() { assert_eq!( errors("let f = fn(x) -> Int { [x] };", vec![]), - vec!["mismatched types: found [Unknown] but expected Int"] + vec!["can't return a [Unknown] from a function that returns an Int"] ); } @@ -1299,7 +1300,7 @@ fn a_return_annotation_settles_what_the_body_left_unknown() { // Each value returned has to fit the annotation. assert_eq!( errors("fn f(x) -> Int { if x { return \"s\"; } 1 }", vec![]), - vec!["mismatched types: found String but expected Int"] + vec!["can't return a String from `f`, which returns an Int"] ); } @@ -1595,6 +1596,60 @@ fn values_that_share_no_type_are_each_labelled() { ); } +// An assignment that doesn't fit its variable is the value's error, with a +// note at the name whose declaration gave the variable its type. +#[test] +fn an_assignment_that_does_not_fit_points_at_the_declaration() { + let source = "let a, b = 0, 0;\nb = \"x\";"; + let (_, result) = analyse_with_globals(source, vec![]); + let [error] = &result.errors[..] else { + panic!("one error expected: {:?}", result.errors); + }; + let text = |span: Span| &source[span.range()]; + assert_eq!( + error.to_string(), + "can't assign a String to `b`, which holds an Int" + ); + assert_eq!(text(error.span()), "\"x\""); + assert_eq!(error.label(), Some("this is a String")); + assert_eq!( + error + .notes() + .iter() + .map(|(span, note)| (text(*span), note.as_str())) + .collect::>(), + vec![("b", "`b` is declared as an Int here")] + ); + // The help about writing a number with a `.` is only for numbers. + assert_eq!(error.help_text(), None); +} + +// A value a function returns that doesn't fit its annotation is the +// value's error, with a note at the annotation: here the body's last value. +#[test] +fn a_return_that_does_not_fit_points_at_the_annotation() { + let source = "fn f() -> Int { let y = 1; \"x\" }"; + let (_, result) = analyse_with_globals(source, vec![]); + let [error] = &result.errors[..] else { + panic!("one error expected: {:?}", result.errors); + }; + let text = |span: Span| &source[span.range()]; + assert_eq!( + error.to_string(), + "can't return a String from `f`, which returns an Int" + ); + assert_eq!(text(error.span()), "\"x\""); + assert_eq!(error.label(), Some("this is a String")); + assert_eq!( + error + .notes() + .iter() + .map(|(span, note)| (text(*span), note.as_str())) + .collect::>(), + vec![("Int", "`f` is declared to return an Int here")] + ); +} + #[test] fn a_generic_function_keeps_one_copy_of_each_call_it_copies() { // Each function calls the one before twice. With a copy of each call's @@ -1993,7 +2048,7 @@ fn an_error_after_a_failed_call_is_still_reported() { ), vec![ "No function called 'len' found that matches the arguments 'Bool'", - "mismatched types: found Int but expected String", + "can't assign an Int to `s`, which holds a String", "No function called 'sum' found that matches the arguments '[String]'", ] ); diff --git a/ndc_analyser/src/error.rs b/ndc_analyser/src/error.rs index e39bc720..9d927ab0 100644 --- a/ndc_analyser/src/error.rs +++ b/ndc_analyser/src/error.rs @@ -294,6 +294,78 @@ impl AnalysisError { } } + /// A value of type `found` assigned to the variable `name`, which holds + /// values of type `expected`, as in `let x = 0; x = "a"`: the error is + /// at the value, with a note where `name` is declared, which decided + /// its type. + pub(crate) fn assigned_to_variable( + name: &str, + found: &StaticType, + expected: &StaticType, + span: Span, + declared_at: Option, + ) -> Self { + let error = Self { + text: format!( + "can't assign {} to `{name}`, which holds {}", + with_article(found), + with_article(expected) + ), + label: Some(format!("this is {}", with_article(found))), + ..Self::mismatched_types(found, expected, span) + }; + match declared_at { + Some(declared_at) => error.with_note( + declared_at, + &format!("`{name}` is declared as {} here", with_article(expected)), + ), + None => error, + } + } + + /// A value of type `found` that a function returns, where it's + /// annotated at `annotation` to return values of type `expected`, as in + /// `fn f() -> Int { "a" }`: the error is at the value, with a note at + /// the annotation. `function` is the function's name, if it has one. + pub(crate) fn returned_from_function( + function: Option<&str>, + found: &StaticType, + expected: &StaticType, + span: Span, + annotation: Span, + ) -> Self { + let (text, note) = match function { + Some(name) => ( + format!( + "can't return {} from `{name}`, which returns {}", + with_article(found), + with_article(expected) + ), + format!( + "`{name}` is declared to return {} here", + with_article(expected) + ), + ), + None => ( + format!( + "can't return {} from a function that returns {}", + with_article(found), + with_article(expected) + ), + format!( + "the function is declared to return {} here", + with_article(expected) + ), + ), + }; + Self { + text, + label: Some(format!("this is {}", with_article(found))), + ..Self::mismatched_types(found, expected, span) + } + .with_note(annotation, ¬e) + } + /// Two values that have to be of one type and aren't, as the elements /// of `[1, "a"]` or the branches of `if c { 1 } else { "a" }`, with a /// label at each. @@ -767,10 +839,13 @@ impl AnalysisError { } } -/// `typ` with `a` or `an` before it, as in `an Int` or `a [String]`. +/// `typ` with `a` or `an` before it, as in `an Int` or `a [String]`, but +/// for `()`, which takes none. fn with_article(typ: &StaticType) -> String { let typ = typ.to_string(); - if typ.starts_with(['A', 'E', 'I', 'O', 'U']) { + if typ == "()" { + typ + } else if typ.starts_with(['A', 'E', 'I', 'O', 'U']) { format!("an {typ}") } else { format!("a {typ}") diff --git a/ndc_lsp/src/document.rs b/ndc_lsp/src/document.rs index 7be6a111..67287079 100644 --- a/ndc_lsp/src/document.rs +++ b/ndc_lsp/src/document.rs @@ -244,7 +244,11 @@ mod tests { assert!(document.set_text("let x = 1;").is_empty()); let diagnostics = document.set_text("let x: Int = \"no\";"); assert_eq!(diagnostics.len(), 1, "{diagnostics:?}"); - assert!(diagnostics[0].message.contains("mismatched types")); + assert!( + diagnostics[0] + .message + .contains("can't assign a String to `x`") + ); } #[test] diff --git a/ndc_resolver/src/name_resolution.rs b/ndc_resolver/src/name_resolution.rs index 3becd5ba..3b0b3cce 100644 --- a/ndc_resolver/src/name_resolution.rs +++ b/ndc_resolver/src/name_resolution.rs @@ -50,6 +50,9 @@ pub struct NameResolver { /// nodes. In `fn a(x) { }`, keyed by the function declaration's node, /// since the name has no node of its own. declarations: HashMap, + /// Where each variable is declared: the name in its `let`, parameter + /// list or loop head. In `let (a, b) = ...`, `a` and `b`. + declared_at: HashMap, /// Every symbol an identifier use could mean, keyed by the identifier's /// node. The type pass picks between them. references: HashMap, @@ -524,6 +527,7 @@ impl NameResolver { symbols, scopes, declarations: Default::default(), + declared_at: Default::default(), references: Default::default(), assignments: Default::default(), captures: Default::default(), @@ -735,6 +739,12 @@ impl NameResolver { self.symbols.name(symbol) } + /// Where the variable `symbol` is declared, if it's a variable: the name + /// in its `let`, parameter list or loop head. + pub fn declared_at(&self, symbol: SymbolId) -> Option { + self.declared_at.get(&symbol).copied() + } + /// What the struct declared at `node` bound. pub fn struct_symbols(&self, node: NodeId) -> &StructSymbols { &self.structs[&node] @@ -1311,12 +1321,13 @@ impl NameResolver { fn declare_pattern(&mut self, pattern: &BindingPatternLocation) { match &pattern.pattern { - BindingPattern::Identifier { identifier, .. } => { + BindingPattern::Identifier { identifier, span } => { let symbol = self .symbols .declare(identifier.to_owned(), BindingKind::Plain); self.scopes.bind(symbol, &self.symbols); self.declarations.insert(pattern.id, symbol); + self.declared_at.insert(symbol, *span); } BindingPattern::Sequence(items) => { for item in items { diff --git a/tests/functional/programs/004_basic/047_annotated_let_type_mismatch.ndc b/tests/functional/programs/004_basic/047_annotated_let_type_mismatch.ndc index 5359df52..bef34edf 100644 --- a/tests/functional/programs/004_basic/047_annotated_let_type_mismatch.ndc +++ b/tests/functional/programs/004_basic/047_annotated_let_type_mismatch.ndc @@ -1,2 +1,2 @@ -// expect-error: mismatched types: found String but expected Int +// expect-error: can't assign a String to `x`, which holds an Int let x: Int = "hello"; diff --git a/tests/functional/programs/004_basic/049_annotated_let_type_mismatch_list.ndc b/tests/functional/programs/004_basic/049_annotated_let_type_mismatch_list.ndc index 63f8d334..a1c9cf04 100644 --- a/tests/functional/programs/004_basic/049_annotated_let_type_mismatch_list.ndc +++ b/tests/functional/programs/004_basic/049_annotated_let_type_mismatch_list.ndc @@ -1,2 +1,2 @@ -// expect-error: mismatched types: found [Int] but expected [String] +// expect-error: can't assign a [Int] to `x`, which holds a [String] let x: [String] = [1, 2, 3]; diff --git a/tests/functional/programs/004_basic/050_annotated_let_type_mismatch_tuple.ndc b/tests/functional/programs/004_basic/050_annotated_let_type_mismatch_tuple.ndc index a05d9e7b..73ee190c 100644 --- a/tests/functional/programs/004_basic/050_annotated_let_type_mismatch_tuple.ndc +++ b/tests/functional/programs/004_basic/050_annotated_let_type_mismatch_tuple.ndc @@ -1,2 +1,2 @@ -// expect-error: mismatched types: found (Int, Int) but expected (String, String) +// expect-error: can't assign a (Int, Int) to `x`, which holds a (String, String) let x: (String, String) = (1, 2); diff --git a/tests/functional/programs/004_basic/052_annotated_let_rejects_supertype.ndc b/tests/functional/programs/004_basic/052_annotated_let_rejects_supertype.ndc index b9ee794f..74c430df 100644 --- a/tests/functional/programs/004_basic/052_annotated_let_rejects_supertype.ndc +++ b/tests/functional/programs/004_basic/052_annotated_let_rejects_supertype.ndc @@ -1,3 +1,3 @@ -// expect-error: mismatched types: found Number but expected Int +// expect-error: can't assign a Number to `y`, which holds an Int let x: Number = 3; let y: Int = x; diff --git a/tests/functional/programs/004_basic/054_annotated_let_reassignment_rejected.ndc b/tests/functional/programs/004_basic/054_annotated_let_reassignment_rejected.ndc index 78dda3c0..735496e3 100644 --- a/tests/functional/programs/004_basic/054_annotated_let_reassignment_rejected.ndc +++ b/tests/functional/programs/004_basic/054_annotated_let_reassignment_rejected.ndc @@ -1,3 +1,3 @@ let x: Int = 5; x = "test"; -// expect-error: mismatched types +// expect-error: can't assign a String to `x`, which holds an Int diff --git a/tests/functional/programs/004_basic/070_a_variable_keeps_its_type.ndc b/tests/functional/programs/004_basic/070_a_variable_keeps_its_type.ndc index d69fddec..ae324fc4 100644 --- a/tests/functional/programs/004_basic/070_a_variable_keeps_its_type.ndc +++ b/tests/functional/programs/004_basic/070_a_variable_keeps_its_type.ndc @@ -1,6 +1,6 @@ // A variable keeps the type its first value gave it, so a call resolved // against that type, like the `+` in `f`, stays right. -// expect-error: mismatched types: found Float but expected Int +// expect-error: can't assign a Float to `x`, which holds an Int let x = "a".len(); fn f() { x + 1 } x = 2.5; diff --git a/tests/functional/programs/004_basic/071_some_has_the_type_of_its_value.ndc b/tests/functional/programs/004_basic/071_some_has_the_type_of_its_value.ndc index 389761e8..14b6c1cc 100644 --- a/tests/functional/programs/004_basic/071_some_has_the_type_of_its_value.ndc +++ b/tests/functional/programs/004_basic/071_some_has_the_type_of_its_value.ndc @@ -1,4 +1,4 @@ // `Some(1)` is an Option, so the variable can't later hold an Option. -// expect-error: mismatched types: found Option but expected Option +// expect-error: can't assign an Option to `o`, which holds an Option let o = Some(1); o = Some("a"); diff --git a/tests/functional/programs/004_basic/086_a_placeholder_is_an_option.ndc b/tests/functional/programs/004_basic/086_a_placeholder_is_an_option.ndc index e89de5f6..055445b6 100644 --- a/tests/functional/programs/004_basic/086_a_placeholder_is_an_option.ndc +++ b/tests/functional/programs/004_basic/086_a_placeholder_is_an_option.ndc @@ -1,4 +1,4 @@ -// expect-error: A value that only comes later is an `Option` +// expect-error: For a value that only comes later, start with `None` and assign `Some(…)` let best = (); for x in [3, 1] { best = x; diff --git a/tests/functional/programs/004_basic/087_a_variable_holds_one_type.ndc b/tests/functional/programs/004_basic/087_a_variable_holds_one_type.ndc index 1e51bad5..a7ee9466 100644 --- a/tests/functional/programs/004_basic/087_a_variable_holds_one_type.ndc +++ b/tests/functional/programs/004_basic/087_a_variable_holds_one_type.ndc @@ -1,4 +1,4 @@ -// The help about writing a number with a `.` is only for numbers. -// expect-error: A variable holds one type, the type of what it's given first +// A variable holds the type of what it's given first. +// expect-error: can't assign a String to `x`, which holds an Int let x = 1; x = "a"; diff --git a/tests/functional/programs/005_functions/038_return_type_annotation_mismatch.ndc b/tests/functional/programs/005_functions/038_return_type_annotation_mismatch.ndc index 90ace995..42e0a395 100644 --- a/tests/functional/programs/005_functions/038_return_type_annotation_mismatch.ndc +++ b/tests/functional/programs/005_functions/038_return_type_annotation_mismatch.ndc @@ -1,2 +1,2 @@ fn bad() -> Int { "hello" } -// expect-error: mismatched types +// expect-error: can't return a String from `bad`, which returns an Int diff --git a/tests/functional/programs/005_functions/057_annotated_return_type_checks_every_return.ndc b/tests/functional/programs/005_functions/057_annotated_return_type_checks_every_return.ndc index 7471028d..6cf4a99e 100644 --- a/tests/functional/programs/005_functions/057_annotated_return_type_checks_every_return.ndc +++ b/tests/functional/programs/005_functions/057_annotated_return_type_checks_every_return.ndc @@ -4,4 +4,4 @@ fn f(x) -> Int { if x { return "early"; } 1 } -// expect-error: mismatched types +// expect-error: can't return a String from `f`, which returns an Int diff --git a/tests/functional/programs/005_functions/151_an_operator_assignment_with_a_lambda_is_blamed_at_the_assignment.ndc b/tests/functional/programs/005_functions/151_an_operator_assignment_with_a_lambda_is_blamed_at_the_assignment.ndc index 00d771b8..5e93c8e2 100644 --- a/tests/functional/programs/005_functions/151_an_operator_assignment_with_a_lambda_is_blamed_at_the_assignment.ndc +++ b/tests/functional/programs/005_functions/151_an_operator_assignment_with_a_lambda_is_blamed_at_the_assignment.ndc @@ -1,5 +1,5 @@ // `x f= v` is `x = f(x, v)`: the mismatch is the assignment's, not the body's. -// expect-error: found Float but expected Int +// expect-error: can't assign a Float to `x`, which holds an Int let x = 1; let f = fn(a, b) { a + b }; x f= 2.5; diff --git a/tests/functional/programs/006_lists/050_a_loop_variable_keeps_the_element_type.ndc b/tests/functional/programs/006_lists/050_a_loop_variable_keeps_the_element_type.ndc index 4d8afb46..c97365bd 100644 --- a/tests/functional/programs/006_lists/050_a_loop_variable_keeps_the_element_type.ndc +++ b/tests/functional/programs/006_lists/050_a_loop_variable_keeps_the_element_type.ndc @@ -1,6 +1,6 @@ // A loop variable keeps the element type: `line` is a String, so it can't // hold the list `split` returns. Give the list a name of its own. -// expect-error: mismatched types: found [String] but expected String +// expect-error: can't assign a [String] to `line`, which holds a String for line in ["a b c"] { line = line.split(" "); } diff --git a/tests/functional/programs/015_struct/015_let_annotation_mismatch.ndc b/tests/functional/programs/015_struct/015_let_annotation_mismatch.ndc index 4c9143c0..5ef1a651 100644 --- a/tests/functional/programs/015_struct/015_let_annotation_mismatch.ndc +++ b/tests/functional/programs/015_struct/015_let_annotation_mismatch.ndc @@ -1,4 +1,4 @@ -// expect-error: mismatched types: found Int but expected Point +// expect-error: can't assign an Int to `p`, which holds a Point struct Point { x: Int, y: Int } let p: Point = 1; diff --git a/tests/functional/programs/015_struct/016_nominal_annotation.ndc b/tests/functional/programs/015_struct/016_nominal_annotation.ndc index a7aab6d9..031e1069 100644 --- a/tests/functional/programs/015_struct/016_nominal_annotation.ndc +++ b/tests/functional/programs/015_struct/016_nominal_annotation.ndc @@ -1,5 +1,5 @@ // Same shape, different name: struct types are nominal. -// expect-error: mismatched types: found Bar but expected Foo +// expect-error: can't assign a Bar to `a`, which holds a Foo struct Foo { x: Int } struct Bar { x: Int } diff --git a/tests/functional/programs/017_dynamic_any/002_an_annotated_let_takes_no_any.ndc b/tests/functional/programs/017_dynamic_any/002_an_annotated_let_takes_no_any.ndc index 1bf4bb09..1d627895 100644 --- a/tests/functional/programs/017_dynamic_any/002_an_annotated_let_takes_no_any.ndc +++ b/tests/functional/programs/017_dynamic_any/002_an_annotated_let_takes_no_any.ndc @@ -1,5 +1,5 @@ // A value of type `Any` doesn't go where an Int is expected without a cast. -// expect-error: mismatched types: found Any but expected Int +// expect-error: can't assign an Any to `n`, which holds an Int let a: Any = "five"; let n: Int = a; print(n); diff --git a/tests/functional/programs/017_dynamic_any/003_an_assignment_takes_no_any.ndc b/tests/functional/programs/017_dynamic_any/003_an_assignment_takes_no_any.ndc index 60823c38..5fc4b2a7 100644 --- a/tests/functional/programs/017_dynamic_any/003_an_assignment_takes_no_any.ndc +++ b/tests/functional/programs/017_dynamic_any/003_an_assignment_takes_no_any.ndc @@ -1,5 +1,5 @@ // `n` is an Int, which a value of type `Any` takes a cast to be. -// expect-error: mismatched types: found Any but expected Int +// expect-error: can't assign an Any to `n`, which holds an Int let a: Any = 5; let n = 1; n = a; diff --git a/tests/functional/programs/017_dynamic_any/004_a_destructuring_takes_no_any.ndc b/tests/functional/programs/017_dynamic_any/004_a_destructuring_takes_no_any.ndc index bc9d565c..50737ee6 100644 --- a/tests/functional/programs/017_dynamic_any/004_a_destructuring_takes_no_any.ndc +++ b/tests/functional/programs/017_dynamic_any/004_a_destructuring_takes_no_any.ndc @@ -1,4 +1,4 @@ -// expect-error: mismatched types: found Any but expected String +// expect-error: can't assign an Any to `s`, which holds a String let a: Any = "five"; let n = 0; let s = ""; diff --git a/tests/functional/programs/018_literals/011_two_literals_of_different_types_are_an_error.ndc b/tests/functional/programs/018_literals/011_two_literals_of_different_types_are_an_error.ndc index 232f9a64..a96277f8 100644 --- a/tests/functional/programs/018_literals/011_two_literals_of_different_types_are_an_error.ndc +++ b/tests/functional/programs/018_literals/011_two_literals_of_different_types_are_an_error.ndc @@ -1,4 +1,4 @@ // `v` is a list of Strings, so it can't be given a list of Ints. -// expect-error: mismatched types: found [Int] but expected [String] +// expect-error: can't assign a [Int] to `v`, which holds a [String] let v = ["s"]; v = [1]; diff --git a/tests/functional/programs/018_literals/012_a_list_of_ints_is_not_a_list_of_any.ndc b/tests/functional/programs/018_literals/012_a_list_of_ints_is_not_a_list_of_any.ndc index 8a323d89..7cc96248 100644 --- a/tests/functional/programs/018_literals/012_a_list_of_ints_is_not_a_list_of_any.ndc +++ b/tests/functional/programs/018_literals/012_a_list_of_ints_is_not_a_list_of_any.ndc @@ -1,5 +1,5 @@ // A [Any] could get a String, which the [String] would then hold. // Converting goes through `Any`. -// expect-error: mismatched types: found [String] but expected [Any] +// expect-error: can't assign a [String] to `anything`, which holds a [Any] let words = "a b".split(" "); let anything: [Any] = words; diff --git a/tests/functional/programs/018_literals/027_a_literal_doesn_t_become_a_float_to_reach_an_any_overload.ndc b/tests/functional/programs/018_literals/027_a_literal_doesn_t_become_a_float_to_reach_an_any_overload.ndc index f920cff7..5c3c4177 100644 --- a/tests/functional/programs/018_literals/027_a_literal_doesn_t_become_a_float_to_reach_an_any_overload.ndc +++ b/tests/functional/programs/018_literals/027_a_literal_doesn_t_become_a_float_to_reach_an_any_overload.ndc @@ -1,7 +1,7 @@ // `[]([T], Int)` gives an Int, which isn't a String. A Float index would // reach `[]([T], Any)`, but that overload is a fallback, so the `0` // stays an Int and the mismatch is reported. -// expect-error: mismatched types: found Int but expected String +// expect-error: can't assign an Int to `e`, which holds a String let ys = ["a".len()]; let cs = [x for x in ys]; let e: String = cs[0]; diff --git a/tests/functional/programs/018_literals/031_values_that_share_no_type_stored_as_an_any_take_a_cast.ndc b/tests/functional/programs/018_literals/031_values_that_share_no_type_stored_as_an_any_take_a_cast.ndc index 26415c98..ac0de8ee 100644 --- a/tests/functional/programs/018_literals/031_values_that_share_no_type_stored_as_an_any_take_a_cast.ndc +++ b/tests/functional/programs/018_literals/031_values_that_share_no_type_stored_as_an_any_take_a_cast.ndc @@ -1,6 +1,6 @@ // `v` becomes an `Any` where it's stored as one, and an `Any` takes a cast to // be stored in an Int. -// expect-error: mismatched types: found Any but expected Int +// expect-error: can't assign an Any to `n`, which holds an Int let v = if false { 1 } else { "a" }; let n: Int = v; let a: Any = v; diff --git a/tests/functional/programs/018_literals/032_a_map_default_function_returning_any_gives_no_typed_values.ndc b/tests/functional/programs/018_literals/032_a_map_default_function_returning_any_gives_no_typed_values.ndc index 7de2c0f7..cdfdf07e 100644 --- a/tests/functional/programs/018_literals/032_a_map_default_function_returning_any_gives_no_typed_values.ndc +++ b/tests/functional/programs/018_literals/032_a_map_default_function_returning_any_gives_no_typed_values.ndc @@ -1,6 +1,6 @@ // A map of Ints calls `fallback` for a missing key, which gives an `Any`, // not an Int. -// expect-error: mismatched types +// expect-error: can't assign a %{Unknown: Any} to `m`, which holds a %{String: Int} fn fallback() -> Any => 1; let m: %{String: Int} = %{:fallback}; print(m["a"]); diff --git a/tests/functional/programs/018_literals/033_a_function_taking_an_int_is_not_a_function_taking_any.ndc b/tests/functional/programs/018_literals/033_a_function_taking_an_int_is_not_a_function_taking_any.ndc index 8804f080..e9710dd3 100644 --- a/tests/functional/programs/018_literals/033_a_function_taking_an_int_is_not_a_function_taking_any.ndc +++ b/tests/functional/programs/018_literals/033_a_function_taking_an_int_is_not_a_function_taking_any.ndc @@ -1,3 +1,3 @@ // A function taking an Int can't be passed what a `fn(Any) -> Int` takes. -// expect-error: mismatched types: found fn(String) -> Int but expected fn(Any) -> Int +// expect-error: can't assign a fn(String) -> Int to `g`, which holds a fn(Any) -> Int let g: fn(Any) -> Int = fn(x: String) => 1; diff --git a/tests/functional/programs/019_iterable/020_a_callback_returning_a_tuple_is_checked.ndc b/tests/functional/programs/019_iterable/020_a_callback_returning_a_tuple_is_checked.ndc index 938727a0..5d8523b8 100644 --- a/tests/functional/programs/019_iterable/020_a_callback_returning_a_tuple_is_checked.ndc +++ b/tests/functional/programs/019_iterable/020_a_callback_returning_a_tuple_is_checked.ndc @@ -1,3 +1,3 @@ -// expect-error: found [Int] but expected [String] +// expect-error: can't assign a [Int] to `r`, which holds a [String] fn dup(x) => [0].flat_map(fn(_) => (x, x)); let r: [String] = dup(1); diff --git a/tests/functional/programs/020_tuples/003_an_element_has_its_own_type.ndc b/tests/functional/programs/020_tuples/003_an_element_has_its_own_type.ndc index 373f880c..1d2968a6 100644 --- a/tests/functional/programs/020_tuples/003_an_element_has_its_own_type.ndc +++ b/tests/functional/programs/020_tuples/003_an_element_has_its_own_type.ndc @@ -1,4 +1,4 @@ // The first element is an Int, which isn't a String. -// expect-error: mismatched types: found Int but expected String +// expect-error: can't assign an Int to `s`, which holds a String let t = (1, "a"); let s: String = t[0]; diff --git a/tests/functional/programs/020_tuples/009_concatenating_onto_a_tuple_variable_changes_its_type.ndc b/tests/functional/programs/020_tuples/009_concatenating_onto_a_tuple_variable_changes_its_type.ndc index 5efb7037..ef90e10f 100644 --- a/tests/functional/programs/020_tuples/009_concatenating_onto_a_tuple_variable_changes_its_type.ndc +++ b/tests/functional/programs/020_tuples/009_concatenating_onto_a_tuple_variable_changes_its_type.ndc @@ -1,4 +1,4 @@ // `++=` would give the variable a tuple of another length, which is another type. -// expect-error: found (Int, Int, Int, Int, Int) but expected (Int, Int, Int) +// expect-error: can't assign a (Int, Int, Int, Int, Int) to `b`, which holds a (Int, Int, Int) let b = (1, 2, 3); b ++= (4, 5); diff --git a/tests/functional/programs/900_bugs/bug0038_destructuring_assignment_checks_types.ndc b/tests/functional/programs/900_bugs/bug0038_destructuring_assignment_checks_types.ndc index 72dae0a9..a49c6759 100644 --- a/tests/functional/programs/900_bugs/bug0038_destructuring_assignment_checks_types.ndc +++ b/tests/functional/programs/900_bugs/bug0038_destructuring_assignment_checks_types.ndc @@ -1,6 +1,6 @@ // Destructuring assignment used to skip type checks, so an Int-annotated // variable could end up holding a String. -// expect-error: mismatched types +// expect-error: can't assign a String to `a`, which holds an Int let a: Int = 1; let b = 2; (a, b) = ("s", 2); diff --git a/tests/functional/programs/900_bugs/bug0044_if_joined_after_fallbacks_in_list.ndc b/tests/functional/programs/900_bugs/bug0044_if_joined_after_fallbacks_in_list.ndc index f865d808..359454e6 100644 --- a/tests/functional/programs/900_bugs/bug0044_if_joined_after_fallbacks_in_list.ndc +++ b/tests/functional/programs/900_bugs/bug0044_if_joined_after_fallbacks_in_list.ndc @@ -1,5 +1,5 @@ // As bug0043, with `h` in a list next to a lambda. -// expect-error: mismatched types: found [Any] but expected Int +// expect-error: can't assign a [Any] to `w`, which holds an Int fn g(a) => a + 1; fn h(a) => if true { g(a) } else { a }; let w: Int = [1, [h, fn(a) => [a]]];