Skip to main content

flm_core/lang/mint/
packages.rs

1//! [`mint_packages`], which builds the techy packages and the fallback provider
2//! from the features' declarations, and reports as [`MintError`] values the
3//! declarations that do not fit.
4//!
5//! [`mint_packages`] takes the declarations of every feature and returns the
6//! [`MintedProviders`] that the language build
7//! ([`build_language`](crate::lang::build_language)) installs. Every
8//! specification a parse can resolve comes from here. The [module
9//! documentation](super) explains minting and the terms techy package,
10//! specification and scope stack.
11//!
12//! # What minting builds
13//!
14//! - **The features' techy packages**, holding every element declaration
15//!   under every name it is written under. A feature has one techy package
16//!   per weakness ([`ElementDef::weak`]) and distinct set of parsing modes
17//!   its declarations list, in the order these first appear. The first is
18//!   named after the feature, and is the only one when all of the feature's
19//!   declarations have the same weakness and list the same modes; each
20//!   further one is named `<feature>#<n>`, with `n` counting from 2. The
21//!   language build puts on the scope stack every package of weak
22//!   declarations under every package of ordinary declarations. Each of the
23//!   two parts is in registration order (each feature at the place of its
24//!   first element declaration, so that the declarations a feature makes
25//!   from a finalizer join its others), with a feature's own packages in the
26//!   order they first appear, so a later feature's package shadows an
27//!   earlier one's.
28//!
29//!   Because a techy package holds one entry per callable kind and name,
30//!   these several packages let one feature declare one name twice in
31//!   parsing modes that do not overlap (a text-only `\vec` and a
32//!   mathematics-only `\vec`). Declaring one name twice in modes that
33//!   overlap is reported ([`MintError::Redeclared`]).
34//! - **The scoped packages**, one techy package per [`ScopedPackageDef`].
35//!   They are not on the scope stack: an environment body or an argument that
36//!   refers to one adds it to the scope stack while that body or argument is
37//!   parsed. Each is built after the scoped packages its own declarations
38//!   refer to (in an environment's body or in any argument), so a reference
39//!   always finds a package that already exists.
40//! - **The fallback provider** ([`FlmFallbackProvider`]), at the bottom of
41//!   the scope stack, which resolves a command that no declaration defines.
42//! - **The fields package**, holding the specifications of tack-on fields.
43//!
44//! Every specification is one of the types of [`super::specs`] and carries a
45//! provenance stamp (techy's
46//! [`SpecProvenance`](techy::core::specs::SpecProvenance)): the record,
47//! issued by the techy package the specification is inserted into, of that
48//! package and of the key the specification is held under. A serialized tree
49//! ([`crate::lang::serialize`]) refers to a specification through its stamp.
50//!
51//! # Two features that define one name
52//!
53//! Minting detects clashes on the built techy packages themselves, asking
54//! each for the names it registers, per callable kind and per parsing mode.
55//! Each parsing mode is decided on its own.
56//!
57//! A declaration is ordinary or weak ([`ElementDef::weak`]). Where one or
58//! more features declare a name ordinarily in a mode, the weak declarations
59//! of that name play no part in that mode, whatever the order of the
60//! features: their packages are under every package of ordinary
61//! declarations on the scope stack, and nothing is reported about them. The
62//! rules below then decide among the ordinary declarations; where only weak
63//! declarations of the name exist in the mode, they decide among the weak
64//! ones in the same way. The feature order, its chains and the overrides
65//! never make a weak declaration apply over an ordinary one.
66//!
67//! Where two or more features define a name in one mode (among the
68//! declarations that the previous paragraph leaves), registration order
69//! decides which definition applies in that mode: the later feature's techy
70//! package is innermost on the scope stack and shadows the others. The
71//! registration order is the final order of the features, which the chains
72//! of the feature order decide ([`crate::core::registry::order`]).
73//!
74//! Such a collision is allowed in a mode when the feature registered last
75//! among the features that define the name in that mode is explicitly after
76//! every other of them in the feature order (`a < b` lets `b` define a name
77//! `a` defines), or when that feature declared an override ([`OverrideDef`]):
78//! the collision is then intended and is not reported. Otherwise it is one
79//! [`MintError::Clash`] for that mode, which lists every feature that defines
80//! the name in it and the chains of the feature order that would settle it
81//! without contradicting the explicit order in force. Only the override of
82//! the definition that applies is consulted: an override that another of
83//! those features declared has no effect.
84//!
85//! Definitions in different modes never clash: a `\vec` for text and a `\vec`
86//! for mathematics are two different commands. A feature that defines a name
87//! in text mode only and another that defines it in math mode only are
88//! therefore never in a collision, even where a third feature defines the name
89//! in both modes; that third feature then meets each of them in one mode.
90//!
91//! One feature that declares one name twice in parsing modes that overlap is
92//! reported ([`MintError::Redeclared`]), whatever the weakness of the two
93//! declarations. A declaration with no syntax ignores the mark, as it ignores
94//! its modes.
95//!
96//! A declaration in a scoped package may not be weak
97//! ([`MintError::WeakInScopedPackage`]): whoever adds a scoped package to a
98//! scope stack chooses its place, above the features' packages, so minting
99//! cannot place it under the ordinary declarations.
100//!
101//! Scoped packages are not checked for clashes, neither against one another
102//! nor against the features' own packages, because a scoped package is on no
103//! scope stack until something adds it: a body or an argument that refers to
104//! it, or a program that adds it to a parsing state. Two
105//! scoped packages that declare one name (two features each giving `\\` a
106//! meaning inside its own environment, in text mode) are therefore available
107//! in separate places, unless one is used inside the other; the inner one then
108//! shadows the outer one while its body or argument is parsed, as any techy
109//! package added later does. Only two scoped packages with the same package
110//! name clash ([`ClashKind::ScopedPackage`]), since a body refers to a
111//! package by its name.
112//!
113//! # The fallback package and the fields package
114//!
115//! Two techy packages are never on the scope stack.
116//!
117//! **The fallback package**, named [`FALLBACK_PACKAGE_NAME`], holds the
118//! fallback specifications under keys built from the owner, the callable kind
119//! and the position of each fallback. It exists so that those specifications
120//! carry provenance stamps like every other and can be serialized and read
121//! back. The scope stack holds the fallback provider instead, which returns a
122//! specification from this package in the declared modes only. The fallback
123//! provider resolves *any* name and so cannot list its entries; a [reading
124//! session](crate::dump::session) is given the package beside it, and
125//! [`BuiltLang::providers`](crate::lang::BuiltLang::providers) lists it.
126//!
127//! After every fallback a feature declares, the fallback provider consults
128//! the language's own two, each applying in every mode: a macro that no declaration
129//! defines resolves to a specification carrying `flm.unknown.macro` and is
130//! reported, and an environment likewise to one carrying `flm.unknown.environment`.
131//! A feature's fallback for a mode shadows the language's in that mode. This is how
132//! mathematics accepts any command without a report when a mathematics feature is
133//! registered, while text mode still reports unknown commands.
134//!
135//! **The fields package**, named [`FIELDS_PACKAGE_NAME`], holds the
136//! specifications of [tack-on fields](super::TackOnField). Each carries the
137//! language's field element
138//! ([`StructuralElements::field`](crate::lang::structural::StructuralElements::field)).
139//! A field's node records such a specification, but no name lookup ever reaches it: the
140//! parser that absorbs the fields holds it directly. The package exists so
141//! that these specifications too carry provenance stamps and can be
142//! serialized. Their keys are built from the declaration alone, so adding an
143//! unrelated declaration elsewhere does not change the key a serialized tree
144//! refers to.
145
146use std::collections::{BTreeMap, BTreeSet};
147use std::fmt;
148use std::sync::Arc;
149
150use techy::core::constructs::{ArgumentParser, TackOnFieldsArgumentParser};
151use techy::core::specs::{
152    ArgumentSpec, CallableQuery, CallableSpec, Package, ProviderError, SpecsProvider,
153};
154use techy::core::{ClosedVocabulary, ParsingState, ParsingStateDelta};
155use techy::latexlike::{MacroSpec, Mode, SpecialsSpec};
156
157use crate::model::element::ElementSpec;
158use crate::model::names::{ElementName, FeatureName, Name};
159use crate::lang::flm::{Flm, FlmCallableType, FlmEvent};
160use crate::lang::mint::decl::{
161    ArgDef, ArgLayout, BodyDef, BodyLayout, CallableKind, ElementDef, FallbackDef,
162    FallbackKind, OverrideDef, ScopedPackageDef, SyntaxDef, TackOnField,
163};
164use crate::lang::mint::opaque::OpaqueWrapperReader;
165use crate::lang::mint::specs::{
166    FlmCallable, FlmEnvironment, FlmUnknownEnvironmentBehavior, FlmUnknownMacroSpec,
167};
168use crate::lang::input::InputSpec;
169use crate::lang::structural::StructuralElements;
170
171/// One registered command name: its callable kind and the name itself (the
172/// trigger, for a special character sequence).
173///
174/// Its `Display` text, such as ``macro `vec` ``, appears in error messages.
175///
176/// It is written to data with `Serialize`; see [serialized
177/// forms](crate::core::registry#serialized-forms).
178#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
179#[derive(serde::Serialize, schemars::JsonSchema)]
180pub struct Symbol {
181    /// The callable kind of the name.
182    pub kind: CallableKind,
183    /// The name without its escape character, or the trigger.
184    pub name: String,
185}
186
187impl fmt::Display for Symbol {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        write!(f, "{} `{}`", self.kind, self.name)
190    }
191}
192
193/// What was declared more than once, in a [`MintError::Clash`].
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub enum ClashKind {
196    /// Two or more features define one command name in parsing modes that
197    /// overlap.
198    Symbol,
199    /// Two fallbacks for one callable kind, declared by one feature or by
200    /// two, apply in parsing modes that overlap.
201    Fallback,
202    /// A scoped package name is declared twice, by one feature or by two.
203    ScopedPackage,
204}
205
206/// A problem with the declarations that minting found.
207///
208/// [`mint_packages`] collects every problem in
209/// [`MintedProviders::errors`] and still builds everything that is sound;
210/// each variant says what was found and, where a choice had to be made, which
211/// declaration applies. The language build reports each one as a
212/// [`LangBuildError::Mint`](crate::lang::LangBuildError::Mint), and the
213/// registry build refuses a language with any such error: it fails in its
214/// language phase
215/// ([`BuildPhase::Language`](crate::core::registry::BuildPhase::Language)).
216/// The `userdefs` feature, which mints a language for the templates of [user
217/// definitions](crate::lang::rewrites::userdefs::Definition), reports these
218/// errors as diagnostics of those user definitions.
219///
220/// The `Display` text states the problem for the author of the feature or of
221/// the user definition; it identifies, where the problem concerns them, the
222/// declaring feature and the element by name.
223#[derive(Debug, Clone, PartialEq, Eq)]
224pub enum MintError {
225    /// Two or more features declare the same thing where it matters. For a
226    /// command name: two or more features define it in one parsing mode
227    /// (ordinarily, or weakly where no feature defines it ordinarily in that
228    /// mode), and the feature registered last among them in that mode is
229    /// neither placed by the feature order explicitly after every other of
230    /// them nor declares an override. There is one error per name and parsing
231    /// mode.
232    Clash {
233        /// What was declared twice.
234        kind: ClashKind,
235        /// The name concerned: the command name; for a fallback, the name of
236        /// the callable kind; for a scoped package, the package's name.
237        symbol: Symbol,
238        /// The parsing modes in which the declarations overlap, in the modes'
239        /// fixed order: for a command name, the one mode concerned. Empty for a
240        /// scoped package, which is not tied to parsing modes.
241        modes: Vec<Mode>,
242        /// Every feature whose declaration is available in one of `modes`, in
243        /// registration order: for a command name, the features that declare
244        /// it ordinarily in that mode, or those that declare it weakly when
245        /// none declares it ordinarily.
246        owners: Vec<FeatureName>,
247        /// The feature whose declaration applies despite the clash: for a
248        /// command name the last of `owners`, since a later feature's package
249        /// shadows an earlier one's; for a fallback or a scoped package the
250        /// first, since a later overlapping one is not installed.
251        winner: FeatureName,
252        /// For a command name, the chains of the feature order that settle
253        /// the clash, each making the definition of its last feature apply.
254        /// Each lists the other features of `owners` in registration order,
255        /// then that feature. A chain is listed only when the explicit order
256        /// in force places none of its features before an earlier one of the
257        /// chain, so that adding it makes no cycle. Empty for a fallback or a
258        /// scoped package, which no chain settles.
259        chains: Box<[Vec<FeatureName>]>,
260    },
261    /// An environment body or an argument refers to a scoped package that no
262    /// feature declares and that the feature declaring the element did not
263    /// declare as a peer. (A package declared as a peer that no feature
264    /// declares makes nothing available and is reported by the registry build
265    /// as a Note, not here.)
266    UnknownScopedPackage {
267        /// The element whose declaration refers to the package.
268        element: ElementName,
269        /// The feature declaring the element.
270        owner: FeatureName,
271        /// `None` when the environment's body refers to the package; the
272        /// argument's position, counting from zero, when an argument does, in
273        /// the argument list that declares it: the element's own, or that of
274        /// the tack-on field given by `field`.
275        argument: Option<usize>,
276        /// The name of the [tack-on field](TackOnField) whose own argument
277        /// list holds the argument; `None` when the argument is the element's
278        /// own.
279        field: Option<String>,
280        /// The package name that was not found.
281        package: Name,
282    },
283    /// Scoped packages refer to each other in a cycle, each through one of its
284    /// declarations (an environment's body or an argument), so there is no
285    /// order in which each is built after the ones it refers to. Minting
286    /// breaks the cycle at the reference that closes it.
287    ScopedPackageCycle {
288        /// The packages of the cycle, each referring to the next, the last to
289        /// the first.
290        packages: Vec<Name>,
291    },
292    /// A special character sequence declaration lists command names. It may
293    /// list none: its trigger is how it is written.
294    SpecialsWithNames {
295        /// The declaring feature.
296        owner: FeatureName,
297        /// The trigger of the declaration.
298        trigger: String,
299    },
300    /// A declaration with no syntax ([`SyntaxDef::Synthesized`]) lists command
301    /// names. It may list none, since nothing in the source writes it.
302    SynthesizedWithNames {
303        /// The declaring feature.
304        owner: FeatureName,
305        /// The element concerned.
306        element: ElementName,
307    },
308    /// A file-inclusion macro ([`SyntaxDef::Inclusion`]) declares no argument
309    /// named [`REFERENCE_ARGUMENT`](crate::lang::input::REFERENCE_ARGUMENT), so
310    /// it has no argument to read the file's reference from.
311    NoReferenceArgument {
312        /// The declaring feature.
313        owner: FeatureName,
314        /// The element concerned.
315        element: ElementName,
316        /// A description of the declared arguments, such as "it declares no
317        /// argument".
318        detail: String,
319    },
320    /// One feature declares one command name twice in parsing modes that
321    /// overlap, so in the overlapping modes only one of the two declarations
322    /// could apply, whatever the weakness of the two
323    /// ([`ElementDef::weak`]). Two declarations of one name whose modes do
324    /// *not* overlap are sound and are built into two of the feature's techy
325    /// packages.
326    Redeclared {
327        /// The name concerned.
328        symbol: Symbol,
329        /// The feature declaring it twice.
330        owner: FeatureName,
331        /// The parsing modes both declarations are available in, in the modes'
332        /// fixed order.
333        modes: Vec<Mode>,
334    },
335    /// A macro or environment declaration lists no name, so nothing can be
336    /// registered for it.
337    NoNames {
338        /// The declaring feature.
339        owner: FeatureName,
340        /// The element concerned.
341        element: ElementName,
342    },
343    /// An argument declared with an opaque wrapper
344    /// ([`ArgDef::opaque_wrapper`]) declares a [layout](ArgLayout) other than
345    /// [`ArgLayout::Inline`]. The [block-structure
346    /// pass](crate::lang::rewrites::blocks) carries the content of an opaque
347    /// wrapper over as written, so the declaration could never take effect.
348    /// The argument is built with the inline layout.
349    LayoutOnOpaqueWrappedArgument {
350        /// The declaring feature.
351        owner: FeatureName,
352        /// The element whose declaration holds the argument.
353        callable: ElementName,
354        /// The argument's position, counting from zero, in the argument list
355        /// that declares it: the element's own, or that of the tack-on field
356        /// given by `field`.
357        index: usize,
358        /// The name of the [tack-on field](TackOnField) whose own argument
359        /// list holds the argument; `None` when the argument is the element's
360        /// own.
361        field: Option<String>,
362    },
363    /// An argument read in mathematics mode ([`ArgDef::mode`]) declares the
364    /// layout [`ArgLayout::Blocks`]. The [block-structure
365    /// pass](crate::lang::rewrites::blocks) carries mathematics over
366    /// untouched, so the declaration could never take effect. The argument is
367    /// built with the inline layout.
368    BlocksOnMathArgument {
369        /// The declaring feature.
370        owner: FeatureName,
371        /// The element whose declaration holds the argument.
372        callable: ElementName,
373        /// The argument's position, counting from zero, in the argument list
374        /// that declares it: the element's own, or that of the tack-on field
375        /// given by `field`.
376        index: usize,
377        /// The name of the [tack-on field](TackOnField) whose own argument
378        /// list holds the argument; `None` when the argument is the element's
379        /// own.
380        field: Option<String>,
381    },
382    /// A tack-on argument declares two fields ([`TackOnField`]) of one name,
383    /// so a macro of that name written after the command could be read as
384    /// either. The second field is left out of the argument.
385    FieldDeclaredTwice {
386        /// The declaring feature.
387        owner: FeatureName,
388        /// The element whose declaration holds the tack-on argument.
389        callable: ElementName,
390        /// The tack-on argument's position, counting from zero, in the
391        /// argument list that declares it: the element's own, or that of the
392        /// tack-on field given by `field`.
393        index: usize,
394        /// The name of the [tack-on field](TackOnField) whose own argument
395        /// list holds the tack-on argument; `None` when the argument is the
396        /// element's own.
397        field: Option<String>,
398        /// The name the two fields share.
399        name: String,
400    },
401    /// A declaration in a [scoped package](ScopedPackageDef) is marked weak
402    /// ([`ElementDef::weak`]). A scoped package is placed on a scope stack by
403    /// whoever adds it (a body, an argument or a program), above the features'
404    /// packages, so no place under the ordinary declarations exists for it.
405    /// The declaration is built as an ordinary one.
406    WeakInScopedPackage {
407        /// The feature declaring the scoped package.
408        owner: FeatureName,
409        /// The scoped package.
410        package: Name,
411        /// The element of the weak declaration.
412        element: ElementName,
413    },
414    /// An environment's body declared with an opaque wrapper
415    /// ([`BodyDef::opaque_wrapper`]) declares a [layout](BodyDef::layout)
416    /// other than [`FromRole`](super::BodyLayout::FromRole). The
417    /// [block-structure pass](crate::lang::rewrites::blocks) carries the
418    /// content of an opaque wrapper over as written, so the declaration could
419    /// never take effect.
420    LayoutOnOpaqueWrappedBody {
421        /// The declaring feature.
422        owner: FeatureName,
423        /// The environment's element.
424        element: ElementName,
425    },
426}
427
428/// Returns the words that identify the tack-on field an argument belongs to,
429/// for a message: empty for an element's own argument.
430fn of_field(field: &Option<String>) -> String {
431    field.as_ref().map(|name| format!(" of the field `{name}`")).unwrap_or_default()
432}
433
434/// Returns feature names written as `` feature `a` `` or
435/// `` features `a`, `b` and `c` ``, for a message.
436fn owner_list(owners: &[FeatureName]) -> String {
437    match owners {
438        [] => String::from("no feature"),
439        [one] => format!("feature `{one}`"),
440        [head @ .., last] => {
441            let head: Vec<String> = head.iter().map(|owner| format!("`{owner}`")).collect();
442            format!("features {} and `{last}`", head.join(", "))
443        }
444    }
445}
446
447/// Returns parsing modes written as `mode Text` or `modes Text and Math`, for
448/// a message (an empty list, which no declaration carries, reads `no mode`).
449fn mode_list(modes: &[Mode]) -> String {
450    match modes {
451        [] => String::from("no mode"),
452        [one] => format!("mode {one:?}"),
453        [head @ .., last] => {
454            let head: Vec<String> = head.iter().map(|mode| format!("{mode:?}")).collect();
455            format!("modes {} and {last:?}", head.join(", "))
456        }
457    }
458}
459
460/// Returns items written as `a`, `a and b` or `a, b, and c` (with `or` for
461/// `and` when `conjunction` says so), for a message.
462fn series(items: &[String], conjunction: &str) -> String {
463    match items {
464        [] => String::new(),
465        [one] => one.clone(),
466        [first, second] => format!("{first} {conjunction} {second}"),
467        [head @ .., last] => format!("{}, {conjunction} {last}", head.join(", ")),
468    }
469}
470
471/// Returns parsing modes written as `in math mode` or `in text and math
472/// modes`, for a message.
473fn in_modes(modes: &[Mode]) -> String {
474    let words: Vec<String> = modes.iter().map(|mode| format!("{mode:?}").to_lowercase()).collect();
475    match words.as_slice() {
476        [] => String::from("in no mode"),
477        [one] => format!("in {one} mode"),
478        [head @ .., last] => format!("in {} and {last} modes", head.join(", ")),
479    }
480}
481
482impl fmt::Display for MintError {
483    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484        match self {
485            MintError::Clash { kind: ClashKind::Symbol, symbol, modes, owners, chains, .. } => {
486                let construct = match symbol.kind {
487                    CallableKind::Macro => format!("‘\\{}’", symbol.name),
488                    CallableKind::Environment => format!("environment ‘{}’", symbol.name),
489                    CallableKind::Specials => format!("‘{}’", symbol.name),
490                };
491                let features: Vec<String> =
492                    owners.iter().map(|owner| format!("‘{owner}’")).collect();
493                let choices: Vec<String> = chains
494                    .iter()
495                    .filter_map(|chain| {
496                        let chosen = chain.last()?;
497                        let chain: Vec<&str> = chain.iter().map(|owner| owner.as_str()).collect();
498                        Some(format!(
499                            "‘flm: feature_order: ['{}']’ for the definition of ‘{chosen}’",
500                            chain.join(" < ")
501                        ))
502                    })
503                    .collect();
504                write!(
505                    f,
506                    "Duplicate definition of {construct} {} (features {})",
507                    in_modes(modes),
508                    series(&features, "and")
509                )?;
510                if choices.is_empty() {
511                    return Ok(());
512                }
513                write!(f, "; in the front matter, set {}", series(&choices, "or"))
514            }
515            MintError::Clash { kind: ClashKind::Fallback, symbol, modes, owners, .. } => {
516                write!(
517                    f,
518                    "the fallbacks for unknown {}s declared by {} overlap in {}; only one \
519                     fallback for unknown {}s may apply in a parsing mode",
520                    symbol.name,
521                    owner_list(owners),
522                    mode_list(modes),
523                    symbol.name
524                )
525            }
526            MintError::Clash { kind: ClashKind::ScopedPackage, symbol, owners, .. } => write!(
527                f,
528                "the scoped package name `{}` is declared more than once (by {}); a \
529                 scoped package name may be declared only once",
530                symbol.name,
531                owner_list(owners)
532            ),
533            MintError::Redeclared { symbol, owner, modes } => write!(
534                f,
535                "feature `{owner}` declares {symbol} twice in {}; a feature may declare a \
536                 name only once per parsing mode",
537                mode_list(modes)
538            ),
539            MintError::UnknownScopedPackage { element, owner, argument: None, package, .. } => write!(
540                f,
541                "the body of `{element}` (an element of the feature `{owner}`) refers to \
542                 the scoped package `{package}`, which no registered feature declares; a \
543                 feature that refers to another feature's scoped package must declare it \
544                 with `FeatureBuilder::peer_scoped_package`"
545            ),
546            MintError::UnknownScopedPackage {
547                element,
548                owner,
549                argument: Some(index),
550                field,
551                package,
552            } => {
553                write!(
554                    f,
555                    "argument {}{} of `{element}` (an element of the feature `{owner}`) \
556                     refers to the scoped package `{package}`, which no registered feature \
557                     declares; a feature that refers to another feature's scoped package \
558                     must declare it with `FeatureBuilder::peer_scoped_package`",
559                    index + 1,
560                    of_field(field)
561                )
562            }
563            MintError::ScopedPackageCycle { packages } => {
564                let names: Vec<String> = packages.iter().map(|name| format!("`{name}`")).collect();
565                write!(
566                    f,
567                    "scoped packages must not refer to each other in a cycle; the cycle is \
568                     {}, the last referring back to the first",
569                    names.join(" → ")
570                )
571            }
572            MintError::SpecialsWithNames { owner, trigger } => write!(
573                f,
574                "feature `{owner}`: the special character sequence `{trigger}` must not \
575                 declare command names; it is written as `{trigger}`"
576            ),
577            MintError::SynthesizedWithNames { owner, element } => write!(
578                f,
579                "feature `{owner}`: the element `{element}`, declared as never written in a \
580                 document (`SyntaxDef::Synthesized`), must not declare command names"
581            ),
582            MintError::NoReferenceArgument { owner, element, detail } => write!(
583                f,
584                "feature `{owner}`: the file-inclusion macro of the element `{element}` must \
585                 declare an argument named `reference` ({detail})"
586            ),
587            MintError::NoNames { owner, element } => {
588                write!(
589                    f,
590                    "feature `{owner}`: the macro or environment declaration of the element \
591                     `{element}` must list at least one name"
592                )
593            }
594            MintError::LayoutOnOpaqueWrappedArgument { owner, callable, index, field } => write!(
595                f,
596                "feature `{owner}`: argument {}{} of `{callable}` must be laid out inline, \
597                 because it is declared with an opaque wrapper",
598                index + 1,
599                of_field(field)
600            ),
601            MintError::BlocksOnMathArgument { owner, callable, index, field } => write!(
602                f,
603                "feature `{owner}`: argument {}{} of `{callable}` must not be laid out as \
604                 blocks, because it is read in mathematics mode",
605                index + 1,
606                of_field(field)
607            ),
608            MintError::FieldDeclaredTwice { owner, callable, index, field, name } => write!(
609                f,
610                "feature `{owner}`: the fields of argument {}{} of `{callable}` must have \
611                 distinct names, and `{name}` is declared twice",
612                index + 1,
613                of_field(field)
614            ),
615            MintError::WeakInScopedPackage { owner, package, element } => write!(
616                f,
617                "Misconfigured feature ‘{owner}’: the declaration of ‘{element}’ in scoped \
618                 package ‘{package}’ may not be weak"
619            ),
620            MintError::LayoutOnOpaqueWrappedBody { owner, element } => write!(
621                f,
622                "feature `{owner}`: the body of `{element}` must not declare a layout, because \
623                 it is declared with an opaque wrapper"
624            ),
625        }
626    }
627}
628
629impl std::error::Error for MintError {}
630
631// --- the fallback provider --------------------------------------------------------------
632
633/// The name of the fallback provider ([`FlmFallbackProvider`]) as a
634/// specification provider on the scope stack, `_fallback.gate`.
635pub const FALLBACK_PROVIDER_NAME: &str = "_fallback.gate";
636
637/// The name of the techy package holding the fallback specifications
638/// ([`FlmFallbackProvider::package`]), `_fallback`.
639pub const FALLBACK_PACKAGE_NAME: &str = "_fallback";
640
641/// The name of the techy package holding the specifications of tack-on fields
642/// ([`MintedProviders::fields`]), `_fields`; see the [module
643/// documentation](self).
644pub const FIELDS_PACKAGE_NAME: &str = "_fields";
645
646/// The feature name recorded as the owner of the language's own declarations,
647/// `flm`: the fallbacks for an unknown macro and an unknown environment. No
648/// registered feature has this name; [`FlmFallbackProvider::entries`] lists
649/// these two fallbacks under it.
650pub const LANGUAGE_OWNER: &str = "flm";
651
652/// One fallback the fallback provider holds: the feature that declared it, the modes it
653/// applies in, the callable kind it applies to, and its key in the fallback
654/// package.
655struct FallbackEntry {
656    owner: FeatureName,
657    modes: Vec<Mode>,
658    kind: FallbackKind,
659    key: String,
660}
661
662/// A fallback while it is being collected, before the package is built.
663struct PendingFallback {
664    owner: FeatureName,
665    modes: Vec<Mode>,
666    kind: FallbackKind,
667    element: Arc<ElementSpec>,
668    /// Whether this is one of the language's own fallbacks, which report the
669    /// unknown callable, rather than a feature's, which passes it silently.
670    recovery: bool,
671}
672
673/// The fallback provider: the specification provider that resolves a macro or
674/// an environment that no declaration defines, according to the fallbacks
675/// ([`FallbackDef`]) declared for the current parsing mode.
676///
677/// techy's own fallback provider cannot be restricted to parsing modes, so
678/// minting builds this provider instead. The language build puts it at the
679/// bottom of the scope stack, so every defined name shadows it. It returns
680/// specifications from the techy package it holds
681/// ([`FlmFallbackProvider::package`]).
682///
683/// The fallbacks are consulted in declaration order, with the language's own
684/// two last, so a feature's fallback for a mode applies in that mode. In a
685/// mode no feature's fallback covers, the language's own fallbacks apply: the
686/// command is reported and its node carries `flm.unknown.macro` or
687/// `flm.unknown.environment`. Text mode therefore reports unknown commands,
688/// while mathematics mode, with a mathematics feature registered, does not.
689///
690/// It resolves *any* name, so it cannot list its entries; the package
691/// beside it is therefore listed separately in [`BuiltLang::providers`].
692///
693/// [`BuiltLang::providers`]: crate::lang::BuiltLang::providers
694pub struct FlmFallbackProvider {
695    name: Box<str>,
696    package: Arc<Package<Flm>>,
697    entries: Vec<FallbackEntry>,
698}
699
700impl FlmFallbackProvider {
701    /// Builds the fallback package and the fallback provider from the
702    /// collected fallbacks, keeping their order.
703    fn build(pending: &[PendingFallback]) -> FlmFallbackProvider {
704        let mut entries = Vec::with_capacity(pending.len());
705        let package = Package::new_shared(FALLBACK_PACKAGE_NAME, |pkg| {
706            for (index, fallback) in pending.iter().enumerate() {
707                let key = format!("{}.{}.{index}", fallback.owner, fallback.kind);
708                let callable_type = fallback.kind.callable_type();
709                let stamp = pkg.provenance_for(callable_type, key.as_str());
710                match fallback.kind {
711                    FallbackKind::Macro => {
712                        let mut callable = if fallback.recovery {
713                            FlmCallable::new(
714                                FlmUnknownMacroSpec::new(),
715                                Arc::clone(&fallback.element),
716                            )
717                        } else {
718                            FlmCallable::new(
719                                MacroSpec::<Flm>::new(Vec::new()),
720                                Arc::clone(&fallback.element),
721                            )
722                        };
723                        if let Some(stamp) = stamp {
724                            callable = callable.with_provenance(stamp);
725                        }
726                        pkg.insert(callable_type, key.as_str(), callable);
727                    }
728                    FallbackKind::Environment => {
729                        // The language layer's own environment body is block
730                        // content; a feature's silent passthrough follows the
731                        // element's role (the default declaration).
732                        let body = if fallback.recovery {
733                            BodyDef::new().blocks().parser(FlmUnknownEnvironmentBehavior::new())
734                        } else {
735                            BodyDef::default()
736                        };
737                        let environment =
738                            FlmEnvironment::new(Vec::new(), Arc::clone(&fallback.element), body);
739                        let mut spec = environment.into_spec();
740                        if let Some(stamp) = stamp {
741                            spec = spec.with_provenance(stamp);
742                        }
743                        pkg.insert(callable_type, key.as_str(), spec);
744                    }
745                }
746                entries.push(FallbackEntry {
747                    owner: fallback.owner.clone(),
748                    modes: fallback.modes.clone(),
749                    kind: fallback.kind,
750                    key,
751                });
752            }
753        });
754        FlmFallbackProvider { name: FALLBACK_PROVIDER_NAME.into(), package, entries }
755    }
756
757    /// Returns the techy package holding the fallback specifications, which
758    /// their provenance stamps refer to. It is never on the scope stack.
759    pub fn package(&self) -> &Arc<Package<Flm>> {
760        &self.package
761    }
762
763    /// Returns the installed fallbacks as `(owner, modes, kind)`, in the order
764    /// they are consulted: declaration order, with the language's own two last
765    /// (owned by [`LANGUAGE_OWNER`]). A fallback reported as a
766    /// [`MintError::Clash`] is not among them.
767    pub fn entries(&self) -> impl Iterator<Item = (&FeatureName, &[Mode], FallbackKind)> + '_ {
768        self.entries.iter().map(|entry| (&entry.owner, entry.modes.as_slice(), entry.kind))
769    }
770
771    /// Returns whether some fallback applies to `kind` in `mode`. It always
772    /// returns `true`, since the language's own two fallbacks apply to both
773    /// kinds in every mode.
774    pub fn answers(&self, kind: FallbackKind, mode: Mode) -> bool {
775        self.entries.iter().any(|entry| entry.kind == kind && entry.modes.contains(&mode))
776    }
777
778    /// Returns the specification for `kind` in `mode`: that of the first
779    /// installed fallback that covers them.
780    pub fn spec_for(
781        &self,
782        kind: FallbackKind,
783        mode: Mode,
784    ) -> Option<&Arc<dyn CallableSpec<Flm>>> {
785        let entry = self
786            .entries
787            .iter()
788            .find(|entry| entry.kind == kind && entry.modes.contains(&mode))?;
789        self.package.get(kind.callable_type(), &entry.key)
790    }
791}
792
793impl fmt::Debug for FlmFallbackProvider {
794    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
795        f.debug_struct("FlmFallbackProvider")
796            .field("name", &self.name)
797            .field("entries", &self.entries.len())
798            .finish()
799    }
800}
801
802impl SpecsProvider<Flm> for FlmFallbackProvider {
803    fn name(&self) -> &str {
804        &self.name
805    }
806
807    fn retrieve_spec(
808        &self,
809        query: &CallableQuery<'_, Flm>,
810        state: &ParsingState<Flm>,
811    ) -> Result<Option<Arc<dyn CallableSpec<Flm>>>, ProviderError> {
812        let kind = match query.callable_type {
813            FlmCallableType::Macro => FallbackKind::Macro,
814            FlmCallableType::Environment => FallbackKind::Environment,
815            _ => return Ok(None),
816        };
817        Ok(self.spec_for(kind, state.mode()).cloned())
818    }
819}
820
821// --- argument minting ----------------------------------------------------------------
822
823/// One declared argument list, built: the argument specifications, and the
824/// layout of each argument in the same order, which the command's
825/// specification records beside its element.
826struct MintedArgs {
827    specs: Vec<Arc<ArgumentSpec<Flm>>>,
828    layouts: Vec<ArgLayout>,
829}
830
831/// The scoped packages a declaration may refer to: those already built, by
832/// name; the names some feature declares, which tell a package caught in a
833/// cycle (declared, and reported separately) from one that no feature
834/// declares; and the names each feature declares as a peer, as (feature,
835/// name), which that feature's declarations may refer to although no feature
836/// declares them.
837struct Scopes<'a> {
838    minted: &'a BTreeMap<Name, Arc<Package<Flm>>>,
839    declared: &'a BTreeSet<Name>,
840    peers: &'a BTreeSet<(FeatureName, Name)>,
841}
842
843/// The fields package, which receives the specification of every tack-on
844/// field, with the element each of those specifications carries: the
845/// language's field element ([`StructuralElements::field`]).
846struct FieldsHome<'a> {
847    package: &'a mut Package<Flm>,
848    element: &'a Arc<ElementSpec>,
849}
850
851/// Builds one declared argument list: the element's own when `field` is
852/// `None`, else that of the tack-on field of this name, which an error
853/// identifies. `home` is the fields package that receives the specifications
854/// of any tack-on fields ([`FieldsHome`]), `def` the declaration they belong to, from which
855/// their keys are built and which an error identifies, and `scopes` the
856/// scoped packages an argument may refer to.
857fn argument_specs_of(
858    args: &[ArgDef],
859    field: Option<&str>,
860    home: &mut FieldsHome<'_>,
861    def: &ElementDef,
862    scopes: &Scopes<'_>,
863    errors: &mut Vec<MintError>,
864) -> MintedArgs {
865    let mut minted = MintedArgs { specs: Vec::new(), layouts: Vec::new() };
866    for (index, arg) in args.iter().enumerate() {
867        minted.specs.push(argument_spec_of(arg, index, field, home, def, scopes, errors));
868        minted.layouts.push(declared_layout(arg, index, field, def, errors));
869    }
870    minted
871}
872
873/// Returns the layout `arg` is built with: its declared one, or inline when the
874/// argument can never take the declared one, which is reported
875/// ([`MintError::LayoutOnOpaqueWrappedArgument`],
876/// [`MintError::BlocksOnMathArgument`]).
877fn declared_layout(
878    arg: &ArgDef,
879    index: usize,
880    field: Option<&str>,
881    def: &ElementDef,
882    errors: &mut Vec<MintError>,
883) -> ArgLayout {
884    let owner = def.owner.clone();
885    let callable = def.element.name.clone();
886    let field = field.map(str::to_string);
887    let error = if arg.opaque_wrapper && arg.layout != ArgLayout::Inline {
888        MintError::LayoutOnOpaqueWrappedArgument { owner, callable, index, field }
889    } else if arg.layout == ArgLayout::Blocks && arg.mode == Some(Mode::Math) {
890        MintError::BlocksOnMathArgument { owner, callable, index, field }
891    } else {
892        return arg.layout;
893    };
894    errors.push(error);
895    ArgLayout::Inline
896}
897
898/// Returns the key a tack-on field's specification is held under in the
899/// fields package, which is also how a serialized tree refers to it.
900///
901/// It is built from the declaration alone, as `owner.element.field`. If that
902/// key is taken (one declaration with two tack-on arguments accepting the same
903/// field name), the argument's position in the declaration is appended; if
904/// that is taken too, a running number is appended. The key therefore stays
905/// the same when unrelated declarations change, and since `.` is not a
906/// character of command names, no name written in the source can reach these
907/// keys.
908fn field_key(
909    home: &Package<Flm>,
910    def: &ElementDef,
911    field: &TackOnField,
912    arg_index: usize,
913) -> String {
914    let free = |key: &str| home.get(FlmCallableType::Macro, key).is_none();
915    let base = format!("{}.{}.{}", def.owner, def.element.name, field.name);
916    if free(&base) {
917        return base;
918    }
919    let indexed = format!("{base}.{arg_index}");
920    if free(&indexed) {
921        return indexed;
922    }
923    (1..)
924        .map(|number| format!("{indexed}.{number}"))
925        .find(|key| free(key))
926        .expect("the running numbers are unbounded, so a free key exists")
927}
928
929/// Builds the specification of one tack-on field and inserts it into the
930/// fields package under its [`field_key`], with that package's provenance
931/// stamp. The specification carries the language's field element, and its
932/// node is named as the field is written, which is how the construct that
933/// declared the field reads it ([`field_name`](super::field_name)). It returns
934/// the value the package holds, so a field node records the same
935/// specification that a serialized tree finds again by its key.
936fn field_spec(
937    field: &TackOnField,
938    home: &mut FieldsHome<'_>,
939    def: &ElementDef,
940    arg_index: usize,
941    scopes: &Scopes<'_>,
942    errors: &mut Vec<MintError>,
943) -> Arc<dyn CallableSpec<Flm>> {
944    let args = argument_specs_of(&field.args, Some(&field.name), home, def, scopes, errors);
945    let syntax = MacroSpec::<Flm>::new(args.specs);
946    let key = field_key(home.package, def, field, arg_index);
947    let mut callable =
948        FlmCallable::new(syntax, Arc::clone(home.element)).with_arg_layouts(args.layouts);
949    if let Some(stamp) = home.package.provenance_for(FlmCallableType::Macro, key.as_str()) {
950        callable = callable.with_provenance(stamp);
951    }
952    home.package.insert(FlmCallableType::Macro, key.as_str(), callable);
953    let spec = home
954        .package
955        .get(FlmCallableType::Macro, &key)
956        .expect("the field's specification was just inserted");
957    Arc::clone(spec)
958}
959
960/// Builds one declared argument, the `arg_index`-th of its declaration, as a
961/// techy argument specification: its parser, and the change of parsing state
962/// its declared mode, scoped packages and state events ask for. `field`,
963/// `home`, `def` and
964/// `scopes` are as for [`argument_specs_of`].
965///
966/// The parser is the declaration's own object ([`ArgDef::kind`]), except for
967/// a tack-on argument: its fields are declarations whose specifications are
968/// built here into `home`, so the reader that absorbs them is built here from
969/// those specifications ([`tack_on_reader`]). When the declaration asks for an
970/// opaque wrapper ([`ArgDef::opaque_wrapper`]), the chosen parser is wrapped
971/// so that what it reads is placed under one ([`OpaqueWrapperReader`]). The
972/// declared mode, scoped packages and state events apply around the parser,
973/// whatever it is,
974/// as the state change of the argument's specification, so a parser of a
975/// feature's own receives them exactly as a standard kind does.
976fn argument_spec_of(
977    arg: &ArgDef,
978    arg_index: usize,
979    field: Option<&str>,
980    home: &mut FieldsHome<'_>,
981    def: &ElementDef,
982    scopes: &Scopes<'_>,
983    errors: &mut Vec<MintError>,
984) -> Arc<ArgumentSpec<Flm>> {
985    let parser: Arc<dyn ArgumentParser<Flm>> = match arg.kind.tack_on_fields() {
986        Some(fields) => Arc::new(tack_on_reader(fields, field, home, def, arg_index, scopes, errors)),
987        None => arg.kind.clone(),
988    };
989    let parser: Arc<dyn ArgumentParser<Flm>> = if arg.opaque_wrapper {
990        Arc::new(OpaqueWrapperReader::new(parser))
991    } else {
992        parser
993    };
994    let spec = match arg.name.as_deref() {
995        Some(name) => ArgumentSpec::new(parser, name),
996        None => ArgumentSpec::new_unnamed(parser),
997    };
998    let unknown = |package: &Name| MintError::UnknownScopedPackage {
999        element: def.element.name.clone(),
1000        owner: def.owner.clone(),
1001        argument: Some(arg_index),
1002        field: field.map(str::to_string),
1003        package: package.clone(),
1004    };
1005    let spec = match region_delta(arg.mode, &arg.scoped, &arg.events, &def.owner, scopes, unknown, errors) {
1006        Some(delta) => spec.with_state_delta(delta),
1007        None => spec,
1008    };
1009    Arc::new(spec)
1010}
1011
1012/// Builds the reader of a tack-on argument, the `arg_index`-th of `def` (in
1013/// the argument list of the tack-on field named `within`, when it is not
1014/// `None`): techy's tack-on reader, configured with the specification of each
1015/// of `fields`, which [`field_spec`] builds into `home`. A field whose name an
1016/// earlier field has is reported ([`MintError::FieldDeclaredTwice`]) and left
1017/// out.
1018// The minting builds this reader, not the argument's parser object: the fields'
1019// specifications are minted into the registry's fields package, and a parser object,
1020// built before any registry exists and shared across registries, cannot hold them.
1021fn tack_on_reader(
1022    fields: &[TackOnField],
1023    within: Option<&str>,
1024    home: &mut FieldsHome<'_>,
1025    def: &ElementDef,
1026    arg_index: usize,
1027    scopes: &Scopes<'_>,
1028    errors: &mut Vec<MintError>,
1029) -> TackOnFieldsArgumentParser<Flm> {
1030    let mut parser = TackOnFieldsArgumentParser::<Flm>::new(FlmCallableType::Macro);
1031    for (position, field) in fields.iter().enumerate() {
1032        if fields[..position].iter().any(|earlier| earlier.name == field.name) {
1033            errors.push(MintError::FieldDeclaredTwice {
1034                owner: def.owner.clone(),
1035                callable: def.element.name.clone(),
1036                index: arg_index,
1037                field: within.map(str::to_string),
1038                name: field.name.clone(),
1039            });
1040            continue;
1041        }
1042        let spec = field_spec(field, home, def, arg_index, scopes, errors);
1043        parser = if field.repeatable {
1044            parser.with_repeatable_field(field.name.as_str(), spec)
1045        } else {
1046            parser.with_field(field.name.as_str(), spec)
1047        };
1048    }
1049    parser
1050}
1051
1052// --- package minting ----------------------------------------------------------------
1053
1054/// The result of [`mint_packages`]: the techy packages and the fallback provider
1055/// that the language build installs, the table of registered command names,
1056/// and the problems found.
1057pub struct MintedProviders {
1058    /// The features' techy packages, in the order of the scope stack,
1059    /// outermost first: every package of weak declarations
1060    /// ([`ElementDef::weak`]), then every package of ordinary declarations,
1061    /// each part in registration order, so a later feature's package shadows
1062    /// an earlier one's and an ordinary declaration shadows every weak one. A
1063    /// feature has one package per weakness and distinct set of parsing modes
1064    /// its declarations list (see the [module documentation](self)), in the
1065    /// order these first appear.
1066    pub packages: Vec<Arc<Package<Flm>>>,
1067    /// The scoped packages, keyed by the name by which an environment body or
1068    /// an argument refers to them.
1069    pub scoped: BTreeMap<Name, Arc<Package<Flm>>>,
1070    /// The fallback provider, which resolves a command that no declaration
1071    /// defines. It always holds at least the language's own two fallbacks.
1072    pub fallback: Arc<FlmFallbackProvider>,
1073    /// The techy package holding the specifications of tack-on fields
1074    /// ([`FIELDS_PACKAGE_NAME`]). It is never on the scope stack; the language
1075    /// build lists it so that a [reading session](crate::dump::session) can
1076    /// find those specifications when it reads a serialized tree.
1077    pub fields: Arc<Package<Flm>>,
1078    /// Every command name the features' techy packages register, with the
1079    /// feature whose definition applies: the one registered last among those
1080    /// that declare the name ordinarily, or, when every declaration of the
1081    /// name is weak ([`ElementDef::weak`]), the one registered last.
1082    pub symbols: BTreeMap<Symbol, FeatureName>,
1083    /// The problems found; empty when every declaration was sound.
1084    pub errors: Vec<MintError>,
1085}
1086
1087impl fmt::Debug for MintedProviders {
1088    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1089        f.debug_struct("MintedProviders")
1090            .field("packages", &self.packages.len())
1091            .field("scoped", &self.scoped.keys().collect::<Vec<_>>())
1092            .field("fallback", &self.fallback)
1093            .field("symbols", &self.symbols.len())
1094            .field("errors", &self.errors)
1095            .finish()
1096    }
1097}
1098
1099/// One feature's definitions of one name: the parsing modes in which it
1100/// declares the name ordinarily, and those in which it declares it weakly.
1101struct Definer {
1102    owner: FeatureName,
1103    ordinary: Vec<Mode>,
1104    weak: Vec<Mode>,
1105}
1106
1107impl Definer {
1108    /// Returns whether the feature declares the name in `mode`, ordinarily
1109    /// when `weak` is false and weakly otherwise.
1110    fn defines(&self, mode: Mode, weak: bool) -> bool {
1111        if weak { self.weak.contains(&mode) } else { self.ordinary.contains(&mode) }
1112    }
1113}
1114
1115/// Returns whether `def` is weak: marked weak ([`ElementDef::weak`]) and
1116/// written in documents. A declaration with no syntax ignores the mark.
1117pub(crate) fn is_weak(def: &ElementDef) -> bool {
1118    def.weak && def.syntax.kind().is_some()
1119}
1120
1121/// The features that own the element declarations `elements`, in the order
1122/// [`mint_packages`] puts their techy packages on the scope stack: the order
1123/// of each feature's first declaration in `elements`. A later feature's
1124/// package shadows an earlier one's.
1125///
1126/// The registry's retained declarations
1127/// ([`Declarations`](crate::core::registry::Declarations)) are kept in this
1128/// order too, so that the last declaration of a name is the one in force.
1129pub(crate) fn feature_stack_order(elements: &[ElementDef]) -> Vec<FeatureName> {
1130    let mut owners: Vec<FeatureName> = Vec::new();
1131    for def in elements {
1132        if !owners.contains(&def.owner) {
1133            owners.push(def.owner.clone());
1134        }
1135    }
1136    owners
1137}
1138
1139/// Builds every techy package and the fallback provider from the features'
1140/// declarations, and reports the declarations that do not fit.
1141///
1142/// `elements`, `fallbacks`, `scoped_packages` and `overrides` are the
1143/// declarations of every feature, in registration order. `explicitly_before`
1144/// holds the pairs `(a, b)` of features such that the feature order places `a`
1145/// explicitly before `b` ([`crate::core::registry::order`]); it decides which
1146/// features may define one name without an override. `peer_scoped_packages`
1147/// lists, as (feature, name), the scoped packages each feature declared as a
1148/// peer: that feature's bodies and arguments may refer to such a package even
1149/// when no feature declares it, in which case the reference adds nothing to
1150/// the parsing state and nothing is reported here. `structural` supplies the
1151/// elements that the language's own two fallbacks carry
1152/// (`flm.unknown.macro`, `flm.unknown.environment`), and the field element
1153/// that every tack-on field's specification carries (`flm.field`).
1154///
1155/// It never fails: every problem is collected in
1156/// [`MintedProviders::errors`] as a [`MintError`], and the rest is built. The
1157/// rules (the order of the packages, how two features that define one name are
1158/// handled, the two packages kept off the scope stack) are in the [module
1159/// documentation](self).
1160///
1161/// The language build ([`build_language`](crate::lang::build_language)) calls
1162/// it with the registry's declarations. Call it directly only to build techy
1163/// packages from declarations outside a registry, as the `userdefs` feature
1164/// does for the language of its templates
1165/// ([`TemplateLanguage`](crate::lang::rewrites::userdefs::TemplateLanguage)).
1166pub fn mint_packages(
1167    elements: &[ElementDef],
1168    fallbacks: &[FallbackDef],
1169    scoped_packages: &[ScopedPackageDef],
1170    overrides: &[OverrideDef],
1171    explicitly_before: &BTreeSet<(FeatureName, FeatureName)>,
1172    peer_scoped_packages: &[(FeatureName, Name)],
1173    structural: &StructuralElements,
1174) -> MintedProviders {
1175    let mut errors = Vec::new();
1176
1177    // Scoped packages first — each after the scoped packages its bodies name —
1178    // so the environment bodies referring to them by name find them minted; then
1179    // the features' own packages, in registration order, one per weakness and
1180    // set of parsing modes a feature's declarations name. Both are minted inside
1181    // the fields package's builder, which receives the specs of every tack-on
1182    // field. A feature may need several packages because a package holds one
1183    // entry per callable form and name: a name declared once for text and once
1184    // for mathematics would otherwise keep only the later declaration, and a
1185    // package's declarations stand at one place of the scope stack, where weak
1186    // and ordinary declarations stand apart.
1187    let declared: BTreeSet<Name> = scoped_packages.iter().map(|p| p.name.clone()).collect();
1188    let peers: BTreeSet<(FeatureName, Name)> = peer_scoped_packages.iter().cloned().collect();
1189    let order = scoped_mint_order(scoped_packages, &mut errors);
1190    let owners = feature_stack_order(elements);
1191    for owner in &owners {
1192        report_redeclarations(owner, elements, &mut errors);
1193    }
1194    let mut scoped: BTreeMap<Name, Arc<Package<Flm>>> = BTreeMap::new();
1195    // Each minted package of the features, in registration order, with its
1196    // owner and whether its declarations are weak: a feature has one package
1197    // per weakness and distinct set of parsing modes its declarations name.
1198    let mut minted_packages: Vec<(FeatureName, bool, Arc<Package<Flm>>)> =
1199        Vec::with_capacity(owners.len());
1200    let fields = Package::new_shared(FIELDS_PACKAGE_NAME, |fields| {
1201        let mut home = FieldsHome { package: fields, element: &structural.field };
1202        for index in order {
1203            let package = &scoped_packages[index];
1204            let minted = Package::new_shared(package.name.as_str(), |pkg| {
1205                for def in &package.elements {
1206                    if is_weak(def) {
1207                        errors.push(MintError::WeakInScopedPackage {
1208                            owner: package.owner.clone(),
1209                            package: package.name.clone(),
1210                            element: def.element.name.clone(),
1211                        });
1212                    }
1213                    let scopes = Scopes { minted: &scoped, declared: &declared, peers: &peers };
1214                    insert_element(pkg, def, &scopes, &mut errors, &mut home);
1215                }
1216            });
1217            scoped.insert(package.name.clone(), minted);
1218        }
1219        for owner in &owners {
1220            let groups = mode_groups(owner, elements);
1221            for (position, (weak, group)) in groups.iter().enumerate() {
1222                let name = package_name(owner, position);
1223                let minted = Package::new_shared(name.as_str(), |pkg| {
1224                    for def in group {
1225                        let scopes = Scopes { minted: &scoped, declared: &declared, peers: &peers };
1226                        insert_element(pkg, def, &scopes, &mut errors, &mut home);
1227                    }
1228                });
1229                minted_packages.push((owner.clone(), *weak, minted));
1230            }
1231        }
1232    });
1233
1234    // Clash detection over the packages' own symbol enumeration, per mode.
1235    let mut symbols: BTreeMap<Symbol, FeatureName> = BTreeMap::new();
1236    let mut definers: BTreeMap<Symbol, Vec<Definer>> = BTreeMap::new();
1237    for (owner, weak, package) in &minted_packages {
1238        for &callable_type in FlmCallableType::ALL {
1239            let kind = match callable_type {
1240                FlmCallableType::Macro => CallableKind::Macro,
1241                FlmCallableType::Environment => CallableKind::Environment,
1242                FlmCallableType::Specials => CallableKind::Specials,
1243                _ => continue,
1244            };
1245            for &mode in Mode::ALL {
1246                let Some(entries) = package.iter_symbols(callable_type, mode) else {
1247                    continue;
1248                };
1249                for entry in entries {
1250                    let symbol = Symbol { kind, name: entry.name.to_string() };
1251                    let list = definers.entry(symbol).or_default();
1252                    let definer = match list.iter().position(|definer| &definer.owner == owner) {
1253                        Some(position) => &mut list[position],
1254                        None => {
1255                            list.push(Definer {
1256                                owner: owner.clone(),
1257                                ordinary: Vec::new(),
1258                                weak: Vec::new(),
1259                            });
1260                            list.last_mut().expect("just pushed")
1261                        }
1262                    };
1263                    let modes = if *weak { &mut definer.weak } else { &mut definer.ordinary };
1264                    if !modes.contains(&mode) {
1265                        modes.push(mode);
1266                    }
1267                }
1268            }
1269        }
1270    }
1271    for (symbol, definers) in &definers {
1272        // The definition that applies: the last ordinary one, or the last weak
1273        // one when every declaration of the name is weak.
1274        let applying = definers
1275            .iter()
1276            .rev()
1277            .find(|definer| !definer.ordinary.is_empty())
1278            .or_else(|| definers.last())
1279            .expect("a symbol has at least one definer");
1280        symbols.insert(symbol.clone(), applying.owner.clone());
1281        // Each parsing mode on its own: the features that define the name
1282        // ordinarily in that mode, or weakly when none does so ordinarily, and
1283        // the last of them, whose definition applies there. Only that feature's
1284        // override is consulted; the feature order allows the collision when
1285        // it places that feature explicitly after every other, since placing a
1286        // feature after another both makes its definition apply and states
1287        // that the collision is intended.
1288        for &mode in Mode::ALL {
1289            let weak = !definers.iter().any(|definer| definer.defines(mode, false));
1290            let owners_of: Vec<FeatureName> = definers
1291                .iter()
1292                .filter(|definer| definer.defines(mode, weak))
1293                .map(|definer| definer.owner.clone())
1294                .collect();
1295            let [_, .., winner] = owners_of.as_slice() else {
1296                continue;
1297            };
1298            let overridden = overrides.iter().any(|o| {
1299                o.owner == *winner && o.kind == symbol.kind && o.name.as_str() == symbol.name
1300            });
1301            let ordered = owners_of[..owners_of.len() - 1]
1302                .iter()
1303                .all(|other| explicitly_before.contains(&(other.clone(), winner.clone())));
1304            if overridden || ordered {
1305                continue;
1306            }
1307            let chains = owners_of
1308                .iter()
1309                .map(|chosen| {
1310                    owners_of
1311                        .iter()
1312                        .filter(|owner| *owner != chosen)
1313                        .chain([chosen])
1314                        .cloned()
1315                        .collect::<Vec<FeatureName>>()
1316                })
1317                .filter(|chain| agrees_with_explicit_order(chain, explicitly_before))
1318                .collect();
1319            errors.push(MintError::Clash {
1320                kind: ClashKind::Symbol,
1321                symbol: symbol.clone(),
1322                modes: vec![mode],
1323                winner: winner.clone(),
1324                owners: owners_of,
1325                chains,
1326            });
1327        }
1328    }
1329
1330    // The fallbacks: the features' first (a later one overlapping an earlier one
1331    // of the same kind is a clash and is not installed), then the language
1332    // layer's own two recovery fallbacks, each for every mode. Being last, they
1333    // are consulted only where no feature answers.
1334    let mut pending: Vec<PendingFallback> = Vec::new();
1335    for def in fallbacks {
1336        let overlapping: Vec<Mode> = Mode::ALL
1337            .iter()
1338            .copied()
1339            .filter(|mode| {
1340                def.modes.contains(mode)
1341                    && pending.iter().any(|p| p.kind == def.kind && p.modes.contains(mode))
1342            })
1343            .collect();
1344        if !overlapping.is_empty() {
1345            let mut owners_of: Vec<FeatureName> = Vec::new();
1346            for earlier in &pending {
1347                let overlaps = earlier.kind == def.kind
1348                    && earlier.modes.iter().any(|mode| overlapping.contains(mode));
1349                if overlaps && !owners_of.contains(&earlier.owner) {
1350                    owners_of.push(earlier.owner.clone());
1351                }
1352            }
1353            owners_of.push(def.owner.clone());
1354            let first = owners_of[0].clone();
1355            errors.push(MintError::Clash {
1356                kind: ClashKind::Fallback,
1357                symbol: Symbol { kind: def.kind.callable_kind(), name: def.kind.to_string() },
1358                modes: overlapping,
1359                owners: owners_of,
1360                winner: first,
1361                chains: Box::default(),
1362            });
1363            continue;
1364        }
1365        pending.push(PendingFallback {
1366            owner: def.owner.clone(),
1367            modes: def.modes.clone(),
1368            kind: def.kind,
1369            element: Arc::clone(&def.element),
1370            recovery: false,
1371        });
1372    }
1373    pending.push(PendingFallback {
1374        owner: FeatureName::from(LANGUAGE_OWNER),
1375        modes: Mode::ALL.to_vec(),
1376        kind: FallbackKind::Macro,
1377        element: Arc::clone(&structural.unknown_macro),
1378        recovery: true,
1379    });
1380    pending.push(PendingFallback {
1381        owner: FeatureName::from(LANGUAGE_OWNER),
1382        modes: Mode::ALL.to_vec(),
1383        kind: FallbackKind::Environment,
1384        element: Arc::clone(&structural.unknown_environment),
1385        recovery: true,
1386    });
1387    let fallback = Arc::new(FlmFallbackProvider::build(&pending));
1388
1389    // The scope stack's order: every package of weak declarations under every
1390    // package of ordinary declarations, each part in registration order.
1391    let (weak, ordinary): (Vec<_>, Vec<_>) =
1392        minted_packages.into_iter().partition(|(_, weak, _)| *weak);
1393    let packages = weak.into_iter().chain(ordinary).map(|(_, _, package)| package).collect();
1394
1395    MintedProviders { packages, scoped, fallback, fields, symbols, errors }
1396}
1397
1398/// Whether adding `chain` to the feature order makes no cycle: the explicit
1399/// order in force (`explicitly_before`, transitively closed) places no feature
1400/// of `chain` before a feature that comes earlier in `chain`.
1401fn agrees_with_explicit_order(
1402    chain: &[FeatureName],
1403    explicitly_before: &BTreeSet<(FeatureName, FeatureName)>,
1404) -> bool {
1405    chain.iter().enumerate().all(|(i, earlier)| {
1406        chain[i + 1..]
1407            .iter()
1408            .all(|later| !explicitly_before.contains(&(later.clone(), earlier.clone())))
1409    })
1410}
1411
1412// --- scoped package ordering ------------------------------------------------------------
1413
1414/// Returns the scoped packages the declarations of `package` refer to: in an
1415/// environment's body, and in any argument, a tack-on field's own arguments
1416/// included.
1417fn scoped_dependencies(package: &ScopedPackageDef) -> Vec<&Name> {
1418    /// Collects the packages an argument list refers to, a tack-on field's
1419    /// arguments included.
1420    fn named_by<'d>(args: &'d [ArgDef], out: &mut Vec<&'d Name>) {
1421        for arg in args {
1422            out.extend(arg.scoped.iter());
1423            if let Some(fields) = arg.kind.tack_on_fields() {
1424                for field in fields {
1425                    named_by(&field.args, out);
1426                }
1427            }
1428        }
1429    }
1430    let mut out = Vec::new();
1431    for def in &package.elements {
1432        match &def.syntax {
1433            SyntaxDef::Macro { args } | SyntaxDef::Inclusion { args } | SyntaxDef::Specials { args, .. } => named_by(args, &mut out),
1434            SyntaxDef::Environment { args, body } => {
1435                named_by(args, &mut out);
1436                out.extend(body.scoped.iter());
1437            }
1438            SyntaxDef::Synthesized => {}
1439        }
1440    }
1441    out
1442}
1443
1444#[derive(Clone, Copy, PartialEq, Eq)]
1445enum Mark {
1446    Unvisited,
1447    Open,
1448    Done,
1449}
1450
1451/// Returns the order in which the scoped packages are built: each after the
1452/// ones its declarations refer to. The traversal is depth-first and follows
1453/// declaration order, so the result is the same on every run.
1454///
1455/// A package name declared twice is reported, and only the first declaration
1456/// is built; a cycle is reported once and broken at the reference that
1457/// closes it.
1458fn scoped_mint_order(packages: &[ScopedPackageDef], errors: &mut Vec<MintError>) -> Vec<usize> {
1459    let mut by_name: BTreeMap<&Name, usize> = BTreeMap::new();
1460    for (index, package) in packages.iter().enumerate() {
1461        match by_name.get(&package.name) {
1462            Some(&first) => {
1463                let owners = vec![packages[first].owner.clone(), package.owner.clone()];
1464                errors.push(MintError::Clash {
1465                    kind: ClashKind::ScopedPackage,
1466                    symbol: Symbol { kind: CallableKind::Macro, name: package.name.to_string() },
1467                    modes: Vec::new(),
1468                    winner: owners[0].clone(),
1469                    owners,
1470                    chains: Box::default(),
1471                });
1472            }
1473            None => {
1474                by_name.insert(&package.name, index);
1475            }
1476        }
1477    }
1478    let mut marks = vec![Mark::Unvisited; packages.len()];
1479    let mut order = Vec::with_capacity(packages.len());
1480    let mut path = Vec::new();
1481    for index in 0..packages.len() {
1482        if by_name.get(&packages[index].name) == Some(&index) {
1483            visit_scoped(index, packages, &by_name, &mut marks, &mut path, &mut order, errors);
1484        }
1485    }
1486    order
1487}
1488
1489/// One step of that ordering: visits the packages this one refers to, then
1490/// places it.
1491fn visit_scoped(
1492    index: usize,
1493    packages: &[ScopedPackageDef],
1494    by_name: &BTreeMap<&Name, usize>,
1495    marks: &mut [Mark],
1496    path: &mut Vec<usize>,
1497    order: &mut Vec<usize>,
1498    errors: &mut Vec<MintError>,
1499) {
1500    match marks[index] {
1501        Mark::Done => return,
1502        Mark::Open => {
1503            let start = path.iter().position(|&open| open == index).unwrap_or(0);
1504            let cycle = path[start..].iter().map(|&open| packages[open].name.clone()).collect();
1505            errors.push(MintError::ScopedPackageCycle { packages: cycle });
1506            return;
1507        }
1508        Mark::Unvisited => {}
1509    }
1510    marks[index] = Mark::Open;
1511    path.push(index);
1512    for name in scoped_dependencies(&packages[index]) {
1513        if let Some(&dependency) = by_name.get(name) {
1514            visit_scoped(dependency, packages, by_name, marks, path, order, errors);
1515        }
1516    }
1517    path.pop();
1518    marks[index] = Mark::Done;
1519    order.push(index);
1520}
1521
1522// --- a feature's packages ---------------------------------------------------------------
1523
1524/// Returns the parsing modes a declaration is available in
1525/// ([`ElementDef::modes`]), as positions in [`Mode::ALL`].
1526fn visible_modes(def: &ElementDef) -> Vec<usize> {
1527    (0..Mode::ALL.len()).filter(|index| def.modes.contains(&Mode::ALL[*index])).collect()
1528}
1529
1530/// Returns the command names one declaration registers, as symbols: the
1531/// declaration's names for a macro or an environment, the trigger for a
1532/// special character sequence, nothing for an element with no syntax.
1533fn declared_symbols(def: &ElementDef) -> Vec<Symbol> {
1534    let Some(kind) = def.syntax.kind() else { return Vec::new() };
1535    match &def.syntax {
1536        SyntaxDef::Specials { trigger, .. } => {
1537            vec![Symbol { kind, name: trigger.clone() }]
1538        }
1539        _ => def
1540            .names
1541            .iter()
1542            .map(|name| Symbol { kind, name: name.to_string() })
1543            .collect(),
1544    }
1545}
1546
1547/// Reports every name `owner` declares twice in parsing modes that overlap.
1548/// Both declarations of such a pair cannot apply where the modes overlap; a
1549/// pair whose modes are disjoint is sound and is built into two packages
1550/// ([`mode_groups`]).
1551fn report_redeclarations(
1552    owner: &FeatureName,
1553    elements: &[ElementDef],
1554    errors: &mut Vec<MintError>,
1555) {
1556    let mut seen: Vec<(Symbol, Vec<usize>)> = Vec::new();
1557    for def in elements.iter().filter(|def| &def.owner == owner) {
1558        let modes = visible_modes(def);
1559        for symbol in declared_symbols(def) {
1560            match seen.iter_mut().find(|(earlier, _)| earlier == &symbol) {
1561                Some((_, earlier_modes)) => {
1562                    let overlapping: Vec<Mode> = modes
1563                        .iter()
1564                        .filter(|index| earlier_modes.contains(index))
1565                        .map(|index| Mode::ALL[*index])
1566                        .collect();
1567                    if !overlapping.is_empty() {
1568                        errors.push(MintError::Redeclared {
1569                            symbol: symbol.clone(),
1570                            owner: owner.clone(),
1571                            modes: overlapping,
1572                        });
1573                    }
1574                    for index in &modes {
1575                        if !earlier_modes.contains(index) {
1576                            earlier_modes.push(*index);
1577                        }
1578                    }
1579                }
1580                None => seen.push((symbol, modes.clone())),
1581            }
1582        }
1583    }
1584}
1585
1586/// Returns the declarations of `owner`, grouped by weakness ([`is_weak`])
1587/// and by the set of parsing modes they list, in the order the groups first
1588/// appear, each with its weakness. Each group becomes one package, and the
1589/// first group's package has the feature's own name ([`package_name`]).
1590///
1591/// Two declarations that list the same modes in a different order, or one
1592/// mode twice, are grouped together.
1593fn mode_groups<'e>(
1594    owner: &FeatureName,
1595    elements: &'e [ElementDef],
1596) -> Vec<(bool, Vec<&'e ElementDef>)> {
1597    let mut keys: Vec<(bool, Vec<usize>)> = Vec::new();
1598    let mut groups: Vec<(bool, Vec<&ElementDef>)> = Vec::new();
1599    for def in elements.iter().filter(|def| &def.owner == owner) {
1600        let key = (is_weak(def), visible_modes(def));
1601        match keys.iter().position(|seen| seen == &key) {
1602            Some(position) => groups[position].1.push(def),
1603            None => {
1604                groups.push((key.0, vec![def]));
1605                keys.push(key);
1606            }
1607        }
1608    }
1609    groups
1610}
1611
1612/// Returns the name of a feature's package at `position` among its packages:
1613/// the feature's own name for the first, which is the only one a feature with
1614/// one set of parsing modes has, and `<feature>#<n>` for the rest, with `n`
1615/// counting from 2.
1616///
1617/// The names must differ, because a serialized tree records the name of the
1618/// package a specification came from and is read back by that name.
1619fn package_name(owner: &FeatureName, position: usize) -> String {
1620    match position {
1621        0 => owner.to_string(),
1622        other => format!("{owner}#{}", other + 1),
1623    }
1624}
1625
1626// --- element insertion ------------------------------------------------------------------
1627
1628/// Builds one element declaration into `pkg`, one specification per name it is
1629/// written under. `fields` is the fields package, which receives the
1630/// specifications of its tack-on fields ([`FieldsHome`]).
1631fn insert_element(
1632    pkg: &mut Package<Flm>,
1633    def: &ElementDef,
1634    scopes: &Scopes<'_>,
1635    errors: &mut Vec<MintError>,
1636    fields: &mut FieldsHome<'_>,
1637) {
1638    match &def.syntax {
1639        SyntaxDef::Macro { args } => {
1640            let args = argument_specs_of(args, None, fields, def, scopes, errors);
1641            let syntax: Arc<dyn CallableSpec<Flm>> = Arc::new(MacroSpec::<Flm>::new(args.specs));
1642            insert_callables(pkg, def, CallableKind::Macro, &syntax, &args.layouts, errors);
1643        }
1644        SyntaxDef::Inclusion { args } => {
1645            let args = argument_specs_of(args, None, fields, def, scopes, errors);
1646            match InputSpec::new(args.specs) {
1647                Ok(spec) => {
1648                    let syntax: Arc<dyn CallableSpec<Flm>> = Arc::new(spec);
1649                    insert_callables(pkg, def, CallableKind::Macro, &syntax, &args.layouts, errors);
1650                }
1651                Err(detail) => errors.push(MintError::NoReferenceArgument {
1652                    owner: def.owner.clone(),
1653                    element: def.element.name.clone(),
1654                    detail,
1655                }),
1656            }
1657        }
1658        SyntaxDef::Specials { trigger, args } => {
1659            let args = argument_specs_of(args, None, fields, def, scopes, errors);
1660            let syntax: Arc<dyn CallableSpec<Flm>> =
1661                Arc::new(SpecialsSpec::<Flm>::new(args.specs));
1662            insert_specials(pkg, def, trigger, &syntax, &args.layouts, errors);
1663        }
1664        SyntaxDef::Environment { args, body } => {
1665            let args = argument_specs_of(args, None, fields, def, scopes, errors);
1666            let environment =
1667                FlmEnvironment::new(args.specs, Arc::clone(&def.element), body.clone())
1668                    .with_arg_layouts(args.layouts);
1669            insert_environment(pkg, def, environment, body, scopes, errors);
1670        }
1671        SyntaxDef::Synthesized => {
1672            if !def.names.is_empty() {
1673                errors.push(MintError::SynthesizedWithNames {
1674                    owner: def.owner.clone(),
1675                    element: def.element.name.clone(),
1676                });
1677            }
1678        }
1679    }
1680}
1681
1682/// Inserts a macro specification under each of the declaration's names,
1683/// restricted to its parsing modes, recording the layouts of its arguments.
1684fn insert_callables(
1685    pkg: &mut Package<Flm>,
1686    def: &ElementDef,
1687    kind: CallableKind,
1688    syntax: &Arc<dyn CallableSpec<Flm>>,
1689    layouts: &[ArgLayout],
1690    errors: &mut Vec<MintError>,
1691) {
1692    if def.names.is_empty() {
1693        errors.push(no_names(def));
1694        return;
1695    }
1696    let callable_type = kind.callable_type();
1697    for name in &def.names {
1698        let mut callable = FlmCallable::new(Arc::clone(syntax), Arc::clone(&def.element))
1699            .with_arg_layouts(layouts.to_vec());
1700        if let Some(provenance) = pkg.provenance_for(callable_type, name.as_str()) {
1701            callable = callable.with_provenance(provenance);
1702        }
1703        insert_in_modes(pkg, callable_type, name, callable, def);
1704    }
1705}
1706
1707/// Inserts a special-character-sequence specification under the declaration's
1708/// trigger, restricted to its parsing modes, recording the layouts of its
1709/// arguments.
1710fn insert_specials(
1711    pkg: &mut Package<Flm>,
1712    def: &ElementDef,
1713    trigger: &str,
1714    syntax: &Arc<dyn CallableSpec<Flm>>,
1715    layouts: &[ArgLayout],
1716    errors: &mut Vec<MintError>,
1717) {
1718    if !def.names.is_empty() {
1719        errors.push(MintError::SpecialsWithNames {
1720            owner: def.owner.clone(),
1721            trigger: trigger.to_string(),
1722        });
1723    }
1724    let mut callable = FlmCallable::new(Arc::clone(syntax), Arc::clone(&def.element))
1725        .with_arg_layouts(layouts.to_vec());
1726    if let Some(provenance) = pkg.provenance_for_specials(FlmCallableType::Specials, trigger) {
1727        callable = callable.with_provenance(provenance);
1728    }
1729    pkg.insert_specials_in_modes(FlmCallableType::Specials, trigger, callable, Some(def.modes.clone()));
1730}
1731
1732/// Inserts an environment under each of the declaration's names, with the change
1733/// of parsing state its body declaration asks for.
1734fn insert_environment(
1735    pkg: &mut Package<Flm>,
1736    def: &ElementDef,
1737    mut environment: FlmEnvironment,
1738    body: &BodyDef,
1739    scopes: &Scopes<'_>,
1740    errors: &mut Vec<MintError>,
1741) {
1742    if def.names.is_empty() {
1743        errors.push(no_names(def));
1744        return;
1745    }
1746    if body.opaque_wrapper && body.layout != BodyLayout::FromRole {
1747        errors.push(MintError::LayoutOnOpaqueWrappedBody {
1748            owner: def.owner.clone(),
1749            element: def.element.name.clone(),
1750        });
1751    }
1752    let unknown = |package: &Name| MintError::UnknownScopedPackage {
1753        element: def.element.name.clone(),
1754        owner: def.owner.clone(),
1755        argument: None,
1756        field: None,
1757        package: package.clone(),
1758    };
1759    if let Some(delta) = region_delta(body.mode, &body.scoped, &body.events, &def.owner, scopes, unknown, errors) {
1760        environment = environment.with_body_delta(delta);
1761    }
1762    let spec = environment.into_spec();
1763    for name in &def.names {
1764        let stamped = match pkg.provenance_for(FlmCallableType::Environment, name.as_str()) {
1765            Some(provenance) => spec.clone().with_provenance(provenance),
1766            None => spec.clone(),
1767        };
1768        insert_in_modes(pkg, FlmCallableType::Environment, name, stamped, def);
1769    }
1770}
1771
1772/// Returns the error for a macro or environment declaration that lists no
1773/// name.
1774fn no_names(def: &ElementDef) -> MintError {
1775    MintError::NoNames { owner: def.owner.clone(), element: def.element.name.clone() }
1776}
1777
1778/// Inserts a specification under one name, restricted to the declaration's
1779/// parsing modes.
1780fn insert_in_modes<M>(
1781    pkg: &mut Package<Flm>,
1782    callable_type: FlmCallableType,
1783    name: &Name,
1784    spec: impl techy::core::specs::IntoCallableSpec<Flm, M>,
1785    def: &ElementDef,
1786) {
1787    pkg.insert_in_modes(callable_type, name.as_str(), spec, Some(def.modes.clone()));
1788}
1789
1790/// Returns the change of parsing state a declared parsing mode asks for, or
1791/// `None` when the declaration keeps the mode of the place where the command
1792/// is written.
1793///
1794/// This is the only place where a declared mode becomes a change of parsing
1795/// state, for an argument ([`ArgDef::mode`]) and for an environment's body
1796/// ([`BodyDef::mode`]) alike, through [`region_delta`]. `Math` enters
1797/// mathematics; `Text` carries the event [`FlmEvent::ExitMathContext`], which
1798/// restores the innermost enclosing non-mathematics context, with its mode and
1799/// its token rules. That change makes `\text{…}`
1800/// inside mathematics hold ordinary document content, and changes nothing
1801/// outside mathematics. The events a declaration lists of its own
1802/// ([`ArgDef::events`], [`BodyDef::events`]) are added after this one by
1803/// [`region_delta`].
1804fn mode_delta(mode: Option<Mode>) -> Option<ParsingStateDelta<Flm>> {
1805    match mode {
1806        Some(Mode::Math) => Some(ParsingStateDelta::new().mode(Mode::Math)),
1807        Some(Mode::Text) => Some(ParsingStateDelta::new().event(FlmEvent::ExitMathContext)),
1808        _ => None,
1809    }
1810}
1811
1812/// Returns the change of parsing state that the declaration of an
1813/// environment's body ([`BodyDef`]) or of an argument ([`ArgDef`]) asks for:
1814/// the mode it enters, the scoped packages it adds to the scope stack, in
1815/// the order they are listed, and its state events (`events`), in the order
1816/// they are listed, after the event of the mode ([`mode_delta`]). Returns
1817/// `None` when the declaration asks for no change.
1818///
1819/// techy applies what the events resolve to before the mode and the scoped
1820/// packages, so one declaration can ask for the standard state, in
1821/// mathematics, with a scoped package of its own.
1822///
1823/// A scoped package that is declared but not yet built (one caught in a
1824/// cycle, which is reported separately) is skipped without a second report.
1825/// So is a package that no feature declares and that `owner`, the feature
1826/// whose declaration refers to it, declared as a peer; the registry build
1827/// reports that one. Any other package that no feature declares is reported
1828/// with the error `unknown` builds.
1829fn region_delta(
1830    mode: Option<Mode>,
1831    packages: &[Name],
1832    events: &[FlmEvent],
1833    owner: &FeatureName,
1834    scopes: &Scopes<'_>,
1835    unknown: impl Fn(&Name) -> MintError,
1836    errors: &mut Vec<MintError>,
1837) -> Option<ParsingStateDelta<Flm>> {
1838    let mut delta = mode_delta(mode).unwrap_or_default();
1839    let mut any = mode.is_some() || !events.is_empty();
1840    for event in events {
1841        delta = delta.event(event.clone());
1842    }
1843    for name in packages {
1844        match scopes.minted.get(name) {
1845            Some(package) => {
1846                let provider: Arc<dyn SpecsProvider<Flm>> = package.clone();
1847                delta = delta.push_provider(provider);
1848                any = true;
1849            }
1850            None if scopes.declared.contains(name) => {}
1851            None if scopes.peers.contains(&(owner.clone(), name.clone())) => {}
1852            None => errors.push(unknown(name)),
1853        }
1854    }
1855    any.then_some(delta)
1856}