From 83ae1c074adfef2fe766154df8451c3c4cbc3f55 Mon Sep 17 00:00:00 2001 From: Tim Fennis Date: Sun, 29 Nov 2026 14:10:53 +0100 Subject: [PATCH] =?UTF-8?q?fix(analyser):=20analyse=20a=20statement=20past?= =?UTF-8?q?=20a=20name=20nothing=20declares=20=F0=9F=94=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- ndc_analyser/src/analyser/calls.rs | 35 ++++++++--- ndc_analyser/src/analyser/function_values.rs | 4 ++ ndc_analyser/src/analyser/mod.rs | 20 +++--- ndc_analyser/src/analyser/tests.rs | 55 +++++++++++++++-- ndc_lsp/src/features/references.rs | 2 +- ndc_lsp/src/resolved.rs | 7 ++- ndc_resolver/src/name_resolution.rs | 61 +++++++++++++++---- .../src/name_resolution/resolver_tests.rs | 41 +++++++++++-- 8 files changed, 184 insertions(+), 41 deletions(-) diff --git a/ndc_analyser/src/analyser/calls.rs b/ndc_analyser/src/analyser/calls.rs index f2f75835..5a0bf78b 100644 --- a/ndc_analyser/src/analyser/calls.rs +++ b/ndc_analyser/src/analyser/calls.rs @@ -113,6 +113,13 @@ impl Analyser { ) -> StaticType { // `xs.len` is the call `len(xs)`, among functions only. let receiver_type = self.analyse_expr(receiver); + if self + .resolver + .getter_candidates(id) + .is_some_and(Candidates::is_empty) + { + return self.skip_failed_callee(&[receiver_type]); + } self.constrain_call( CallSite::Getter(id), vec![receiver_type], @@ -122,6 +129,18 @@ impl Analyser { ) } + /// Skips a call of a value whose check failed, or of a name nothing + /// declares, as that was reported where it failed: it settles what only + /// the call could have said about its arguments as failed too, and gives + /// a value whose check failed. + fn skip_failed_callee(&mut self, arguments: &[StaticType]) -> StaticType { + for argument in arguments { + self.vars + .settle_unknowns_but_literals(argument, &StaticType::Error); + } + StaticType::Error + } + /// Resolves a call (regular or operator-form) and returns its result type. /// Only an operator other than a comparison can apply to each element of /// tuple arguments: see [`CallKind`]. @@ -178,13 +197,7 @@ impl Analyser { } callee @ StaticType::Var(_) => self.call_unknown_function(&callee, arguments), // The callee's check failed, which was reported there. - StaticType::Error => { - for argument in &arguments { - self.vars - .settle_unknowns_but_literals(argument, &StaticType::Error); - } - StaticType::Error - } + StaticType::Error => self.skip_failed_callee(&arguments), // Nothing tells what the callee does with its arguments. callee if callee.could_be_callable() => { for argument in &arguments { @@ -205,6 +218,14 @@ impl Analyser { }; }; + if self.resolver.reference_candidates(function.id).is_empty() { + let arguments = arguments + .iter() + .map(|argument| self.analyse_expr(argument)) + .collect::>(); + return self.skip_failed_callee(&arguments); + } + // A named callee declares nothing, so its overload can be picked after // the arguments' types are known. let site = CallSite::Call(function.id); diff --git a/ndc_analyser/src/analyser/function_values.rs b/ndc_analyser/src/analyser/function_values.rs index 835676d0..eea03aaa 100644 --- a/ndc_analyser/src/analyser/function_values.rs +++ b/ndc_analyser/src/analyser/function_values.rs @@ -84,6 +84,10 @@ impl Analyser { type_arguments: Vec, span: Span, ) -> StaticType { + // A name nothing declares was reported where it's written. + if self.resolver.reference_candidates(id).is_empty() { + return StaticType::Error; + } let symbol = self.resolver.innermost_reference(id); let mut groups = self.overloaded_function_groups(id, symbol); let reachable = groups.concat(); diff --git a/ndc_analyser/src/analyser/mod.rs b/ndc_analyser/src/analyser/mod.rs index 039bb034..c8e7ec75 100644 --- a/ndc_analyser/src/analyser/mod.rs +++ b/ndc_analyser/src/analyser/mod.rs @@ -555,19 +555,21 @@ impl Analyser { typ.replace(&|part| matches!(part, StaticType::Iterable(_)).then_some(StaticType::Error)) } - /// Analyses a top-level statement. Names resolve first; a statement with - /// unresolved names isn't analysed further, which would only repeat its errors. - /// The names it still declared are bound as failed checks, so in - /// `fn f() { missing } let g = f`, only `missing` is reported. + /// Analyses a top-level statement. Names resolve first. A name nothing + /// declares is a failed check, so in `for l in ls { xs.push(l.missing) }`, + /// only `missing` is reported and `xs` holds failed checks. A statement + /// that didn't resolve for another reason, as `fn f(a, a) {}`, isn't + /// analysed further. The names it still declared are bound as failed + /// checks, so in `fn f(a, a) {} let g = f`, only `a` is reported. pub fn analyse(&mut self, expr_loc: &ExpressionLocation) -> StaticType { self.vars.prune_literals(); let bound_before = self.resolver.current_bindings().len(); - self.resolver.resolve_statement(expr_loc); + let resolved = self.resolver.resolve_statement(expr_loc); let name_errors = self.resolver.take_errors(); - if !name_errors.is_empty() { - self.result - .errors - .extend(name_errors.into_iter().map(AnalysisError::from)); + self.result + .errors + .extend(name_errors.into_iter().map(AnalysisError::from)); + if !resolved { let declared = self.resolver.current_bindings()[bound_before..].to_vec(); for symbol in declared { self.types.declare(symbol, StaticType::Error); diff --git a/ndc_analyser/src/analyser/tests.rs b/ndc_analyser/src/analyser/tests.rs index c666cc6c..a882ed0c 100644 --- a/ndc_analyser/src/analyser/tests.rs +++ b/ndc_analyser/src/analyser/tests.rs @@ -286,7 +286,16 @@ fn map_default_value_contributes_to_value_type() { /// declaration: the names it declared are bound as failed, so using them adds /// no second error. fn assert_one_error_then_failed(source: &str, expected: &str) { - let (last_type, result) = analyse_with_globals(source, vec![]); + assert_one_error_then_failed_with(source, vec![], expected); +} + +/// As [`assert_one_error_then_failed`], with `globals` declared. +fn assert_one_error_then_failed_with( + source: &str, + globals: Vec<(String, StaticType)>, + expected: &str, +) { + let (last_type, result) = analyse_with_globals(source, globals); assert_eq!(result.errors.len(), 1, "errors: {:?}", result.errors); assert!( result.errors[0].to_string().contains(expected), @@ -319,12 +328,12 @@ fn an_annotated_name_the_value_has_no_part_for_keeps_its_annotation() { } #[test] -fn a_statement_with_an_unknown_name_binds_its_declarations_as_failed() { +fn a_name_nothing_declares_is_a_failed_check() { for source in [ - "fn f() { missing; } let g = f; g", - "fn f() { missing; } f()", + "fn f() { missing } let g = f; g", + "fn f() { missing } f()", // Read from inside another function. - "fn f() { missing; } fn g() { f } g()", + "fn f() { missing } fn g() { f } g()", "let a = missing; a", "let (a, b) = missing; b", ] { @@ -333,6 +342,42 @@ fn a_statement_with_an_unknown_name_binds_its_declarations_as_failed() { "Identifier missing has not previously been declared", ); } + // The rest of the statement is analysed, so what it pushes is failed. + for source in [ + "let xs = []; for x in [1] { let y = x.missing; xs.push(y); } xs", + "let xs = []; for x in [1] { xs.push(missing(x)); } xs", + ] { + assert_one_error_then_failed_with( + source, + natives(&[("push", "([T], T)")]), + "Identifier missing has not previously been declared", + ); + } +} + +#[test] +fn every_name_nothing_declares_is_reported() { + let (_, result) = analyse_with_globals("let x = missing(other);", vec![]); + let errors = result + .errors + .iter() + .map(ToString::to_string) + .collect::>(); + assert_eq!( + errors, + [ + "Identifier missing has not previously been declared", + "Identifier other has not previously been declared", + ] + ); +} + +#[test] +fn a_statement_that_fails_to_resolve_binds_its_declarations_as_failed() { + assert_one_error_then_failed( + "fn f(a, a) { a } let g = f; g", + "Illegal redefinition of parameter a", + ); } #[test] diff --git a/ndc_lsp/src/features/references.rs b/ndc_lsp/src/features/references.rs index 8e2637d6..aededa01 100644 --- a/ndc_lsp/src/features/references.rs +++ b/ndc_lsp/src/features/references.rs @@ -590,7 +590,7 @@ mod tests { assert!(renamed("let x$0 = 1;", "fn").is_err()); assert!(renamed("let x$0 = 1;", "a b").is_err()); // A name the resolver didn't get to might be one of the renamed. - assert!(renamed("let x$0 = 1;\nprint(missing, x);", "y").is_err()); + assert!(renamed("let x$0 = 1;\nfn f(a, a) { x }", "y").is_err()); } #[test] diff --git a/ndc_lsp/src/resolved.rs b/ndc_lsp/src/resolved.rs index 488ba212..829f07fa 100644 --- a/ndc_lsp/src/resolved.rs +++ b/ndc_lsp/src/resolved.rs @@ -85,8 +85,9 @@ impl Resolved { // A name the analyser picked nothing for, as one in the body of a // generic function nothing calls yet, could mean what the nearest // scope that declares it declares: every overload there. + // A name nothing declares means nothing. for (node, candidates) in resolver.references() { - if definitions.contains_key(&node) { + if definitions.contains_key(&node) || candidates.is_empty() { continue; } let nearest = candidates @@ -105,8 +106,8 @@ impl Resolved { } /// Where the name at `node` is declared: empty for a built-in, and - /// `None` for a name the resolver didn't get to, as one after an unknown - /// name in the same statement. + /// `None` for a name nothing declares, or one the resolver didn't get + /// to, as one after a duplicate parameter in the same statement. pub fn definitions_of(&self, node: NodeId) -> Option<&[Definition]> { self.definitions.get(&node).map(Vec::as_slice) } diff --git a/ndc_resolver/src/name_resolution.rs b/ndc_resolver/src/name_resolution.rs index 6d7e71f8..3becd5ba 100644 --- a/ndc_resolver/src/name_resolution.rs +++ b/ndc_resolver/src/name_resolution.rs @@ -91,9 +91,12 @@ pub struct NameResolver { /// The natives the compiler writes as bytecode where they're used, as /// `cast`. Each still has its registry position in [`Self::native_slots`]. intrinsics: HashMap, - /// Errors from statements that failed to resolve. Resolution carries on with - /// the next statement, so `a; b;` reports both unknown names. + /// Every error found, from names nothing declares, which resolution + /// carries on past, and from statements that failed to resolve, where + /// it carries on with the next statement. errors: Vec, + /// How many statements have failed to resolve. + failed_statements: usize, } #[derive(Debug, Clone, thiserror::Error)] @@ -189,8 +192,7 @@ impl NameResolutionError { /// Same-named symbols visible at a use, nearest scope first, newest first /// within a scope. For `x` in `let x = 1; { let x = 2; x }`: `[[x2], [x1]]`. -/// Identifiers always have at least one candidate, augmented operators may -/// not. +/// A name nothing declares has none, and so may an augmented operator. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Candidates(Vec>); @@ -536,6 +538,7 @@ impl NameResolver { native_slots, intrinsics, errors: Default::default(), + failed_statements: 0, } } @@ -566,12 +569,18 @@ impl NameResolver { } } - /// Resolves `statement`, recording its error instead of returning it so the - /// statements after it still resolve. A failed statement stops at its first error. - pub fn resolve_statement(&mut self, statement: &ExpressionLocation) { + /// Resolves `statement`, recording its errors instead of returning them so + /// the statements after it still resolve, and returns whether it resolved: + /// it and every statement in it. A name nothing declares is an error that + /// doesn't stop it, and resolves to no symbol, as `missing` in `let x = + /// missing; x + 1`. Any other error stops the statement it's in. + pub fn resolve_statement(&mut self, statement: &ExpressionLocation) -> bool { + let failed_before = self.failed_statements; if let Err(error) = self.resolve(statement) { self.errors.push(error); + self.failed_statements += 1; } + self.failed_statements == failed_before } /// The value symbols bound in the current scope, oldest first. A failed @@ -610,7 +619,8 @@ impl NameResolver { self.references[&node].innermost() } - /// Every symbol the identifier at `node` could mean. + /// Every symbol the identifier at `node` could mean: none if nothing + /// declares it. pub fn reference_candidates(&self, node: NodeId) -> &Candidates { &self.references[&node] } @@ -800,7 +810,7 @@ impl NameResolver { for argument in type_arguments { self.resolve_type(argument)?; } - let candidates = self.use_name(name, loc.span)?; + let candidates = self.use_written_name(name, loc.span); self.references.insert(loc.id, candidates); self.record_use_site(loc.id); } @@ -896,7 +906,7 @@ impl NameResolver { for argument in type_arguments { self.resolve_type(argument)?; } - let candidates = self.use_function_name(name, function.span)?; + let candidates = self.use_written_function_name(name, function.span); self.references.insert(function.id, candidates); self.record_use_site(function.id); for argument in arguments { @@ -910,7 +920,7 @@ impl NameResolver { .. } => { self.resolve(receiver)?; - let candidates = self.use_function_name(member, *member_span)?; + let candidates = self.use_written_function_name(member, *member_span); self.getters.insert(loc.id, candidates); self.record_use_site(loc.id); } @@ -1043,6 +1053,30 @@ impl NameResolver { Ok(()) } + /// Resolves a name written in the code, as `x` in `x + 1`: every + /// candidate it could mean. One that nothing declares is reported, and + /// resolves to none. + fn use_written_name(&mut self, name: &str, span: Span) -> Candidates { + let candidates = self.use_name(name, span); + self.or_none(candidates) + } + + /// Resolves a function name written in the code, as `len` in `xs.len`, + /// as [`Self::use_function_name`] does. One that no function has is + /// reported, and resolves to none. + fn use_written_function_name(&mut self, name: &str, span: Span) -> Candidates { + let candidates = self.use_function_name(name, span); + self.or_none(candidates) + } + + /// The candidates found, or none, recording the error that found none. + fn or_none(&mut self, found: Result) -> Candidates { + found.unwrap_or_else(|error| { + self.errors.push(error); + Candidates(Vec::new()) + }) + } + /// Resolves a use of `name` from the current scope: every candidate it could /// mean, each recorded as a use so closures capture it. Any candidate may be /// the one the type pass picks, so all of them are captured. @@ -1392,6 +1426,11 @@ impl NameResolver { } impl Candidates { + /// Whether there are none, as for a name nothing declares. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + /// The groups, nearest scope first. pub fn iter(&self) -> impl Iterator> { self.0.iter() diff --git a/ndc_resolver/src/name_resolution/resolver_tests.rs b/ndc_resolver/src/name_resolution/resolver_tests.rs index bbb9692c..c36595f7 100644 --- a/ndc_resolver/src/name_resolution/resolver_tests.rs +++ b/ndc_resolver/src/name_resolution/resolver_tests.rs @@ -53,7 +53,7 @@ fn uses(resolver: &NameResolver, symbol: SymbolId) -> usize { let reads = resolver .references .values() - .filter(|candidates| innermost(candidates) == symbol) + .filter(|candidates| !candidates.is_empty() && innermost(candidates) == symbol) .count(); let writes = resolver .assignments @@ -1276,15 +1276,46 @@ fn errors_are_reported_for_every_failing_statement() { #[test] fn a_failing_statement_stops_at_its_first_error() { assert_eq!( - all_errors("(a, b);"), - ["Identifier a has not previously been declared"] + all_errors("fn f(a, a) { missing }"), + ["Illegal redefinition of parameter a"] ); } +#[test] +fn a_name_nothing_declares_resolves_to_none_and_resolution_carries_on() { + let mut resolver = new_resolver([]); + let statement = Parser::from_tokens( + Lexer::new("let x = 1; (a, x.b, c(x));", SourceId::new(0)) + .collect::, _>>() + .expect("source lexes"), + ) + .parse() + .expect("source parses"); + for expression in &statement { + assert!(resolver.resolve_statement(expression)); + } + let errors = resolver + .take_errors() + .iter() + .map(ToString::to_string) + .collect::>(); + assert_eq!( + errors, + [ + "Identifier a has not previously been declared", + "Identifier b has not previously been declared", + "Identifier c has not previously been declared", + ] + ); + let [x] = declared(&resolver); + assert_eq!(uses(&resolver, x), 2); + assert!(resolver.getters.values().all(Candidates::is_empty)); +} + #[test] fn statements_after_an_error_still_resolve() { let mut resolver = new_resolver([]); - resolve_source(&mut resolver, "missing; let x = 1; x;").unwrap_err(); + resolve_source(&mut resolver, "missing = 1; let x = 1; x;").unwrap_err(); let [x] = declared(&resolver); assert_eq!(uses(&resolver, x), 1); @@ -1294,7 +1325,7 @@ fn statements_after_an_error_still_resolve() { #[test] fn a_function_whose_declaration_fails_still_binds_its_name() { let mut resolver = new_resolver([]); - resolve_source(&mut resolver, "fn f() => missing;").unwrap_err(); + resolve_source(&mut resolver, "fn f() { missing = 1; }").unwrap_err(); resolve_source(&mut resolver, "f;").unwrap(); let [f] = declared(&resolver);