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
50 changes: 42 additions & 8 deletions ndc_analyser/src/analyser/solver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1902,7 +1902,7 @@ impl Analyser {
[only]
if (!self.operand_could_be_a_tuple(kind, arguments)
|| self.takes_whole_tuples(only, type_arguments, arguments))
&& self.iterables_known(only, arguments)
&& self.shapes_known(only, arguments)
&& !(literals
&& self.fits_once_any(
&reachable,
Expand Down Expand Up @@ -1958,7 +1958,7 @@ impl Analyser {
})
.find(|group| !group.is_empty())?;
let narrowest = self.most_specific(&nearest)?;
if !self.iterables_known(narrowest, arguments) {
if !self.shapes_known(narrowest, arguments) {
return None;
}
// What isn't known yet of the overload itself, such as the parameter
Expand Down Expand Up @@ -1995,11 +1995,14 @@ impl Analyser {
free.then_some(narrowest)
}

/// Whether `symbol`'s `Iterable` parameters are given arguments whose
/// kind of sequence is known. An `Iterable<T>` parameter takes any kind
/// of sequence, so it can't tell what an argument nothing is known about
/// is, and the call waits for it as `for x in xs` does.
fn iterables_known(&self, symbol: SymbolId, arguments: &[StaticType]) -> bool {
/// Whether `symbol`'s parameters that take arguments of many shapes are
/// given arguments whose shape is known. An `Iterable<T>` parameter
/// takes any kind of sequence, so it can't tell what an argument nothing
/// is known about is, and the call waits for it as `for x in xs` does.
/// A tuple with another spread into it, as `(..A)` in `len`'s
/// signature, takes tuples of any length, so the call waits for its
/// argument to be a tuple, as it would if each length had an overload.
fn shapes_known(&self, symbol: SymbolId, arguments: &[StaticType]) -> bool {
self.overloads()
.parameters_of(symbol)
.is_some_and(|parameters| {
Expand All @@ -2008,11 +2011,42 @@ impl Analyser {
.zip(arguments)
.all(|(parameter, argument)| match parameter {
StaticType::Iterable(_) => !self.vars.waits_to_iterate(argument),
_ => true,
_ => self.lengths_known(parameter, argument),
})
})
}

/// Whether `argument` is, at each tuple of `parameter` with another
/// spread into it, a tuple: see [`Self::shapes_known`].
fn lengths_known(&self, parameter: &StaticType, argument: &StaticType) -> bool {
if !parameter.contains(&|part| matches!(part, StaticType::Spread(_))) {
return true;
}
match (parameter, self.vars.resolve(argument)) {
(_, StaticType::Var(_)) => false,
(StaticType::Tuple(parameters), StaticType::Tuple(arguments)) => {
match StaticType::split_spread(parameters) {
Some((prefix, _, suffix)) => {
arguments.len() >= prefix.len() + suffix.len()
&& prefix
.iter()
.zip(&arguments)
.chain(suffix.iter().rev().zip(arguments.iter().rev()))
.all(|(parameter, argument)| {
self.lengths_known(parameter, argument)
})
}
None => parameters
.iter()
.zip(&arguments)
.all(|(parameter, argument)| self.lengths_known(parameter, argument)),
}
}
// Spread deeper in, as in `[(A, ..R)]`: everything has to be known.
(_, argument) => !self.vars.has_unknowns(&argument),
}
}

/// `arguments` with each literal among them whose values share no type
/// as `Any`, when there's one and that leaves nothing unknown.
fn unshared_literals_as_any(&mut self, arguments: &[StaticType]) -> Option<Vec<StaticType>> {
Expand Down
79 changes: 79 additions & 0 deletions ndc_analyser/src/analyser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2201,3 +2201,82 @@ fn a_named_function_declared_as_a_statement_is_accepted() {
assert_eq!(errors(source, vec![]), Vec::<String>::new(), "{source}");
}
}

/// Tuple concatenation and the ends of a tuple, with list overloads beside
/// them, as the stdlib has them.
fn spread_natives() -> Vec<(String, StaticType)> {
let mut globals = natives(&[
("++", "<T>([T], [T]) -> [T]"),
("++", "<..A, ..B>((..A), (..B)) -> (..A, ..B)"),
("first", "<T>([T]) -> T"),
("first", "<A, ..R>((A, ..R)) -> A"),
("last", "<..R, A>((..R, A)) -> A"),
("push", "<T>([T], T)"),
]);
globals.extend(index_natives());
globals
}

#[test]
fn a_signature_with_a_spread_takes_a_tuple_of_any_length() {
let tuple = |elements: Vec<StaticType>| StaticType::Tuple(elements);
assert_eq!(
analyse_last_type_with_globals("(1, \"a\") ++ (2.5, ())", spread_natives()),
tuple(vec![
StaticType::Int,
StaticType::String,
StaticType::Float,
StaticType::unit()
])
);
assert_eq!(
analyse_last_type_with_globals("() ++ ()", spread_natives()),
StaticType::unit()
);
assert_eq!(
analyse_last_type_with_globals(
"let t = (1, \"a\", 2.5, true); (first(t), last(t))",
spread_natives()
),
tuple(vec![StaticType::Int, StaticType::Bool])
);
// `first` takes no empty tuple, and `last` no list.
assert_analysis_error("first(())", spread_natives(), "first");
assert_analysis_error("last([1])", spread_natives(), "last");
}

#[test]
fn a_type_argument_for_a_spread_is_a_tuple_type() {
let globals = || natives(&[("len", "<..A>((..A)) -> Int")]);
assert_eq!(
analyse_last_type_with_globals("len::<(Int, String)>((1, \"a\"))", globals()),
StaticType::Int
);
assert_analysis_error("len::<(Int, String)>((1, 2))", globals(), "len");
assert_analysis_error("len::<Int>((1,))", globals(), "len");
}

#[test]
fn a_call_with_a_spread_waits_for_its_argument_to_be_a_tuple() {
// `xs[0]` could be a tuple of any length until `push` says it's a
// `(String,)`, as it could be one of each length were there an overload
// per length.
assert_eq!(
analyse_last_type_with_globals(
"let xs = []; let t = xs[0] ++ (1,); xs.push((\"a\",)); t",
spread_natives()
),
StaticType::Tuple(vec![StaticType::String, StaticType::Int])
);
// A function's parameter gets its tuple at each call.
assert_eq!(
analyse_last_type_with_globals(
"fn ends(t) => (first(t), last(t)); (ends((1, \"a\")), ends((true,)))",
spread_natives()
),
StaticType::Tuple(vec![
StaticType::Tuple(vec![StaticType::Int, StaticType::String]),
StaticType::Tuple(vec![StaticType::Bool, StaticType::Bool]),
])
);
}
20 changes: 15 additions & 5 deletions ndc_analyser/src/overloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,13 +245,23 @@ impl<'a> Overloads<'a> {
///
/// A type parameter such as `T` in `first<T>([T]) -> T` is `Any`
/// here: only a call that commits to the overload knows what it stands
/// for.
/// for. So is a tuple with one spread into it, as `(..A, ..B)`, which
/// could be of any length.
pub(crate) fn scalar_return_type(self, symbol: SymbolId) -> StaticType {
match self.type_of(symbol).as_ref() {
StaticType::Function { return_type, .. } => self
.vars
.resolve(return_type)
.replace(&|part| matches!(part, StaticType::Generic(_)).then_some(StaticType::Any)),
StaticType::Function { return_type, .. } => {
self.vars.resolve(return_type).replace(&|part| match part {
StaticType::Generic(_) => Some(StaticType::Any),
StaticType::Tuple(elements)
if elements
.iter()
.any(|element| matches!(element, StaticType::Spread(_))) =>
{
Some(StaticType::Any)
}
_ => None,
})
}
_ => StaticType::Any,
}
}
Expand Down
61 changes: 56 additions & 5 deletions ndc_analyser/src/types/unify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,9 @@ impl TypeVars {
| (StaticType::Lazy(x), StaticType::Lazy(y))
| (StaticType::MinHeap(x), StaticType::MinHeap(y))
| (StaticType::MaxHeap(x), StaticType::MaxHeap(y))
| (StaticType::Deque(x), StaticType::Deque(y)) => self.unify(x, y),
(StaticType::Tuple(xs), StaticType::Tuple(ys)) => {
xs.len() == ys.len() && xs.iter().zip(ys).all(|(x, y)| self.unify(x, y))
}
| (StaticType::Deque(x), StaticType::Deque(y))
| (StaticType::Spread(x), StaticType::Spread(y)) => self.unify(x, y),
(StaticType::Tuple(xs), StaticType::Tuple(ys)) => self.unify_tuples(xs, ys),
(StaticType::Map { key: k1, value: v1 }, StaticType::Map { key: k2, value: v2 }) => {
let keys = self.unify(k1, k2);
let values = self.unify(v1, v2);
Expand Down Expand Up @@ -136,6 +135,58 @@ impl TypeVars {
}
}

/// Makes two tuples the same, as [`Self::unify`]. A tuple with another
/// one spread into it, as `(A, ..R)` from `first`'s signature, is
/// the same as one with at least the elements around it: `R` is the
/// tuple of the elements in its place, so `(?A, ..?R)` and
/// `(Int, String, Bool)` are the same once `?A` is an Int and `?R` a
/// `(String, Bool)`. Where two tuples are spread into one, as in
/// `(..A, ..B)`, or both have one, which elements are whose isn't said,
/// so they're the same only element by element.
fn unify_tuples(&mut self, xs: &[StaticType], ys: &[StaticType]) -> bool {
let (xs, ys) = (self.spliced(xs), self.spliced(ys));
let spreads = |elements: &[StaticType]| {
elements
.iter()
.filter(|e| matches!(e, StaticType::Spread(_)))
.count()
};
let (pattern, elements) = match (spreads(&xs), spreads(&ys)) {
(1, 0) => (&xs, &ys),
(0, 1) => (&ys, &xs),
_ => {
return xs.len() == ys.len() && xs.iter().zip(&ys).all(|(x, y)| self.unify(x, y));
}
};
let (prefix, spread, suffix) =
StaticType::split_spread(pattern).expect("one tuple is spread into it");
let Some(middle) = elements.len().checked_sub(prefix.len() + suffix.len()) else {
return false;
};
let (before, rest) = elements.split_at(prefix.len());
let (spread_elements, after) = rest.split_at(middle);
let prefixes = prefix.iter().zip(before).all(|(x, y)| self.unify(x, y));
let suffixes = suffix.iter().zip(after).all(|(x, y)| self.unify(x, y));
prefixes && suffixes && self.unify(spread, &StaticType::Tuple(spread_elements.to_vec()))
}

/// `elements` with each tuple spread into them that's known by now in
/// its place: `(A, ..?R)` is `(A, String, Bool)` once `?R` is a
/// `(String, Bool)`.
fn spliced(&self, elements: &[StaticType]) -> Vec<StaticType> {
let mut spliced = Vec::with_capacity(elements.len());
for element in elements {
match element {
StaticType::Spread(spread) => match self.shallow(spread) {
StaticType::Tuple(spread) => spliced.extend(self.spliced(&spread)),
_ => spliced.push(element.clone()),
},
_ => spliced.push(element.clone()),
}
}
spliced
}

/// The parameters of the function type `typ`, with new variables for
/// its type parameters but those `made` already has, or `None` when
/// `typ` isn't a function whose parameters are known.
Expand Down Expand Up @@ -449,7 +500,7 @@ impl TypeVars {
}

/// Whether `typ` has a part not known yet that isn't a literal's type.
pub(super) fn has_unknowns(&self, typ: &StaticType) -> bool {
pub(crate) fn has_unknowns(&self, typ: &StaticType) -> bool {
self.unsettled(typ)
.into_iter()
.any(|var| !self.is_literal(var))
Expand Down
2 changes: 1 addition & 1 deletion ndc_bin/src/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ pub fn docs(query: Option<&str>, no_color: bool) -> anyhow::Result<()> {
let mut line = String::new();
write!(line, "{}", function.name.bold().yellow())?;
// In the order type arguments bind them: `fold::<Int, String>`.
let type_parameters = function.static_type.type_parameters();
let type_parameters = function.static_type.type_parameter_declarations();
if !type_parameters.is_empty() {
write!(
line,
Expand Down
Loading
Loading