From 9f8f61c81a1ef4d8e2af79d421fc9327c6668447 Mon Sep 17 00:00:00 2001 From: Tim Fennis Date: Sun, 29 Nov 2026 16:06:10 +0100 Subject: [PATCH] =?UTF-8?q?feat(analyser):=20type=20tuples=20of=20any=20le?= =?UTF-8?q?ngth=20with=20spread=20type=20parameters=20=F0=9F=A7=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A built-in's signature can declare a type parameter `..R` that stands for a tuple type and spread it into a tuple, as in `((A, ..R)) -> A`. A tuple among the parameters takes at most one spread, so a call's arguments say what each is. `len`, `first`, `last` and the comparisons take tuples of any length with one signature each instead of one per length up to twelve. Co-Authored-By: Claude Opus 5.5 --- ndc_analyser/src/analyser/solver.rs | 50 ++++++- ndc_analyser/src/analyser/tests.rs | 79 ++++++++++ ndc_analyser/src/overloads.rs | 20 ++- ndc_analyser/src/types/unify.rs | 61 +++++++- ndc_bin/src/docs.rs | 2 +- ndc_core/src/signature.rs | 140 +++++++++++++++++- ndc_core/src/static_type.rs | 92 +++++++++++- ndc_lsp/src/features/hover.rs | 2 +- ndc_stdlib/src/math.rs | 33 +---- ndc_stdlib/src/sequence.rs | 67 ++++----- ...079_tuples_compare_whole_at_any_length.ndc | 9 ++ ...es_compare_whole_up_to_twelve_elements.ndc | 7 - ...ples_of_different_lengths_dont_compare.ndc | 3 + ...a_function_takes_a_tuple_of_any_length.ndc | 8 + ...st_and_last_take_a_tuple_of_any_length.ndc | 7 + ...tuples_up_to_twelve_elements_are_typed.ndc | 5 - tests/functional/tests/stdlib_signatures.rs | 19 ++- 17 files changed, 486 insertions(+), 118 deletions(-) create mode 100644 tests/functional/programs/001_math/079_tuples_compare_whole_at_any_length.ndc delete mode 100644 tests/functional/programs/001_math/079_tuples_compare_whole_up_to_twelve_elements.ndc create mode 100644 tests/functional/programs/020_tuples/006_tuples_of_different_lengths_dont_compare.ndc create mode 100644 tests/functional/programs/020_tuples/007_a_function_takes_a_tuple_of_any_length.ndc create mode 100644 tests/functional/programs/603_stdlib_seq/029_first_and_last_take_a_tuple_of_any_length.ndc delete mode 100644 tests/functional/programs/603_stdlib_seq/029_tuples_up_to_twelve_elements_are_typed.ndc diff --git a/ndc_analyser/src/analyser/solver.rs b/ndc_analyser/src/analyser/solver.rs index 4acab3fe..37e61f44 100644 --- a/ndc_analyser/src/analyser/solver.rs +++ b/ndc_analyser/src/analyser/solver.rs @@ -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, @@ -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 @@ -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` 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` 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| { @@ -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> { diff --git a/ndc_analyser/src/analyser/tests.rs b/ndc_analyser/src/analyser/tests.rs index a2e09dd2..e6e7d20e 100644 --- a/ndc_analyser/src/analyser/tests.rs +++ b/ndc_analyser/src/analyser/tests.rs @@ -2201,3 +2201,82 @@ fn a_named_function_declared_as_a_statement_is_accepted() { assert_eq!(errors(source, vec![]), Vec::::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]"), + ("++", "<..A, ..B>((..A), (..B)) -> (..A, ..B)"), + ("first", "([T]) -> T"), + ("first", "((A, ..R)) -> A"), + ("last", "<..R, A>((..R, A)) -> A"), + ("push", "([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::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::((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]), + ]) + ); +} diff --git a/ndc_analyser/src/overloads.rs b/ndc_analyser/src/overloads.rs index 4ec889f8..a749974f 100644 --- a/ndc_analyser/src/overloads.rs +++ b/ndc_analyser/src/overloads.rs @@ -245,13 +245,23 @@ impl<'a> Overloads<'a> { /// /// A type parameter such as `T` in `first([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, } } diff --git a/ndc_analyser/src/types/unify.rs b/ndc_analyser/src/types/unify.rs index 9f1733b5..0f78d6ab 100644 --- a/ndc_analyser/src/types/unify.rs +++ b/ndc_analyser/src/types/unify.rs @@ -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); @@ -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 { + 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. @@ -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)) diff --git a/ndc_bin/src/docs.rs b/ndc_bin/src/docs.rs index 9b13e0ca..59732d3b 100644 --- a/ndc_bin/src/docs.rs +++ b/ndc_bin/src/docs.rs @@ -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::`. - let type_parameters = function.static_type.type_parameters(); + let type_parameters = function.static_type.type_parameter_declarations(); if !type_parameters.is_empty() { write!( line, diff --git a/ndc_core/src/signature.rs b/ndc_core/src/signature.rs index b0ac3302..cd67f0b6 100644 --- a/ndc_core/src/signature.rs +++ b/ndc_core/src/signature.rs @@ -9,16 +9,31 @@ impl StaticType { /// parameters and a return type. Without `-> …` the function returns /// `()`. `(*)` takes any number of arguments of any type, and /// `fn(Int) -> Int` is a function type. + /// + /// A type parameter declared as `..R` stands for a tuple type whose + /// elements are spread into a tuple, as in `((A, ..R)) -> A`, + /// which takes a tuple of one element or more. A call's arguments say + /// what each one is, so a tuple among the parameters has at most one + /// spread into it, and each is spread into a parameter: `<..A, + /// ..B>((..A), (..B)) -> (..A, ..B)` concatenates two tuples. pub fn signature(text: &str) -> Result { let mut parser = SignatureParser { tokens: tokenize(text)?, position: 0, generics: Vec::new(), + spreads: Vec::new(), }; let signature = parser.signature()?; if let Some(token) = parser.peek() { return Err(format!("unexpected '{token}' after the signature")); } + if let Self::Function { + parameters: Some(parameters), + .. + } = &signature + { + check_spreads(parameters, &parser.spreads)?; + } // Explicit type arguments, as in `f::(…)`, bind the // type parameters in the order they're declared, which is the order // they're first used in, so the type alone says it. @@ -38,6 +53,36 @@ impl StaticType { } } +/// Checks that a call's arguments say what each type parameter declared +/// as `..R` is: each is spread into a parameter, and no tuple among them +/// has more than one spread into it, as `(..A, ..B)` could split a tuple +/// anywhere. +fn check_spreads(parameters: &[StaticType], spreads: &[&str]) -> Result<(), String> { + let several = parameters.iter().find(|parameter| { + parameter.contains(&|part| { + matches!(part, StaticType::Tuple(elements) + if elements.iter().filter(|element| matches!(element, StaticType::Spread(_))).count() > 1) + }) + }); + if let Some(parameter) = several { + return Err(format!( + "a parameter can't have two tuples spread into one, as '{parameter}' does: which elements are which?" + )); + } + for &spread in spreads { + let spread_type = StaticType::Spread(Box::new(StaticType::Generic(spread.into()))); + if !parameters + .iter() + .any(|parameter| parameter.contains(&|part| *part == spread_type)) + { + return Err(format!( + "spread '..{spread}' into a parameter, so the arguments say what it is" + )); + } + } + Ok(()) +} + /// The tokens of `text`, as slices of it: `[T]` is `[`, `T` and `]`. fn tokenize(text: &str) -> Result, String> { let mut tokens = Vec::new(); @@ -54,6 +99,9 @@ fn tokenize(text: &str) -> Result, String> { '-' if chars.next_if(|&(_, next)| next == '>').is_some() => { tokens.push(&text[start..start + 2]); } + '.' if chars.next_if(|&(_, next)| next == '.').is_some() => { + tokens.push(&text[start..start + 2]); + } c if c.is_alphabetic() || c == '_' => { let mut end = start + c.len_utf8(); while let Some((index, next)) = @@ -74,6 +122,9 @@ struct SignatureParser<'a> { position: usize, /// The type parameters the signature declared, such as `T` in ``. generics: Vec<&'a str>, + /// The ones of them declared as `..R`, which stand for a tuple type + /// spread into a tuple. + spreads: Vec<&'a str>, } impl<'a> SignatureParser<'a> { @@ -111,11 +162,15 @@ impl<'a> SignatureParser<'a> { fn signature(&mut self) -> Result { if self.eat("<") { loop { + let spread = self.eat(".."); let name = self.next()?; if self.generics.contains(&name) { return Err(format!("type parameter '{name}' is declared twice")); } self.generics.push(name); + if spread { + self.spreads.push(name); + } if !self.eat(",") { break; } @@ -159,15 +214,44 @@ impl<'a> SignatureParser<'a> { Ok(types) } + /// What follows `..` in a tuple: a type parameter declared as `..R`. + fn spread(&mut self) -> Result { + let name = self.next()?; + if self.spreads.contains(&name) { + Ok(StaticType::Spread(Box::new(StaticType::Generic( + name.into(), + )))) + } else { + Err(format!( + "only a type parameter declared as '..{name}' can be spread into a tuple" + )) + } + } + fn typ(&mut self) -> Result { let token = self.next()?; match token { - // `()` is unit, `(A, B)` and `(A,)` are tuples, and `(A)` is just `A`. + // `()` is unit, `(A, B)` and `(A,)` are tuples, and `(A)` is + // just `A`. `(..R)` is a tuple with the elements of `R`. "(" => { let start = self.position; - let mut elements = self.list(")")?; + let mut elements = Vec::new(); + while !self.eat(")") { + elements.push(if self.eat("..") { + self.spread()? + } else { + self.typ()? + }); + if !self.eat(",") { + self.expect(")")?; + break; + } + } let trailing_comma = self.tokens[start..self.position].ends_with(&[",", ")"]); - if elements.len() == 1 && !trailing_comma { + if let [only] = &elements[..] + && !trailing_comma + && !matches!(only, StaticType::Spread(_)) + { Ok(elements.remove(0)) } else { Ok(StaticType::Tuple(elements)) @@ -192,6 +276,9 @@ impl<'a> SignatureParser<'a> { }) } "fn" => self.function(), + name if self.spreads.contains(&name) => Err(format!( + "'{name}' stands for a tuple's elements: spread it into a tuple, as in '(..{name})'" + )), name if self.generics.contains(&name) => Ok(StaticType::Generic(name.into())), name => { let arguments = if self.eat("<") { @@ -301,6 +388,53 @@ mod tests { } } + fn spread(name: &str) -> StaticType { + StaticType::Spread(Box::new(generic(name))) + } + + #[test] + fn a_tuple_type_parameter_is_spread_into_tuples() { + assert_eq!( + StaticType::signature("<..A, ..B>((..A), (..B)) -> (..A, ..B)"), + Ok(function( + Some(vec![ + StaticType::Tuple(vec![spread("A")]), + StaticType::Tuple(vec![spread("B")]), + ]), + StaticType::Tuple(vec![spread("A"), spread("B")]), + )) + ); + assert_eq!( + StaticType::signature("<..R, A>((..R, A)) -> A"), + Ok(function( + Some(vec![StaticType::Tuple(vec![spread("R"), generic("A")])]), + generic("A"), + )) + ); + assert_eq!( + StaticType::signature("([(A, ..R)]) -> [A]") + .map(|signature| signature.to_string()), + Ok("fn([(A, ..R)]) -> [A]".to_string()) + ); + } + + #[test] + fn a_spread_the_arguments_cant_say_is_rejected() { + for (text, says) in [ + ( + "<..A, ..B>((..A, ..B)) -> Int", + "two tuples spread into one", + ), + ("((..A)) -> Int", "declared as '..A'"), + ("<..A>(A) -> Int", "spread it into a tuple"), + ("<..A>([A]) -> Int", "spread it into a tuple"), + ("(T) -> (..A)", "spread '..A' into a parameter"), + ] { + let error = StaticType::signature(text).unwrap_err(); + assert!(error.contains(says), "{text}: {error}"); + } + } + #[test] fn type_parameters_are_declared_in_the_order_they_are_first_used_in() { assert!(StaticType::signature("(Iterable, A) -> A").is_ok()); diff --git a/ndc_core/src/static_type.rs b/ndc_core/src/static_type.rs index 5c2bfe40..bfaca154 100644 --- a/ndc_core/src/static_type.rs +++ b/ndc_core/src/static_type.rs @@ -58,6 +58,13 @@ pub enum StaticType { List(Box), String, Tuple(Vec), + /// The elements of a tuple spread into a tuple, as `..R` is in + /// `first((A, ..R)) -> A`, where `R` is a tuple type: a + /// `(Int, String, Bool)` is a `(A, ..R)` with `A` an Int and `R` a + /// `(String, Bool)`. It's only ever an element of a tuple in a built-in's + /// signature. Once what it spreads is a known tuple, the tuple holding + /// it has those elements in its place: see [`Self::replace`]. + Spread(Box), Map { key: Box, value: Box, @@ -337,9 +344,18 @@ impl StaticType { | (Self::MinHeap(a), Self::MinHeap(p)) | (Self::MaxHeap(a), Self::MaxHeap(p)) | (Self::Deque(a), Self::Deque(p)) => matches(a, p), - (Self::Tuple(a), Self::Tuple(p)) => { - a.len() == p.len() && a.iter().zip(p).all(|(a, p)| matches(a, p)) - } + (Self::Tuple(a), Self::Tuple(p)) => match Self::split_spread(p) { + // What's spread is a type parameter, which any elements are. + Some((prefix, _, suffix)) => { + a.len() >= prefix.len() + suffix.len() + && a.iter().zip(prefix).all(|(a, p)| matches(a, p)) + && a.iter() + .rev() + .zip(suffix.iter().rev()) + .all(|(a, p)| matches(a, p)) + } + None => a.len() == p.len() && a.iter().zip(p).all(|(a, p)| matches(a, p)), + }, (Self::Map { key: ak, value: av }, Self::Map { key: pk, value: pv }) => { matches(ak, pk) && matches(av, pv) } @@ -423,9 +439,20 @@ impl StaticType { Self::MinHeap(t) => Self::MinHeap(map(t)), Self::MaxHeap(t) => Self::MaxHeap(map(t)), Self::Deque(t) => Self::Deque(map(t)), - Self::Tuple(elements) => { - Self::Tuple(elements.iter().map(|e| e.replace(replace)).collect()) - } + Self::Tuple(elements) => Self::Tuple( + elements + .iter() + .flat_map(|element| match element.replace(replace) { + // A tuple spread into a tuple is its elements there. + Self::Spread(spread) => match *spread { + Self::Tuple(spread) => spread, + other => vec![Self::Spread(Box::new(other))], + }, + element => vec![element], + }) + .collect(), + ), + Self::Spread(t) => Self::Spread(map(t)), Self::Map { key, value } => Self::Map { key: map(key), value: map(value), @@ -469,7 +496,8 @@ impl StaticType { | Self::Lazy(t) | Self::MinHeap(t) | Self::MaxHeap(t) - | Self::Deque(t) => t.contains(test), + | Self::Deque(t) + | Self::Spread(t) => t.contains(test), Self::Tuple(elements) => elements.iter().any(|e| e.contains(test)), Self::Map { key, value } => key.contains(test) || value.contains(test), Self::Any @@ -504,6 +532,23 @@ impl StaticType { names.into_inner() } + /// The type parameters in this type as a signature declares them, in + /// the order of [`Self::type_parameters`], one spread into a tuple as + /// `..R`: `["A", "..R"]` for `fn((A, ..R)) -> A`. + pub fn type_parameter_declarations(&self) -> Vec { + self.type_parameters() + .into_iter() + .map(|name| { + let spread = Self::Spread(Box::new(Self::Generic(name.clone()))); + if self.contains(&|part| *part == spread) { + format!("..{name}") + } else { + name.into() + } + }) + .collect() + } + /// The type parameters a built-in's signature declares, as the types /// that stand for them: a signature declares them in the order they're /// first used in, which is the order of [`Self::type_parameters`]. @@ -525,6 +570,25 @@ impl StaticType { Self::Tuple(vec![]) } + /// The elements of a tuple before the one tuple spread into it, what's + /// spread, and the elements after it: `(A, ..R, Z)` is `[A]`, `R` and + /// `[Z]`. `None` if nothing is spread into it, or more than one tuple + /// is, as in `(..A, ..B)`, which only a signature's return type has. + #[must_use] + pub fn split_spread(elements: &[Self]) -> Option<(&[Self], &Self, &[Self])> { + let mut spreads = elements + .iter() + .enumerate() + .filter(|(_, element)| matches!(element, Self::Spread(_))); + let (index, Self::Spread(spread)) = spreads.next()? else { + unreachable!("only spreads are left"); + }; + if spreads.next().is_some() { + return None; + } + Some((&elements[..index], spread, &elements[index + 1..])) + } + /// Whether this is the type of a set: a map whose values are `()`, /// `%{K}`, which iterates as its keys. #[must_use] @@ -610,6 +674,14 @@ impl StaticType { | (Self::MinHeap(s), Self::MinHeap(t)) | (Self::MaxHeap(s), Self::MaxHeap(t)) | (Self::Deque(s), Self::Deque(t)) => Self::held_overlap(s, t), + // A tuple with elements spread into it could be of any length + // but that of the elements around them. + (Self::Tuple(s_elems), Self::Tuple(t_elems)) + if Self::split_spread(s_elems).is_some() + || Self::split_spread(t_elems).is_some() => + { + true + } (Self::Tuple(s_elems), Self::Tuple(t_elems)) => { s_elems.len() == t_elems.len() && s_elems.iter().zip(t_elems).all(|(s, t)| s.overlaps(t)) @@ -714,6 +786,7 @@ impl StaticType { // A lazy sequence is unpacked once it's a list. | Self::Lazy(_) | Self::Struct { .. } // for now, we won't have positional unpacking + | Self::Spread(_) | Self::Never | Self::Unknown => None, } @@ -748,7 +821,9 @@ impl fmt::Display for StaticType { Self::List(elem) => write!(f, "[{elem}]"), Self::String => write!(f, "String"), Self::Tuple(tup) if tup.is_empty() => write!(f, "()"), - Self::Tuple(tup) if tup.len() == 1 => write!(f, "({},)", tup[0]), + Self::Tuple(tup) if tup.len() == 1 && !matches!(tup[0], Self::Spread(_)) => { + write!(f, "({},)", tup[0]) + } Self::Tuple(tup) => write!(f, "({})", tup.iter().join(", ")), Self::Map { key, value } if matches!(value.as_ref(), Self::Tuple(t) if t.is_empty()) => { write!(f, "%{{{key}}}") @@ -760,6 +835,7 @@ impl fmt::Display for StaticType { Self::MinHeap(elem) => write!(f, "MinHeap<{elem}>"), Self::MaxHeap(elem) => write!(f, "MaxHeap<{elem}>"), Self::Deque(elem) => write!(f, "Deque<{elem}>"), + Self::Spread(spread) => write!(f, "..{spread}"), } } } diff --git a/ndc_lsp/src/features/hover.rs b/ndc_lsp/src/features/hover.rs index 259cef84..d4eb77e7 100644 --- a/ndc_lsp/src/features/hover.rs +++ b/ndc_lsp/src/features/hover.rs @@ -186,7 +186,7 @@ fn with_type_arguments(state: &DocumentState, typ: &StaticType, offset: usize) - /// with its type parameters after the name, in the order type arguments /// bind them: `fold(Iterable, A, fn(A, T) -> A) -> A`. fn format_signature(name: &str, typ: &StaticType) -> String { - let type_parameters = typ.type_parameters(); + let type_parameters = typ.type_parameter_declarations(); let name = if type_parameters.is_empty() { name.to_string() } else { diff --git a/ndc_stdlib/src/math.rs b/ndc_stdlib/src/math.rs index f1146476..2ebca623 100644 --- a/ndc_stdlib/src/math.rs +++ b/ndc_stdlib/src/math.rs @@ -528,12 +528,10 @@ fn compare_operands(args: &[Value]) -> Result { /// The parameter lists of the comparisons, for the values that have an /// order: numbers of any kind, against each other, strings, booleans, and -/// lists and tuples of what has an order, a tuple of each length up to -/// twelve, as `first` and `last` take, with one of the same length. The empty -/// tuple's is declared apart, as a signature can't spell it. Maps, deques, -/// options, structs and functions have none, and neither do values of two -/// different kinds. A list or tuple of what has no order still passes as one: -/// that needs a constraint on the type parameter. +/// lists and tuples of what has an order, a tuple with one of the same +/// length. Maps, deques, options, structs and functions have none, and +/// neither do values of two different kinds. A list or tuple of what has no +/// order still passes as one: that needs a constraint on the type parameter. fn orderable_parameters() -> Vec { let numbers = ["Int", "Float", "Number"]; let mut parameters = Vec::new(); @@ -545,13 +543,7 @@ fn orderable_parameters() -> Vec { parameters.push("(String, String)".to_string()); parameters.push("(Bool, Bool)".to_string()); parameters.push("([T], [T])".to_string()); - for arity in 1..=12 { - let names = (0..arity) - .map(|index| char::from(b'A' + index).to_string()) - .collect::>() - .join(", "); - parameters.push(format!("<{names}>(({names},), ({names},))")); - } + parameters.push("<..A>((..A), (..A))".to_string()); parameters } @@ -581,13 +573,6 @@ fn register_comparisons(env: &mut FunctionRegistry) { for parameters in orderable_parameters() { declare_operator(env, name, format!("{parameters} -> Bool"), docs, operator); } - let unit = StaticType::unit(); - env.declare_global_fn(NativeSpec::operator( - name, - docs, - move || function_type(vec![unit.clone(), unit], StaticType::Bool), - operator, - )); } declare_operator( @@ -620,14 +605,6 @@ fn register_comparisons(env: &mut FunctionRegistry) { for parameters in orderable_parameters() { declare_signature(env, name, format!("{parameters} -> Int"), docs, compare); } - let unit = StaticType::unit(); - declare( - env, - name, - docs, - move || function_type(vec![unit.clone(), unit], StaticType::Int), - compare, - ); } } diff --git a/ndc_stdlib/src/sequence.rs b/ndc_stdlib/src/sequence.rs index 3096f5b5..f31cd4b9 100644 --- a/ndc_stdlib/src/sequence.rs +++ b/ndc_stdlib/src/sequence.rs @@ -1209,20 +1209,13 @@ fn scan_into( } pub mod extra { - use ndc_core::{FunctionRegistry, StaticType}; + use ndc_core::FunctionRegistry; use ndc_vm::NativeSpec; use ndc_vm::error::VmError; use ndc_vm::value::{NativeFunc, Object, Value}; use std::rc::Rc; pub fn register(env: &mut FunctionRegistry) { - // A tuple's elements have their own types, and a signature can't say - // "a tuple of any length", so each length up to twelve, as far as - // Rust's standard library goes for tuples, gets one that says which. - const LONGEST: usize = 12; - let names = |count: usize| { - ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"][..count].to_vec() - }; // Every tuple, the empty one too, has a length. let tuple_len = |args: &[Value]| match args { [Value::Object(object)] => match object.as_ref() { @@ -1231,47 +1224,37 @@ pub mod extra { }, _ => Err(VmError::native("len of a tuple takes a tuple")), }; - env.declare_global_fn(NativeSpec::new( + env.declare_global_fn(NativeSpec::with_signature( "len", "Returns the number of elements of a tuple.", - move || StaticType::Function { - parameters: Some(vec![StaticType::unit()]), - return_type: Box::new(StaticType::Int), - }, + "<..A>((..A)) -> Int", move || NativeFunc::Simple(Box::new(tuple_len)), )); - for length in 1..=LONGEST { - let names = names(length); - let parameters = names.join(", "); - let tuple = if length == 1 { - "(A,)".to_string() - } else { - format!("({parameters})") - }; + for (name, signature, documentation) in [ + ( + "first", + "((A, ..R)) -> A", + "Returns the first element of a tuple.", + ), + ( + "last", + "<..R, A>((..R, A)) -> A", + "Returns the last element of a tuple.", + ), + ] { env.declare_global_fn(NativeSpec::with_signature( - "len", - "Returns the number of elements of a tuple.", - format!("<{parameters}>({tuple}) -> Int"), - move || NativeFunc::Simple(Box::new(tuple_len)), + name, + documentation, + signature, + move || NativeFunc::Simple(Box::new(move |args| tuple_end(args, name == "first"))), )); - for (name, returns, documentation) in [ - ("first", names[0], "Returns the first element of a tuple."), - ( - "last", - names[length - 1], - "Returns the last element of a tuple.", - ), - ] { - env.declare_global_fn(NativeSpec::with_signature( - name, - documentation, - format!("<{parameters}>({tuple}) -> {returns}"), - move || { - NativeFunc::Simple(Box::new(move |args| tuple_end(args, name == "first"))) - }, - )); - } } + // Each length of the sequences zipped, up to twelve, gets its own + // overload, as Rust's standard library does for tuples. + const LONGEST: usize = 12; + let names = |count: usize| { + ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"][..count].to_vec() + }; // Two or more sequences zip into tuples of their elements. for length in 2..=LONGEST { let names = names(length); diff --git a/tests/functional/programs/001_math/079_tuples_compare_whole_at_any_length.ndc b/tests/functional/programs/001_math/079_tuples_compare_whole_at_any_length.ndc new file mode 100644 index 00000000..b3ee714d --- /dev/null +++ b/tests/functional/programs/001_math/079_tuples_compare_whole_at_any_length.ndc @@ -0,0 +1,9 @@ +// A tuple compares as a whole with one of the same length, the empty tuple +// and tuples of more than twelve elements too. +// expect-output: true -1 0 false true false 13 0 12 +let nine = (1, 2, 3, 4, 5, 6, 7, 8, 9); +let other = (1, 2, 3, 4, 5, 6, 7, 8, 10); +let twelve = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "z"); +let thirteen = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, "a"); +let later = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, "b"); +print(nine < other, nine <=> other, () <=> (), () < (), thirteen < later, thirteen >= later, len(thirteen), len(()), len(twelve)); diff --git a/tests/functional/programs/001_math/079_tuples_compare_whole_up_to_twelve_elements.ndc b/tests/functional/programs/001_math/079_tuples_compare_whole_up_to_twelve_elements.ndc deleted file mode 100644 index 93e48614..00000000 --- a/tests/functional/programs/001_math/079_tuples_compare_whole_up_to_twelve_elements.ndc +++ /dev/null @@ -1,7 +0,0 @@ -// A tuple compares as a whole with one of the same length, the empty tuple -// too, up to twelve elements, as `first`, `last` and `zip` take. -// expect-output: true -1 0 false 9 0 12 -let nine = (1, 2, 3, 4, 5, 6, 7, 8, 9); -let other = (1, 2, 3, 4, 5, 6, 7, 8, 10); -let twelve = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "z"); -print(nine < other, nine <=> other, () <=> (), () < (), len(nine), len(()), len(twelve)); diff --git a/tests/functional/programs/020_tuples/006_tuples_of_different_lengths_dont_compare.ndc b/tests/functional/programs/020_tuples/006_tuples_of_different_lengths_dont_compare.ndc new file mode 100644 index 00000000..f9ea41d9 --- /dev/null +++ b/tests/functional/programs/020_tuples/006_tuples_of_different_lengths_dont_compare.ndc @@ -0,0 +1,3 @@ +// Tuples compare only with tuples of the same length. +// expect-error: No function called '<' found that matches the arguments '(Int, Int), (Int, Int, Int)' +print((1, 2) < (1, 2, 3)); diff --git a/tests/functional/programs/020_tuples/007_a_function_takes_a_tuple_of_any_length.ndc b/tests/functional/programs/020_tuples/007_a_function_takes_a_tuple_of_any_length.ndc new file mode 100644 index 00000000..ac738bb1 --- /dev/null +++ b/tests/functional/programs/020_tuples/007_a_function_takes_a_tuple_of_any_length.ndc @@ -0,0 +1,8 @@ +// A function whose parameter isn't annotated takes a tuple of any length +// where the functions it calls do, and gives each call's own types. +// expect-output: 3 z 2.5 true +fn ends(t) => (t.first, t.last, len(t)); +let (n, s, size) = ends((1, "y", "z")); +let (x, _, _) = ends((2.5,)); +let before = fn(a, b) => a < b; +print(size, s, x, before((1, "a"), (1, "b")) and n == 1); diff --git a/tests/functional/programs/603_stdlib_seq/029_first_and_last_take_a_tuple_of_any_length.ndc b/tests/functional/programs/603_stdlib_seq/029_first_and_last_take_a_tuple_of_any_length.ndc new file mode 100644 index 00000000..b173474c --- /dev/null +++ b/tests/functional/programs/603_stdlib_seq/029_first_and_last_take_a_tuple_of_any_length.ndc @@ -0,0 +1,7 @@ +// `first` and `last` take a tuple of any length, and `zip` up to twelve +// sequences. +// expect-output: 2 z! (1,) [(1,2,3,4,5)] +let t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "z"); +let zipped: [(Int, Int, Int, Int, Int)] = zip([1], [2], [3], [4], [5]); +let one = ((1,),); +print(t.first + 1, t.last ++ "!", one.last, zipped); diff --git a/tests/functional/programs/603_stdlib_seq/029_tuples_up_to_twelve_elements_are_typed.ndc b/tests/functional/programs/603_stdlib_seq/029_tuples_up_to_twelve_elements_are_typed.ndc deleted file mode 100644 index d782139a..00000000 --- a/tests/functional/programs/603_stdlib_seq/029_tuples_up_to_twelve_elements_are_typed.ndc +++ /dev/null @@ -1,5 +0,0 @@ -// `first`, `last` and `zip` are typed for tuples of up to twelve elements. -// expect-output: 2 z! [(1,2,3,4,5)] -let t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "z"); -let zipped: [(Int, Int, Int, Int, Int)] = zip([1], [2], [3], [4], [5]); -print(t.first + 1, t.last ++ "!", zipped); diff --git a/tests/functional/tests/stdlib_signatures.rs b/tests/functional/tests/stdlib_signatures.rs index 2b53f415..28b6b9ea 100644 --- a/tests/functional/tests/stdlib_signatures.rs +++ b/tests/functional/tests/stdlib_signatures.rs @@ -186,13 +186,22 @@ fn first(mut values: Vec, count: usize) -> Vec { } /// `typ` with each type parameter named in `names` as the type at the same -/// place in `types`. +/// place in `types`, or, for one spread into a tuple as `..R` is, a pair of +/// them: `(A, ..R)` with Ints is `(Int, Int, Int)`. fn instantiate(typ: &StaticType, names: &[Box], types: &[StaticType]) -> StaticType { - typ.replace(&|part| match part { - StaticType::Generic(name) => names + let chosen = |name: &str| { + names .iter() - .position(|named| named == name) - .map(|index| types[index].clone()), + .position(|named| named.as_ref() == name) + .map(|index| types[index].clone()) + }; + typ.replace(&|part| match part { + StaticType::Spread(spread) => match spread.as_ref() { + StaticType::Generic(name) => chosen(name) + .map(|typ| StaticType::Spread(Box::new(StaticType::Tuple(vec![typ.clone(), typ])))), + _ => None, + }, + StaticType::Generic(name) => chosen(name), _ => None, }) }