Skip to content
Open
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
2 changes: 1 addition & 1 deletion manual/src/reference/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion manual/src/reference/types/function.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down
2 changes: 1 addition & 1 deletion manual/src/reference/types/number.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions manual/src/reference/variables-and-scopes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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:
Expand Down
91 changes: 62 additions & 29 deletions ndc_analyser/src/analyser/assignments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand All @@ -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<WriteTarget>,
) {
if let StaticType::Var(var) = self.vars.resolve(value_type)
&& self.vars.is_literal(var)
Expand All @@ -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);
Expand All @@ -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;
}
Expand All @@ -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 { .. } => {
Expand All @@ -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<String>,
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<WriteTarget>,
recording: Option<SymbolId>,
copied_through: Option<Origin>,
}
19 changes: 13 additions & 6 deletions ndc_analyser/src/analyser/declarations.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::assignments::WriteTarget;
use super::generics::{BodyStart, Generalizing};
use super::solver::Constraint;
use super::{Analyser, Returns};
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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<Int> = 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);
Expand Down
21 changes: 15 additions & 6 deletions ndc_analyser/src/analyser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -176,8 +176,10 @@ pub struct Analyser {
/// What a function returns.
#[derive(Debug)]
pub(super) struct Returns {
/// Its annotated return type.
annotated: Option<StaticType>,
/// Its name, if it has one.
function: Option<String>,
/// 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)>,
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion ndc_analyser/src/analyser/solver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(_) => {}
Expand Down
Loading
Loading