Skip to main content

zelkova_compiler/canonical/
mod.rs

1//! The canonical representation of a zelkova programs is a translation of a local
2//! source into the broader world.
3//!
4//! This phase is where we integrate the local parsed module into the rest of the
5//! program. We do the following steps:
6//!
7//! - Resolve all imports
8//! - Qualify all `Name` (eg. a local value `test` in a `Mod.A` module will be renamed `Mod.A.test`)
9//! - Checks that exported names are actually present in the module
10//! - Checks there is none cyclic dependency between this module and others (Might be done earlier, let's see)
11//!
12//! Note that we use `HashMap`'s a lot in this module's structures. This is because later phases will
13//! want to have cheap access to the different components of a `Module`.
14//!
15//! TODO Rename this to core ? I feel it's going to be te main internal representation of the language.
16use super::resolve::CORE_PACKAGE;
17use super::scalars;
18use super::Interface;
19use super::PhaseError;
20use super::SpanLabel;
21use super::{ModuleName, PackageName};
22use crate::utils::{collect_accumulate, collect_partial};
23use log::{debug, trace};
24use petgraph::graph::{DiGraph, NodeIndex};
25use petgraph::Direction;
26use std::cmp::Reverse;
27use std::collections::BinaryHeap;
28use std::collections::{BTreeMap, HashMap, HashSet};
29use zelkova_syntax::parser;
30
31mod classes;
32pub use classes::{
33    Class, ClassSignature, Constraint, DeclarationSite, Derivation, DerivationBindings,
34    DerivationRole, HeadName, Instance, InstanceHead, InstanceName, InstanceSignature, Member,
35    PublishedInstance,
36};
37mod derivation;
38pub use derivation::{
39    DerivationSignatureProblem, DerivedContextGap, DerivedPart, DerivedRequirement,
40    DerivedShapeProblem,
41};
42mod environment;
43/// Part of [`Error::AmbiguousVariables`] and [`Error::AmbiguousVariants`]'s public
44/// shape, so it is re-exported alongside the error rather than left behind a
45/// private module.
46pub use environment::ImportOrigin;
47/// Part of [`Error::AmbiguousOperatorPrecedence`]'s public shape, so it is
48/// re-exported alongside the error rather than left behind a private module.
49pub use environment::InfixDeclaration;
50use environment::{
51    new_environment, suggest_name, EnvError, Environment, InfixFunction, RootEnvironment, ValueType,
52};
53
54// Some elements which are common to both AST
55use crate::name::{Name, QualName};
56use crate::source::files::SourceFileId;
57pub use parser::Associativity;
58use zelkova_syntax::position::NodeSpan;
59use zelkova_syntax::tuple::Tuple;
60
61// begin AST
62
63/// A resolved module
64#[derive(Debug)]
65pub struct Module {
66    pub name: ModuleName,
67    pub exports: Exports,
68    /// Where the header's `exposing (...)` was written — `parser::Module::exposing_span`,
69    /// carried through. A diagnostic about what the module exposes as a whole points here.
70    pub exposing_span: NodeSpan,
71    /// Operator name to infix details
72    pub infixes: HashMap<Name, Infix>,
73    pub types: HashMap<Name, UnionType>,
74    /// Every `class` declaration that canonicalized, by name. A member is not in
75    /// [`values`](Self::values): it has a signature and no body, and the class carries it.
76    pub classes: HashMap<Name, Class>,
77    /// Every `instance` declaration that passed every check, in source order.
78    pub instances: Vec<Instance>,
79    /// Every instance this module's imports brought into scope, each once.
80    /// [`to_interface`](Self::to_interface) publishes them beside the module's own, which
81    /// is what carries an instance to every module that can reach its declaring one.
82    pub imported_instances: Vec<PublishedInstance>,
83    pub values: HashMap<Name, Value>,
84    /// The value declarations that were written and have no canonical form, sorted by name.
85    ///
86    /// A declaration is here when its annotation or its body did not canonicalize, or, in
87    /// a facade, when its signature was rejected by the per-declaration checks; an error
88    /// beside the module says which. It is also here when a declaration chunk that failed
89    /// to parse names it ([`parser::Module::failed`]), whatever else of it parsed; the
90    /// syntax error says why, and only its annotation, when one parsed, is checked. The
91    /// checks that run on the whole signature list before those (`FacadeConstrained` and
92    /// a facade's malformed context, `UnsafeOutsideFacade`) report an error and leave the
93    /// declaration where the per-declaration checks put it. Outside a facade, a context
94    /// is part of its annotation, and a declaration whose context does not resolve is
95    /// here with no type.
96    /// Every other value declaration is in [`values`](Self::values), and no name is in
97    /// both. What survives of one is its annotation, when that canonicalized:
98    /// [`to_interface`](Self::to_interface) exposes it and the typer declares it, so a
99    /// caller of a broken declaration is checked against the type it was written with.
100    pub broken: Vec<Broken>,
101    /// True when this module is a `module foreign` facade.
102    /// Such modules have synthetic placeholder bodies and must not be type-checked.
103    pub binding_foreign: bool,
104    /// Whether a name could be missing from this module for a reason already reported.
105    ///
106    /// Set when the module's scope ended incomplete: an import did not resolve, an
107    /// import resolved to an [`Interface`] whose own
108    /// [`incomplete`](Interface::incomplete) is set, a `type`, `infix`, `class` or
109    /// `instance` declaration failed, or a declaration chunk that names nothing failed to
110    /// parse. Also set when a
111    /// value declaration was written with an annotation that did not canonicalize, or is
112    /// named by a chunk that failed to parse and has no type, since its annotation may be
113    /// that chunk: those are the two ways a name goes missing from
114    /// [`to_interface`](Self::to_interface) while the module's own scope is whole.
115    /// [`to_interface`](Self::to_interface) copies it to [`Interface::incomplete`].
116    pub incomplete: bool,
117}
118
119/// A value declaration canonicalization rejected, recorded in [`Module::broken`].
120#[derive(Debug, Clone, PartialEq)]
121pub struct Broken {
122    pub name: Name,
123    /// Where the declaration was written, annotation and body together.
124    pub span: NodeSpan,
125    /// The type of the declaration's annotation, when it has one and both that type and
126    /// its context canonicalized; `None` when either failed.
127    pub tpe: Option<Type>,
128    /// The constraints written in front of that annotation's `=>`, each resolved, in
129    /// the order written; empty when `tpe` is `None`. Beside the type and not inside
130    /// it, as on [`Value::TypedValue`].
131    pub context: Vec<Constraint>,
132    /// Where that annotation was written; `NodeSpan::none()` when `tpe` is `None`.
133    pub annotation_span: NodeSpan,
134}
135
136impl Broken {
137    /// `function`, recorded as broken, with `annotation` as its annotation's type and
138    /// context when those canonicalized.
139    fn of(function: &parser::Function, annotation: Option<(Type, Vec<Constraint>)>) -> Broken {
140        let (tpe, context, annotation_span) = match annotation {
141            Some((tpe, context)) => (Some(tpe), context, function.annotation_span),
142            None => (None, Vec::new(), NodeSpan::none()),
143        };
144
145        Broken {
146            name: function.name.clone(),
147            span: function.span,
148            tpe,
149            context,
150            annotation_span,
151        }
152    }
153}
154
155/// What an [`Interface`] publishes of a value: where it was declared, its type, and the
156/// constraints its annotation wrote in front of that type.
157///
158/// One struct rather than a map per field, so an entry cannot have a type and lack the
159/// context it was written with: an importer's call to a constrained function is checked
160/// against this entry, and an empty [`context`](Self::context) here means the function
161/// is unconstrained.
162#[derive(Debug, Clone, PartialEq)]
163pub struct ValueSignature {
164    /// Where the declaration (annotation and body together) was written —
165    /// [`Value::span`] — so a diagnostic about a name found in an interface can point at
166    /// the declaration, not just name it.
167    pub span: NodeSpan,
168    /// The annotation's resolved constraints, in the order written.
169    pub context: Vec<Constraint>,
170    pub tpe: Type,
171}
172
173impl ValueSignature {
174    /// The signature of a value declared at `span` with the type `tpe` and no
175    /// constraint.
176    pub fn unconstrained(span: NodeSpan, tpe: Type) -> ValueSignature {
177        ValueSignature {
178            span,
179            context: Vec::new(),
180            tpe,
181        }
182    }
183}
184
185/// What [`canonicalize_recovering`] built of a module, beside every error it reported.
186#[derive(Debug)]
187pub struct Canonicalized {
188    /// The module, holding every declaration that canonicalized. A value declaration
189    /// that did not is in [`Module::broken`]; a `type`, `infix`, `class` or `instance`
190    /// declaration that did not is in neither.
191    pub module: Module,
192    /// Every error canonicalization reported. Empty exactly when [`canonicalize`] would
193    /// answer `Ok` with [`module`](Self::module).
194    ///
195    /// An error is left out of it only when another stands behind it: a not-found error
196    /// raised in an [incomplete](Module::incomplete) scope restates the failure that made
197    /// the scope incomplete (`without_restated`), and nothing about a declaration a chunk
198    /// that failed to parse names is said beyond its annotation's own errors, since the
199    /// syntax error stands for it. A declaration that every error was left out of is
200    /// either still absent from the module, because the error broke it, or present holding
201    /// a hole for a name that did not resolve ([`Value::holds_hole`]). So empty here does
202    /// not mean [`Module::broken`] is empty, that [`Module::incomplete`] is false, nor that
203    /// no value holds a hole.
204    pub errors: Vec<Error>,
205}
206
207impl Module {
208    /// Build the trimmed-down view of this module other modules import against.
209    ///
210    /// `file` is the [`SourceFileId`] this module was read from, which is what lets
211    /// a later module's diagnostic point back into *this* module's source — see
212    /// [`Interface::file`](super::Interface::file). It is a parameter rather than
213    /// something this method could work out because a `canonical::Module` does not
214    /// know it: only driver code does, and the sole caller
215    /// (`dependencies::ModuleWalker::check_in_order`) is driver code that has the
216    /// map from module name to file in hand. A caller with nothing to give — every
217    /// test that hand-builds an interface — passes `None`, and
218    /// [`Interface::source_span`](super::Interface::source_span) then declines to
219    /// build a cross-module label rather than building one at the wrong place.
220    ///
221    /// # What the `exposing (...)` header removes here
222    ///
223    /// This is the only place a module's own [`Exports`] is read, and reading it
224    /// here is what makes a declaration left out of the header private (`BUG-9`).
225    /// `self.values`, `self.types` and `self.infixes` stay complete — the typer,
226    /// exhaustiveness and every later phase run against the whole
227    /// [`Module`](Self), because a private declaration is still callable from
228    /// inside the module that wrote it. Only this external view is trimmed, and
229    /// only by three rules:
230    ///
231    /// - a value reaches the interface when the header exposes its name as
232    ///   [`ExportType::Value`], on top of the requirement that it carry a type
233    ///   annotation (`Value::TypedValue`). `do_exports` reports an exposed,
234    ///   unannotated declaration (`SPEC-5`), and the declaration is left out
235    ///   here. A [`Broken`] declaration the header exposes reaches the
236    ///   interface the same way when its annotation canonicalized, with that
237    ///   annotation as its type, so an importer is checked against it;
238    /// - an infix reaches it when the header exposes the operator;
239    /// - a union type reaches it when the header names it either way, but a
240    ///   `Size` entry ([`ExportType::UnionPrivate`]) hands over the declaration
241    ///   with its `variants` emptied, and records its name in
242    ///   [`Interface::opaque_unions`]. That is the opaque type: importers still
243    ///   get the name and its type variables — [`Interface::unions`] is where
244    ///   `process_import`'s `Privacy::Private` arm reads the arity from — and no
245    ///   constructor to build or match one with.
246    ///
247    /// A class reaches it, with every member and the derivations it carries, when the
248    /// header names it ([`ExportType::Class`]).
249    ///
250    /// [`Exports::Everything`] — a `exposing (..)` header — exposes every
251    /// declaration with every constructor, so nothing is dropped in that case.
252    ///
253    /// # What the header does not remove
254    ///
255    /// Every instance reaches the interface: the module's own, and every one its imports
256    /// brought into scope ([`imported_instances`](Self::imported_instances)). An instance
257    /// has no name for a header to list, and it has to be in scope in every module that
258    /// can reach the module declaring it, through however many imports, so each module
259    /// passes on what it received
260    /// ([Type classes](../../docs/spec/type-classes.md#declaring-an-instance)).
261    ///
262    /// An exposed infix whose backing function is not itself separately exposed
263    /// — `infix left 6 (+) = add` with `(+)` in the header and `add` not, which
264    /// is every operator `std/core` declares — still needs `add`'s type
265    /// reachable, or an importer that brings `(+)` into scope has no type to
266    /// give a use of it. [`Interface::infix_functions`] carries exactly that,
267    /// kept out of `values` itself so `add` stays unreachable under its own
268    /// name.
269    pub fn to_interface(&self, file: Option<SourceFileId>) -> super::Interface {
270        let values: HashMap<Name, ValueSignature> = self
271            .values
272            .keys()
273            .chain(self.broken.iter().map(|broken| &broken.name))
274            .filter(|name| self.exports.exposes(name, &ExportType::Value))
275            // An exposed, unannotated declaration is an error `do_exports` has reported
276            // (`SPEC-5`, `BUG-14`); it has no type to publish, and neither has a broken
277            // one whose annotation did not canonicalize.
278            .filter_map(|name| self.declared_signature(name))
279            .collect();
280
281        let mut opaque_unions = HashSet::new();
282        let unions = self
283            .types
284            .iter()
285            .filter_map(|(name, union)| match self.exports.union_visibility(name) {
286                UnionVisibility::Hidden => None,
287                UnionVisibility::Transparent => Some((name.clone(), union.clone())),
288                UnionVisibility::Opaque => {
289                    opaque_unions.insert(name.clone());
290                    Some((
291                        name.clone(),
292                        UnionType {
293                            variables: union.variables.clone(),
294                            variants: Vec::new(),
295                            span: union.span,
296                        },
297                    ))
298                }
299            })
300            .collect();
301
302        let infixes: HashMap<Name, Infix> = self
303            .infixes
304            .iter()
305            .filter(|(name, _)| self.exports.exposes(name, &ExportType::Infix))
306            .map(|(name, infix)| (name.clone(), infix.clone()))
307            .collect();
308
309        // See `Interface::infix_functions`'s doc comment: only a backing function
310        // *not* already reaching `values` on its own needs a supplementary entry
311        // here — one that is already exposed by name is inserted twice
312        // otherwise, which `insert_foreign_value` reads as the same value
313        // imported from two places.
314        let infix_functions: HashMap<Name, ValueSignature> = infixes
315            .values()
316            .filter(|infix| !values.contains_key(&infix.function_name))
317            .filter_map(|infix| self.declared_signature(&infix.function_name))
318            .collect();
319
320        // A broken value has no parameters to count, so it gets no entry; an importer
321        // reads its absence as arity 0 (see `Interface::arities`).
322        let arities = values
323            .keys()
324            .chain(infix_functions.keys())
325            .filter_map(|name| {
326                self.values
327                    .get(name)
328                    .map(|value| (name.clone(), self.emitted_arity(value)))
329            })
330            .collect();
331
332        let classes = self
333            .classes
334            .iter()
335            .filter(|(name, _)| self.exports.exposes(name, &ExportType::Class))
336            .map(|(name, class)| (name.clone(), class.signature.clone()))
337            .collect();
338
339        let instances = self
340            .instances
341            .iter()
342            .map(|instance| PublishedInstance {
343                signature: instance.signature.clone(),
344                source: file.and_then(|file| {
345                    instance
346                        .signature
347                        .span
348                        .span()
349                        .map(|span| super::SourceSpan { file, span })
350                }),
351            })
352            .chain(self.imported_instances.iter().cloned())
353            .collect();
354
355        super::Interface {
356            module_name: self.name.clone(),
357            values,
358            unions,
359            opaque_unions,
360            infixes,
361            infix_functions,
362            arities,
363            classes,
364            instances,
365            file,
366            incomplete: self.incomplete,
367        }
368    }
369
370    /// The annotation this module declares `name` with, context included, and where the
371    /// declaration was written: an annotated value's, or a [`Broken`] one's whose
372    /// annotation canonicalized.
373    fn declared_signature(&self, name: &Name) -> Option<(Name, ValueSignature)> {
374        let signature = match self.values.get(name) {
375            Some(Value::TypedValue {
376                tpe, context, span, ..
377            }) => ValueSignature {
378                span: *span,
379                context: context.clone(),
380                tpe: tpe.clone(),
381            },
382            Some(Value::Value { .. }) => return None,
383            None => {
384                let broken = self.broken.iter().find(|broken| &broken.name == name)?;
385                ValueSignature {
386                    span: broken.span,
387                    context: broken.context.clone(),
388                    tpe: broken.tpe.clone()?,
389                }
390            }
391        };
392
393        Some((name.clone(), signature))
394    }
395
396    /// How many parameters `value`, one of this module's declarations, is emitted with:
397    /// the count a call has to supply to be a direct call.
398    ///
399    /// For a declaration with a body that is [`Value::arity`], the parameters it was
400    /// written with. A `module foreign` facade's declaration is a signature with no
401    /// parameters to count, and its forwarding function takes one parameter per arrow in
402    /// the signature ([`Type::arrow_count`]), the [plain parameter
403    /// list](../../docs/spec/interop.md#the-javascript-companion) its companion's
404    /// export takes.
405    ///
406    /// [`to_interface`](Self::to_interface) records it for each exported value, so that
407    /// an importer's call site is saturated at the same count this module's own call
408    /// sites are.
409    pub fn emitted_arity(&self, value: &Value) -> usize {
410        match value {
411            Value::TypedValue { tpe, .. } if self.binding_foreign => tpe.arrow_count(),
412            value => value.arity(),
413        }
414    }
415}
416
417#[derive(Debug, PartialEq)]
418pub enum Exports {
419    Everything,
420    /// Non qualified name to its export type
421    Specifics(HashMap<Name, ExportType>),
422}
423
424impl Exports {
425    /// Whether the `exposing (...)` header exposes `name` *as* `kind`.
426    ///
427    /// The kind is part of the question rather than a detail of the answer
428    /// because the three namespaces a module exports into are separate: a
429    /// header naming `map` exposes the value `map`, and says nothing about an
430    /// operator or a type that happened to share the spelling. Union types ask
431    /// [`union_visibility`](Self::union_visibility) instead, which has a third
432    /// answer for the opaque case.
433    pub(crate) fn exposes(&self, name: &Name, kind: &ExportType) -> bool {
434        match self {
435            Exports::Everything => true,
436            Exports::Specifics(specifics) => specifics.get(name) == Some(kind),
437        }
438    }
439
440    /// How far a union type declared in this module crosses the module boundary.
441    fn union_visibility(&self, name: &Name) -> UnionVisibility {
442        match self {
443            Exports::Everything => UnionVisibility::Transparent,
444            Exports::Specifics(specifics) => match specifics.get(name) {
445                Some(ExportType::UnionPublic) => UnionVisibility::Transparent,
446                Some(ExportType::UnionPrivate) => UnionVisibility::Opaque,
447                Some(ExportType::Value)
448                | Some(ExportType::Infix)
449                | Some(ExportType::Class)
450                | None => UnionVisibility::Hidden,
451            },
452        }
453    }
454}
455
456/// The three answers [`Exports::union_visibility`] can give for one of the
457/// module's own union types, in the order a reader of an `exposing (...)` list
458/// meets them: no entry at all, a bare `Size` entry, a `Size(..)` entry.
459#[derive(Debug)]
460enum UnionVisibility {
461    /// Not in the header: other modules cannot name the type at all.
462    Hidden,
463    /// `Size` — the type's name and arity cross the boundary, its constructors
464    /// do not.
465    Opaque,
466    /// `Size(..)` — the declaration crosses whole, constructors included.
467    Transparent,
468}
469
470#[derive(Debug, PartialEq)]
471pub enum ExportType {
472    Value,
473    Infix,
474    UnionPublic,
475    UnionPrivate,
476    /// A class, named bare in the header, which exposes it with every member.
477    Class,
478}
479
480#[derive(Debug, Clone, PartialEq)]
481pub struct Infix {
482    pub associativity: Associativity,
483    pub precedence: u8,
484    pub function_name: Name,
485    /// Where the `infix` declaration this came from was written.
486    pub span: NodeSpan,
487}
488
489#[derive(Debug, Clone, PartialEq)]
490pub struct UnionType {
491    pub variables: Vec<Name>,
492    pub variants: Vec<TypeConstructor>,
493    /// Where the `type` declaration this came from was written.
494    pub span: NodeSpan,
495}
496
497// TODO Once we have most of the pipeline built, revisit the decision of
498// having Vec<Type> + Type instead of Type::Arrow(Box<Type>, Box<Type>)
499// as it's essentially what a constructor is, a function from parameter
500// to the resulting type.
501// Later me: well, that's only true at the type level. The value also need
502// to tag what variant it represent.
503#[derive(Debug, Clone, PartialEq)]
504pub struct TypeConstructor {
505    /// Constructor name. eg. in `type A = B`, the name is `B`
506    pub name: Name,
507    /// The types of the parameters
508    pub type_parameters: Vec<Type>,
509    /// The type's name once constructed, qualified by the package and module that
510    /// declared it — `Widget.Size` for a `type Size = …` written in `Widget`.
511    ///
512    /// Qualified for the same reason [`Type::Type`]'s head is (`AST-4`): a
513    /// constructor travels into every module that imports it, and the type it
514    /// builds has to stay the declaring module's type there. The `Type` this
515    /// field is turned into at a use site — `Expression::from_parser`'s
516    /// `TypeConstructor` arm — is built straight out of it, so the two agree by
517    /// construction.
518    pub tpe: QualName,
519}
520
521/// A canonical type.
522///
523/// # Why there is no span on this type, or on [`TypeConstructor`]
524///
525/// Every other canonical node this module builds carries a [`NodeSpan`] taken from
526/// the parser node it came from. A `Type` deliberately does not.
527///
528/// The reason `ERR-3` recorded is that a `Type` does not always come from the module
529/// being canonicalized: `Type::from_parser_type` resolves a name through the
530/// `Environment`, which clones types straight out of the [`Interface`]s of the
531/// modules this one imports, so the `Type` handed back may well have been *written
532/// in a different file* — and a bare span on it would be read as a position in the
533/// importing module's source. `ERR-5` settled that half: a [`SpanLabel`] can now
534/// carry a file of its own, so "written in another file" is no longer the obstacle.
535///
536/// The other half is unfinished work, not an impossibility. `parser::Type` carries a
537/// [`NodeSpan`] per node like every other parser node, and `Type::from_parser_type`
538/// is the recursive walk over it — `tpe.span` is in hand at every level, and each
539/// branch of an `Arrow` arrives as its own spanned `parser::Type`. Those spans are
540/// discarded here by choice. Keeping them means a span field on every canonical
541/// `Type` node, plus a decision about what a `Type` cloned out of an `Environment`
542/// should then report — where it was written, or where it was used. Nobody has
543/// written that.
544///
545/// What exists instead is coarser and enough for the diagnostics that exist: the
546/// *declaration* a `Type` is the type of — [`Value`]'s own `span`, [`UnionType`]'s,
547/// [`Infix`]'s — is what a diagnostic wants to underline ("defined here"), not a
548/// position inside the type expression itself. [`Interface::values`] pairs each
549/// value's `Type` with that declaration's [`NodeSpan`], and
550/// [`Interface::source_span`] pairs it with the file, once [`Interface::file`] is
551/// set. A type error still points at the whole declaration that failed rather than
552/// the sub-expression that disagrees, which is `ERR-4`, a separate limit in the
553/// typer's own `Term`/`Constraint` translation.
554#[derive(Debug, Clone, PartialEq)]
555pub enum Type {
556    Variable(Name),
557    /// A named type applied to its arguments, the name being the [`QualName`] of
558    /// the declaration it resolved to.
559    ///
560    /// The module is part of the identity of the type, not decoration on it: a
561    /// `type Size` in `Widget` and a `type Size` in `Gadget` are two types, and
562    /// two values of them are interchangeable nowhere. Carrying only the
563    /// spelling made them one value here, which is what `AST-4` closed. The
564    /// package is part of it for the same reason: a local `Size` and a wrapped
565    /// dependency's, reached as `AcmeWidgets.Size`, both declare `Size.Size`.
566    ///
567    /// The name is the *declaration's*, never the spelling that reached it.
568    /// `import Widget as W` followed by `W.Size` records `Widget.Size`, the same
569    /// rule [name resolution](../../docs/spec/name-resolution.md) states for
570    /// values: an alias names a route to a declaration and not a second
571    /// declaration. A dependency's namespace is a route too.
572    Type(QualName, Vec<Type>),
573    /// A [record type](../../docs/spec/records.md#the-type): each label, and the type
574    /// of the field it names.
575    ///
576    /// A map rather than the list the source wrote, because [a record type is a set
577    /// of fields](../../docs/spec/records.md#a-record-type-is-a-set-of-fields): `{ a :
578    /// Int, b : Char }` and `{ b : Char, a : Int }` are one type, and are one value
579    /// here. The map is ordered by label ([`Name`]'s `Ord`), so walking it is the
580    /// label order two spellings of a type agree on. A label appears once:
581    /// `Type::from_parser_type` reports a repeated one as [`Error::RepeatedLabel`]
582    /// and builds no `Record`.
583    Record(BTreeMap<Name, Type>),
584    Arrow(Box<Type>, Box<Type>),
585    /// A tuple type. Zelkova keeps Elm's restriction of two or three elements,
586    /// which [`Tuple`] carries in its shape.
587    Tuple(Tuple<Type>),
588    /// [The unit type](../../docs/spec/types.md#the-unit-type), `()`.
589    ///
590    /// A form of its own rather than a [`Type::Type`] naming a declaration: `()` is
591    /// syntax, declared nowhere and resolved through no environment, so no module can
592    /// declare a type that shares its spelling and there is no name for a lookup to
593    /// find. Contrast the [`scalars`], which are declared in `std/core` and known by
594    /// the qualified name of that declaration.
595    Unit,
596    // Alias
597}
598
599impl Type {
600    /// The one conversion in this module that reads a span and produces none.
601    ///
602    /// `parser::Type` carries a [`NodeSpan`] like every other parser node, and it is
603    /// dropped here on purpose — see this type's documentation for why a canonical
604    /// `Type` holds no span at all, and what `ERR-5` built instead.
605    fn from_parser_type(env: &dyn Environment, tpe: &parser::Type) -> Result<Type, Error> {
606        match &tpe.kind {
607            parser::TypeKind::Unqualified(name, vars) => {
608                let args = vars
609                    .iter()
610                    .map(|t| Type::from_parser_type(env, t))
611                    .collect::<Result<Vec<_>, Error>>()?;
612
613                match env.find_type(name) {
614                    // `name` resolves to a declared type: `args` is what was
615                    // written after it, and has to match the declaration's own
616                    // arity (`BUG-17`) — nothing else here re-derives that check.
617                    // The head is the *declaration's* qualified name, not the one
618                    // written: `Lib.Option`, `Option` and an alias' `L.Option` are
619                    // three spellings of one entry, and every one of them records
620                    // the module that declared it.
621                    Some(declared) if declared.arity() == args.len() => {
622                        Ok(Type::Type(declared.name.clone(), args))
623                    }
624                    Some(declared) => Err(Error::TypeArityMismatch(
625                        name.clone(),
626                        declared.arity(),
627                        args.len(),
628                        tpe.span,
629                    )),
630                    // `name` resolves to nothing, so there is no type here to
631                    // build one out of. The name is reported as written, dotted
632                    // prefix and all: a written `W.Thing` says which *route* was
633                    // written and not which module declared anything — under
634                    // `import Widget as W` that half is an alias — so there is no
635                    // module to attribute it to, and quoting the spelling back is
636                    // what lets the reader find it in their own source.
637                    None => Err(Error::TypeNotFound(name.clone(), tpe.span)),
638                }
639            }
640            parser::TypeKind::Arrow(t1, t2) => Ok(Type::Arrow(
641                Box::new(Type::from_parser_type(env, t1)?),
642                Box::new(Type::from_parser_type(env, t2)?),
643            )),
644            parser::TypeKind::Variable(n) => Ok(Type::Variable(n.clone())),
645            parser::TypeKind::Tuple(tuple) => Ok(Type::Tuple(
646                tuple.try_map(|t| Type::from_parser_type(env, t))?,
647            )),
648            parser::TypeKind::Unit => Ok(Type::Unit),
649            parser::TypeKind::Record(fields) => {
650                repeated_labels(fields, RecordForm::Type)?;
651
652                let fields = fields
653                    .iter()
654                    .map(|field| {
655                        Ok((
656                            field.label.clone(),
657                            Type::from_parser_type(env, &field.value)?,
658                        ))
659                    })
660                    .collect::<Result<BTreeMap<_, _>, Error>>()?;
661
662                Ok(Type::Record(fields))
663            }
664        }
665    }
666
667    /// How many arguments a value of this type takes before its result is not a
668    /// function: the length of its arrow spine. `Int -> Int -> Bool` is 2, `Int` is 0.
669    pub fn arrow_count(&self) -> usize {
670        match self {
671            Type::Arrow(_, result) => 1 + result.arrow_count(),
672            _ => 0,
673        }
674    }
675
676    // TODO Write some tests
677    fn to_linear_types(tpe: &Type) -> Vec<Type> {
678        match tpe {
679            Type::Arrow(a, b) => {
680                let mut next = Type::to_linear_types(b);
681
682                next.insert(0, *a.clone());
683
684                next
685            }
686            _ => vec![tpe.clone()],
687        }
688    }
689}
690
691#[derive(Debug, Clone, PartialEq)]
692pub enum Value {
693    Value {
694        name: Name,
695        patterns: Vec<Pattern>,
696        body: Expression,
697        /// Where the declaration was written, annotation and body together.
698        span: NodeSpan,
699    },
700    TypedValue {
701        name: Name,
702        patterns: Vec<(Pattern, Type)>,
703        body: Expression,
704        tpe: Type,
705        /// The constraints the annotation wrote in front of `=>`, each resolved to its
706        /// class, in the order written; empty for an annotation with no `=>`.
707        ///
708        /// A field beside `tpe` and not a case of [`Type`],
709        /// which keeps a context out of every match over a type. Nothing needs one
710        /// *inside* a type: a constraint stands only at the front of an annotation, and
711        /// a [member signature carries
712        /// none](../../docs/spec/type-classes.md#declaring-a-class). Always empty in a
713        /// facade, whose context is [`Error::FacadeConstrained`] and is not resolved.
714        context: Vec<Constraint>,
715        /// True when the annotation was written `unsafe name : Type`.
716        ///
717        /// The word is only meaningful on a facade signature, where it declares a
718        /// plain function in place of the effect a facade declares by default —
719        /// see [Foreign interoperability](../../docs/spec/interop.md). Only a
720        /// module whose `binding_foreign` is set can carry it: [`canonicalize`]
721        /// reports [`Error::UnsafeOutsideFacade`] for one written anywhere else,
722        /// so this is `false` on every value of an ordinary module.
723        marked_unsafe: bool,
724        /// Where the declaration was written, annotation and body together.
725        span: NodeSpan,
726        /// Where the `name : Type` annotation alone was written.
727        ///
728        /// [`Type`] itself carries no span — it may have been cloned out of another
729        /// module's `Interface` — so this is the only thing that can answer "where
730        /// was the expected type declared". A type error uses it for the secondary
731        /// label that says the annotation is what the body is being held to.
732        annotation_span: NodeSpan,
733    },
734}
735
736impl Value {
737    /// Where this declaration was written, whichever variant it is.
738    ///
739    /// The typer falls back to this when a type error has no finer position of its
740    /// own — see `typer::Error::labels`.
741    pub fn span(&self) -> NodeSpan {
742        match self {
743            Value::Value { span, .. } | Value::TypedValue { span, .. } => *span,
744        }
745    }
746
747    /// How many parameters this declaration was written with.
748    ///
749    /// This is the count of patterns on the left of the `=`, and deliberately not the
750    /// number of arrows in the declaration's type: `f : Int -> Int -> Int` written `f a =
751    /// add a` has arity 1, and returns a function for the second argument.
752    ///
753    /// The rule lives here rather than at any of its readers because they feed fields a
754    /// backend reads together, from different phases. `typer`'s `Translation` uses it as
755    /// the callee's arity at every call site naming this declaration, which is what
756    /// decides [`ir::Saturation`](crate::ir::Saturation); `ir::build` uses it as
757    /// [`ir::Declaration::arity`](crate::ir::Declaration::arity), the count a
758    /// direct call has to supply; and [`Module::to_interface`] records it, through
759    /// [`Module::emitted_arity`], for a module that imports the declaration. Copies that
760    /// drifted apart would mark a call site saturated at a count the emitted function
761    /// does not take. A facade signature has no patterns to count, and
762    /// [`Module::emitted_arity`] reads its arrows instead.
763    pub fn arity(&self) -> usize {
764        // Two arms rather than an or-pattern: a `TypedValue`'s patterns each carry the
765        // type the annotation gave them, so the two fields are different types.
766        match self {
767            Value::Value { patterns, .. } => patterns.len(),
768            Value::TypedValue { patterns, .. } => patterns.len(),
769        }
770    }
771
772    /// Whether the declaration's parameters or body hold a hole, an
773    /// [`ExpressionKind::Hole`] or a [`PatternKind::Hole`] — a name that did not resolve.
774    ///
775    /// A hole is made only where the error for it was raised, and that error is either
776    /// reported or dropped in an [incomplete](Module::incomplete) scope, where the failure
777    /// that made the scope incomplete stands in its place
778    /// ([`DEC-23` decision 3](../../../docs/decisions/dec-23.md)). So a declaration for which this
779    /// is true always has an error standing behind it, which is what
780    /// [`ir::Unchecked::reported`](crate::ir::Unchecked::reported) asks of an entry.
781    /// A facade signature has no body, and the body of a `TypedValue` is read the same way
782    /// a `Value`'s is.
783    pub fn holds_hole(&self) -> bool {
784        match self {
785            Value::Value { patterns, body, .. } => {
786                patterns.iter().any(pattern_holds_hole) || expression_holds_hole(body)
787            }
788            Value::TypedValue { patterns, body, .. } => {
789                patterns
790                    .iter()
791                    .any(|(pattern, _)| pattern_holds_hole(pattern))
792                    || expression_holds_hole(body)
793            }
794        }
795    }
796}
797
798/// Whether `expr` is a hole or holds one in any subexpression or `case` pattern. The
799/// walk is [`collect_top_level_refs`]'s, looking for a different kind.
800fn expression_holds_hole(expr: &Expression) -> bool {
801    match &expr.kind {
802        ExpressionKind::Hole => true,
803        ExpressionKind::VarTopLevel(_)
804        | ExpressionKind::VarLocal(_)
805        | ExpressionKind::VarKernel(_)
806        | ExpressionKind::VarForeign(_, _, _)
807        | ExpressionKind::VarConstructor(_, _)
808        | ExpressionKind::Char(_)
809        | ExpressionKind::String(_)
810        | ExpressionKind::Int(_)
811        | ExpressionKind::Float(_)
812        | ExpressionKind::Unit
813        // A label is not a name, so it never resolves and is never a hole.
814        | ExpressionKind::Accessor(_, _) => false,
815        ExpressionKind::Access(record, _, _) => expression_holds_hole(record),
816        ExpressionKind::Apply(a, b) => expression_holds_hole(a) || expression_holds_hole(b),
817        ExpressionKind::If(cond, then, els) => {
818            expression_holds_hole(cond) || expression_holds_hole(then) || expression_holds_hole(els)
819        }
820        ExpressionKind::Case(scrutinee, branches) => {
821            expression_holds_hole(scrutinee)
822                || branches.iter().any(|branch| {
823                    pattern_holds_hole(&branch.pattern) || expression_holds_hole(&branch.expression)
824                })
825        }
826        ExpressionKind::Tuple(tuple) => tuple.iter().any(expression_holds_hole),
827        ExpressionKind::Record(fields) => fields
828            .iter()
829            .any(|field| expression_holds_hole(&field.value)),
830        ExpressionKind::Update(record, fields) => {
831            expression_holds_hole(record)
832                || fields
833                    .iter()
834                    .any(|field| expression_holds_hole(&field.value))
835        }
836    }
837}
838
839/// Whether `pattern` is a hole or holds one in any argument or element.
840fn pattern_holds_hole(pattern: &Pattern) -> bool {
841    match &pattern.kind {
842        PatternKind::Hole(_) => true,
843        PatternKind::Constructor { args, .. } => args.iter().any(pattern_holds_hole),
844        PatternKind::Tuple(tuple) => tuple.iter().any(pattern_holds_hole),
845        PatternKind::Record(fields) => fields
846            .iter()
847            .any(|field| pattern_holds_hole(&field.pattern)),
848        PatternKind::Anything
849        | PatternKind::Variable(_)
850        | PatternKind::Int(_)
851        | PatternKind::Float(_)
852        | PatternKind::Char(_)
853        | PatternKind::String(_)
854        | PatternKind::Unit => false,
855    }
856}
857
858/// A canonical pattern, and where it was written.
859///
860/// Same shape as [`parser::Pattern`] — a [`NodeSpan`] beside a kind — and for the
861/// same reason: the children stay plain `Pattern`s, so a reader matches `&p.kind`.
862#[derive(Debug, Clone, PartialEq)]
863pub struct Pattern {
864    pub span: NodeSpan,
865    pub kind: PatternKind,
866}
867
868#[derive(Debug, Clone, PartialEq)]
869pub enum PatternKind {
870    Anything,
871    Variable(Name), // TODO Name or QualName ?
872    Int(i64),
873    Float(f64),
874    Char(char),
875    String(String),
876    /// A tuple pattern. Zelkova keeps Elm's restriction of two or three
877    /// elements, which [`Tuple`] carries in its shape.
878    Tuple(Tuple<Pattern>),
879    /// The unit pattern, `()`: it matches the one value of the unit type and binds
880    /// nothing.
881    Unit,
882
883    Constructor {
884        ctor: TypeConstructor,
885        args: Vec<Pattern>,
886    },
887    /// A constructor pattern whose constructor did not resolve, with the patterns written
888    /// as its arguments. The error saying so has been reported, or dropped in an
889    /// [incomplete](Module::incomplete) scope, and the declaration is kept ([`DEC-23`
890    /// decision
891    /// 6](../../../docs/decisions/dec-23.md#6--an-unresolved-name-inside-a-sound-body-is-a-typed-hole)).
892    ///
893    /// The arguments are kept so that the names they bind are still in scope in the
894    /// branch or the body the pattern governs, and a use of one there is not reported as a
895    /// second missing name.
896    Hole(Vec<Pattern>),
897    /// A [record pattern](../../docs/spec/records.md#record-patterns), `{ label =
898    /// pattern, … }`: the fields it names, each with the pattern its value is matched
899    /// against, in the order they were written. The `{ label }` shorthand is not a form
900    /// of its own: the grammar desugared it to `label = label`.
901    ///
902    /// The entries name a **subset** of the record's fields, so this is not the whole
903    /// field set a [`Type::Record`] is, and it is not keyed by label the way that one
904    /// is. No label appears twice — `Pattern::from_parser` reports a repeated one as
905    /// [`Error::RepeatedLabel`] — and what the pattern matches does not depend on the
906    /// order of its entries. They are kept as the source wrote them, as a tuple's
907    /// elements are, and `ScopedEnvironment::expose_pattern` walks them in that order.
908    /// Each entry keeps its label's span, which is where a diagnostic about that field
909    /// points.
910    ///
911    /// Refutable exactly when one of its entries' patterns is (`{ x }` cannot fail,
912    /// `{ x = 0 }` can). Nothing here records that, and nothing may read a record
913    /// pattern as irrefutable for being a record.
914    Record(Vec<PatternField>),
915}
916
917/// One entry of a [record pattern](PatternKind::Record): the label it names, where the
918/// label alone was written, and the pattern that field's value is matched against.
919#[derive(Debug, Clone, PartialEq)]
920pub struct PatternField {
921    pub label: Name,
922    /// Where the label alone was written; the pattern carries its own span. For the
923    /// `{ label }` shorthand the two are the same text.
924    pub label_span: NodeSpan,
925    pub pattern: Pattern,
926}
927
928impl Pattern {
929    /// A pattern canonicalized from source, keeping the parser node's position.
930    pub fn new(span: NodeSpan, kind: PatternKind) -> Pattern {
931        Pattern { span, kind }
932    }
933
934    /// A pattern with no position — hand-built by a test. See [`NodeSpan`].
935    pub fn bare(kind: PatternKind) -> Pattern {
936        Pattern {
937            span: NodeSpan::none(),
938            kind,
939        }
940    }
941
942    /// The canonical form of `p`, or the first error that kept it from having one.
943    ///
944    /// A constructor that does not resolve is not such an error: its `VariantNotFound` is
945    /// pushed onto `unresolved` and the pattern becomes a [`PatternKind::Hole`] holding its
946    /// arguments, canonicalized as a resolved constructor's are.
947    fn from_parser(
948        p: &parser::Pattern,
949        env: &dyn Environment,
950        unresolved: &mut Vec<Error>,
951    ) -> Result<Pattern, Error> {
952        let kind = match &p.kind {
953            parser::PatternKind::Anything => PatternKind::Anything,
954            parser::PatternKind::Variable(name) => PatternKind::Variable(name.clone()),
955            parser::PatternKind::Literal(parser::Literal::Int(i)) => PatternKind::Int(*i),
956            parser::PatternKind::Literal(parser::Literal::Float(f)) => PatternKind::Float(*f),
957            parser::PatternKind::Literal(parser::Literal::Char(c)) => PatternKind::Char(*c),
958            parser::PatternKind::Literal(parser::Literal::String(s)) => {
959                PatternKind::String(s.clone())
960            }
961            parser::PatternKind::Tuple(tuple) => {
962                PatternKind::Tuple(tuple.try_map(|p| Pattern::from_parser(p, env, unresolved))?)
963            }
964            parser::PatternKind::Unit => PatternKind::Unit,
965            parser::PatternKind::Constructor(name, args) => {
966                // `p.span` covers the constructor and its arguments, which is the
967                // text a "no such constructor" caret should sit under.
968                let ctor = match env.find_type_constructor(name) {
969                    Some(ctor) => Some(ctor.clone()),
970                    None => {
971                        let suggestion =
972                            suggest_name(name, env.type_constructor_names().into_iter());
973                        unresolved.push(Error::VariantNotFound(
974                            env.module_name().qualify_name(name),
975                            p.span,
976                            suggestion,
977                        ));
978                        None
979                    }
980                };
981
982                let args = args
983                    .iter()
984                    .map(|p| Pattern::from_parser(p, env, unresolved))
985                    .collect::<Result<Vec<_>, Error>>()?;
986
987                match ctor {
988                    Some(ctor) => PatternKind::Constructor { ctor, args },
989                    None => PatternKind::Hole(args),
990                }
991            }
992            // Every entry's pattern is canonicalized before the labels are compared, as a
993            // record's fields are in `Field::from_parser`, so a constructor that does not
994            // resolve in one is pushed onto `unresolved` whether or not a label repeats.
995            parser::PatternKind::Record(fields) => {
996                let entries = fields
997                    .iter()
998                    .map(|field| {
999                        Ok(PatternField {
1000                            label: field.label.clone(),
1001                            label_span: field.label_span,
1002                            pattern: Pattern::from_parser(&field.value, env, unresolved)?,
1003                        })
1004                    })
1005                    .collect::<Result<Vec<_>, Error>>()?;
1006
1007                repeated_labels(fields, RecordForm::Pattern)?;
1008
1009                PatternKind::Record(entries)
1010            }
1011        };
1012
1013        Ok(Pattern::new(p.span, kind))
1014    }
1015}
1016
1017/// A canonical expression, and where it was written.
1018///
1019/// Same shape as [`parser::Expression`] — a [`NodeSpan`] beside a kind — and for the
1020/// same reason: the children stay `Box<Expression>`, so a reader matches `&e.kind`.
1021#[derive(Debug, Clone, PartialEq)]
1022pub struct Expression {
1023    pub span: NodeSpan,
1024    pub kind: ExpressionKind,
1025}
1026
1027// TODO Find a way to detect recursive functions (even indirect recursivity,
1028// eg. `a` calls `b` calls `a`)
1029/// Expression is an optimized version for checks and caches.
1030///
1031/// Elm declare those expressions:
1032/// ```haskell
1033/// data Expr_
1034///   = VarLocal Name
1035///   | VarTopLevel ModuleName.Canonical Name
1036///   | VarKernel Name Name
1037///   | VarForeign ModuleName.Canonical Name Annotation
1038///   | VarCtor CtorOpts ModuleName.Canonical Name Index.ZeroBased Annotation
1039///   | VarDebug ModuleName.Canonical Name Annotation
1040///   | VarOperator Name ModuleName.Canonical Name Annotation -- CACHE real name for optimization
1041///   | Chr ES.String
1042///   | Str ES.String
1043///   | Int Int
1044///   | Float EF.Float
1045///   | List [Expr]
1046///   | Negate Expr
1047///   | Binop Name ModuleName.Canonical Name Annotation Expr Expr -- CACHE real name for optimization
1048///   | Lambda [Pattern] Expr
1049///   | Call Expr [Expr]
1050///   | If [(Expr, Expr)] Expr
1051///   | Let Def Expr
1052///   | LetRec [Def] Expr
1053///   | LetDestruct Pattern Expr Expr
1054///   | Case Expr [CaseBranch]
1055///   | Accessor Name
1056///   | Access Expr (A.Located Name)
1057///   | Update Name Expr (Map.Map Name FieldUpdate)
1058///   | Record (Map.Map Name Expr)
1059///   | Unit
1060///   | Tuple Expr Expr (Maybe Expr)
1061/// ```
1062#[derive(Debug, Clone, PartialEq)]
1063pub enum ExpressionKind {
1064    VarLocal(Name),
1065    VarTopLevel(QualName),
1066    VarKernel(QualName),
1067    /// A value another module declares, named by that module, beside the package that
1068    /// declares it. The package is what a backend builds the import path from: a
1069    /// module's name is unique within its package and not across a build, and the
1070    /// output keeps one directory per package
1071    /// ([`DEC-18` decision 5](../../docs/decisions/dec-18.md#5--output-is-written-per-package-beside-the-root-manifest)).
1072    VarForeign(QualName, PackageName, Type),
1073    /// A union constructor, named by the package and module that declared its union
1074    /// whichever module the reference is written in. The [`QualName`] carries the
1075    /// package: `AcmeWidgets.Size.Small` and a local `Size.Small` are two constructors.
1076    VarConstructor(QualName, Type),
1077    Char(char),
1078    String(String),
1079    Int(i64),
1080    Float(f64),
1081    // List
1082    // Lambda
1083    Apply(Box<Expression>, Box<Expression>),
1084    If(Box<Expression>, Box<Expression>, Box<Expression>),
1085    // Let
1086    // LetRec
1087    // LetDestruct (eg. `(a,b) = someTuple`)
1088    Case(Box<Expression>, Vec<CaseBranch>),
1089    /// An [accessor](../../docs/spec/records.md#the-accessor), `.name`, the function
1090    /// reading that field: the label, and where the label alone was written.
1091    ///
1092    /// The label names no declaration, so nothing about it is resolved here: [labels
1093    /// are not values](../../docs/spec/records.md#labels-are-not-values), and which
1094    /// record the label belongs to is decided by the type the accessor is read against.
1095    Accessor(Name, NodeSpan),
1096    /// A [field access](../../docs/spec/records.md#reading-a-field), `r.name`: the
1097    /// record, the label, and where the label alone was written. The label is not
1098    /// resolved here either, for the reason an [`Accessor`](ExpressionKind::Accessor)'s
1099    /// is not.
1100    Access(Box<Expression>, Name, NodeSpan),
1101    /// A [record](../../docs/spec/records.md#building-a-record), `{ label = expr, … }`,
1102    /// its fields in the order they were written.
1103    ///
1104    /// A list and not a map, as [`Type::Record`] is: each field is a subexpression,
1105    /// and [subexpressions are evaluated left to
1106    /// right](../../docs/spec/evaluation-semantics.md#order-of-evaluation), so `{ b = f
1107    /// x, a = g y }` calls `f` first and a backend has to be able to see that. Only the
1108    /// set of labels is order-independent, and no label appears twice:
1109    /// `Expression::from_parser` reports a repeated one as [`Error::RepeatedLabel`].
1110    Record(Vec<Field>),
1111    /// An [update](../../docs/spec/records.md#updating-a-record), `{ expr | label =
1112    /// expr, … }`: the record being updated, and the fields replaced in it in the order
1113    /// they were written, for the reason a [`Record`](ExpressionKind::Record)'s are.
1114    Update(Box<Expression>, Vec<Field>),
1115    /// The unit value, `()`.
1116    Unit,
1117    /// A tuple expression. Zelkova keeps Elm's restriction of two or three
1118    /// elements, which [`Tuple`] carries in its shape.
1119    Tuple(Tuple<Expression>),
1120    /// A value or a constructor that did not resolve, inside a body that otherwise
1121    /// canonicalized. The error saying so has been reported, or dropped in an
1122    /// [incomplete](Module::incomplete) scope, and the declaration is kept, so the rest of
1123    /// its body is still checked ([`DEC-23` decision
1124    /// 6](../../../docs/decisions/dec-23.md#6--an-unresolved-name-inside-a-sound-body-is-a-typed-hole)).
1125    Hole,
1126}
1127
1128/// One field of a [record](ExpressionKind::Record) or an
1129/// [update](ExpressionKind::Update): a label, where the label was written, and the
1130/// expression it was given.
1131#[derive(Debug, Clone, PartialEq)]
1132pub struct Field {
1133    pub label: Name,
1134    /// Where the label alone was written; the value carries its own span.
1135    pub label_span: NodeSpan,
1136    pub value: Expression,
1137}
1138
1139impl Field {
1140    /// The canonical form of `fields`, a record's or an update's, in the order they
1141    /// were written. Every value is canonicalized before the labels are compared, so a
1142    /// name that does not resolve in one is pushed onto `unresolved` whether or not a
1143    /// label is repeated; a repeated label is then the error returned.
1144    fn from_parser(
1145        fields: &[parser::Field<parser::Expression>],
1146        form: RecordForm,
1147        env: &dyn Environment,
1148        unresolved: &mut Vec<Error>,
1149    ) -> Result<Vec<Field>, Error> {
1150        let canonical = fields
1151            .iter()
1152            .map(|field| {
1153                Ok(Field {
1154                    label: field.label.clone(),
1155                    label_span: field.label_span,
1156                    value: Expression::from_parser(&field.value, env, unresolved)?,
1157                })
1158            })
1159            .collect::<Result<Vec<_>, Error>>()?;
1160
1161        repeated_labels(fields, form)?;
1162
1163        Ok(canonical)
1164    }
1165}
1166
1167/// Which of the four record forms a [`Error::RepeatedLabel`] was found in.
1168#[derive(Debug, PartialEq, Clone, Copy)]
1169pub enum RecordForm {
1170    /// A record type, `{ label : Type, … }`.
1171    Type,
1172    /// A record, `{ label = expr, … }`.
1173    Record,
1174    /// An update, `{ expr | label = expr, … }`.
1175    Update,
1176    /// A record pattern, `{ label = pattern, … }`, the `{ label }` shorthand included.
1177    Pattern,
1178}
1179
1180/// Every field of `fields` whose label an earlier field already has, each as an
1181/// [`Error::RepeatedLabel`] at its own label and naming the first field's: `Ok` when
1182/// there is none, the one error when there is one, and [`Error::Many`] of them when
1183/// there are several. A label written three times is two errors, both naming the
1184/// first.
1185fn repeated_labels<T>(fields: &[parser::Field<T>], form: RecordForm) -> Result<(), Error> {
1186    let mut first: HashMap<&Name, NodeSpan> = HashMap::new();
1187    let mut errors = vec![];
1188
1189    for field in fields {
1190        match first.get(&field.label) {
1191            Some(earlier) => errors.push(Error::RepeatedLabel(
1192                field.label.clone(),
1193                form,
1194                field.label_span,
1195                *earlier,
1196            )),
1197            None => {
1198                first.insert(&field.label, field.label_span);
1199            }
1200        }
1201    }
1202
1203    match errors.len() {
1204        0 => Ok(()),
1205        1 => Err(errors.remove(0)),
1206        _ => Err(Error::Many(errors)),
1207    }
1208}
1209
1210impl Expression {
1211    /// An expression canonicalized from source, keeping the parser node's position.
1212    pub fn new(span: NodeSpan, kind: ExpressionKind) -> Expression {
1213        Expression { span, kind }
1214    }
1215
1216    /// An expression with no position: hand-built by a test, or synthesised by the
1217    /// compiler with nothing in the user's text behind it. See [`NodeSpan`].
1218    pub fn bare(kind: ExpressionKind) -> Expression {
1219        Expression {
1220            span: NodeSpan::none(),
1221            kind,
1222        }
1223    }
1224
1225    /// The canonical form of `e`, or the first error that kept it from having one.
1226    ///
1227    /// A value or a constructor that does not resolve is not such an error: its
1228    /// `VariableNotFound` or `VariantNotFound` is pushed onto `unresolved` and the node
1229    /// becomes an [`ExpressionKind::Hole`]. Every other failure is returned, among them an
1230    /// ambiguous name, which did resolve, and an operator that does not resolve or an infix
1231    /// chain that cannot be associated, either of which leaves the chain with no shape to
1232    /// put a hole in.
1233    fn from_parser(
1234        e: &parser::Expression,
1235        env: &dyn Environment,
1236        unresolved: &mut Vec<Error>,
1237    ) -> Result<Expression, Error> {
1238        // Every arm builds a kind and every kind gets `e.span`, so a name the
1239        // environment cannot resolve is underlined where it was written rather than
1240        // somewhere up the tree.
1241        let kind = match &e.kind {
1242            parser::ExpressionKind::Lit(parser::Literal::Int(i)) => ExpressionKind::Int(*i),
1243            parser::ExpressionKind::Lit(parser::Literal::Float(f)) => ExpressionKind::Float(*f),
1244            parser::ExpressionKind::Lit(parser::Literal::Char(c)) => ExpressionKind::Char(*c),
1245            parser::ExpressionKind::Lit(parser::Literal::String(s)) => {
1246                ExpressionKind::String(s.clone())
1247            }
1248            parser::ExpressionKind::Variable(name) => {
1249                let Some(found) = env.find_value(name) else {
1250                    let suggestion = suggest_name(name, env.value_names().into_iter());
1251                    unresolved.push(Error::VariableNotFound(
1252                        env.module_name().qualify_name(name),
1253                        e.span,
1254                        suggestion,
1255                    ));
1256                    return Ok(Expression::new(e.span, ExpressionKind::Hole));
1257                };
1258
1259                match found {
1260                    ValueType::Local => ExpressionKind::VarLocal(name.clone()),
1261                    ValueType::TopLevel => {
1262                        ExpressionKind::VarTopLevel(env.module_name().qualify_name(name))
1263                    }
1264                    // Named by the package and module that declared the value, `m`. The
1265                    // written spelling is bare for an exposed value and carries a module
1266                    // or an alias for a qualified one (`Js.Basics.add`), and only its
1267                    // last segment is the value's own name.
1268                    ValueType::Foreign(m, _source, tpe, _origin) => {
1269                        let declared = name.last_segment();
1270                        ExpressionKind::VarForeign(
1271                            m.qualify_name(&declared),
1272                            m.package().clone(),
1273                            tpe.clone(),
1274                        )
1275                    }
1276                    ValueType::Foreigns(candidates) => {
1277                        return Err(Error::AmbiguousVariables(
1278                            name.clone(),
1279                            candidates.clone(),
1280                            e.span,
1281                        ))
1282                    }
1283                }
1284            }
1285            parser::ExpressionKind::TypeConstructor(name) => {
1286                let Some(ctor) = env.find_type_constructor(name) else {
1287                    let suggestion = suggest_name(name, env.type_constructor_names().into_iter());
1288                    unresolved.push(Error::VariantNotFound(
1289                        env.module_name().qualify_name(name),
1290                        e.span,
1291                        suggestion,
1292                    ));
1293                    return Ok(Expression::new(e.span, ExpressionKind::Hole));
1294                };
1295
1296                let tpe = if ctor.type_parameters.is_empty() {
1297                    Type::Type(ctor.tpe.clone(), vec![])
1298                } else {
1299                    // TODO Rework that part. ctor.types is only for the type parameters of the constructor, not for the overall type.
1300                    let mut iter = ctor.type_parameters.iter().rev();
1301                    let first = iter.next().unwrap().clone();
1302
1303                    // TODO tests this, 99.999% I'm wrong about it (like everytime I try to implement arrows, plus
1304                    // the foldr in this particular case)
1305                    let tpe = iter.fold(first, |acc, t| {
1306                        Type::Arrow(Box::new(t.clone()), Box::new(acc))
1307                    });
1308
1309                    Type::Arrow(
1310                        Box::new(Type::Type(ctor.tpe.clone(), vec![])),
1311                        Box::new(tpe),
1312                    )
1313                };
1314
1315                // Named by the package and module that declared the union, the way
1316                // `VarForeign` is named by the ones that declared the value — not by the
1317                // spelling the source wrote, which is bare for an exposed constructor and
1318                // carries the importer's alias or a dependency's namespace for a
1319                // qualified one.
1320                let name = ctor.tpe.sibling(&ctor.name);
1321
1322                ExpressionKind::VarConstructor(name, tpe)
1323            }
1324            parser::ExpressionKind::Application(a, b) => {
1325                let a = Expression::from_parser(a, env, unresolved)?;
1326                let b = Expression::from_parser(b, env, unresolved)?;
1327
1328                ExpressionKind::Apply(Box::new(a), Box::new(b))
1329            }
1330            parser::ExpressionKind::InfixChain(first, rest) => {
1331                let first = Expression::from_parser(first, env, unresolved)?;
1332
1333                let rest = rest
1334                    .iter()
1335                    .map(|(op_name, op_span, operand)| {
1336                        let op = resolve_infix_operator(op_name, *op_span, env)?;
1337                        let operand = Expression::from_parser(operand, env, unresolved)?;
1338                        Ok((op, operand))
1339                    })
1340                    .collect::<Result<Vec<_>, Error>>()?;
1341
1342                let mut rest = rest.into_iter().peekable();
1343                let reassociated = reassociate_infix_chain(first, &mut rest, 0)?;
1344
1345                reassociated.kind
1346            }
1347            parser::ExpressionKind::Tuple(tuple) => ExpressionKind::Tuple(
1348                tuple.try_map(|e| Expression::from_parser(e, env, unresolved))?,
1349            ),
1350            parser::ExpressionKind::Unit => ExpressionKind::Unit,
1351            parser::ExpressionKind::Case(expr, branches) => {
1352                let expr = Expression::from_parser(expr, env, unresolved)?;
1353
1354                let b = branches.iter().map::<Result<CaseBranch, Error>, _>(|cb| {
1355                    let pattern = Pattern::from_parser(&cb.pattern, env, unresolved)?;
1356                    let mut scoped = env.new_scope();
1357
1358                    scoped.expose_pattern(&pattern);
1359
1360                    let expression = Expression::from_parser(&cb.expression, &scoped, unresolved)?;
1361
1362                    Ok(CaseBranch {
1363                        pattern,
1364                        expression,
1365                        span: cb.span,
1366                    })
1367                });
1368
1369                let branches = collect_accumulate(b)?;
1370
1371                ExpressionKind::Case(Box::new(expr), branches)
1372            }
1373            parser::ExpressionKind::If(cond, then, els) => {
1374                let cond = Expression::from_parser(cond, env, unresolved)?;
1375                let then = Expression::from_parser(then, env, unresolved)?;
1376                let els = Expression::from_parser(els, env, unresolved)?;
1377
1378                ExpressionKind::If(Box::new(cond), Box::new(then), Box::new(els))
1379            }
1380            parser::ExpressionKind::Record(fields) => ExpressionKind::Record(Field::from_parser(
1381                fields,
1382                RecordForm::Record,
1383                env,
1384                unresolved,
1385            )?),
1386            // The record being updated is canonicalized ahead of its fields, the order
1387            // it is written and evaluated in.
1388            parser::ExpressionKind::Update(record, fields) => {
1389                let record = Expression::from_parser(record, env, unresolved)?;
1390                let fields = Field::from_parser(fields, RecordForm::Update, env, unresolved)?;
1391
1392                ExpressionKind::Update(Box::new(record), fields)
1393            }
1394            parser::ExpressionKind::Access(record, label, label_span) => ExpressionKind::Access(
1395                Box::new(Expression::from_parser(record, env, unresolved)?),
1396                label.clone(),
1397                *label_span,
1398            ),
1399            parser::ExpressionKind::Accessor(label, label_span) => {
1400                ExpressionKind::Accessor(label.clone(), *label_span)
1401            }
1402        };
1403
1404        Ok(Expression::new(e.span, kind))
1405    }
1406}
1407
1408/// One operator of an `ExpressionKind::InfixChain`, resolved against the infix
1409/// environment: its own `Infix` (precedence, associativity, and where it was
1410/// declared) alongside the canonical `Expression` it resolves to as a value —
1411/// a reference to the function its `infix` declaration names, qualified with the
1412/// module that wrote that declaration. `reassociate_infix_chain` consults `infix`
1413/// to decide how to nest, and `span` and `expr` to build the invented
1414/// `Application` nodes.
1415struct ResolvedInfixOp {
1416    name: Name,
1417    /// Where the operator itself was written — not its `infix` declaration.
1418    span: NodeSpan,
1419    expr: Expression,
1420    infix: Infix,
1421    /// Where the `infix` declaration was written, and in which module's file —
1422    /// the operator may well have been declared by an imported module, in which
1423    /// case `infix.span` is a byte range in *that* module's source. See
1424    /// [`InfixDeclaration`].
1425    declaration: InfixDeclaration,
1426}
1427
1428/// Resolves one operator of an `InfixChain` into the function its `infix`
1429/// declaration names, plus the `Infix` re-association needs.
1430///
1431/// The `infixes` map is the whole of an operator's scope: nothing else can hold
1432/// a key spelled like one, since a function's own name always comes from
1433/// `VarIdent`, a distinct token from `Op`. So `find_infix` failing is exactly
1434/// "no operator by that name is in scope", and gets the `VariableNotFound` a
1435/// reader would expect for a name they wrote and nothing declares.
1436///
1437/// The function behind the operator is resolved from the entry
1438/// ([`InfixFunction`]) rather than looked up in the scope the operator is *used*
1439/// in. An operator has no qualified spelling, so naming it in an `exposing` list
1440/// is the only way to reach one across a module boundary, and whether the
1441/// exporting module's backing function is separately in scope is neither the
1442/// importer's choice nor visible to them. The resulting `VarTopLevel`/`VarForeign`
1443/// is qualified with the module that wrote the `infix` declaration and names the
1444/// function, not the operator symbol, so it matches the binding a later phase
1445/// looks it up against.
1446fn resolve_infix_operator(
1447    name: &Name,
1448    span: NodeSpan,
1449    env: &dyn Environment,
1450) -> Result<ResolvedInfixOp, Error> {
1451    let entry = env.find_infix(name).cloned().ok_or_else(|| {
1452        let suggestion = suggest_name(name, env.value_names().into_iter());
1453        Error::VariableNotFound(env.module_name().qualify_name(name), span, suggestion)
1454    })?;
1455
1456    let function_name = &entry.infix.function_name;
1457    let kind = match &entry.function {
1458        InfixFunction::Local => {
1459            ExpressionKind::VarTopLevel(env.module_name().qualify_name(function_name))
1460        }
1461        InfixFunction::Imported(module, tpe) => ExpressionKind::VarForeign(
1462            module.qualify_name(function_name),
1463            module.package().clone(),
1464            tpe.clone(),
1465        ),
1466        // The exporting module declared the backing function without an
1467        // annotation, so its interface carries no type for it. The name that
1468        // failed to resolve is the function's, and that is what is reported —
1469        // the operator is in scope, and saying otherwise would send the reader
1470        // to check their own `import` line.
1471        InfixFunction::ImportedUntyped(module) => {
1472            return Err(Error::VariableNotFound(
1473                module.qualify_name(function_name),
1474                span,
1475                None,
1476            ))
1477        }
1478    };
1479
1480    Ok(ResolvedInfixOp {
1481        name: name.clone(),
1482        span,
1483        expr: Expression::new(span, kind),
1484        infix: entry.infix,
1485        declaration: entry.declaration,
1486    })
1487}
1488
1489/// Re-associates a flat run of operator applications into a tree of
1490/// `Application` nodes, in one pass over the operators — no operator or operand
1491/// is visited twice — using precedence climbing (a standard algorithm; see e.g.
1492/// https://en.wikipedia.org/wiki/Operator-precedence_parser#Precedence_climbing_method).
1493///
1494/// `min_prec` is the lowest precedence this call is willing to fold into `lhs`;
1495/// the outer, top-level call passes 0, admitting every operator. A recursive
1496/// call raises it to bind only the tighter operators that belong on the right
1497/// of the operator being folded — `op.infix.precedence + 1` for strictly higher
1498/// precedence, or `op.infix.precedence` itself when the next operator ties and
1499/// both associate right, which is what lets a right-associative run keep
1500/// folding at the same level (`a <| b <| c` → `a <| (b <| c)`).
1501///
1502/// Two adjacent operators of equal precedence are rejected rather than guessed
1503/// at unless they agree — both `left` (fold `lhs`, the usual case) or both
1504/// `right` (recurse into `rhs`). Anything else — a `left` against a `right`, or
1505/// either against an `infix non` operator, including one against itself — is
1506/// `Error::AmbiguousOperatorPrecedence`: nothing here says which one should
1507/// bind first, and guessing would silently pick a grouping the user did not
1508/// write.
1509fn reassociate_infix_chain(
1510    mut lhs: Expression,
1511    rest: &mut std::iter::Peekable<impl Iterator<Item = (ResolvedInfixOp, Expression)>>,
1512    min_prec: u8,
1513) -> Result<Expression, Error> {
1514    while let Some((op, mut rhs)) = rest.next_if(|(op, _)| op.infix.precedence >= min_prec) {
1515        loop {
1516            let next_min = match rest.peek() {
1517                None => None,
1518                Some((next_op, _)) => {
1519                    if next_op.infix.precedence > op.infix.precedence {
1520                        Some(op.infix.precedence + 1)
1521                    } else if next_op.infix.precedence == op.infix.precedence {
1522                        match (op.infix.associativity, next_op.infix.associativity) {
1523                            (Associativity::Left, Associativity::Left) => None,
1524                            (Associativity::Right, Associativity::Right) => {
1525                                Some(op.infix.precedence)
1526                            }
1527                            _ => {
1528                                return Err(Error::AmbiguousOperatorPrecedence(
1529                                    AmbiguousOperator::new(&op),
1530                                    AmbiguousOperator::new(next_op),
1531                                    op.span.merge(next_op.span),
1532                                ))
1533                            }
1534                        }
1535                    } else {
1536                        None
1537                    }
1538                }
1539            };
1540
1541            match next_min {
1542                Some(min) => rhs = reassociate_infix_chain(rhs, rest, min)?,
1543                None => break,
1544            }
1545        }
1546
1547        lhs = apply_infix(op, lhs, rhs);
1548    }
1549
1550    Ok(lhs)
1551}
1552
1553/// Builds the two `Application` nodes one step of infix re-association adds,
1554/// following the same span convention the grammar's right-recursive rewrite
1555/// used before this: the partial application of the operator to `lhs` — a node
1556/// with nothing in the user's text of its own — takes the operator's own span,
1557/// and the outer application, which stands for `lhs op rhs` as the user wrote
1558/// it, spans from wherever `lhs` starts to wherever `rhs` ends.
1559fn apply_infix(op: ResolvedInfixOp, lhs: Expression, rhs: Expression) -> Expression {
1560    let span = lhs.span.merge(rhs.span);
1561
1562    let partial = Expression::new(
1563        op.span,
1564        ExpressionKind::Apply(Box::new(op.expr), Box::new(lhs)),
1565    );
1566
1567    Expression::new(
1568        span,
1569        ExpressionKind::Apply(Box::new(partial), Box::new(rhs)),
1570    )
1571}
1572
1573/// One side of an [`Error::AmbiguousOperatorPrecedence`]: the operator as the user
1574/// spelled it, how its `infix` declaration said it associates, and where that
1575/// declaration was written.
1576///
1577/// `associativity` is carried rather than re-derived because the message depends on
1578/// it — an `infix non` operator does not chain at all, where a `left` against a
1579/// `right` is a choice the user can make with parentheses — and the error outlives
1580/// the environment the declaration was looked up in.
1581#[derive(Debug)]
1582pub struct AmbiguousOperator {
1583    pub name: Name,
1584    pub associativity: Associativity,
1585    pub declaration: InfixDeclaration,
1586}
1587
1588impl AmbiguousOperator {
1589    fn new(op: &ResolvedInfixOp) -> Self {
1590        AmbiguousOperator {
1591            name: op.name.clone(),
1592            associativity: op.infix.associativity,
1593            declaration: op.declaration,
1594        }
1595    }
1596
1597    fn is_non_associative(&self) -> bool {
1598        self.associativity == Associativity::None
1599    }
1600}
1601
1602#[derive(Debug, Clone, PartialEq)]
1603pub struct CaseBranch {
1604    pub pattern: Pattern,
1605    pub expression: Expression,
1606    /// The whole branch, pattern and expression together.
1607    pub span: NodeSpan,
1608}
1609
1610// end AST
1611
1612/// Everything canonicalization can reject.
1613///
1614/// # Why only some variants carry a span
1615///
1616/// A variant carries a [`NodeSpan`] when its construction site has one in hand — it
1617/// is looking at a `parser::Import`, `parser::Infix`, `parser::UnionType`,
1618/// `parser::Function` or `parser::Exposed`, all of which the grammar gives a span.
1619/// Those are the variants a diagnostic can put a caret under, and today that is every
1620/// variant below except three: the two group variants, `EnvironmentErrors` and
1621/// `Many`, have no position of their own and flatten their members' labels instead;
1622/// and `InvalidTupleSize` carries none for an unrelated reason — see its own doc
1623/// comment. Writing `NodeSpan::none()` into a variant that lacks a real position
1624/// would say "this error has a position we happen not to know", which is a lie;
1625/// leaving the field off says "this error has nowhere to point", which is true, and
1626/// the reporter renders it as message-plus-notes with no caret.
1627#[derive(Debug)]
1628pub enum Error {
1629    /// A name in the `module … exposing (…)` header that nothing in the module
1630    /// declares, and where that name was written (`ERR-9`).
1631    ExportNotFound(Name, ExportType, NodeSpan),
1632    /// A value exposed by this module — named explicitly in its `exposing` list,
1633    /// or implicitly by `exposing (..)` — whose declaration carries no type
1634    /// annotation (`SPEC-5`: an exposed declaration must be annotated).
1635    ///
1636    /// The first [`NodeSpan`] is where the `exposing` list names it — a real
1637    /// position for an explicit list, `NodeSpan::none()` for `exposing (..)`,
1638    /// which names nothing individually and so has no per-value span to point
1639    /// at (`parser::Exposing::Open` carries none at all). The second is the
1640    /// declaration's own span, always real: `labels()` falls back to it as the
1641    /// primary label when the first is absent, rather than pointing nowhere.
1642    ExportedValueNotAnnotated(Name, NodeSpan, NodeSpan),
1643    EnvironmentErrors(Vec<EnvError>),
1644    /// (infix, function), and where the `infix` declaration was written
1645    InfixReferenceInvalidValue(Name, Name, NodeSpan),
1646    /// Infix re-association (`reassociate_infix_chain`) found two adjacent
1647    /// operators of equal precedence that do not agree how to group: the left
1648    /// one, the right one, and the ambiguous pair's own span — from the left
1649    /// operator through the right one.
1650    ///
1651    /// Three shapes reach this, and [`PhaseError::message`] says which:
1652    /// `left.name == right.name` is one `infix non` operator chained with
1653    /// itself (`a == b == c`); either side being `infix non` against a
1654    /// different operator is a non-associative operator that does not chain at
1655    /// all (`a < b > c`); and a `left` against a `right` is the genuine
1656    /// disagreement about which side groups first (`a << b >> c`).
1657    AmbiguousOperatorPrecedence(AmbiguousOperator, AmbiguousOperator, NodeSpan),
1658    BindingPatternsInvalidLen(NodeSpan),
1659    /// A declaration with a type annotation and no body, and where the annotation
1660    /// was written — which is the only part of it there is to point at.
1661    NoBindings(NodeSpan),
1662    /// A name used as a value that nothing in scope declares, where it was
1663    /// written — the identifier alone, not the declaration around it — and,
1664    /// when one name in scope is a close enough typo-distance match, a
1665    /// suggestion for what was meant (`ERR-7`).
1666    VariableNotFound(QualName, NodeSpan, Option<Name>),
1667    /// A name exposed unqualified by more than one imported module, and where it
1668    /// was used. Each candidate module is paired with where the name is declared
1669    /// there — `Some` when that module's `Interface` knows both its file and the
1670    /// declaration's span, `None` for a hand-built interface (a test) or one built
1671    /// before its module's file was known (`ERR-5`) — and with whether that import
1672    /// was written by the module under check or supplied by [the default import
1673    /// list](../../docs/spec/modules.md#the-default-imports), which a default
1674    /// entry participates in exactly as a written import does
1675    /// (`SPEC-32`/[`DEC-15`](../../docs/decisions/dec-15.md)); the note calls out
1676    /// a default contributor as implicit.
1677    AmbiguousVariables(
1678        Name,
1679        Vec<(ModuleName, Option<super::SourceSpan>, ImportOrigin)>,
1680        NodeSpan,
1681    ),
1682    /// A constructor used in an expression or a pattern that nothing in scope
1683    /// declares, where it was written, and an optional "did you mean …?"
1684    /// suggestion (`ERR-7`).
1685    VariantNotFound(QualName, NodeSpan, Option<Name>),
1686    /// Nothing constructs this today — `Environment::find_type_constructor` returns
1687    /// at most one constructor per name, so it has no way to report an ambiguity.
1688    /// It is the designated rejection path once it can, and carries the span the
1689    /// construction site would have, alongside each candidate's declaration
1690    /// location — see [`Error::AmbiguousVariables`].
1691    AmbiguousVariants(
1692        Name,
1693        Vec<(ModuleName, Option<super::SourceSpan>, ImportOrigin)>,
1694        NodeSpan,
1695    ),
1696    /// A tuple type, pattern or expression had a size other than 2 or 3 (the
1697    /// only sizes the language supports).
1698    ///
1699    /// Nothing constructs this today, and it is kept deliberately. Both ASTs
1700    /// now hold their tuples in [`Tuple`], which cannot represent another
1701    /// arity, and the grammar has one production per arity — so a bad tuple is
1702    /// a parse error and never reaches canonicalization. This variant is the
1703    /// designated rejection path should a future source of tuples (a REPL, a
1704    /// desugaring pass) build one from a list.
1705    InvalidTupleSize(usize),
1706    /// A function was declared with multiple bindings (multi-clause definitions),
1707    /// which the compiler does not support yet.
1708    MultipleBindingsUnsupported(Name, NodeSpan),
1709    /// A class head that is not an uppercase name applied to exactly one type variable,
1710    /// and where the head was written, context excluded.
1711    InvalidClassHead(NodeSpan),
1712    /// A class declared where a type or an earlier class of the module already has its
1713    /// name, the two sharing [one namespace](../../docs/spec/name-resolution.md#namespaces):
1714    /// the name, which kind of declaration had it first, the class's head line and the
1715    /// other declaration's.
1716    ClassNameTaken(Name, NameTakenBy, NodeSpan, NodeSpan),
1717    /// A class name — a superclass, an instance's class, a constraint in an instance's
1718    /// or an annotation's context — that nothing in scope declares: the name as
1719    /// written, and the constraint or the instance head it was written in.
1720    ClassNotFound(Name, NodeSpan),
1721    /// A constraint in a class head, an instance's context or an annotation's context
1722    /// whose argument is not one type variable, and the constraint's span.
1723    ConstraintNotOnVariable(NodeSpan),
1724    /// A constraint in a class head or an instance's context on a type variable the head
1725    /// does not bind: the variable, and where it was written.
1726    ConstraintVariableUnbound(Name, NodeSpan),
1727    /// A constraint in an annotation's context on a type variable the annotation's type
1728    /// does not mention, so no caller could say which type it meant: the variable, and
1729    /// where it was written.
1730    ConstraintVariableNotInType(Name, NodeSpan),
1731    /// A member signature written with a context of its own: the member, and the
1732    /// context's span. A member signature carries no constraint.
1733    MemberConstrained(Name, NodeSpan),
1734    /// A member signature marked `unsafe`, which only a facade signature may be: the
1735    /// member, and the signature's span, which starts at the word.
1736    MemberUnsafe(Name, NodeSpan),
1737    /// A member signature that never mentions the class variable, so no use of it could
1738    /// say which instance it meant: the member, the class, the class variable, and the
1739    /// signature's span.
1740    MemberMissesClassVariable(Name, Name, Name, NodeSpan),
1741    /// Two member signatures of one name in one class: the name, the second signature's
1742    /// span and the first's.
1743    MemberDeclaredTwice(Name, NodeSpan, NodeSpan),
1744    /// A member whose name another value of the module already has — a top-level
1745    /// declaration, or a member of another of its classes. A member is a top-level
1746    /// value of the module declaring its class. Carries the member, its class, the
1747    /// other class when the other is a member, the member's signature span and the
1748    /// other declaration's.
1749    MemberNameTaken(Name, Name, Option<Name>, NodeSpan, NodeSpan),
1750    /// A member named on its own in its module's `exposing` list, where it is exposed
1751    /// with its class or not at all: the member, its class, and the entry's span.
1752    MemberExposedAlone(Name, Name, NodeSpan),
1753    /// `Name(..)` in a module's `exposing` list naming one of its classes, which has no
1754    /// constructors: the class, and the entry's span.
1755    ClassExposedWithConstructors(Name, NodeSpan),
1756    /// An instance head that is not one of the forms
1757    /// [a head may take](../../docs/spec/type-classes.md#what-an-instance-is-declared-for):
1758    /// what is wrong with it, and the span of the part that is.
1759    InvalidInstanceHead(InstanceHeadProblem, NodeSpan),
1760    /// An instance binding that names no member of the class: the binding's name, the
1761    /// class, and the binding's span.
1762    InstanceBindingNotMember(Name, Name, NodeSpan),
1763    /// A member of the class no binding of the instance defines: the member, the class,
1764    /// and the instance's head line.
1765    InstanceMemberMissing(Name, Name, NodeSpan),
1766    /// A member an instance binds twice: the member, the second binding's span and the
1767    /// first's.
1768    InstanceMemberBoundTwice(Name, NodeSpan, NodeSpan),
1769    /// An instance declared in a module that declares neither its class nor its head's
1770    /// type ([the orphan rule](../../docs/spec/type-classes.md#where-an-instance-may-be-declared)):
1771    /// the instance's class and head, and its head line. The class and a declared head
1772    /// type each carry the module that declares them, which the message names.
1773    OrphanInstance(Box<InstanceName>, NodeSpan),
1774    /// A second instance of one class for one head name: that class and head, the
1775    /// second instance's head line, and where the first was declared.
1776    DuplicateInstance(Box<InstanceName>, NodeSpan, DeclarationSite),
1777    /// An instance of a class with a superclass, with no instance of the superclass for
1778    /// the same head name in scope: the instance's class and head, the superclass, and
1779    /// the instance's head line.
1780    MissingSuperclassInstance(Box<InstanceName>, QualName, NodeSpan),
1781    /// A `derived` in a class body for a name the class does not declare as a member: the
1782    /// name as written, the class, and where `derived name` was written.
1783    DerivationForNonMember(Name, Name, NodeSpan),
1784    /// A second `derived` for a member that has one: the member, the second derivation's
1785    /// span and the first's. A member has at most one.
1786    DerivationRepeated(Name, NodeSpan, NodeSpan),
1787    /// A derivation for a member whose signature cannot carry one: the member, what is
1788    /// wrong with the signature, where `derived member` was written and where the
1789    /// member's signature was.
1790    DerivationSignature(Name, DerivationSignatureProblem, NodeSpan, NodeSpan),
1791    /// A derivation without a binding its member's signature calls for: the binding, the
1792    /// member, and where `derived member` was written.
1793    DerivationBindingMissing(Name, Name, NodeSpan),
1794    /// A binding in a derivation that its member's signature does not call for: the
1795    /// binding, the member, the bindings the derivation takes, and the binding's span.
1796    DerivationBindingUnexpected(Name, Name, Vec<Name>, NodeSpan),
1797    /// A binding written twice in one derivation: the binding, the member, the second
1798    /// one's span and the first's.
1799    DerivationBindingRepeated(Name, Name, NodeSpan, NodeSpan),
1800    /// A binding in a derivation written with more parameters than the walk supplies it:
1801    /// the binding, the member, how many parameters it may take, and the binding's span.
1802    /// The compiler's limit rather than the language's: canonical code has no lambda to place
1803    /// such a binding with, and `LANG-87` is the ticket.
1804    DerivationBindingTakesTooMany(Name, Name, usize, NodeSpan),
1805    /// A class that derives some of its members and not the rest: the class, the members
1806    /// left out, and the class's head line.
1807    DerivationIncomplete(Name, Vec<Name>, NodeSpan),
1808    /// An instance asking to be derived for a class that is not derivable — one whose
1809    /// members do not all carry a derivation: the class, and the word `derived`.
1810    DerivedInstanceNotDerivable(Name, NodeSpan),
1811    /// A `derived` instance for a type with no shape for a walk to read: what is wrong, and
1812    /// the word `derived`.
1813    DerivedInstanceNoShape(DerivedShapeProblem, NodeSpan),
1814    /// A `derived` instance for a type holding an argument with no instance of the
1815    /// class: which argument, and the word `derived`.
1816    DerivedInstanceRequires(Box<DerivedRequirement>, NodeSpan),
1817    /// A context written on a `derived` instance that does not provide a constraint the
1818    /// type's arguments need: which constraint, the written context's span and the word
1819    /// `derived`.
1820    DerivedInstanceContextTooNarrow(Box<DerivedContextGap>, NodeSpan, NodeSpan),
1821    /// A type name applied to the wrong number of arguments: the name, its
1822    /// declaration's own arity, the number of arguments actually written, and
1823    /// `tpe.span` — the whole application, so the caret covers every argument
1824    /// along with the name (`BUG-17`).
1825    TypeArityMismatch(Name, usize, usize, NodeSpan),
1826    /// A type name written in a type expression that nothing in scope declares:
1827    /// the name exactly as it was written, and `tpe.span` — the application, so
1828    /// the caret covers the name along with whatever it was applied to.
1829    ///
1830    /// The declarations of the module under check are in scope here as much as
1831    /// its imports are, so this is a name neither half offers. Only the
1832    /// `TypeKind::Unqualified` arm of `Type::from_parser_type` raises it: a
1833    /// type *variable* arrives as `TypeKind::Variable` and is bound by the
1834    /// annotation it appears in, so it resolves through nothing and cannot
1835    /// reach here.
1836    TypeNotFound(Name, NodeSpan),
1837    /// Something other than a constructor name and its arguments written in a
1838    /// `type` declaration's variant position: what was written there, and that
1839    /// variant's own span rather than the declaration's, so the caret sits under
1840    /// the offending variant alone (`BUG-18`).
1841    InvalidVariant(InvalidVariantKind, NodeSpan),
1842    /// An opaque scalar's `type` declaration — `Basics.Int`, `Basics.Float`,
1843    /// `Char.Char` or `String.String` — whose body is something other than
1844    /// exactly its own name with no arguments (`LANG-59`,
1845    /// [`DEC-15` decision
1846    /// 2](../../docs/decisions/dec-15.md#2--a-scalar-type-is-declared-in-zelkova-and-an-opaque-ones-declaration-names-itself)).
1847    /// Nothing in the language constructs or inspects a value of one of these
1848    /// four, so the declaration exists to be read rather than built from, and a
1849    /// body naming anything else — a different type, extra variants, arguments —
1850    /// would describe a representation the language does not have.
1851    ///
1852    /// Carries the declaration's qualified name and the whole declaration's span
1853    /// (`tpe.span`), the same position [`Error::InvalidVariant`] would rather than
1854    /// a per-variant one — the check runs on the shape of the whole variant list,
1855    /// not on one variant that is wrong among otherwise-good ones.
1856    InvalidScalarDeclaration(QualName, NodeSpan),
1857    /// Something other than a constraint written in front of an annotation's
1858    /// `=>`: what was written, and that piece's own span — one constraint of a
1859    /// parenthesised list rather than the whole context, so the caret sits under
1860    /// the part that is wrong.
1861    ///
1862    /// The grammar parses each element of a context as a type (see
1863    /// `parser::Context`), so every shape a type can take arrives here;
1864    /// `validate_context` is what narrows each one to a constraint.
1865    InvalidConstraint(InvalidConstraintKind, NodeSpan),
1866    /// A label given to two fields of one record type, record, update or record
1867    /// pattern: the label, which of the four forms it was found in, where the repeat
1868    /// was written and where the first field with that label was. Both spans are the
1869    /// label's alone, so the primary caret sits under the repeat and a secondary one
1870    /// under the first.
1871    ///
1872    /// [Records](../../docs/spec/records.md) makes it an error in all four, once
1873    /// where it states it for [a record type](../../docs/spec/records.md#the-type),
1874    /// [a record](../../docs/spec/records.md#building-a-record),
1875    /// [an update](../../docs/spec/records.md#updating-a-record) and
1876    /// [a record pattern](../../docs/spec/records.md#record-patterns): a record type is
1877    /// a set of fields, a record and an update say each field's value once, and a
1878    /// record pattern says once what each field it names is matched against. One error
1879    /// per repeat, each naming the first, so a label written three times is two.
1880    RepeatedLabel(Name, RecordForm, NodeSpan, NodeSpan),
1881
1882    // Binding module
1883    InfixDeclared(Name, NodeSpan),
1884    TypeDeclared(Name, NodeSpan),
1885    /// A `class` declaration in a `module foreign` facade, which holds signatures only:
1886    /// the class's head line.
1887    ClassDeclared(NodeSpan),
1888    /// An `instance` declaration in a `module foreign` facade: its head line.
1889    InstanceDeclared(NodeSpan),
1890    NoTypeInBinding(Name, NodeSpan),
1891    /// An annotation outside a `module foreign` facade was marked `unsafe`: the
1892    /// name it annotates, and the annotation's span — which the grammar takes
1893    /// from the modifier, so the caret starts on the word itself.
1894    ///
1895    /// `unsafe` asserts something about the companion behind a facade signature
1896    /// (`LANG-53`, [`DEC-12`](../../docs/decisions/dec-12.md)). There is no
1897    /// companion behind an ordinary declaration for it to be a claim about, and
1898    /// accepting the word there would make it mean nothing in half the places it
1899    /// can be written.
1900    UnsafeOutsideFacade(Name, NodeSpan),
1901    /// A `module foreign` facade signature naming a type variable or a
1902    /// function type, in a parameter or in the result, once the arrows
1903    /// separating a facade's own parameters are stripped
1904    /// (`docs/spec/interop.md#what-a-facade-signature-may-not-name`): the
1905    /// value's name, which form was found, and `function.annotation_span`.
1906    ///
1907    /// The span is the whole annotation rather than the offending piece of it,
1908    /// because a canonical `Type` carries no span of its own — see
1909    /// `Type::from_parser_type`'s doc comment — and the annotation is the
1910    /// finest caret available without first teaching that conversion to keep
1911    /// per-node spans.
1912    FacadeTypeNotAdmitted(Name, FacadeRejectedKind, NodeSpan),
1913    /// An unmarked `module foreign` facade signature whose result type — the
1914    /// last piece `facade_signature_pieces` returns, once
1915    /// `check_facade_admitted_type` has already accepted it — is not exactly
1916    /// `Task (Result Failure a)`: the value's name, and `function.annotation_span`.
1917    ///
1918    /// [An effectful facade](../../docs/spec/interop.md#an-effectful-facade)
1919    /// settles the shape: a facade declares an effect unless its signature is
1920    /// marked [`unsafe`](../../docs/spec/interop.md#an-unsafe-facade), and an
1921    /// effectful facade's result type must be exactly `Task (Result Failure a)`.
1922    /// Never raised for a signature `function.marked_unsafe` — `unsafe` removes
1923    /// the requirement, not the boundary check itself.
1924    ///
1925    /// The span is the whole annotation rather than the offending piece of it,
1926    /// for the same reason [`Error::FacadeTypeNotAdmitted`] uses it — a
1927    /// canonical `Type` carries no span of its own.
1928    FacadeResultNotEffect(Name, NodeSpan),
1929    /// `Task` named anywhere in a `module foreign` facade signature other than
1930    /// the whole of an unmarked facade's result: the value's name, and
1931    /// `function.annotation_span`.
1932    ///
1933    /// [An effectful facade](../../docs/spec/interop.md#an-effectful-facade)
1934    /// confines `Task` to that one position — never as an argument, and never
1935    /// nested inside another type, whether or not the signature is marked
1936    /// [`unsafe`](../../docs/spec/interop.md#an-unsafe-facade). `Task` is
1937    /// recognised by the qualified name of its declaration
1938    /// (`is_task_declaration`) and never by spelling, so a module's own type
1939    /// named `Task` is an ordinary union here, not this.
1940    ///
1941    /// The span is the whole annotation, as [`Error::FacadeTypeNotAdmitted`]'s
1942    /// is.
1943    FacadeTaskMisplaced(Name, NodeSpan),
1944    /// A `module foreign` facade signature written with a constraint context:
1945    /// the value's name, and the context's span.
1946    ///
1947    /// A facade is monomorphic — its signature names the types the code behind
1948    /// it really handles ([Type
1949    /// classes](../../docs/spec/type-classes.md#a-constrained-function-may-not-be-a-foreign-facade),
1950    /// [`DEC-2` decision 6](../../docs/decisions/dec-2.md)) — and a constrained
1951    /// function is specialised per instance out of a body a facade does not have.
1952    /// Reported whatever the context's shape, a well-formed one included.
1953    FacadeConstrained(Name, NodeSpan),
1954
1955    /// A parameterless binding that depends on itself — [evaluation
1956    /// semantics](../../docs/spec/evaluation-semantics.md#a-binding-may-not-depend-on-itself):
1957    /// such a binding is evaluated once, before the program runs, after everything it
1958    /// depends on, and a cycle through it describes no such order. *Depends on* is
1959    /// transitive mention: the declarations its body mentions, the ones *their* bodies
1960    /// mention, and so on, through functions as well as parameterless bindings — see
1961    /// `dependency_graph`.
1962    ///
1963    /// One entry per member of the cycle — every declaration of one strongly-connected
1964    /// component of that graph — each carrying its own declaration's span
1965    /// (`Value::span()`) and whether it is a function. Length 1 for a parameterless
1966    /// binding that mentions itself (`x = x`), length 2 or more for a cycle running
1967    /// through several declarations (`a = b` beside `b = a`, or `a = f 1` beside `f x =
1968    /// a`). `check_self_dependency` orders the members parameterless bindings first,
1969    /// then functions, each group by name, so the first entry is always a parameterless
1970    /// binding and the order is not an artifact of traversal. `labels()` gives that first
1971    /// entry the primary label and every other entry a secondary one.
1972    ///
1973    /// A cycle of functions only is never reported: a function's value exists before its
1974    /// body runs, so `f n = f n` and mutual recursion between two functions are untouched
1975    /// by this check.
1976    SelfDependency(Vec<CycleMember>),
1977
1978    // Utility error
1979    Many(Vec<Error>),
1980}
1981
1982/// One declaration of a cycle [`Error::SelfDependency`] reports.
1983#[derive(Debug, Clone)]
1984pub struct CycleMember {
1985    pub name: Name,
1986    /// The whole declaration, as `Value::span()` gives it.
1987    pub span: NodeSpan,
1988    /// Whether the declaration names a parameter. A cycle is only ever reported when it
1989    /// holds at least one member for which this is `false`.
1990    pub function: bool,
1991}
1992
1993/// What was written where a `type` declaration expected a variant — see
1994/// [`Error::InvalidVariant`].
1995///
1996/// A variant is a constructor name followed by zero or more type arguments, and
1997/// nothing else. The grammar does not enforce that: it parses a variant list with
1998/// the general `Type` production, so every shape a type expression can take reaches
1999/// `do_types`. This enum names the five that are not a variant, one per remaining
2000/// [`parser::TypeKind`], so each can say what it is in the words of the source.
2001#[derive(Debug, PartialEq, Clone)]
2002pub enum InvalidVariantKind {
2003    /// A name beginning with a lowercase letter, which the grammar reads as a type
2004    /// variable — `type Colour = red`, and a mistyped constructor name along with
2005    /// it. Carries the name so the message can quote it.
2006    LowercaseName(Name),
2007    /// A tuple type — `type Pair = (Int, Int)`.
2008    Tuple,
2009    /// The unit type — `type Nothing = ()`.
2010    Unit,
2011    /// A function type — `type Wrapper = Wrap Int -> Int`. The arrow is the *whole*
2012    /// variant rather than a suffix of it, `Wrap Int` being its left operand, so
2013    /// there is no constructor here to keep either.
2014    Arrow,
2015    /// A record type — `type Point = { x : Int }`. A record type is declared by no
2016    /// `type` declaration; one may sit inside a variant, `Point { x : Int }`.
2017    Record,
2018}
2019
2020/// What was written in front of `=>` in place of a constraint — see
2021/// [`Error::InvalidConstraint`].
2022///
2023/// A constraint is an uppercase name applied to one or more type arguments, and a
2024/// context is one constraint or a parenthesised, comma-separated list of them
2025/// ([`parser::Context`]). This names every other shape an element of that list can
2026/// take, one per remaining [`parser::TypeKind`] case.
2027#[derive(Debug, PartialEq, Clone)]
2028pub enum InvalidConstraintKind {
2029    /// A type variable on its own — `a => a`.
2030    Variable(Name),
2031    /// An uppercase name with no argument — `Int => a`, and so each half of
2032    /// `(Int, Char) => a`. Carries the name so the message can quote it.
2033    Unapplied(Name),
2034    /// A function type — `Int -> Int => a`.
2035    Arrow,
2036    /// A tuple inside the parenthesised list — `((Eq a, Eq b), Eq c) => a`. The
2037    /// parser reads the outermost parentheses as the list, so only a tuple nested
2038    /// in it reaches here.
2039    Tuple,
2040    /// The unit type — `() => a`.
2041    Unit,
2042    /// A record type — `{ x : a } => a`.
2043    Record,
2044}
2045
2046/// What had a class's name first — see [`Error::ClassNameTaken`].
2047#[derive(Debug, PartialEq, Clone, Copy)]
2048pub enum NameTakenBy {
2049    /// A `type` declaration of the same module.
2050    Type,
2051    /// An earlier `class` declaration of the same module.
2052    Class,
2053}
2054
2055/// What is wrong with an instance head — see [`Error::InvalidInstanceHead`].
2056///
2057/// A head is a class name applied to one type, and that type is a declared type applied
2058/// to distinct variables, a tuple of distinct variables, or `()`.
2059#[derive(Debug, PartialEq, Clone)]
2060pub enum InstanceHeadProblem {
2061    /// Something other than a class name applied to a type — `instance a where`.
2062    NotAClass,
2063    /// The class applied to some number of types other than one — `instance Eq Int Char`.
2064    ClassApplied(usize),
2065    /// A bare type variable — `instance Eq a`.
2066    Variable(Name),
2067    /// A function type — `instance Eq (a -> b)`.
2068    Function,
2069    /// A record type.
2070    Record,
2071    /// An argument of the head's type that is not a type variable — `Int` in
2072    /// `instance Eq (Maybe Int)`.
2073    ArgumentNotVariable,
2074    /// A variable the head already bound — the second `a` of `instance Eq (Pair a a)`.
2075    RepeatedVariable(Name),
2076}
2077
2078/// The two forms [What a facade signature may not
2079/// name](../../docs/spec/interop.md#what-a-facade-signature-may-not-name)
2080/// rejects — see [`Error::FacadeTypeNotAdmitted`].
2081#[derive(Debug, PartialEq, Clone, Copy)]
2082pub enum FacadeRejectedKind {
2083    /// A type variable, which excludes no value: there is nothing for a
2084    /// runtime predicate to decide.
2085    Variable,
2086    /// A function type, wherever it is found — as the signature's own result
2087    /// or nested inside a parameter, a tuple or a union's argument.
2088    Function,
2089}
2090
2091/// Canonicalization errors name source constructs — a value, a type, an operator —
2092/// so their messages can be written in the same words the user wrote.
2093///
2094/// The variants whose construction site had a declaration in hand also point at it;
2095/// see the enum's own documentation for why the others do not.
2096impl PhaseError for Error {
2097    fn message(&self) -> String {
2098        match self {
2099            Error::ExportNotFound(name, tpe, _) => format!(
2100                "`{}` is exposed by this module but no {} of that name is declared in it",
2101                name,
2102                export_type_noun(tpe)
2103            ),
2104            Error::ExportedValueNotAnnotated(name, _, _) => format!(
2105                "`{}` is exposed by this module but has no type annotation",
2106                name
2107            ),
2108            Error::EnvironmentErrors(errors) => match errors.as_slice() {
2109                [only] => only.message(),
2110                many => format!("{} of this module's imports could not be resolved", many.len()),
2111            },
2112            Error::InfixReferenceInvalidValue(infix, function, _) => format!(
2113                "the infix operator `{}` is declared as `{}`, which is not a value declared in this module",
2114                infix, function
2115            ),
2116            Error::AmbiguousOperatorPrecedence(left, right, _) => {
2117                // Three shapes, and the everyday one is the middle: `Basics`
2118                // declares six operators `infix non 4`, so `a < b > c` reaches
2119                // here with two *different* operators that do not disagree about
2120                // anything — both say they do not chain. Calling that a
2121                // disagreement about which side groups first would name a reason
2122                // that is not the reason.
2123                if left.name == right.name {
2124                    format!(
2125                        "`{}` is declared `infix non`, so it cannot be chained with itself without parentheses to say which application comes first",
2126                        left.name
2127                    )
2128                } else if left.is_non_associative() && right.is_non_associative() {
2129                    format!(
2130                        "`{}` and `{}` are both declared `infix non` at the same precedence, so neither groups the other and this needs parentheses",
2131                        left.name, right.name
2132                    )
2133                } else if left.is_non_associative() || right.is_non_associative() {
2134                    let (non, other) = if left.is_non_associative() {
2135                        (&left.name, &right.name)
2136                    } else {
2137                        (&right.name, &left.name)
2138                    };
2139
2140                    format!(
2141                        "`{}` is declared `infix non`, so it does not chain with `{}` at the same precedence without parentheses",
2142                        non, other
2143                    )
2144                } else {
2145                    format!(
2146                        "`{}` and `{}` have the same precedence but disagree on which side groups first, so this needs parentheses to say which one applies first",
2147                        left.name, right.name
2148                    )
2149                }
2150            }
2151            Error::BindingPatternsInvalidLen(_) => {
2152                "the arguments of this declaration do not line up with its type annotation"
2153                    .to_owned()
2154            }
2155            Error::NoBindings(_) => {
2156                "this declaration has a type annotation but no body".to_owned()
2157            }
2158            Error::VariableNotFound(name, _, _) => {
2159                format!("cannot find a value named `{}`", name.to_name())
2160            }
2161            Error::AmbiguousVariables(name, _, _) => {
2162                format!("`{}` is exposed by several imported modules", name)
2163            }
2164            Error::VariantNotFound(name, _, _) => {
2165                format!("cannot find a type constructor named `{}`", name.to_name())
2166            }
2167            Error::AmbiguousVariants(name, _, _) => format!(
2168                "the type constructor `{}` is exposed by several imported modules",
2169                name
2170            ),
2171            Error::InvalidTupleSize(size) => format!(
2172                "a tuple has two or three elements, this one has {}",
2173                size
2174            ),
2175            Error::MultipleBindingsUnsupported(name, _) => format!(
2176                "`{}` is declared over several bindings, which is not supported yet",
2177                name
2178            ),
2179            Error::InvalidClassHead(_) => {
2180                "a class head is the class's name applied to one type variable".to_owned()
2181            }
2182            Error::ClassNameTaken(name, NameTakenBy::Type, _, _) => format!(
2183                "`{}` is declared as both a type and a class, and the two share one namespace",
2184                name
2185            ),
2186            Error::ClassNameTaken(name, NameTakenBy::Class, _, _) => {
2187                format!("the class `{}` is declared twice", name)
2188            }
2189            Error::ClassNotFound(name, _) => format!("cannot find a class named `{}`", name),
2190            Error::ConstraintNotOnVariable(_) => {
2191                "a constraint is a class applied to one type variable".to_owned()
2192            }
2193            Error::ConstraintVariableUnbound(name, _) => format!(
2194                "the type variable `{}` is constrained, but the head does not bind it",
2195                name
2196            ),
2197            Error::ConstraintVariableNotInType(name, _) => format!(
2198                "the type variable `{}` is constrained, but the annotated type does not mention it",
2199                name
2200            ),
2201            Error::MemberConstrained(name, _) => format!(
2202                "the member `{}` is written with a constraint, and a member signature carries none",
2203                name
2204            ),
2205            Error::MemberUnsafe(name, _) => format!(
2206                "the member `{}` is marked `unsafe`, which only a signature in a `module foreign` facade may be",
2207                name
2208            ),
2209            Error::MemberMissesClassVariable(name, class, variable, _) => format!(
2210                "the member `{}` of `{}` never mentions the class variable `{}`, so no use of it could say which instance it means",
2211                name, class, variable
2212            ),
2213            Error::MemberDeclaredTwice(name, _, _) => {
2214                format!("the member `{}` is declared twice in this class", name)
2215            }
2216            Error::MemberNameTaken(name, class, Some(other), _, _) => format!(
2217                "`{}` is a member of both `{}` and `{}`",
2218                name, other, class
2219            ),
2220            Error::MemberNameTaken(name, class, None, _, _) => format!(
2221                "`{}` is a member of `{}` and is also declared as a value of this module",
2222                name, class
2223            ),
2224            Error::MemberExposedAlone(name, class, _) => format!(
2225                "`{}` is a member of `{}`, and a member is exposed with its class, not on its own",
2226                name, class
2227            ),
2228            Error::ClassExposedWithConstructors(name, _) => format!(
2229                "`{}` is a class, and a class has no constructors for `(..)` to expose",
2230                name
2231            ),
2232            Error::InvalidInstanceHead(problem, _) => match problem {
2233                InstanceHeadProblem::NotAClass => {
2234                    "an instance head is a class name applied to the type the instance is for"
2235                        .to_owned()
2236                }
2237                InstanceHeadProblem::ClassApplied(n) => format!(
2238                    "an instance head applies its class to one type, and this one applies it to {}",
2239                    n
2240                ),
2241                InstanceHeadProblem::Variable(name) => format!(
2242                    "an instance is for a type, and the type variable `{}` is not one",
2243                    name
2244                ),
2245                InstanceHeadProblem::Function => {
2246                    "an instance cannot be declared for a function type".to_owned()
2247                }
2248                InstanceHeadProblem::Record => {
2249                    "an instance cannot be declared for a record type".to_owned()
2250                }
2251                InstanceHeadProblem::ArgumentNotVariable => {
2252                    "every argument of an instance head's type must be a type variable"
2253                        .to_owned()
2254                }
2255                InstanceHeadProblem::RepeatedVariable(name) => format!(
2256                    "the type variable `{}` is written twice in this instance head",
2257                    name
2258                ),
2259            },
2260            Error::InstanceBindingNotMember(name, class, _) => {
2261                format!("`{}` is not a member of the class `{}`", name, class)
2262            }
2263            Error::InstanceMemberMissing(name, class, _) => format!(
2264                "this instance does not define `{}`, a member of the class `{}`",
2265                name, class
2266            ),
2267            Error::InstanceMemberBoundTwice(name, _, _) => {
2268                format!("this instance defines `{}` twice", name)
2269            }
2270            Error::OrphanInstance(instance, _) => match instance.head.module() {
2271                Some(head_module) => format!(
2272                    "`{}` is declared in `{}` and {} in `{}`; an instance may go in either",
2273                    instance.class.unqualified_name(),
2274                    instance.class.module_name(),
2275                    instance.head.describe(),
2276                    head_module.name()
2277                ),
2278                None => format!(
2279                    "`{}` is declared in `{}`, and an instance of it for {} may go only there",
2280                    instance.class.unqualified_name(),
2281                    instance.class.module_name(),
2282                    instance.head.describe()
2283                ),
2284            },
2285            Error::DuplicateInstance(instance, _, _) => format!(
2286                "`{}` already has an instance for {}",
2287                instance.class.unqualified_name(),
2288                instance.head.describe()
2289            ),
2290            Error::MissingSuperclassInstance(instance, superclass, _) => format!(
2291                "an instance of `{}` for {} needs an instance of its superclass `{}` for {}",
2292                instance.class.unqualified_name(),
2293                instance.head.describe(),
2294                superclass.unqualified_name(),
2295                instance.head.describe()
2296            ),
2297            Error::DerivationForNonMember(member, class, _) => format!(
2298                "`derived {}` is in the class `{}`, which has no member `{}`",
2299                member, class, member
2300            ),
2301            Error::DerivationRepeated(member, _, _) => {
2302                format!("the member `{}` has a derivation already", member)
2303            }
2304            Error::DerivationSignature(member, problem, _, _) => match problem {
2305                DerivationSignatureProblem::NoClassValue => format!(
2306                    "the member `{}` takes no value of the class's type, so there is none for a derivation to walk",
2307                    member
2308                ),
2309                DerivationSignatureProblem::ResultMentionsClassVariable => format!(
2310                    "the member `{}` answers with a type that mentions the class variable, which a derivation cannot build",
2311                    member
2312                ),
2313                DerivationSignatureProblem::Shape => format!(
2314                    "the signature of `{}` is neither a value of the class's type nor two, followed by an answer",
2315                    member
2316                ),
2317            },
2318            Error::DerivationBindingMissing(binding, member, _) => format!(
2319                "the derivation of `{}` has no `{}`",
2320                member, binding
2321            ),
2322            Error::DerivationBindingUnexpected(binding, member, takes, _) => format!(
2323                "`{}` is not a binding of the derivation of `{}`, which takes {}",
2324                binding,
2325                member,
2326                name_list(takes)
2327            ),
2328            Error::DerivationBindingRepeated(binding, member, _, _) => format!(
2329                "the derivation of `{}` defines `{}` twice",
2330                member, binding
2331            ),
2332            Error::DerivationBindingTakesTooMany(binding, member, most, _) => format!(
2333                "`{}` in the derivation of `{}` takes at most {}, the ones the walk gives it",
2334                binding,
2335                member,
2336                parameter_count(*most)
2337            ),
2338            Error::DerivationIncomplete(class, left_out, _) => format!(
2339                "the class `{}` derives some of its members and not {}, and an instance of it could only be half derived",
2340                class,
2341                name_list(left_out)
2342            ),
2343            Error::DerivedInstanceNotDerivable(class, _) => format!(
2344                "`{}` cannot be derived: not every member of it carries a derivation",
2345                class
2346            ),
2347            Error::DerivedInstanceNoShape(problem, _) => match problem {
2348                DerivedShapeProblem::Scalar(tpe) => format!(
2349                    "`{}` is a scalar type, which has no shape for a derivation to walk",
2350                    tpe
2351                ),
2352                DerivedShapeProblem::NoConstructors(tpe) => format!(
2353                    "the constructors of `{}` are not in scope, and a derivation is read off them",
2354                    tpe
2355                ),
2356                DerivedShapeProblem::UnitHasNoElement(class) => format!(
2357                    "`()` has no element for the derivation of `{}` to begin at",
2358                    class
2359                ),
2360            },
2361            Error::DerivedInstanceContextTooNarrow(gap, _, _) => {
2362                let part = match &gap.part {
2363                    DerivedPart::Variant(variant) => format!("`{}`", variant),
2364                    DerivedPart::Element(position) => format!("element {} of the tuple", position),
2365                };
2366                format!(
2367                    "{} holds a `{}`, which needs `{}` for the derived instance of `{}`, and the instance's context does not provide it",
2368                    part, gap.argument, gap.missing, gap.class
2369                )
2370            }
2371            Error::DerivedInstanceRequires(requirement, _) => {
2372                let part = match &requirement.part {
2373                    DerivedPart::Variant(variant) => format!("`{}`", variant),
2374                    DerivedPart::Element(position) => format!("element {} of the tuple", position),
2375                };
2376                if requirement.argument == requirement.missing {
2377                    if requirement.function {
2378                        format!(
2379                            "{} holds a function, `{}`, and no instance of `{}` can be declared for one",
2380                            part, requirement.missing, requirement.class
2381                        )
2382                    } else {
2383                        format!(
2384                            "{} holds a `{}`, which has no instance of `{}`",
2385                            part, requirement.missing, requirement.class
2386                        )
2387                    }
2388                } else {
2389                    format!(
2390                        "{} holds a `{}`, which needs an instance of `{}` for `{}`, and there is none",
2391                        part, requirement.argument, requirement.class, requirement.missing
2392                    )
2393                }
2394            }
2395            Error::TypeArityMismatch(name, declared, written, _) => format!(
2396                "`{}` takes {}, but is applied to {} here",
2397                name,
2398                type_argument_count(*declared),
2399                type_argument_count(*written)
2400            ),
2401            Error::TypeNotFound(name, _) => {
2402                format!("cannot find a type named `{}`", name)
2403            }
2404            Error::InvalidVariant(kind, _) => match kind {
2405                InvalidVariantKind::LowercaseName(name) => format!(
2406                    "`{}` is not a constructor name: a constructor name begins with an uppercase letter",
2407                    name
2408                ),
2409                InvalidVariantKind::Tuple => {
2410                    "a variant is a constructor name followed by its arguments, and this one is a tuple type"
2411                        .to_owned()
2412                }
2413                InvalidVariantKind::Unit => {
2414                    "a variant is a constructor name followed by its arguments, and this one is the unit type"
2415                        .to_owned()
2416                }
2417                InvalidVariantKind::Arrow => {
2418                    "a variant is a constructor name followed by its arguments, and this one is a function type"
2419                        .to_owned()
2420                }
2421                InvalidVariantKind::Record => {
2422                    "a variant is a constructor name followed by its arguments, and this one is a record type"
2423                        .to_owned()
2424                }
2425            },
2426            Error::InvalidScalarDeclaration(name, _) => format!(
2427                "`{}` is an opaque scalar type, so its declaration must be exactly `type {} = {}`",
2428                name.to_name(),
2429                name.unqualified_name(),
2430                name.unqualified_name()
2431            ),
2432            Error::RepeatedLabel(label, form, _, _) => format!(
2433                "`{}` labels two fields of one {}, and a label may be given only once",
2434                label,
2435                match form {
2436                    RecordForm::Type => "record type",
2437                    RecordForm::Record => "record",
2438                    RecordForm::Update => "update",
2439                    RecordForm::Pattern => "record pattern",
2440                }
2441            ),
2442            Error::InvalidConstraint(kind, _) => match kind {
2443                InvalidConstraintKind::Variable(name) => format!(
2444                    "only constraints may be written before `=>`, and the type variable `{}` is not one",
2445                    name
2446                ),
2447                InvalidConstraintKind::Unapplied(name) => format!(
2448                    "only constraints may be written before `=>`, and `{}` on its own is not one",
2449                    name
2450                ),
2451                InvalidConstraintKind::Arrow => {
2452                    "only constraints may be written before `=>`, and a function type is not one"
2453                        .to_owned()
2454                }
2455                InvalidConstraintKind::Tuple => {
2456                    "only constraints may be written before `=>`, and a tuple inside the list of constraints is not one"
2457                        .to_owned()
2458                }
2459                InvalidConstraintKind::Record => {
2460                    "only constraints may be written before `=>`, and a record type is not one"
2461                        .to_owned()
2462                }
2463                InvalidConstraintKind::Unit => {
2464                    "only constraints may be written before `=>`, and the unit type is not one"
2465                        .to_owned()
2466                }
2467            },
2468            Error::InfixDeclared(name, _) => format!(
2469                "a `module foreign` facade cannot declare an infix operator, but declares `{}`",
2470                name
2471            ),
2472            Error::TypeDeclared(name, _) => format!(
2473                "a `module foreign` facade cannot declare a type, but declares `{}`",
2474                name
2475            ),
2476            Error::ClassDeclared(_) => {
2477                "a `module foreign` facade cannot declare a class".to_owned()
2478            }
2479            Error::InstanceDeclared(_) => {
2480                "a `module foreign` facade cannot declare an instance".to_owned()
2481            }
2482            Error::NoTypeInBinding(name, _) => format!(
2483                "`{}` has no type annotation, and a `module foreign` facade is annotations only",
2484                name
2485            ),
2486            Error::UnsafeOutsideFacade(name, _) => format!(
2487                "`{}` is marked `unsafe`, which only a signature in a `module foreign` facade may be",
2488                name
2489            ),
2490            Error::FacadeTypeNotAdmitted(name, kind, _) => format!(
2491                "`{}` is a `module foreign` facade signature naming {}, which no target can check at the boundary",
2492                name,
2493                match kind {
2494                    FacadeRejectedKind::Variable => "a type variable",
2495                    FacadeRejectedKind::Function => "a function type",
2496                }
2497            ),
2498            Error::FacadeResultNotEffect(name, _) => format!(
2499                "`{}` is a `module foreign` facade signature with no `unsafe`, so it must return `Task (Result Failure a)`",
2500                name
2501            ),
2502            Error::FacadeTaskMisplaced(name, _) => format!(
2503                "`{}` names `Task` somewhere other than the whole of an unmarked facade's result",
2504                name
2505            ),
2506            Error::FacadeConstrained(name, _) => format!(
2507                "`{}` is a `module foreign` facade signature, and a facade signature may not carry a constraint",
2508                name
2509            ),
2510            // A one-binding cycle reads better as its own sentence than as "a
2511            // cycle of length one" — see the enum's own doc comment.
2512            // A larger cycle may hold functions, so it is described by its first member —
2513            // always a parameterless binding — and every member is named for what it is.
2514            Error::SelfDependency(members) => match members.as_slice() {
2515                [only] => format!(
2516                    "`{}` is a parameterless binding whose value depends on itself",
2517                    only.name
2518                ),
2519                [first, ..] => {
2520                    let mut named: Vec<String> = members
2521                        .iter()
2522                        .map(|member| {
2523                            if member.function {
2524                                format!("the function `{}`", member.name)
2525                            } else {
2526                                format!("`{}`", member.name)
2527                            }
2528                        })
2529                        .collect();
2530                    let last = named.pop().unwrap_or_default();
2531                    format!(
2532                        "`{}` needs its own value before it has one: {} and {} depend on each other",
2533                        first.name,
2534                        named.join(", "),
2535                        last
2536                    )
2537                }
2538                [] => "a parameterless binding depends on itself".to_owned(),
2539            },
2540            Error::Many(errors) => match errors.as_slice() {
2541                [only] => only.message(),
2542                many => format!("{} errors while canonicalizing this module", many.len()),
2543            },
2544        }
2545    }
2546
2547    fn labels(&self) -> Vec<SpanLabel> {
2548        // One helper per shape: a variant either has a span and one thing to say
2549        // about it, or it delegates to the errors it wraps.
2550        let primary = |span: &NodeSpan, message: &str| match span.span() {
2551            Some(span) => vec![SpanLabel {
2552                span,
2553                message: message.to_owned(),
2554                primary: true,
2555                file: None,
2556            }],
2557            None => Vec::new(),
2558        };
2559
2560        // A secondary label in the module under check, when the span has a position.
2561        let secondary = |span: &NodeSpan, message: String| {
2562            span.span().map(|span| SpanLabel {
2563                span,
2564                message,
2565                primary: false,
2566                file: None,
2567            })
2568        };
2569
2570        // A secondary label pointing at where one ambiguous candidate is declared,
2571        // in *its own* module's file rather than the one being checked — the
2572        // mechanism `ERR-5` adds. `None` when that candidate's `Interface` cannot
2573        // say (a hand-built interface, or one built before its file was known)
2574        // yields no label for that candidate rather than one at the wrong place.
2575        let ambiguous_candidates =
2576            |candidates: &[(ModuleName, Option<super::SourceSpan>, ImportOrigin)]| {
2577                candidates
2578                    .iter()
2579                    .filter_map(|(module, source, _origin)| {
2580                        source.map(|s| SpanLabel {
2581                            span: s.span,
2582                            message: format!("also exposed here, by `{}`", module.name()),
2583                            primary: false,
2584                            file: Some(s.file),
2585                        })
2586                    })
2587                    .collect::<Vec<_>>()
2588            };
2589
2590        match self {
2591            Error::ExportNotFound(name, _, span) => primary(
2592                span,
2593                &format!("`{}` is not declared anywhere in this module", name),
2594            ),
2595            Error::ExportedValueNotAnnotated(name, exposed_span, declared_span) => {
2596                let mut labels = primary(
2597                    exposed_span,
2598                    &format!("`{}` is exposed here but has no type annotation", name),
2599                );
2600                if labels.is_empty() {
2601                    // Reached only for `exposing (..)`: it names nothing
2602                    // individually, so there is no exposing-list position to put
2603                    // the primary label under — the declaration becomes the
2604                    // primary (and only) label instead of a secondary one.
2605                    labels = primary(
2606                        declared_span,
2607                        &format!(
2608                            "`{}` is exposed by `exposing (..)` but has no type annotation",
2609                            name
2610                        ),
2611                    );
2612                } else if let Some(span) = declared_span.span() {
2613                    labels.push(SpanLabel {
2614                        span,
2615                        message: "declared here, with no type annotation".to_owned(),
2616                        primary: false,
2617                        file: None,
2618                    });
2619                }
2620                labels
2621            }
2622            Error::InfixReferenceInvalidValue(_, _, span) => primary(span, "declared here"),
2623            // The two "declared here" labels go through `InfixDeclaration`, which
2624            // is what knows whether the declaration is in the module under check
2625            // or in an imported one. An operator's `infix` declaration is very
2626            // often not local — `Basics` declares every one the standard library
2627            // uses — and `Infix::span` is then a byte range in *that* module's
2628            // file, so a label built with `file: None` would underline unrelated
2629            // text in the importing module (`ERR-5` is the mechanism that avoids
2630            // it).
2631            Error::AmbiguousOperatorPrecedence(left, right, span) => {
2632                let mut labels = primary(span, "ambiguous without parentheses");
2633
2634                labels.extend(
2635                    left.declaration
2636                        .label(format!("`{}` declared here", left.name)),
2637                );
2638
2639                // Both sides naming the same operator is the `infix non`
2640                // self-conflict — they point at the very same declaration, so a
2641                // second label there would only repeat the first one.
2642                if left.name != right.name {
2643                    labels.extend(
2644                        right
2645                            .declaration
2646                            .label(format!("`{}` declared here", right.name)),
2647                    );
2648                }
2649
2650                labels
2651            }
2652            // The four that name an identifier: the caret sits under the name the
2653            // user wrote, which is the whole point of spanning expressions and
2654            // patterns rather than only declarations. `VariableNotFound` and
2655            // `VariantNotFound` append their suggestion, when they have one, to
2656            // this same label rather than a free-floating note, so the caret and
2657            // the suggestion agree about which name is meant (`ERR-7`).
2658            Error::VariableNotFound(_, span, suggestion) => primary(
2659                span,
2660                &format!(
2661                    "no value of this name is in scope{}",
2662                    suggestion_suffix(suggestion)
2663                ),
2664            ),
2665            Error::AmbiguousVariables(_, candidates, span) => {
2666                let mut labels = primary(span, "this name is ambiguous");
2667                labels.extend(ambiguous_candidates(candidates));
2668                labels
2669            }
2670            Error::VariantNotFound(_, span, suggestion) => primary(
2671                span,
2672                &format!(
2673                    "no type constructor of this name is in scope{}",
2674                    suggestion_suffix(suggestion)
2675                ),
2676            ),
2677            Error::AmbiguousVariants(_, candidates, span) => {
2678                let mut labels = primary(span, "this type constructor is ambiguous");
2679                labels.extend(ambiguous_candidates(candidates));
2680                labels
2681            }
2682            Error::BindingPatternsInvalidLen(span) => primary(span, "declared here"),
2683            Error::NoBindings(span) => primary(span, "this annotation has no body"),
2684            Error::MultipleBindingsUnsupported(_, span) => primary(span, "declared here"),
2685            Error::InvalidClassHead(span) => primary(span, "not a class name and one variable"),
2686            Error::ClassNameTaken(name, taken_by, span, other) => {
2687                let mut labels = primary(span, &format!("the class `{}` is declared here", name));
2688                if let Some(other) = other.span() {
2689                    labels.push(SpanLabel {
2690                        span: other,
2691                        message: match taken_by {
2692                            NameTakenBy::Type => format!("the type `{}` is declared here", name),
2693                            NameTakenBy::Class => format!("`{}` is first declared here", name),
2694                        },
2695                        primary: false,
2696                        file: None,
2697                    });
2698                }
2699                labels
2700            }
2701            Error::ClassNotFound(_, span) => primary(span, "no class of this name is in scope"),
2702            Error::ConstraintNotOnVariable(span) => {
2703                primary(span, "this constrains something other than one type variable")
2704            }
2705            Error::ConstraintVariableUnbound(_, span) => {
2706                primary(span, "not bound by the head")
2707            }
2708            Error::ConstraintVariableNotInType(_, span) => {
2709                primary(span, "not mentioned by the type after `=>`")
2710            }
2711            Error::MemberConstrained(_, span) => primary(span, "a constraint on a member signature"),
2712            Error::MemberUnsafe(_, span) => primary(span, "marked `unsafe` here"),
2713            Error::MemberMissesClassVariable(_, _, variable, span) => primary(
2714                span,
2715                &format!("this signature does not mention `{}`", variable),
2716            ),
2717            Error::MemberDeclaredTwice(name, span, first) => {
2718                let mut labels = primary(span, &format!("`{}` is declared a second time here", name));
2719                labels.extend(secondary(first, format!("`{}` is first declared here", name)));
2720                labels
2721            }
2722            Error::MemberNameTaken(name, _, _, span, other) => {
2723                let mut labels = primary(span, &format!("the member `{}` is declared here", name));
2724                labels.extend(secondary(other, format!("`{}` is also declared here", name)));
2725                labels
2726            }
2727            Error::MemberExposedAlone(_, class, span) => primary(
2728                span,
2729                &format!("expose `{}` to expose this member", class),
2730            ),
2731            Error::ClassExposedWithConstructors(_, span) => {
2732                primary(span, "a class has no constructors")
2733            }
2734            Error::InvalidInstanceHead(problem, span) => primary(
2735                span,
2736                match problem {
2737                    InstanceHeadProblem::NotAClass => "not a class applied to a type",
2738                    InstanceHeadProblem::ClassApplied(_) => "a class applied to other than one type",
2739                    InstanceHeadProblem::Variable(_) => "a type variable, where a type belongs",
2740                    InstanceHeadProblem::Function => "a function type",
2741                    InstanceHeadProblem::Record => "a record type",
2742                    InstanceHeadProblem::ArgumentNotVariable => "not a type variable",
2743                    InstanceHeadProblem::RepeatedVariable(_) => "already bound in this head",
2744                },
2745            ),
2746            Error::InstanceBindingNotMember(_, class, span) => {
2747                primary(span, &format!("not a member of `{}`", class))
2748            }
2749            Error::InstanceMemberMissing(name, _, span) => {
2750                primary(span, &format!("this instance has no definition of `{}`", name))
2751            }
2752            Error::InstanceMemberBoundTwice(name, span, first) => {
2753                let mut labels = primary(span, &format!("`{}` is defined a second time here", name));
2754                labels.extend(secondary(first, format!("`{}` is first defined here", name)));
2755                labels
2756            }
2757            Error::OrphanInstance(instance, span) => primary(
2758                span,
2759                &match instance.head.module() {
2760                    Some(head_module) => format!(
2761                        "declare this instance in `{}` or in `{}`",
2762                        instance.class.module_name(),
2763                        head_module.name()
2764                    ),
2765                    None => format!(
2766                        "declare this instance in `{}`",
2767                        instance.class.module_name()
2768                    ),
2769                },
2770            ),
2771            Error::DuplicateInstance(_, span, first) => {
2772                let mut labels = primary(span, "declared a second time here");
2773                labels.extend(first.label("first declared here".to_owned()));
2774                labels
2775            }
2776            Error::MissingSuperclassInstance(instance, superclass, span) => primary(
2777                span,
2778                &format!(
2779                    "no instance of `{}` for {} is in scope",
2780                    superclass.unqualified_name(),
2781                    instance.head.describe()
2782                ),
2783            ),
2784            Error::DerivationForNonMember(member, class, span) => {
2785                primary(span, &format!("`{}` is not a member of `{}`", member, class))
2786            }
2787            Error::DerivationRepeated(member, span, first) => {
2788                let mut labels = primary(span, &format!("`{}` is derived a second time here", member));
2789                labels.extend(secondary(first, format!("`{}` is first derived here", member)));
2790                labels
2791            }
2792            Error::DerivationSignature(_, problem, span, signature) => {
2793                let mut labels = primary(
2794                    span,
2795                    match problem {
2796                        DerivationSignatureProblem::NoClassValue => "no value to walk",
2797                        DerivationSignatureProblem::ResultMentionsClassVariable => {
2798                            "a derivation cannot build a value of the class's type"
2799                        }
2800                        DerivationSignatureProblem::Shape => "not a shape a derivation walks",
2801                    },
2802                );
2803                labels.extend(secondary(signature, "the signature of the member".to_owned()));
2804                labels
2805            }
2806            Error::DerivationBindingMissing(binding, _, span) => {
2807                primary(span, &format!("this derivation has no `{}`", binding))
2808            }
2809            Error::DerivationBindingUnexpected(binding, _, _, span) => {
2810                primary(span, &format!("`{}` is not taken here", binding))
2811            }
2812            Error::DerivationBindingRepeated(binding, _, span, first) => {
2813                let mut labels = primary(span, &format!("`{}` is defined a second time here", binding));
2814                labels.extend(secondary(first, format!("`{}` is first defined here", binding)));
2815                labels
2816            }
2817            Error::DerivationBindingTakesTooMany(_, _, most, span) => primary(
2818                span,
2819                &format!("more than the {} the walk supplies", parameter_count(*most)),
2820            ),
2821            Error::DerivationIncomplete(_, left_out, span) => primary(
2822                span,
2823                &format!("no derivation for {}", name_list(left_out)),
2824            ),
2825            Error::DerivedInstanceNotDerivable(class, span) => primary(
2826                span,
2827                &format!("`{}` does not say how it is derived", class),
2828            ),
2829            Error::DerivedInstanceNoShape(_, span) => primary(span, "nothing to walk"),
2830            Error::DerivedInstanceContextTooNarrow(gap, context, derived) => {
2831                let mut labels = primary(
2832                    context,
2833                    &format!("this context does not provide `{}`", gap.missing),
2834                );
2835                labels.extend(secondary(
2836                    derived,
2837                    format!("the derivation needs `{}`", gap.missing),
2838                ));
2839                labels
2840            }
2841            Error::DerivedInstanceRequires(requirement, span) => {
2842                let mut labels = primary(
2843                    span,
2844                    &format!("this instance needs `{}` of `{}`", requirement.class, requirement.missing),
2845                );
2846                labels.extend(
2847                    requirement
2848                        .declared
2849                        .label("the type is declared here".to_owned()),
2850                );
2851                labels
2852            }
2853            Error::TypeArityMismatch(name, declared, written, span) => primary(
2854                span,
2855                &format!(
2856                    "`{}` takes {}, this application has {}",
2857                    name,
2858                    type_argument_count(*declared),
2859                    type_argument_count(*written)
2860                ),
2861            ),
2862            Error::TypeNotFound(_, span) => primary(span, "no type of this name is in scope"),
2863            Error::InvalidVariant(kind, span) => primary(
2864                span,
2865                match kind {
2866                    InvalidVariantKind::LowercaseName(_) => "this begins with a lowercase letter",
2867                    InvalidVariantKind::Tuple => "a tuple type, written where a variant belongs",
2868                    InvalidVariantKind::Unit => "the unit type, written where a variant belongs",
2869                    InvalidVariantKind::Arrow => "a function type, written where a variant belongs",
2870                    InvalidVariantKind::Record => "a record type, written where a variant belongs",
2871                },
2872            ),
2873            Error::InvalidScalarDeclaration(name, span) => primary(
2874                span,
2875                &format!(
2876                    "an opaque scalar's body must be exactly `{}`, with no other variant and no arguments",
2877                    name.unqualified_name()
2878                ),
2879            ),
2880            Error::InvalidConstraint(kind, span) => primary(
2881                span,
2882                match kind {
2883                    InvalidConstraintKind::Variable(_) => {
2884                        "a type variable, written where a constraint belongs"
2885                    }
2886                    InvalidConstraintKind::Unapplied(_) => {
2887                        "a name with no argument, written where a constraint belongs"
2888                    }
2889                    InvalidConstraintKind::Arrow => {
2890                        "a function type, written where a constraint belongs"
2891                    }
2892                    InvalidConstraintKind::Tuple => "a tuple, written where a constraint belongs",
2893                    InvalidConstraintKind::Unit => {
2894                        "the unit type, written where a constraint belongs"
2895                    }
2896                    InvalidConstraintKind::Record => {
2897                        "a record type, written where a constraint belongs"
2898                    }
2899                },
2900            ),
2901            Error::RepeatedLabel(label, _, repeat, first) => {
2902                let mut labels = primary(repeat, &format!("`{}` is given a second time here", label));
2903                if let Some(span) = first.span() {
2904                    labels.push(SpanLabel {
2905                        span,
2906                        message: format!("`{}` is first given here", label),
2907                        primary: false,
2908                        file: None,
2909                    });
2910                }
2911                labels
2912            }
2913            Error::InfixDeclared(_, span) => primary(span, "declared here"),
2914            Error::TypeDeclared(_, span) => primary(span, "declared here"),
2915            Error::ClassDeclared(span) => primary(span, "declared here"),
2916            Error::InstanceDeclared(span) => primary(span, "declared here"),
2917            Error::NoTypeInBinding(_, span) => primary(span, "declared here"),
2918            Error::UnsafeOutsideFacade(_, span) => primary(span, "marked `unsafe` here"),
2919            Error::FacadeTypeNotAdmitted(_, kind, span) => primary(
2920                span,
2921                match kind {
2922                    FacadeRejectedKind::Variable => "this signature names a type variable",
2923                    FacadeRejectedKind::Function => "this signature names a function type",
2924                },
2925            ),
2926            Error::FacadeResultNotEffect(_, span) => {
2927                primary(span, "this signature must return `Task (Result Failure a)`")
2928            }
2929            Error::FacadeTaskMisplaced(_, span) => primary(
2930                span,
2931                "this signature names `Task` outside the one position it may occupy",
2932            ),
2933            Error::FacadeConstrained(_, span) => primary(span, "a constraint on a facade signature"),
2934            Error::SelfDependency(members) => members
2935                .iter()
2936                .enumerate()
2937                .filter_map(|(i, member)| {
2938                    let name = &member.name;
2939                    let message = if members.len() == 1 {
2940                        format!("`{}` refers to its own value here", name)
2941                    } else if i == 0 {
2942                        format!(
2943                            "`{}` depends on itself through the declarations it mentions",
2944                            name
2945                        )
2946                    } else if member.function {
2947                        format!("the function `{}` is also part of the cycle", name)
2948                    } else {
2949                        format!("`{}` is also part of the cycle", name)
2950                    };
2951
2952                    member.span.span().map(|s| SpanLabel {
2953                        span: s,
2954                        message,
2955                        primary: i == 0,
2956                        file: None,
2957                    })
2958                })
2959                .collect(),
2960            // A group has no position of its own; the errors it swallowed do.
2961            Error::EnvironmentErrors(errors) => errors.iter().flat_map(|e| e.labels()).collect(),
2962            Error::Many(errors) => errors.iter().flat_map(|e| e.labels()).collect(),
2963            _ => Vec::new(),
2964        }
2965    }
2966
2967    fn notes(&self) -> Vec<String> {
2968        match self {
2969            Error::UnsafeOutsideFacade(..) => vec![
2970                "`unsafe` asserts that the companion behind a facade signature is a function of its arguments and that it returns"
2971                    .to_owned(),
2972            ],
2973            Error::FacadeTypeNotAdmitted(..) => vec![
2974                "a facade signature may only name a type whose values a target can decide from the value alone, which admits the primitives, tuples, records and union types applied to admitted types"
2975                    .to_owned(),
2976            ],
2977            Error::InvalidConstraint(..) => vec![
2978                "a constraint is a class name followed by the type it constrains, as in `Comparable a`, and several are written in parentheses separated by commas, as in `(Comparable k, Eq v)`"
2979                    .to_owned(),
2980            ],
2981            Error::FacadeResultNotEffect(..) => vec![
2982                "a facade declares an effect unless its signature is marked `unsafe`, and an effectful facade's result type must be exactly `Task (Result Failure a)` — any other result type needs `unsafe` to write"
2983                    .to_owned(),
2984            ],
2985            Error::FacadeTaskMisplaced(..) => vec![
2986                "`Task` may appear only as the whole of an unmarked facade's result type — not as an argument, and not nested inside another type"
2987                    .to_owned(),
2988            ],
2989            Error::FacadeConstrained(..) => vec![
2990                "a facade signature names the types the code behind it really handles, so the constraint belongs on an ordinary function that calls the facade at those types"
2991                    .to_owned(),
2992            ],
2993            Error::InvalidScalarDeclaration(..) => vec![
2994                "nothing in the language constructs or inspects a value of an opaque scalar, so its declaration exists to be read rather than built from"
2995                    .to_owned(),
2996            ],
2997            Error::OrphanInstance(..) => vec![
2998                "where neither the class nor the type is declared in this module, a type of this module's own that wraps the one wanted can be given the instance"
2999                    .to_owned(),
3000            ],
3001            Error::AmbiguousVariables(_, candidates, _)
3002            | Error::AmbiguousVariants(_, candidates, _) => vec![ambiguous_note(candidates)],
3003            // A group renders as a summary, so every message it swallowed becomes a
3004            // note. A group of one is rendered by its own message and adds nothing.
3005            Error::EnvironmentErrors(errors) => match errors.as_slice() {
3006                [only] => only.notes(),
3007                many => many.iter().flat_map(|e| e.message_and_notes()).collect(),
3008            },
3009            Error::Many(errors) => match errors.as_slice() {
3010                [only] => only.notes(),
3011                many => many.iter().flat_map(|e| e.message_and_notes()).collect(),
3012            },
3013            _ => Vec::new(),
3014        }
3015    }
3016}
3017
3018/// A "did you mean `X`?" suffix for a label message, when a suggestion was
3019/// found — empty otherwise, so callers can always append the result without
3020/// checking `is_some()` first (`ERR-7`). Mirrors the identically-named helper
3021/// in `environment.rs`; kept separate rather than shared because the two
3022/// modules' `EnvError`/`Error` types are unrelated and neither should reach
3023/// into the other for a two-line formatter.
3024fn suggestion_suffix(suggestion: &Option<Name>) -> String {
3025    match suggestion {
3026        Some(name) => format!(" — did you mean `{}`?", name),
3027        None => String::new(),
3028    }
3029}
3030
3031/// The `it is exposed by: …` note shared by `Error::AmbiguousVariables` and
3032/// `Error::AmbiguousVariants` — one clause for the contributors the module wrote
3033/// an `import` for, one for those supplied by [the default import
3034/// list](../../docs/spec/modules.md#the-default-imports) because it wrote
3035/// none. Naming the latter as implicit is what removes the surprise a module can
3036/// otherwise get from colliding with an import it never wrote (`SPEC-32`).
3037///
3038/// Every candidate this ever runs over comes from `ValueType::Foreigns`, so
3039/// `written`/`implicit` are never both empty in practice — `Foreigns` has at
3040/// least two entries and each is one or the other — but the match is written to
3041/// say something sensible even if that stopped holding.
3042fn ambiguous_note(candidates: &[(ModuleName, Option<super::SourceSpan>, ImportOrigin)]) -> String {
3043    let name_of =
3044        |(m, _, _): &(ModuleName, Option<super::SourceSpan>, ImportOrigin)| m.name().to_string();
3045    let written: Vec<String> = candidates
3046        .iter()
3047        .filter(|(_, _, origin)| *origin == ImportOrigin::Written)
3048        .map(name_of)
3049        .collect();
3050    let implicit: Vec<String> = candidates
3051        .iter()
3052        .filter(|(_, _, origin)| *origin == ImportOrigin::Default)
3053        .map(name_of)
3054        .collect();
3055
3056    match (written.is_empty(), implicit.is_empty()) {
3057        (false, true) => format!("it is exposed by: {}", written.join(", ")),
3058        (true, false) => format!("it is exposed implicitly by: {}", implicit.join(", ")),
3059        (true, true) => "it is exposed by nothing this module can see".to_owned(),
3060        (false, false) => format!(
3061            "it is exposed by: {}, and implicitly by {}",
3062            written.join(", "),
3063            implicit.join(", ")
3064        ),
3065    }
3066}
3067
3068/// "1 type argument" or "N type arguments" — the two counts an
3069/// `Error::TypeArityMismatch` message quotes.
3070fn type_argument_count(n: usize) -> String {
3071    if n == 1 {
3072        "1 type argument".to_owned()
3073    } else {
3074        format!("{} type arguments", n)
3075    }
3076}
3077
3078/// "no parameters", "1 parameter" or "N parameters": what a derivation's binding may take.
3079fn parameter_count(n: usize) -> String {
3080    match n {
3081        0 => "no parameters".to_owned(),
3082        1 => "1 parameter".to_owned(),
3083        n => format!("{} parameters", n),
3084    }
3085}
3086
3087/// The names of `names`, each in backticks, joined as a sentence does: `a`, `b` and `c`.
3088fn name_list(names: &[Name]) -> String {
3089    let quoted: Vec<String> = names.iter().map(|name| format!("`{}`", name)).collect();
3090
3091    match quoted.split_last() {
3092        None => String::new(),
3093        Some((only, [])) => only.clone(),
3094        Some((last, rest)) => format!("{} and {}", rest.join(", "), last),
3095    }
3096}
3097
3098/// How a name is exposed, said in the words the source uses for it.
3099fn export_type_noun(tpe: &ExportType) -> &'static str {
3100    match tpe {
3101        ExportType::Value => "value",
3102        ExportType::Infix => "infix operator",
3103        ExportType::UnionPublic | ExportType::UnionPrivate => "type",
3104        ExportType::Class => "class",
3105    }
3106}
3107
3108impl From<Vec<EnvError>> for Error {
3109    fn from(errors: Vec<EnvError>) -> Self {
3110        Error::EnvironmentErrors(errors)
3111    }
3112}
3113
3114impl From<Vec<Error>> for Error {
3115    fn from(errors: Vec<Error>) -> Self {
3116        Error::Many(errors)
3117    }
3118}
3119
3120/// Every piece of a facade signature [`check_facade_admitted_type`] walks: its
3121/// parameters and its result, the top-level `Arrow`s separating them stripped
3122/// away first. A facade is itself a function, so those are the one place an
3123/// arrow is admitted — a parameter or a result that is itself a function type
3124/// is what [`check_facade_admitted_type`] then rejects. A facade constant has
3125/// no top-level arrow to strip, so it is returned whole, as its own one piece.
3126fn facade_signature_pieces(tpe: &Type) -> Vec<&Type> {
3127    match tpe {
3128        Type::Arrow(param, rest) => {
3129            let mut pieces = vec![param.as_ref()];
3130            pieces.extend(facade_signature_pieces(rest));
3131            pieces
3132        }
3133        _ => vec![tpe],
3134    }
3135}
3136
3137/// Whether `tpe` — one piece of a facade signature, as
3138/// [`facade_signature_pieces`] cuts it up — is one of [the admitted
3139/// types](../../docs/spec/interop.md#which-types-may-cross-the-boundary).
3140///
3141/// A bare `Type::Variable` or a `Type::Arrow` anywhere inside `tpe` is
3142/// rejected, the latter regardless of depth — a function type is inadmissible
3143/// wherever it is found, not only at the top of the signature.
3144/// `Type::Type`, `Type::Tuple` and `Type::Record` recurse into their own arguments or
3145/// fields, which may still hide either form. `Type::Unit` is admitted: it has one
3146/// value, and the table gives it a predicate like any other admitted type.
3147fn check_facade_admitted_type(tpe: &Type) -> Result<(), FacadeRejectedKind> {
3148    match tpe {
3149        Type::Variable(_) => Err(FacadeRejectedKind::Variable),
3150        Type::Arrow(_, _) => Err(FacadeRejectedKind::Function),
3151        Type::Type(_, args) => args.iter().try_for_each(check_facade_admitted_type),
3152        Type::Tuple(tuple) => tuple.iter().try_for_each(check_facade_admitted_type),
3153        Type::Record(fields) => fields.values().try_for_each(check_facade_admitted_type),
3154        Type::Unit => Ok(()),
3155    }
3156}
3157
3158/// Whether `name` is the declaration `module` of `zelkova-core` writes `item`
3159/// as — `is_core_declaration(name, "Task", "Failure")` for `Task.Failure`.
3160///
3161/// All three parts have to match, the same way [`scalars::Scalar::declares`]
3162/// recognises a scalar: a module named `Task` can only belong to
3163/// `zelkova-core` ([`default_imports`](super::default_imports)'s doc comment
3164/// says why), so this is what keeps a package's own `Task` module — were one
3165/// ever allowed — or a differently-named module's own `Task` type from being
3166/// misread as the one [`Error::FacadeResultNotEffect`] and
3167/// [`Error::FacadeTaskMisplaced`] care about.
3168fn is_core_declaration(name: &QualName, module: &str, item: &str) -> bool {
3169    name.package().as_str() == CORE_PACKAGE
3170        && name.module_name().as_str() == module
3171        && name.unqualified_name().as_str() == item
3172}
3173
3174/// Whether `name` is `Task.Task`'s declaration.
3175fn is_task_declaration(name: &QualName) -> bool {
3176    is_core_declaration(name, "Task", "Task")
3177}
3178
3179/// Whether `name` is `Result.Result`'s declaration.
3180fn is_result_declaration(name: &QualName) -> bool {
3181    is_core_declaration(name, "Result", "Result")
3182}
3183
3184/// Whether `name` is `Task.Failure`'s declaration.
3185fn is_failure_declaration(name: &QualName) -> bool {
3186    is_core_declaration(name, "Task", "Failure")
3187}
3188
3189/// Whether `Task` — recognised by [`is_task_declaration`], never by spelling —
3190/// appears anywhere inside `tpe`, at the top or nested inside a tuple, a record's
3191/// fields or another type's arguments.
3192///
3193/// What [`Error::FacadeTaskMisplaced`] is raised from: `Task` may appear only
3194/// as the whole of an unmarked facade's result
3195/// (`docs/spec/interop.md#an-effectful-facade`), so every other piece of a
3196/// facade signature, and the payload inside an accepted `Task (Result Failure
3197/// a)` result, is walked with this rather than left to
3198/// [`check_facade_admitted_type`], which does not know `Task` from any other
3199/// union.
3200fn contains_task(tpe: &Type) -> bool {
3201    match tpe {
3202        Type::Type(name, args) => is_task_declaration(name) || args.iter().any(contains_task),
3203        Type::Tuple(tuple) => tuple.iter().any(contains_task),
3204        Type::Record(fields) => fields.values().any(contains_task),
3205        Type::Arrow(param, rest) => contains_task(param) || contains_task(rest),
3206        Type::Variable(_) | Type::Unit => false,
3207    }
3208}
3209
3210/// Whether `tpe`'s own outermost constructor is `Task` — true of `Task Int`
3211/// and of `Task (Result Failure a)` alike, and false of `Maybe (Task Int)`,
3212/// where `Task` is present but not in that position.
3213///
3214/// [`effectful_result_payload`] tells the two admitted shapes apart; this is
3215/// what lets the caller tell "the right shape with the wrong contents" apart
3216/// from "`Task` in a position that was never going to be it", which is what
3217/// distinguishes [`Error::FacadeResultNotEffect`] from
3218/// [`Error::FacadeTaskMisplaced`].
3219fn is_task_applied(tpe: &Type) -> bool {
3220    matches!(tpe, Type::Type(name, _) if is_task_declaration(name))
3221}
3222
3223/// The payload `a` of `tpe`, when `tpe` is exactly the shape an unmarked
3224/// facade's result must be — `Task (Result Failure a)`, `Task`, `Result` and
3225/// `Failure` each recognised by the qualified name of their declaration and
3226/// never by spelling. `None` for any other shape, `Task Int` and
3227/// `Maybe (Task Int)` included — those are [`Error::FacadeResultNotEffect`],
3228/// not this function's business to name.
3229pub fn effectful_result_payload(tpe: &Type) -> Option<&Type> {
3230    let Type::Type(task, task_args) = tpe else {
3231        return None;
3232    };
3233    if !is_task_declaration(task) {
3234        return None;
3235    }
3236    let [result_tpe] = task_args.as_slice() else {
3237        return None;
3238    };
3239    let Type::Type(result, result_args) = result_tpe else {
3240        return None;
3241    };
3242    if !is_result_declaration(result) {
3243        return None;
3244    }
3245    let [failure_tpe, payload] = result_args.as_slice() else {
3246        return None;
3247    };
3248    let Type::Type(failure, failure_args) = failure_tpe else {
3249        return None;
3250    };
3251    if !is_failure_declaration(failure) || !failure_args.is_empty() {
3252        return None;
3253    }
3254    Some(payload)
3255}
3256
3257/// Hold a facade signature `function`, whose type canonicalized to `tpe`, to what a
3258/// facade may declare: every piece one of the admitted types, `Task` nowhere but the
3259/// whole of an unmarked signature's result, and that result exactly
3260/// `Task (Result Failure a)` unless the signature is `unsafe`.
3261///
3262/// The first rule a signature breaks is its error. One bad signature does not hide the
3263/// next: the caller records this one as broken and goes on to the next.
3264fn check_facade_signature(function: &parser::Function, tpe: &Type) -> Result<(), Error> {
3265    // Every parameter and the result — the arrows a facade's own
3266    // parameter list contributes stripped first, since a facade is
3267    // itself a function and that is the one place an arrow is
3268    // admitted — must be one of the admitted types
3269    // (`docs/spec/interop.md#which-types-may-cross-the-boundary`).
3270    // Walked once and reused below for the `Task`-placement check.
3271    let pieces = facade_signature_pieces(tpe);
3272    if let Some(kind) = pieces
3273        .iter()
3274        .copied()
3275        .find_map(|piece| check_facade_admitted_type(piece).err())
3276    {
3277        return Err(Error::FacadeTypeNotAdmitted(
3278            function.name.clone(),
3279            kind,
3280            function.annotation_span,
3281        ));
3282    }
3283
3284    // `Task` is confined to the whole of an unmarked facade's result
3285    // (`docs/spec/interop.md#an-effectful-facade`), so a parameter
3286    // piece may never hold one, whether or not the signature is
3287    // `unsafe`. Reached only once the loop above admits every piece,
3288    // so nothing here still hides a bare type variable or function
3289    // type for `contains_task` to misread.
3290    if let Some((&result, parameters)) = pieces.split_last() {
3291        if parameters.iter().copied().any(contains_task) {
3292            return Err(Error::FacadeTaskMisplaced(
3293                function.name.clone(),
3294                function.annotation_span,
3295            ));
3296        }
3297
3298        // The result is held to the required effect shape unless the
3299        // signature says `unsafe` (`DEC-12` decision 1 and 7): an
3300        // unmarked facade's result must be exactly
3301        // `Task (Result Failure a)`, and `unsafe` is what removes that
3302        // requirement rather than any shape `check_facade_admitted_type`
3303        // already accepted. `Task` still may not appear anywhere else —
3304        // nested in the payload `a` above, nested under some other type
3305        // (`Maybe (Task Int)`), or anywhere at all in an `unsafe`
3306        // facade's result, which gets no exemption from this.
3307        //
3308        // `is_task_applied(result)` tells "the right shape with the
3309        // wrong contents" (`Task Int`) apart from "`Task` in a position
3310        // that was never going to be it" (`Maybe (Task Int)`), which is
3311        // what keeps the two error variants pointed at what each is
3312        // actually about.
3313        if function.marked_unsafe {
3314            if contains_task(result) {
3315                return Err(Error::FacadeTaskMisplaced(
3316                    function.name.clone(),
3317                    function.annotation_span,
3318                ));
3319            }
3320        } else if is_task_applied(result) {
3321            match effectful_result_payload(result) {
3322                Some(payload) if contains_task(payload) => {
3323                    return Err(Error::FacadeTaskMisplaced(
3324                        function.name.clone(),
3325                        function.annotation_span,
3326                    ));
3327                }
3328                Some(_) => {}
3329                None => {
3330                    return Err(Error::FacadeResultNotEffect(
3331                        function.name.clone(),
3332                        function.annotation_span,
3333                    ))
3334                }
3335            }
3336        } else if contains_task(result) {
3337            return Err(Error::FacadeTaskMisplaced(
3338                function.name.clone(),
3339                function.annotation_span,
3340            ));
3341        } else {
3342            return Err(Error::FacadeResultNotEffect(
3343                function.name.clone(),
3344                function.annotation_span,
3345            ));
3346        }
3347    }
3348
3349    Ok(())
3350}
3351
3352/// Check that every element of `context` — what an annotation wrote in front of
3353/// `=>`, already split into a list by the parser — is shaped like a constraint,
3354/// and hand back each constraint's class name and arguments.
3355///
3356/// A constraint here is an uppercase name applied to one or more arguments.
3357/// Nothing is resolved here: whether the name is a class, and whether its arguments
3358/// are types in scope, is not checked. A class head's, an instance's and an
3359/// annotation's constraints are resolved afterwards, by `classes::constraints`; a
3360/// facade signature's are not resolved at all. The list may be of any length. Every
3361/// malformed element is reported, each at its own span.
3362fn validate_context(
3363    context: &parser::Context,
3364) -> Result<Vec<(&Name, &[parser::Type])>, Vec<Error>> {
3365    collect_accumulate(context.constraints.iter().map(|constraint| {
3366        let kind = match &constraint.kind {
3367            parser::TypeKind::Unqualified(class, args) if !args.is_empty() => {
3368                return Ok((class, args.as_slice()));
3369            }
3370            parser::TypeKind::Unqualified(name, _) => {
3371                InvalidConstraintKind::Unapplied(name.clone())
3372            }
3373            parser::TypeKind::Variable(name) => InvalidConstraintKind::Variable(name.clone()),
3374            parser::TypeKind::Arrow(..) => InvalidConstraintKind::Arrow,
3375            parser::TypeKind::Tuple(..) => InvalidConstraintKind::Tuple,
3376            parser::TypeKind::Unit => InvalidConstraintKind::Unit,
3377            parser::TypeKind::Record(..) => InvalidConstraintKind::Record,
3378        };
3379
3380        Err(Error::InvalidConstraint(kind, constraint.span))
3381    }))
3382}
3383
3384/// Transform a given `parser::Module` into a `canonical::Module`, or into the errors
3385/// that kept it from being one.
3386///
3387/// [`canonicalize_recovering`], reduced to all-or-nothing: a module that came back with
3388/// errors is `Err` with all of them.
3389pub fn canonicalize(
3390    package: &PackageName,
3391    interfaces: &HashMap<Name, Interface>,
3392    source: &parser::Module,
3393) -> Result<Module, Vec<Error>> {
3394    let Canonicalized { module, errors } = canonicalize_recovering(package, interfaces, source);
3395
3396    if errors.is_empty() {
3397        Ok(module)
3398    } else {
3399        Err(errors)
3400    }
3401}
3402
3403/// Transform a given `parser::Module` into a `canonical::Module`, and hand it back
3404/// beside every error found on the way.
3405///
3406/// There is always a module. An import that does not resolve is reported as one
3407/// [`Error::EnvironmentErrors`] and costs the module that import and nothing else. A
3408/// declaration that does not canonicalize costs the module that declaration and nothing
3409/// else. A value declaration is recorded in [`Module::broken`], with its annotation when
3410/// that canonicalized; a `type`, `infix`, `class` or `instance` declaration is left out of
3411/// [`Module::types`], [`Module::infixes`], [`Module::classes`] or [`Module::instances`]. An
3412/// `exposing` entry that does not resolve is left out of [`Module::exports`].
3413///
3414/// # Declarations that failed to parse
3415///
3416/// `source` may be a module that parsed only in part ([`parser::Module::failed`]), and
3417/// each declaration chunk that failed has already been reported as a syntax error. A chunk
3418/// that names a value puts that name in scope, so a reference to it resolves, and the
3419/// value is recorded in [`Module::broken`] with no error of its own: its annotation, when
3420/// one parsed, is read and checked as any other's, and nothing else of it is. A chunk that
3421/// names nothing makes the scope incomplete before the first sub-pass runs ([`DEC-23`
3422/// decision
3423/// 4](../../../docs/decisions/dec-23.md#4--one-name-is-read-off-a-failed-chunk-a-values)).
3424///
3425/// # Incomplete scopes
3426///
3427/// A scope is [incomplete](Module::incomplete) when a name could be missing from it for
3428/// a reason already reported, and a not-found error raised in one is dropped
3429/// ([`DEC-23` decision
3430/// 3](../../../docs/decisions/dec-23.md#3--an-error-that-restates-a-reported-failure-is-dropped-by-a-flag-on-the-scope)).
3431/// Each sub-pass's errors are filtered by the flag as it stood **before** that sub-pass
3432/// ran: a declaration's own failure is reported, and what it makes incomplete is
3433/// everything after it. A failed `infix` declaration makes the scope incomplete for
3434/// everything after the infixes, a failed `type` declaration for everything after the
3435/// types, a failed `class` declaration for the values, the bindings of the classes and
3436/// the instances, and the `exposing` list, a derivation that failed its checks for the
3437/// instances, and the `exposing` list, and a failed `instance` declaration for the
3438/// `exposing` list. Dropping an error does not make
3439/// its declaration sound. A declaration the dropped error broke is left out all the same;
3440/// one whose only error was a name that did not resolve stays in [`Module::values`] holding
3441/// a hole ([`ExpressionKind::Hole`], [`PatternKind::Hole`]) for it, which no backend emits
3442/// and [`Value::holds_hole`] finds.
3443///
3444/// Whether this module is exempt from the default imports is not this function's
3445/// question to answer: `new_environment` derives it from `package` itself
3446/// ([`PackageName::is_core`]) once `name` is built.
3447pub fn canonicalize_recovering(
3448    package: &PackageName,
3449    interfaces: &HashMap<Name, Interface>,
3450    source: &parser::Module,
3451) -> Canonicalized {
3452    let name = ModuleName {
3453        package: package.clone(),
3454        name: source.name.clone(),
3455    };
3456
3457    let mut errors: Vec<Error> = vec![];
3458    let (mut env, import_errors) = new_environment(&name, interfaces, &source.imports);
3459    if !import_errors.is_empty() {
3460        // Reported whole, and never filtered: this is the failure everything else
3461        // in an incomplete scope restates.
3462        errors.push(import_errors.into());
3463    }
3464
3465    // A declaration that failed to parse has already been reported as a syntax error.
3466    // One that names a value puts the name in scope, so a reference to it resolves, and
3467    // the value is broken below with no error of its own. One that names nothing could
3468    // have declared any name at all, so the scope is incomplete from the first sub-pass
3469    // on ([`DEC-23` decision
3470    // 4](../../../docs/decisions/dec-23.md#4--one-name-is-read-off-a-failed-chunk-a-values)).
3471    let unparsed = unparsed_values(source);
3472    for name in unparsed.keys() {
3473        env.insert_top_level_value(name.clone());
3474    }
3475    if source.failed.iter().any(|failed| failed.declares.is_none()) {
3476        env.set_incomplete();
3477    }
3478
3479    // `unsafe` is a claim about the companion standing behind a facade signature,
3480    // so it has nothing to say on a declaration with a body above it. The grammar
3481    // accepts the word on any annotation — it has no way to know the module's
3482    // header — which leaves this as the only place that can reject one. Reported
3483    // for every marked declaration, then canonicalization carries on, so a module
3484    // with a stray `unsafe` still reports whatever else is wrong with it.
3485    if !source.binding_foreign {
3486        errors.extend(
3487            source
3488                .functions
3489                .iter()
3490                .filter(|f| f.marked_unsafe)
3491                .map(|f| Error::UnsafeOutsideFacade(f.name.clone(), f.annotation_span)),
3492        );
3493    }
3494
3495    // A facade signature's context is checked for its shape and rejected here, and is
3496    // not resolved: a facade takes no constraint, so the classes it names do not matter.
3497    // Every other module's annotation context is resolved with the annotation, in
3498    // `annotation`, and kept on the canonical value beside the type
3499    // (`Value::TypedValue::context`, `Broken::context`), from where `to_interface`
3500    // publishes it. The type checker reads only the type after `=>`.
3501    if source.binding_foreign {
3502        for function in source.functions.iter() {
3503            if let Some(context) = &function.context {
3504                if let Err(malformed) = validate_context(context) {
3505                    errors.extend(malformed);
3506                }
3507
3508                errors.push(Error::FacadeConstrained(
3509                    function.name.clone(),
3510                    context.span,
3511                ));
3512            }
3513        }
3514    }
3515
3516    let (infixes, types, classes, instances, values, mut broken) = if source.binding_foreign {
3517        // A `module foreign` facade runs a parallel canonicalization process as the constraints are a bit different:
3518        // - Only functions without bindings are authorized.
3519        // - Infixes and types are forbidden.
3520        // The idea being to have the facade stand for the companion file shipped beside it.
3521        // Assuming Json types are part of the prelude, this should goes well with the restriction on what types are available for bindings.
3522
3523        // Verify no infix present
3524        if !source.infixes.is_empty() {
3525            let e = source
3526                .infixes
3527                .iter()
3528                .map(|i| Error::InfixDeclared(i.operator.clone(), i.span));
3529            errors.extend(e);
3530        }
3531        // Verify no types present
3532        if !source.types.is_empty() {
3533            let e = source
3534                .types
3535                .iter()
3536                .map(|t| Error::TypeDeclared(t.name.clone(), t.span));
3537            errors.extend(e);
3538        }
3539        // Nor classes and instances: a facade holds signatures only.
3540        errors.extend(
3541            source
3542                .classes
3543                .iter()
3544                .map(|class| Error::ClassDeclared(class.span)),
3545        );
3546        errors.extend(
3547            source
3548                .instances
3549                .iter()
3550                .map(|instance| Error::InstanceDeclared(instance.span)),
3551        );
3552
3553        // Register each binding as a top-level value before resolving any of
3554        // them, the same as the non-`foreign` branch below — otherwise
3555        // `do_exports`'s existence check (`BUG-8`) would reject a facade
3556        // exposing its own declared binding, since nothing would have told
3557        // `env` the binding exists.
3558        for f in source.functions.iter() {
3559            env.insert_top_level_value(f.name.clone());
3560        }
3561
3562        // Iterate on values. A signature that is rejected is recorded as broken, with
3563        // its type when that canonicalized.
3564        let iter = source.functions.iter().map(|function| {
3565            let tpe = function
3566                .tpe
3567                .as_ref()
3568                .map(|tpe| Type::from_parser_type(&env, tpe));
3569
3570            // A declaration a failed chunk names is broken whatever parsed of it, and
3571            // only its annotation, when one parsed, is checked: a missing signature or
3572            // a binding beside it may be the chunk that failed.
3573            if let Some(chunk) = unparsed.get(&function.name) {
3574                return Err(match tpe {
3575                    Some(Ok(tpe)) => {
3576                        let errors = check_facade_signature(function, &tpe).err();
3577                        Rejected::unparsed(
3578                            function,
3579                            Some((tpe, Vec::new())),
3580                            errors.into_iter().collect(),
3581                            *chunk,
3582                        )
3583                    }
3584                    Some(Err(error)) => Rejected::unparsed(function, None, vec![error], *chunk),
3585                    None => Rejected::unparsed(function, None, vec![], *chunk),
3586                });
3587            }
3588
3589            // Make sure there is no binding
3590            if !function.bindings.is_empty() {
3591                // The signature's own error is reported too, as `do_values` does for a
3592                // body beside a failed annotation: the annotation's first, then the
3593                // binding's. A missing signature is that error as well.
3594                // TODO More specific error
3595                let binding = Error::BindingPatternsInvalidLen(function.span);
3596                return Err(match tpe {
3597                    Some(Ok(tpe)) => {
3598                        Rejected::new(function, Some((tpe, Vec::new())), vec![binding])
3599                    }
3600                    Some(Err(error)) => Rejected::new(function, None, vec![error, binding]),
3601                    None => Rejected::new(
3602                        function,
3603                        None,
3604                        vec![
3605                            Error::NoTypeInBinding(function.name.clone(), function.span),
3606                            binding,
3607                        ],
3608                    ),
3609                });
3610            }
3611
3612            // Make sure there is a type
3613            let tpe = match tpe {
3614                Some(Ok(tpe)) => tpe,
3615                Some(Err(error)) => return Err(Rejected::new(function, None, vec![error])),
3616                None => {
3617                    return Err(Rejected::new(
3618                        function,
3619                        None,
3620                        vec![Error::NoTypeInBinding(function.name.clone(), function.span)],
3621                    ))
3622                }
3623            };
3624
3625            match check_facade_signature(function, &tpe) {
3626                Ok(()) => {}
3627                Err(error) => {
3628                    return Err(Rejected::new(
3629                        function,
3630                        Some((tpe, Vec::new())),
3631                        vec![error],
3632                    ))
3633                }
3634            }
3635
3636            let name = function.name.clone();
3637            // TODO Think how it's going to be represented. Currently canonical values assume an expression is present
3638            //      I'd like to not introduce a trait or new struct for binding. Should we fake an expression or create
3639            //      a new type of value ? New type of value will be annoying for regular modules as they aren't present
3640            //      there. Fake expression might be ok as MVP. We have to make sure that binding module are removed from
3641            //      some phase of the compilation pipeline.
3642            let value = Value::TypedValue {
3643                name: name.clone(),
3644                patterns: vec![],
3645                // A `module foreign` facade has no body in the source, so this
3646                // stand-in has nothing to point at (see the TODO above).
3647                body: Expression::bare(ExpressionKind::Unit),
3648                tpe,
3649                // A facade's context is `FacadeConstrained`, reported above.
3650                context: Vec::new(),
3651                marked_unsafe: function.marked_unsafe,
3652                span: function.span,
3653                annotation_span: function.annotation_span,
3654            };
3655
3656            Ok((name, value))
3657        });
3658        let (values, rejected): (HashMap<Name, Value>, Vec<Box<Rejected>>) = collect_partial(iter);
3659        let (broken, rejected_errors) = Rejected::split(rejected);
3660        errors.extend(without_restated(rejected_errors, env.is_incomplete()));
3661
3662        (
3663            HashMap::new(),
3664            HashMap::new(),
3665            HashMap::new(),
3666            Vec::new(),
3667            values,
3668            broken,
3669        )
3670    } else {
3671        // Because we are rewriting infixes in this phase, we must do this check before
3672        // resolving values.
3673        //
3674        // Each sub-pass below has its errors filtered by whether the scope was
3675        // incomplete when the sub-pass *started* (`without_restated`): the failure of a
3676        // declaration is reported, and what it makes incomplete is what comes after it.
3677        // A class member is a top-level value of this module, which is what lets an
3678        // `infix` declaration name one.
3679        let members: Vec<(&Name, &Name, NodeSpan)> = source
3680            .classes
3681            .iter()
3682            .filter_map(|class| match &class.head.kind {
3683                parser::TypeKind::Unqualified(name, _) => Some((name, class)),
3684                _ => None,
3685            })
3686            .flat_map(|(class_name, class)| {
3687                classes::member_names(class).map(move |(member, span)| (member, class_name, span))
3688            })
3689            .collect();
3690
3691        let incomplete = env.is_incomplete();
3692        let (infixes, infix_errors) = do_infixes(
3693            &source.infixes,
3694            &mut env,
3695            &source.functions,
3696            &members,
3697            &unparsed,
3698        );
3699        if !infix_errors.is_empty() {
3700            // The operator the declaration would have named is missing from the scope.
3701            env.set_incomplete();
3702        }
3703        errors.extend(without_restated(infix_errors, incomplete));
3704
3705        // Every `type` declaration of this module is in scope for every one of
3706        // them, its own body included, so all of their names are registered
3707        // before any body is canonicalized. Doing it as `do_types` produced each
3708        // union instead would make a declaration resolvable only from the ones
3709        // written below it, and leave a self-referential declaration —
3710        // `type Never = JustOneMore Never` — naming a type nothing has heard of.
3711        // The name and its arity are all a use site needs; `insert_union_type`
3712        // below fills the constructors in once the bodies are built.
3713        for tpe in source.types.iter() {
3714            env.insert_declared_type(&tpe.name, tpe.type_arguments.clone());
3715        }
3716
3717        let incomplete = env.is_incomplete();
3718        let (types, type_errors) = do_types(&env, &source.types);
3719        if !type_errors.is_empty() {
3720            // The constructors the declaration would have named are missing from the
3721            // scope, and so is the type from the interface.
3722            env.set_incomplete();
3723        }
3724        errors.extend(without_restated(type_errors, incomplete));
3725
3726        for (n, t) in types.iter() {
3727            env.insert_union_type(n.clone(), t.clone());
3728        }
3729
3730        trace!("Environment after do_types: {:#?}", env);
3731
3732        // Every class name is registered before any class is read, so a superclass or an
3733        // instance can name one written further down the file. A class that fails leaves
3734        // its members, and the instances of it, missing from the scope.
3735        let incomplete = env.is_incomplete();
3736        let (declared, mut class_errors) =
3737            classes::declare_classes(&mut env, &source.classes, &source.types);
3738        let mut signatures = Vec::new();
3739        for (index, name, variable) in declared {
3740            let class = &source.classes[index];
3741            match classes::class_signature(&env, class, name, variable) {
3742                Ok(signature) => {
3743                    env.insert_class_signature(name, signature.clone());
3744                    signatures.push((class, name, signature));
3745                }
3746                Err(errors) => class_errors.extend(errors),
3747            }
3748        }
3749        if !class_errors.is_empty() {
3750            env.set_incomplete();
3751        }
3752        errors.extend(without_restated(class_errors, incomplete));
3753        // A member and a value sharing a name leave neither missing from the scope.
3754        errors.extend(member_clashes(&members, &source.functions, &unparsed));
3755
3756        for (member, _, _) in members.iter() {
3757            env.insert_top_level_value((*member).clone());
3758        }
3759
3760        // TODO Should I manage infixes rewrite here too ?
3761        // Yes I should do it here
3762        let incomplete = env.is_incomplete();
3763        let Values {
3764            values,
3765            broken,
3766            errors: value_errors,
3767        } = do_values(&mut env, &source.functions, &unparsed);
3768        errors.extend(without_restated(value_errors, incomplete));
3769
3770        // A derivation's bindings and an instance's are ordinary values, and may name
3771        // any value of the module, so they are read once every value is in scope.
3772        let incomplete = env.is_incomplete();
3773        let mut unresolved = Vec::new();
3774        let mut derivation_errors = Vec::new();
3775        let mut canonical_classes = HashMap::new();
3776        for (class, name, mut signature) in signatures {
3777            let (derivations, errors) =
3778                derivation::class_derivations(&env, class, name, &signature, &mut unresolved);
3779            signature.derivations_rejected = !errors.is_empty();
3780            derivation_errors.extend(errors);
3781            signature.derivations = derivations;
3782            // An instance of the class, in this module, is read against the derivations.
3783            env.insert_class_signature(name, signature.clone());
3784            canonical_classes.insert(name.clone(), Class { signature });
3785        }
3786        // A failed derivation removes no name from the scope, so the scope stays as complete
3787        // as it was. The class carries that its derivations were rejected, which is what
3788        // keeps an instance asking to be derived from restating it.
3789        errors.extend(without_restated(derivation_errors, incomplete));
3790
3791        let incomplete = env.is_incomplete();
3792        let mut binding_errors = Vec::new();
3793        let classes::Instances {
3794            instances,
3795            errors: instance_errors,
3796        } = classes::do_instances(&env, &source.instances, &mut unresolved);
3797        // An instance left out of the module is one an importer's scope will not have, and
3798        // some are left out with no error here: one of a class whose derivations were
3799        // rejected.
3800        if !instance_errors.is_empty() || instances.len() < source.instances.len() {
3801            env.set_incomplete();
3802        }
3803        binding_errors.extend(instance_errors);
3804        binding_errors.extend(unresolved);
3805        errors.extend(without_restated(binding_errors, incomplete));
3806
3807        (infixes, types, canonical_classes, instances, values, broken)
3808    };
3809
3810    // A value only a failed chunk declares has no `parser::Function` for either branch
3811    // to have read, and nothing of it to keep but where it was written.
3812    broken.extend(
3813        unparsed
3814            .iter()
3815            .filter(|(name, _)| !source.functions.iter().any(|f| &f.name == *name))
3816            .map(|(name, chunk)| Broken {
3817                name: name.clone(),
3818                span: *chunk,
3819                tpe: None,
3820                context: Vec::new(),
3821                annotation_span: NodeSpan::none(),
3822            }),
3823    );
3824    broken.sort_by(|left, right| left.name.as_str().cmp(right.name.as_str()));
3825
3826    // A parameterless binding's value has to exist before it can be used, so a
3827    // cycle that holds one — through other bindings or through functions — is an
3828    // error (`docs/spec/evaluation-semantics.md#a-binding-may-not-depend-on-itself`).
3829    // Independent of exports, so this runs regardless of what `do_exports` below
3830    // finds.
3831    if let Err(err) = check_self_dependency(&values) {
3832        errors.extend(err);
3833    }
3834
3835    // We do exports at the end, and verify that all exported value do
3836    // have a reference within the current module
3837    // A declaration that is broken and was written with no annotation is in neither
3838    // `values` nor `Broken::tpe`, so `do_exports` is told of it here: it is as exposed
3839    // and as unannotated as a sound `Value::Value`. A facade is left out: its unannotated
3840    // signature already is `NoTypeInBinding`. So is a declaration a failed chunk names,
3841    // whose annotation may be that chunk.
3842    let unannotated_broken: HashMap<Name, NodeSpan> = source
3843        .functions
3844        .iter()
3845        .filter(|f| {
3846            !source.binding_foreign
3847                && f.tpe.is_none()
3848                && !unparsed.contains_key(&f.name)
3849                && broken.iter().any(|b| b.name == f.name)
3850        })
3851        .map(|f| (f.name.clone(), f.span))
3852        .collect();
3853    let member_classes: HashMap<&Name, &Name> = classes
3854        .iter()
3855        .flat_map(|(class, c)| c.signature.members.iter().map(move |m| (&m.name, class)))
3856        .collect();
3857    let (exports, export_errors) = do_exports(
3858        &source.exposing,
3859        &env,
3860        &values,
3861        &unannotated_broken,
3862        &member_classes,
3863    );
3864    errors.extend(without_restated(export_errors, env.is_incomplete()));
3865
3866    // A declaration written with an annotation that did not canonicalize is recorded
3867    // with no type, and the interface cannot publish it. That is a name missing from
3868    // the interface while this module's own scope is whole, so it is a case the
3869    // environment's flag does not already say. A declaration a failed chunk names and
3870    // that has no type is the other: its annotation may be the chunk that failed.
3871    let annotation_failed = source
3872        .functions
3873        .iter()
3874        .any(|f| f.tpe.is_some() && broken.iter().any(|b| b.name == f.name && b.tpe.is_none()))
3875        || broken
3876            .iter()
3877            .any(|b| b.tpe.is_none() && unparsed.contains_key(&b.name));
3878
3879    Canonicalized {
3880        module: Module {
3881            name,
3882            exports,
3883            exposing_span: source.exposing_span,
3884            infixes,
3885            types,
3886            classes,
3887            instances,
3888            imported_instances: env.imported_instances().to_vec(),
3889            values,
3890            broken,
3891            binding_foreign: source.binding_foreign,
3892            incomplete: env.is_incomplete() || annotation_failed,
3893        },
3894        errors,
3895    }
3896}
3897
3898/// Every value a declaration chunk of `source` that failed to parse names
3899/// ([`parser::Failed::declares`]), with where it was written: the chunk's text, or the
3900/// text of every chunk naming it merged.
3901fn unparsed_values(source: &parser::Module) -> HashMap<Name, NodeSpan> {
3902    let mut unparsed: HashMap<Name, NodeSpan> = HashMap::new();
3903    for failed in &source.failed {
3904        if let Some(name) = &failed.declares {
3905            let chunk = NodeSpan::new(failed.span.start, failed.span.end);
3906            let span = unparsed.entry(name.clone()).or_insert(chunk);
3907            *span = span.merge(chunk);
3908        }
3909    }
3910    unparsed
3911}
3912
3913/// `errors` without the ones that only restate a failure already reported, when the scope
3914/// they were raised in is `incomplete`.
3915///
3916/// An incomplete scope is one where a name could be missing for a reason that has been
3917/// reported ([`Module::incomplete`]), so a name that is not found in it says nothing new:
3918/// `VariableNotFound`, `VariantNotFound`, `TypeNotFound`, `ClassNotFound`,
3919/// `ExportNotFound`, `InfixReferenceInvalidValue` and `MissingSuperclassInstance` are
3920/// dropped, and every other error is kept. An
3921/// [`Error::Many`] is flattened into its members first, so a group holding one of each
3922/// keeps the member that is not a restatement. With `incomplete` false, `errors` comes
3923/// back untouched.
3924///
3925/// `InfixReferenceInvalidValue` is on that list although it is raised in one place only,
3926/// for an `infix` declaration naming a function this module does not declare, and so
3927/// restates nothing today: in an incomplete scope it is deferred, and the failure that
3928/// made the scope incomplete stands in the build. It would restate one if a function that
3929/// failed were ever left out of that function list.
3930///
3931/// `MissingSuperclassInstance` is on it because an instance that failed is published by
3932/// no interface, so a superclass instance its module wrote and could not keep is missing
3933/// from every importer's scope, and the module that wrote it has already said why.
3934///
3935/// Dropping an error does not make its declaration sound. A declaration the error broke
3936/// has already been left out of the module by the caller, and stays left out; one whose
3937/// error was a name that did not resolve keeps the hole standing for it, which no backend
3938/// emits.
3939fn without_restated(errors: Vec<Error>, incomplete: bool) -> Vec<Error> {
3940    if !incomplete {
3941        return errors;
3942    }
3943
3944    fn flatten(error: Error, into: &mut Vec<Error>) {
3945        match error {
3946            Error::Many(members) => members.into_iter().for_each(|member| flatten(member, into)),
3947            error => into.push(error),
3948        }
3949    }
3950
3951    let mut flat = Vec::new();
3952    for error in errors {
3953        flatten(error, &mut flat);
3954    }
3955
3956    flat.retain(|error| {
3957        !matches!(
3958            error,
3959            Error::VariableNotFound(..)
3960                | Error::VariantNotFound(..)
3961                | Error::TypeNotFound(..)
3962                | Error::ClassNotFound(..)
3963                | Error::ExportNotFound(..)
3964                | Error::InfixReferenceInvalidValue(..)
3965                | Error::MissingSuperclassInstance(..)
3966        )
3967    });
3968    flat
3969}
3970
3971/// Whether `value` names no parameter — the kind of binding a cycle
3972/// [`check_self_dependency`] reports must hold, and the only kind
3973/// [`initialisation_order`] schedules. Both `Value` variants carry
3974/// their patterns under a different shape (`Vec<Pattern>` vs. `Vec<(Pattern,
3975/// Type)>`), so this is the one place that reaches past the difference to ask
3976/// how many there are.
3977fn is_parameterless(value: &Value) -> bool {
3978    match value {
3979        Value::Value { patterns, .. } => patterns.is_empty(),
3980        Value::TypedValue { patterns, .. } => patterns.is_empty(),
3981    }
3982}
3983
3984/// Every `VarTopLevel` reference `expr` makes, walking every subexpression a
3985/// body can hold — a reference is a reference wherever it sits, including
3986/// inside a `case` branch or an `if` arm
3987/// (`docs/spec/evaluation-semantics.md#a-binding-may-not-depend-on-itself`).
3988///
3989/// `VarTopLevel` is the only expression kind this needs to look for: it is
3990/// what `Expression::from_parser`'s `Variable` arm produces for a name
3991/// `Environment::find_value` resolves to `ValueType::TopLevel`, which
3992/// `insert_top_level_value` sets only for a declaration of *this* module — a
3993/// local pattern binding resolves to `VarLocal` and an imported name to
3994/// `VarForeign`, neither of which this pass has any business following.
3995fn collect_top_level_refs(expr: &Expression, out: &mut Vec<Name>) {
3996    match &expr.kind {
3997        ExpressionKind::VarTopLevel(qual) => out.push(qual.unqualified_name()),
3998        ExpressionKind::VarLocal(_)
3999        | ExpressionKind::VarKernel(_)
4000        | ExpressionKind::VarForeign(_, _, _)
4001        | ExpressionKind::VarConstructor(_, _)
4002        | ExpressionKind::Char(_)
4003        | ExpressionKind::String(_)
4004        | ExpressionKind::Int(_)
4005        | ExpressionKind::Float(_)
4006        | ExpressionKind::Unit
4007        // A label names no declaration.
4008        | ExpressionKind::Accessor(_, _)
4009        // A name that did not resolve names no declaration of this module.
4010        | ExpressionKind::Hole => {}
4011        ExpressionKind::Access(record, _, _) => collect_top_level_refs(record, out),
4012        ExpressionKind::Apply(a, b) => {
4013            collect_top_level_refs(a, out);
4014            collect_top_level_refs(b, out);
4015        }
4016        ExpressionKind::If(cond, then, els) => {
4017            collect_top_level_refs(cond, out);
4018            collect_top_level_refs(then, out);
4019            collect_top_level_refs(els, out);
4020        }
4021        ExpressionKind::Case(scrutinee, branches) => {
4022            collect_top_level_refs(scrutinee, out);
4023            for branch in branches {
4024                collect_top_level_refs(&branch.expression, out);
4025            }
4026        }
4027        ExpressionKind::Tuple(tuple) => {
4028            for e in tuple.iter() {
4029                collect_top_level_refs(e, out);
4030            }
4031        }
4032        ExpressionKind::Record(fields) => {
4033            for field in fields {
4034                collect_top_level_refs(&field.value, out);
4035            }
4036        }
4037        ExpressionKind::Update(record, fields) => {
4038            collect_top_level_refs(record, out);
4039            for field in fields {
4040                collect_top_level_refs(&field.value, out);
4041            }
4042        }
4043    }
4044}
4045
4046/// The graph *depends on* is read off: one node per top-level declaration of `values`,
4047/// functions included, and an edge from `u` to `v` for every [`collect_top_level_refs`]
4048/// reference `u`'s body makes to `v`. A binding depends on everything it can reach along
4049/// these edges ([evaluation
4050/// semantics](../../docs/spec/evaluation-semantics.md#a-binding-with-no-parameters-is-evaluated-once)):
4051/// initialising a binding runs its body and whatever functions that body calls, and a
4052/// function can only be called by code that names it or was handed it by code that did,
4053/// so what can run while a binding is initialised is contained in what it reaches. The
4054/// relation over-approximates — `a = f` beside `f x = a` mentions `f` without calling it —
4055/// and [`DEC-19`](../../docs/decisions/dec-19.md) is why that is the rule.
4056///
4057/// A reference to an imported name is never an edge: it never canonicalizes to
4058/// `VarTopLevel` in the first place (see [`collect_top_level_refs`]), and a cross-module
4059/// cycle is [`dependencies::ModuleWalker`](super::dependencies::ModuleWalker)'s to report.
4060/// A body that mentions `v` twice gives one edge.
4061///
4062/// Shared by [`check_self_dependency`], which asks which strongly-connected components hold
4063/// a parameterless binding and a cycle, and [`initialisation_order`] (`GEN-7`), which
4064/// orders the components — one edge set read by two passes, rather than two graphs built
4065/// from the same rule.
4066///
4067/// Nodes are added in name-sorted order, not `values`' raw `HashMap` iteration order, so
4068/// node indices — and everything `petgraph` derives from them, such as the order
4069/// `tarjan_scc` returns components in — depend on the names in the source rather than on
4070/// `values`' hash seed.
4071fn dependency_graph(values: &HashMap<Name, Value>) -> DiGraph<(&Name, &Value), ()> {
4072    let mut graph: DiGraph<(&Name, &Value), ()> = DiGraph::new();
4073    let mut nodes: HashMap<&Name, NodeIndex> = HashMap::new();
4074
4075    let mut sorted: Vec<(&Name, &Value)> = values.iter().collect();
4076    sorted.sort_by(|(l, _), (r, _)| l.as_str().cmp(r.as_str()));
4077
4078    for &(name, value) in &sorted {
4079        let idx = graph.add_node((name, value));
4080        nodes.insert(name, idx);
4081    }
4082
4083    for &(name, value) in &sorted {
4084        let Some(&from) = nodes.get(name) else {
4085            continue;
4086        };
4087
4088        let body = match value {
4089            Value::Value { body, .. } | Value::TypedValue { body, .. } => body,
4090        };
4091
4092        let mut refs = Vec::new();
4093        collect_top_level_refs(body, &mut refs);
4094
4095        for referenced in &refs {
4096            if let Some(&to) = nodes.get(referenced) {
4097                graph.update_edge(from, to, ());
4098            }
4099        }
4100    }
4101
4102    graph
4103}
4104
4105/// `LANG-35`: a strict, parameterless binding is evaluated once, before the program runs,
4106/// after everything it depends on — so a binding that depends on itself describes no such
4107/// order, whether the cycle is one binding long (`x = x`) or runs through other bindings
4108/// and functions (`a = f 1` beside `f x = a`).
4109///
4110/// Reports one [`Error::SelfDependency`] per strongly-connected component of
4111/// [`dependency_graph`] that both holds a parameterless binding and is a cycle: two or
4112/// more members, or one member with an edge to itself. `tarjan_scc` puts a single node in
4113/// its own component whether or not it has that edge, which is why the one-member case is
4114/// asked separately. A component of functions only is never reported — a function's value
4115/// exists before its body runs — so `isEven`/`isOdd` and `f n = f n` pass. A binding with
4116/// an edge to itself inside a larger component (`a = (a, b)` beside `b = a`) is reported
4117/// once, with that component.
4118///
4119/// Members are ordered parameterless bindings first, then functions, each group by name,
4120/// so the report does not depend on traversal order and its first member — the one the
4121/// message and the primary label are about — is always a parameterless binding.
4122fn check_self_dependency(values: &HashMap<Name, Value>) -> Result<(), Vec<Error>> {
4123    let graph = dependency_graph(values);
4124
4125    let mut errors = Vec::new();
4126
4127    for component in petgraph::algo::tarjan_scc(&graph) {
4128        let cyclic = match component.as_slice() {
4129            [only] => graph.contains_edge(*only, *only),
4130            _ => true,
4131        };
4132        let holds_binding = component.iter().any(|&idx| is_parameterless(graph[idx].1));
4133
4134        if !(cyclic && holds_binding) {
4135            continue;
4136        }
4137
4138        let mut members: Vec<CycleMember> = component
4139            .iter()
4140            .map(|&idx| {
4141                let (name, value) = graph[idx];
4142                CycleMember {
4143                    name: name.clone(),
4144                    span: value.span(),
4145                    function: !is_parameterless(value),
4146                }
4147            })
4148            .collect();
4149        members.sort_by(|l, r| {
4150            l.function
4151                .cmp(&r.function)
4152                .then_with(|| l.name.as_str().cmp(r.name.as_str()))
4153        });
4154
4155        errors.push(Error::SelfDependency(members));
4156    }
4157
4158    if errors.is_empty() {
4159        Ok(())
4160    } else {
4161        Err(errors)
4162    }
4163}
4164
4165/// `GEN-7`: the order `module`'s parameterless bindings must be initialised in — each
4166/// only after every parameterless binding it depends on, through functions as well as
4167/// directly
4168/// (`docs/spec/evaluation-semantics.md#a-binding-with-no-parameters-is-evaluated-once`).
4169///
4170/// Reads [`dependency_graph`], the graph [`check_self_dependency`] (`LANG-35`) reads, and
4171/// orders its strongly-connected components dependency-first, keeping only the
4172/// parameterless bindings. A plain topological sort of the graph itself would not do: a
4173/// cycle of functions only is legal, and a topological sort refuses any cycle. So the
4174/// components are condensed to one node each, which is acyclic, and that is what is
4175/// sorted. Functions take part in the sort — an edge through one is still an edge — but
4176/// are left out of what comes back.
4177///
4178/// Among components with no path between them, the one whose smallest member name sorts
4179/// first comes first, so the order is fixed by the names in the source: two runs of the
4180/// compiler over one unchanged module produce the same order, and two independent
4181/// constants come back in name order.
4182///
4183/// After `check_self_dependency` accepts a module, every component holding a
4184/// parameterless binding is that binding alone, so each binding has one well-defined
4185/// place. `ir::build`, this function's sole caller, also builds a module canonicalization
4186/// reported errors for, and one of those can be the cycle `check_self_dependency`
4187/// rejected. A component holding several parameterless bindings does not panic — this
4188/// codebase holds `panic!`/`unwrap()`/`expect()` off every non-test path — its bindings
4189/// come back together, in name order. A module with an error is never emitted, so that
4190/// order is never run.
4191///
4192/// A `module foreign` facade has no parameterless declarations to order for this purpose:
4193/// `unsafe pi : Float` names a foreign binding directly, with no Zelkova body to place,
4194/// and is evaluated on whatever schedule the target gives it
4195/// (`docs/spec/interop.md#facade-constants`), so this returns the empty list for one
4196/// without inspecting its (structurally parameterless, but synthetic) values.
4197pub(crate) fn initialisation_order(module: &Module) -> Vec<Name> {
4198    if module.binding_foreign {
4199        return Vec::new();
4200    }
4201
4202    // `make_acyclic` drops the edges inside a component, so the condensation is a DAG.
4203    let condensed = petgraph::algo::condensation(dependency_graph(&module.values), true);
4204
4205    let first_name = |idx: NodeIndex| -> &str {
4206        condensed[idx]
4207            .iter()
4208            .map(|(name, _)| name.as_str())
4209            .min()
4210            .unwrap_or_default()
4211    };
4212
4213    // An edge `u -> v` means `u` depends on `v`, so a component is ready once every edge
4214    // out of it has been satisfied. `condensation(g, true)` calls `update_edge` for every
4215    // original edge between two distinct components, which updates an existing
4216    // component-to-component edge's weight rather than duplicating it, so no parallel
4217    // edges between distinct components ever reach `condensed` — the count below and the
4218    // one edge released per neighbor in the loop are counting the same, already
4219    // deduplicated set.
4220    let mut unsatisfied: Vec<usize> = condensed
4221        .node_indices()
4222        .map(|idx| condensed.edges_directed(idx, Direction::Outgoing).count())
4223        .collect();
4224
4225    let mut ready: BinaryHeap<Reverse<(&str, NodeIndex)>> = condensed
4226        .node_indices()
4227        .filter(|idx| unsatisfied[idx.index()] == 0)
4228        .map(|idx| Reverse((first_name(idx), idx)))
4229        .collect();
4230
4231    let mut order = Vec::new();
4232
4233    while let Some(Reverse((_, idx))) = ready.pop() {
4234        let mut bindings: Vec<&Name> = condensed[idx]
4235            .iter()
4236            .filter(|(_, value)| is_parameterless(value))
4237            .map(|(name, _)| *name)
4238            .collect();
4239        bindings.sort_by(|l, r| l.as_str().cmp(r.as_str()));
4240        order.extend(bindings.into_iter().cloned());
4241
4242        for dependent in condensed.neighbors_directed(idx, Direction::Incoming) {
4243            let count = &mut unsatisfied[dependent.index()];
4244            *count = count.saturating_sub(1);
4245            if *count == 0 {
4246                ready.push(Reverse((first_name(dependent), dependent)));
4247            }
4248        }
4249    }
4250
4251    order
4252}
4253
4254/// What [`do_values`] made of a module's value declarations.
4255struct Values {
4256    /// Every declaration that canonicalized.
4257    values: HashMap<Name, Value>,
4258    /// Every declaration that did not, in declaration order.
4259    broken: Vec<Broken>,
4260    /// Why each of [`broken`](Self::broken) did not, one or two errors per declaration,
4261    /// and every name a declaration of either list could not resolve, in declaration
4262    /// order.
4263    errors: Vec<Error>,
4264}
4265
4266/// Canonicalize every value declaration of a module that is not a facade.
4267///
4268/// A declaration's annotation is canonicalized first and on its own, so that an error
4269/// in the body cannot keep the annotation from being read. A declaration whose
4270/// annotation (when it has one) and body both canonicalize is a [`Value`]. One whose
4271/// annotation or body does not is [`Broken`], carrying its annotation when that
4272/// canonicalized, and every error of the two is reported: the annotation's, then the
4273/// body's. A declaration `unparsed` names — a chunk of it failed to parse — is
4274/// [`Broken`] whatever its body, with its annotation's error alone reported.
4275///
4276/// A name in the body that does not resolve does not stop the body canonicalizing: it
4277/// is a hole ([`ExpressionKind::Hole`], [`PatternKind::Hole`]), and its error is
4278/// reported after the declaration's others, whether the declaration is a [`Value`] or
4279/// [`Broken`].
4280fn do_values(
4281    env: &mut RootEnvironment,
4282    functions: &[parser::Function],
4283    unparsed: &HashMap<Name, NodeSpan>,
4284) -> Values {
4285    // Before resolving expressions, we store the top-level values in the environment.
4286    // We do so first because their expression below could refer to them.
4287    for f in functions.iter() {
4288        env.insert_top_level_value(f.name.clone());
4289    }
4290
4291    let mut values = HashMap::new();
4292    let mut broken = Vec::new();
4293    let mut errors = Vec::new();
4294
4295    for function in functions {
4296        let mut unresolved = Vec::new();
4297        match value_declaration(env, function, unparsed, &mut unresolved) {
4298            Ok(value) => {
4299                values.insert(function.name.clone(), value);
4300            }
4301            Err(rejected) => {
4302                broken.push(rejected.broken);
4303                errors.extend(rejected.errors);
4304            }
4305        }
4306        errors.extend(unresolved);
4307    }
4308
4309    Values {
4310        values,
4311        broken,
4312        errors,
4313    }
4314}
4315
4316/// One value declaration of [`do_values`], or the declaration recorded as broken beside
4317/// the errors that say why. Every name its body could not resolve is pushed onto
4318/// `unresolved`, whichever it is.
4319fn value_declaration(
4320    env: &RootEnvironment,
4321    function: &parser::Function,
4322    unparsed: &HashMap<Name, NodeSpan>,
4323    unresolved: &mut Vec<Error>,
4324) -> Result<Value, Box<Rejected>> {
4325    let annotation = annotation(env, function);
4326
4327    // A declaration a failed chunk names is broken whatever parsed of it. Its body
4328    // is not read: a binding that parsed may be one of several, and a missing one
4329    // may be the chunk that failed, so nothing said about it would be news.
4330    if let Some(chunk) = unparsed.get(&function.name) {
4331        return Err(match annotation {
4332            Annotation::Absent => Rejected::unparsed(function, None, vec![], *chunk),
4333            Annotation::Canonical(tpe, context) => {
4334                Rejected::unparsed(function, Some((tpe, context)), vec![], *chunk)
4335            }
4336            Annotation::Failed(errors) => Rejected::unparsed(function, None, errors, *chunk),
4337        });
4338    }
4339
4340    match (annotation, value_body(env, function, unresolved)) {
4341        (Annotation::Absent, Ok((patterns, body))) => Ok(Value::Value {
4342            name: function.name.clone(),
4343            patterns,
4344            body,
4345            span: function.span,
4346        }),
4347        (Annotation::Canonical(tpe, context), Ok((patterns, body))) => {
4348            let linear = Type::to_linear_types(&tpe);
4349
4350            // Linear is a list of types making the function. Because it includes the return type,
4351            // it will always be bigger than the number of patterns by one.
4352            if !patterns.is_empty() && (linear.len() - 1 != patterns.len()) {
4353                // TODO Better error message
4354                debug!(
4355                    "linear = {:#?}\nbindings = {:#?} (linear.len ({}) != patterns.len ({}))",
4356                    linear,
4357                    function.bindings,
4358                    linear.len(),
4359                    patterns.len()
4360                );
4361                return Err(Rejected::new(
4362                    function,
4363                    Some((tpe, context)),
4364                    vec![Error::BindingPatternsInvalidLen(function.span)],
4365                ));
4366            }
4367
4368            let patterns = patterns.into_iter().zip(linear).collect();
4369
4370            Ok(Value::TypedValue {
4371                name: function.name.clone(),
4372                patterns,
4373                body,
4374                tpe,
4375                context,
4376                // `do_values` only runs for a module that is not a facade,
4377                // and `canonicalize` has already rejected a marked
4378                // annotation there.
4379                marked_unsafe: false,
4380                span: function.span,
4381                annotation_span: function.annotation_span,
4382            })
4383        }
4384        (Annotation::Absent, Err(body_error)) => {
4385            Err(Rejected::new(function, None, vec![body_error]))
4386        }
4387        (Annotation::Canonical(tpe, context), Err(body_error)) => Err(Rejected::new(
4388            function,
4389            Some((tpe, context)),
4390            vec![body_error],
4391        )),
4392        (Annotation::Failed(mut errors), body) => {
4393            errors.extend(body.err());
4394            Err(Rejected::new(function, None, errors))
4395        }
4396    }
4397}
4398
4399/// A value declaration recorded as broken, beside the errors that say why.
4400///
4401/// Boxed where it is the `Err` of a declaration's result, since a [`Broken`] carries a
4402/// whole [`Type`] and the `Ok` side is usually the one taken.
4403struct Rejected {
4404    broken: Broken,
4405    errors: Vec<Error>,
4406}
4407
4408impl Rejected {
4409    /// `function`, recorded as broken with `annotation` as its annotation's type and
4410    /// context, because of `errors`.
4411    fn new(
4412        function: &parser::Function,
4413        annotation: Option<(Type, Vec<Constraint>)>,
4414        errors: Vec<Error>,
4415    ) -> Box<Rejected> {
4416        Box::new(Rejected {
4417            broken: Broken::of(function, annotation),
4418            errors,
4419        })
4420    }
4421
4422    /// `function`, which a declaration chunk that failed to parse also declares, recorded
4423    /// as broken with `annotation` as its annotation's type and context, because of
4424    /// `errors` and of the syntax error already reported. Its span covers the failed
4425    /// chunk, `chunk`, as well as what parsed.
4426    fn unparsed(
4427        function: &parser::Function,
4428        annotation: Option<(Type, Vec<Constraint>)>,
4429        errors: Vec<Error>,
4430        chunk: NodeSpan,
4431    ) -> Box<Rejected> {
4432        let mut rejected = Rejected::new(function, annotation, errors);
4433        rejected.broken.span = rejected.broken.span.merge(chunk);
4434        rejected
4435    }
4436
4437    /// Every declaration of `rejected`, and every error behind them, in the same order.
4438    fn split(rejected: impl IntoIterator<Item = Box<Rejected>>) -> (Vec<Broken>, Vec<Error>) {
4439        let mut broken = Vec::new();
4440        let mut errors = Vec::new();
4441        for rejected in rejected {
4442            broken.push(rejected.broken);
4443            errors.extend(rejected.errors);
4444        }
4445        (broken, errors)
4446    }
4447}
4448
4449/// What a value declaration's annotation canonicalized to, read apart from its body.
4450enum Annotation {
4451    /// The declaration has no annotation.
4452    Absent,
4453    /// The annotation's type, and the constraints of its context, each resolved.
4454    Canonical(Type, Vec<Constraint>),
4455    /// Every error in the annotation: its context's, in the order written, then its
4456    /// type's.
4457    Failed(Vec<Error>),
4458}
4459
4460/// What `function`'s annotation canonicalizes to, read apart from its body.
4461///
4462/// Its context is resolved through the routine a class head's and an instance's go
4463/// through ([`classes::constraints`]), each constraint held to a variable the type after
4464/// `=>` mentions. An annotation with a bad constraint fails as one with a bad type does.
4465fn annotation(env: &RootEnvironment, function: &parser::Function) -> Annotation {
4466    let Some(written) = &function.tpe else {
4467        return Annotation::Absent;
4468    };
4469
4470    let context = classes::constraints(
4471        env,
4472        function.context.as_ref(),
4473        &classes::written_variables(written),
4474        Error::ConstraintVariableNotInType,
4475    );
4476
4477    match (context, Type::from_parser_type(env, written)) {
4478        (Ok(context), Ok(tpe)) => Annotation::Canonical(tpe, context),
4479        (context, tpe) => {
4480            let mut errors = context.err().unwrap_or_default();
4481            errors.extend(tpe.err());
4482            Annotation::Failed(errors)
4483        }
4484    }
4485}
4486
4487/// The parameters and the body of `function`, a value declaration of a module that is
4488/// not a facade, or the first error that kept them from canonicalizing. Every name they
4489/// could not resolve is a hole, with its error pushed onto `unresolved`.
4490fn value_body(
4491    env: &RootEnvironment,
4492    function: &parser::Function,
4493    unresolved: &mut Vec<Error>,
4494) -> Result<(Vec<Pattern>, Expression), Error> {
4495    // TODO Better error message with position of mismatch
4496    let bindings_size = function
4497        .bindings
4498        .iter()
4499        .all(|v| v.patterns.len() == function.bindings[0].patterns.len());
4500
4501    if !bindings_size {
4502        return Err(Error::BindingPatternsInvalidLen(function.span));
4503    }
4504
4505    match function.bindings.len() {
4506        0 => Err(Error::NoBindings(function.span)),
4507        // if one binding, we can convert directly to canonical format
4508        1 => match_body(env, &function.bindings[0], unresolved),
4509        _ => {
4510            // if multiple bindings, we need to create synthetics variables and put all bindings into a case expression
4511            Err(Error::MultipleBindingsUnsupported(
4512                function.name.clone(),
4513                function.span,
4514            ))
4515        }
4516    }
4517}
4518
4519/// The parameters and the body of one binding, its parameters in scope in its body, or
4520/// the first error that kept them from canonicalizing. Every name they could not resolve
4521/// is a hole, with its error pushed onto `unresolved`.
4522fn match_body(
4523    env: &RootEnvironment,
4524    binding: &parser::Match,
4525    unresolved: &mut Vec<Error>,
4526) -> Result<(Vec<Pattern>, Expression), Error> {
4527    let mut scoped = env.new_scope();
4528
4529    let patterns: Vec<Pattern> = binding
4530        .patterns
4531        .iter()
4532        .map(|p| Pattern::from_parser(p, env, unresolved))
4533        .collect::<Result<Vec<_>, Error>>()?;
4534
4535    for p in &patterns {
4536        scoped.expose_pattern(p);
4537    }
4538
4539    // Maybe create a case_branch function and make it common with Expression::Case ?
4540    // Or maybe not at the case_branch level, as here we can have multiple patterns
4541    // whereas cases cannot.
4542    // eg. a: Int -> Int -> Int  ==>  a b c = b + c
4543    let body = Expression::from_parser(&binding.body, &scoped, unresolved)?;
4544
4545    Ok((patterns, body))
4546}
4547
4548/// One binding written inside a class or an instance body, canonicalized as an ordinary
4549/// value with no annotation.
4550fn binding_value(
4551    env: &RootEnvironment,
4552    binding: &parser::FunBinding,
4553    unresolved: &mut Vec<Error>,
4554) -> Result<Value, Error> {
4555    let (patterns, body) = match_body(env, &binding.pattern, unresolved)?;
4556
4557    Ok(Value::Value {
4558        name: binding.name.clone(),
4559        patterns,
4560        body,
4561        span: binding.span,
4562    })
4563}
4564
4565/// Every class member whose name another value of the module already has: a top-level
4566/// declaration, one a chunk that failed to parse names, or a member of an earlier class.
4567/// `members` is every member of every class the module writes, with its class and its
4568/// signature's span, in source order.
4569fn member_clashes(
4570    members: &[(&Name, &Name, NodeSpan)],
4571    functions: &[parser::Function],
4572    unparsed: &HashMap<Name, NodeSpan>,
4573) -> Vec<Error> {
4574    let mut errors = Vec::new();
4575
4576    for (index, (member, class, span)) in members.iter().enumerate() {
4577        let value = functions
4578            .iter()
4579            .find(|f| &f.name == *member)
4580            .map(|f| f.span)
4581            .or_else(|| unparsed.get(*member).copied());
4582
4583        if let Some(other) = value {
4584            errors.push(Error::MemberNameTaken(
4585                (*member).clone(),
4586                (*class).clone(),
4587                None,
4588                *span,
4589                other,
4590            ));
4591            continue;
4592        }
4593
4594        // A member repeated inside one class is that class's own error.
4595        if let Some((_, other_class, other)) = members[..index]
4596            .iter()
4597            .find(|(earlier, earlier_class, _)| earlier == member && earlier_class != class)
4598        {
4599            errors.push(Error::MemberNameTaken(
4600                (*member).clone(),
4601                (*class).clone(),
4602                Some((*other_class).clone()),
4603                *span,
4604                *other,
4605            ));
4606        }
4607    }
4608
4609    errors
4610}
4611
4612/// Canonicalize every `type` declaration of a module, keeping each one that canonicalized
4613/// beside the errors of those that did not.
4614fn do_types(
4615    env: &dyn Environment,
4616    types: &[parser::UnionType],
4617) -> (HashMap<Name, UnionType>, Vec<Error>) {
4618    let iter = types.iter().map(|tpe| {
4619        let tpe_name = tpe.name.clone();
4620        // The declaration is this module's, so this is where its variants learn
4621        // which module the type they build belongs to (`AST-4`).
4622        let qualified_tpe_name = env.module_name().qualify_name(&tpe_name);
4623        let variables = tpe.type_arguments.clone();
4624
4625        trace!("do_types(in:{:?})", tpe);
4626
4627        // An opaque scalar's declaration writes only its own name and contributes
4628        // no constructor (`LANG-59`, `DEC-15` decision 2): nothing in the language
4629        // builds or inspects an `Int`, a `Float`, a `Char` or a `String`, so the
4630        // only body worth accepting is the one that says so. This runs on the
4631        // *qualified* name, the same way `scalars::Scalar::declares` always does —
4632        // a module other than the one a scalar is declared in shares its spelling
4633        // and nothing else (`BUG-26`), so its own `type Int = …` reaches the
4634        // ordinary path below untouched.
4635        if let Some(scalar) = scalars::opaque_scalar_of(&qualified_tpe_name) {
4636            let is_self_naming = matches!(
4637                tpe.variants.as_slice(),
4638                [variant] if matches!(
4639                    &variant.kind,
4640                    parser::TypeKind::Unqualified(name, args) if *name == tpe_name && args.is_empty()
4641                )
4642            );
4643
4644            if !is_self_naming {
4645                return Err(Error::InvalidScalarDeclaration(
4646                    scalar.qual_name(),
4647                    tpe.span,
4648                ));
4649            }
4650
4651            return Ok((
4652                tpe_name,
4653                UnionType {
4654                    variables,
4655                    variants: Vec::new(),
4656                    span: tpe.span,
4657                },
4658            ));
4659        }
4660
4661        // A variant is a constructor name and its arguments, which the parser spells
4662        // `TypeKind::Unqualified`. It is the grammar's general `Type` production that
4663        // parses a variant list, though, so the five other kinds arrive here too —
4664        // and each is a declaration the user wrote that has no meaning, not a variant
4665        // this pass may leave out. Skipping one deletes a constructor from the
4666        // declaration and reports nothing, which was `BUG-18`.
4667        //
4668        // The `collect` below short-circuits on the first `Err`, so only the first bad
4669        // variant in a single `type` declaration is reported — `type T = c | (Int,
4670        // Int)` names only `c`. The enclosing `collect_partial` still reports the
4671        // next `type` declaration independently, matching what the `Unqualified` arm
4672        // already did for `from_parser_type`.
4673        let variants = tpe
4674            .variants
4675            .iter()
4676            .map(|t| match &t.kind {
4677                // TODO It might actually make more sense to put Type::from_parser_type
4678                // on `Environment`.
4679                parser::TypeKind::Unqualified(name, vars) => {
4680                    let type_parameters = vars
4681                        .iter()
4682                        .map(|t| Type::from_parser_type(env, t))
4683                        .collect::<Result<Vec<_>, Error>>()?;
4684
4685                    Ok(TypeConstructor {
4686                        name: name.clone(),
4687                        type_parameters,
4688                        tpe: qualified_tpe_name.clone(),
4689                    })
4690                }
4691                parser::TypeKind::Variable(name) => Err(Error::InvalidVariant(
4692                    InvalidVariantKind::LowercaseName(name.clone()),
4693                    t.span,
4694                )),
4695                parser::TypeKind::Tuple(_) => {
4696                    Err(Error::InvalidVariant(InvalidVariantKind::Tuple, t.span))
4697                }
4698                parser::TypeKind::Unit => {
4699                    Err(Error::InvalidVariant(InvalidVariantKind::Unit, t.span))
4700                }
4701                parser::TypeKind::Arrow(_, _) => {
4702                    Err(Error::InvalidVariant(InvalidVariantKind::Arrow, t.span))
4703                }
4704                parser::TypeKind::Record(_) => {
4705                    Err(Error::InvalidVariant(InvalidVariantKind::Record, t.span))
4706                }
4707            })
4708            .collect::<Result<Vec<_>, Error>>()?;
4709
4710        Ok((
4711            tpe_name,
4712            UnionType {
4713                variables,
4714                variants,
4715                span: tpe.span,
4716            },
4717        ))
4718    });
4719
4720    collect_partial(iter)
4721}
4722
4723/// Canonicalize every `infix` declaration of a module, registering each one that names a
4724/// function this module declares, beside the errors of those that do not. A function
4725/// `unparsed` names is declared, though nothing of it parsed, and so is a member of one of
4726/// the module's classes, `members`.
4727fn do_infixes(
4728    infixes: &[parser::Infix],
4729    env: &mut RootEnvironment,
4730    functions: &[parser::Function],
4731    members: &[(&Name, &Name, NodeSpan)],
4732    unparsed: &HashMap<Name, NodeSpan>,
4733) -> (HashMap<Name, Infix>, Vec<Error>) {
4734    let iter = infixes.iter().map(|infix| {
4735        let op_name = infix.operator.clone();
4736        let function_name = infix.function_name.clone();
4737
4738        let function_exist = functions.iter().any(|f| f.name == infix.function_name)
4739            || unparsed.contains_key(&infix.function_name)
4740            || members
4741                .iter()
4742                .any(|(member, _, _)| **member == infix.function_name);
4743
4744        if function_exist {
4745            let infix = Infix {
4746                associativity: infix.associativity,
4747                precedence: infix.precedence,
4748                function_name,
4749                span: infix.span,
4750            };
4751
4752            env.insert_local_infix(op_name.clone(), infix.clone());
4753
4754            Ok((op_name, infix))
4755        } else {
4756            Err(Error::InfixReferenceInvalidValue(
4757                op_name,
4758                function_name,
4759                infix.span,
4760            ))
4761        }
4762    });
4763
4764    collect_partial(iter)
4765}
4766
4767// The `Lower` and `Upper` arms below check that the name they name is one this module
4768// declares: such a name in a module's own `exposing (...)` header that nothing declares, or
4769// that only an import brought into scope, is `Error::ExportNotFound`
4770// (`docs/spec/modules.md#everything-exposed-must-be-declared-here`). The `Operator` arm
4771// checks only that an `infix` of that name is in scope (`local_infix_exists`, which asks
4772// whether the environment's `infixes` map has the key, and an import fills that map), so an
4773// operator only an import brought in is accepted; `BUG-51` is the ticket. `Upper`'s two arms
4774// differ only in which `ExportType` they report on success: `Privacy` governs whether the
4775// type's constructors are exposed, not whether the type itself exists, so both check
4776// existence the same way.
4777//
4778// What tells a declaration from an import differs by kind, each by what the environment
4779// already records. A value is `ValueType::Local`/`TopLevel` when this module declares it
4780// and `Foreign`/`Foreigns` when an import brought it in. A type and a class carry the
4781// qualified name of their declaration, and `declaring_module` of it is this module only
4782// for a declaration of its own (`declares_type`, `classes::declaring_module`).
4783//
4784// A declaration and an unqualified import of one name do not reach this check as two
4785// candidates: the declaration replaces the import's entry in `env` before any export is
4786// read, so such a name counts as declared here. That collision is an error of its own
4787// (`docs/spec/name-resolution.md#a-top-level-name-comes-from-exactly-one-place`), not
4788// something this function decides.
4789//
4790// `values` is this module's own declarations (from `do_values`/the facade iterator above),
4791// separate from `env`: `env.find_value` also answers `Some` for a name resolved through an
4792// import. A name reaches `Lower`'s annotation check only once the arm has established it is
4793// `TopLevel`/`Local`, so that check never has to consider an imported name.
4794//
4795// `unannotated_broken` is the declarations of this module that were written with no
4796// annotation and are in `Module::broken` — absent from `values`, so without it an exposed
4797// one would be accepted here and then be missing from the interface with nothing in this
4798// module to say why. Each is reported exactly as an unannotated `Value::Value` is.
4799//
4800// What comes back is the exports that resolved beside the errors of those that did not:
4801// for an explicit list, every entry that did not error, so a bad entry costs the module
4802// that entry alone; for `exposing (..)`, everything, beside an error per unannotated
4803// declaration.
4804//
4805// `member_classes` is each member of this module's own classes, to its class. A member is
4806// exposed with its class, and an entry naming one alone is an error.
4807fn do_exports(
4808    source_exposing: &parser::Exposing,
4809    env: &RootEnvironment,
4810    values: &HashMap<Name, Value>,
4811    unannotated_broken: &HashMap<Name, NodeSpan>,
4812    member_classes: &HashMap<&Name, &Name>,
4813) -> (Exports, Vec<Error>) {
4814    match source_exposing {
4815        // `exposing (..)` exposes every top-level declaration this module
4816        // makes, so `SPEC-5` applies to every one of them, not just those
4817        // named individually — and there is no per-name span in this header
4818        // to blame (`parser::Exposing::Open` carries none), so
4819        // `ExportedValueNotAnnotated`'s first span is `NodeSpan::none()` and
4820        // the declaration itself is what a diagnostic points at.
4821        parser::Exposing::Open => {
4822            let checked = values.values().map(|value| match value {
4823                Value::TypedValue { .. } => Ok(()),
4824                Value::Value { name, span, .. } => Err(Error::ExportedValueNotAnnotated(
4825                    name.clone(),
4826                    NodeSpan::none(),
4827                    *span,
4828                )),
4829            });
4830
4831            let ((), mut errors) = collect_partial(checked);
4832            errors.extend(unannotated_broken.iter().map(|(name, span)| {
4833                Error::ExportedValueNotAnnotated(name.clone(), NodeSpan::none(), *span)
4834            }));
4835
4836            (Exports::Everything, errors)
4837        }
4838        parser::Exposing::Explicit(exposed) => {
4839            let specifics =
4840                exposed.iter().map(|exposed| match &exposed.kind {
4841                    parser::ExposedKind::Lower(name) => {
4842                        if let Some(class) = member_classes.get(name) {
4843                            return Err(Error::MemberExposedAlone(
4844                                name.clone(),
4845                                (*class).clone(),
4846                                exposed.span,
4847                            ));
4848                        }
4849
4850                        // Only a declaration of this module is exposed by it: a name an
4851                        // `import ... exposing (...)` brought in is `Foreign`/`Foreigns`,
4852                        // and is as much `ExportNotFound` as one nothing declares.
4853                        if !matches!(
4854                            env.find_value(name),
4855                            Some(ValueType::Local | ValueType::TopLevel)
4856                        ) {
4857                            return Err(Error::ExportNotFound(
4858                                name.clone(),
4859                                ExportType::Value,
4860                                exposed.span,
4861                            ));
4862                        }
4863
4864                        if let Some(span) = unannotated_broken.get(name) {
4865                            return Err(Error::ExportedValueNotAnnotated(
4866                                name.clone(),
4867                                exposed.span,
4868                                *span,
4869                            ));
4870                        }
4871
4872                        match values.get(name) {
4873                            Some(Value::Value { span, .. }) => Err(
4874                                Error::ExportedValueNotAnnotated(name.clone(), exposed.span, *span),
4875                            ),
4876                            // `Some(TypedValue)` is declared locally and annotated;
4877                            // `None` is a local declaration that is not in `values`
4878                            // (one whose annotation was rejected, say), whose own error
4879                            // is already reported.
4880                            Some(Value::TypedValue { .. }) | None => {
4881                                Ok((name.clone(), ExportType::Value))
4882                            }
4883                        }
4884                    }
4885                    // Privacy governs whether the type's constructors are exposed,
4886                    // not whether the type itself exists — both arms check
4887                    // existence the same way, and only the `ExportType` they
4888                    // report on success differs.
4889                    parser::ExposedKind::Upper(name, parser::Privacy::Public) => {
4890                        if declares_type(env, name) {
4891                            Ok((name.clone(), ExportType::UnionPublic))
4892                        } else if env.find_class(name).is_some() {
4893                            Err(Error::ClassExposedWithConstructors(
4894                                name.clone(),
4895                                exposed.span,
4896                            ))
4897                        } else {
4898                            Err(Error::ExportNotFound(
4899                                name.clone(),
4900                                ExportType::UnionPublic,
4901                                exposed.span,
4902                            ))
4903                        }
4904                    }
4905                    parser::ExposedKind::Upper(name, parser::Privacy::Private) => {
4906                        if declares_type(env, name) {
4907                            Ok((name.clone(), ExportType::UnionPrivate))
4908                        } else if let Some(class) = env.find_class(name) {
4909                            // A class an import brought into scope is one this module
4910                            // may not re-export
4911                            // (docs/spec/modules.md#everything-exposed-must-be-declared-here).
4912                            if classes::declaring_module(class) == *env.module_name() {
4913                                Ok((name.clone(), ExportType::Class))
4914                            } else {
4915                                Err(Error::ExportNotFound(
4916                                    name.clone(),
4917                                    ExportType::Class,
4918                                    exposed.span,
4919                                ))
4920                            }
4921                        } else {
4922                            Err(Error::ExportNotFound(
4923                                name.clone(),
4924                                ExportType::UnionPrivate,
4925                                exposed.span,
4926                            ))
4927                        }
4928                    }
4929                    parser::ExposedKind::Operator(name) => {
4930                        if env.local_infix_exists(name) {
4931                            Ok((name.clone(), ExportType::Infix))
4932                        } else {
4933                            Err(Error::ExportNotFound(
4934                                name.clone(),
4935                                ExportType::Infix,
4936                                exposed.span,
4937                            ))
4938                        }
4939                    }
4940                });
4941
4942            let (specifics, errors) = collect_partial(specifics);
4943
4944            (Exports::Specifics(specifics), errors)
4945        }
4946    }
4947}
4948
4949/// Whether `name` is a type this module declares, as opposed to one an import brought
4950/// into scope under that spelling: the [`TypeArity`](environment::TypeArity) a lookup
4951/// finds records the declaration's qualified name, so it is this module's when the module
4952/// that name carries is this one.
4953fn declares_type(env: &RootEnvironment, name: &Name) -> bool {
4954    env.find_type(name)
4955        .is_some_and(|declared| classes::declaring_module(&declared.name) == *env.module_name())
4956}
4957
4958#[cfg(test)]
4959mod tests {
4960    use super::*;
4961
4962    fn not_found() -> Error {
4963        Error::TypeNotFound("T".into(), NodeSpan::none())
4964    }
4965
4966    fn no_bindings() -> Error {
4967        Error::NoBindings(NodeSpan::none())
4968    }
4969
4970    /// A group is flattened before the filter reads it, so a member that is not a
4971    /// restatement survives its group, and a group holding only restatements leaves
4972    /// nothing behind. With the flag unset the list comes back as it went in, groups
4973    /// included.
4974    ///
4975    /// Mutation-checked by pushing a group through without flattening it: the group is
4976    /// kept whole and the first assertion goes red.
4977    #[test]
4978    fn without_restated_flattens_groups_and_keeps_what_is_not_a_missing_name() {
4979        let errors = vec![
4980            Error::Many(vec![
4981                Error::Many(vec![not_found(), no_bindings()]),
4982                not_found(),
4983            ]),
4984            Error::Many(vec![not_found()]),
4985        ];
4986
4987        let kept = without_restated(errors, true);
4988        assert!(
4989            matches!(kept.as_slice(), [Error::NoBindings(_)]),
4990            "got {:?}",
4991            kept
4992        );
4993
4994        let untouched = without_restated(vec![Error::Many(vec![not_found()])], false);
4995        assert!(
4996            matches!(untouched.as_slice(), [Error::Many(members)] if members.len() == 1),
4997            "got {:?}",
4998            untouched
4999        );
5000    }
5001}