Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
35 changes: 28 additions & 7 deletions ndc_analyser/src/analyser/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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`].
Expand Down Expand Up @@ -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 {
Expand All @@ -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::<Vec<_>>();
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);
Expand Down
4 changes: 4 additions & 0 deletions ndc_analyser/src/analyser/function_values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ impl Analyser {
type_arguments: Vec<StaticType>,
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();
Expand Down
20 changes: 11 additions & 9 deletions ndc_analyser/src/analyser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
55 changes: 50 additions & 5 deletions ndc_analyser/src/analyser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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",
] {
Expand All @@ -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], 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::<Vec<_>>();
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]
Expand Down
2 changes: 1 addition & 1 deletion ndc_lsp/src/features/references.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
7 changes: 4 additions & 3 deletions ndc_lsp/src/resolved.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
Expand Down
61 changes: 50 additions & 11 deletions ndc_resolver/src/name_resolution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SymbolId, Intrinsic>,
/// 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<NameResolutionError>,
/// How many statements have failed to resolve.
failed_statements: usize,
}

#[derive(Debug, Clone, thiserror::Error)]
Expand Down Expand Up @@ -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<Vec<SymbolId>>);

Expand Down Expand Up @@ -536,6 +538,7 @@ impl NameResolver {
native_slots,
intrinsics,
errors: Default::default(),
failed_statements: 0,
}
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
}
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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);
}
Expand Down Expand Up @@ -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, NameResolutionError>) -> 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.
Expand Down Expand Up @@ -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<Item = &Vec<SymbolId>> {
self.0.iter()
Expand Down
Loading
Loading