flm-core 0.7.0

FLM semantic markup framework — core library, built on techy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Building the language that every parse of a document runs under:
//! [`build_language`], its inputs ([`LangInputs`]) and its result
//! ([`BuiltLang`]).
//!
//! The registry collects what every [feature](crate::core::registry::FlmFeature)
//! declares and passes it to [`build_language`] as [`LangInputs`].
//! [`build_language`] turns the inputs into a [`BuiltLang`]: one techy
//! `Language` value, the parsing state every parse starts from, and the
//! providers and elements that state refers to. Everything a parse needs is decided here, once;
//! [`crate::lang::parse`] only runs it. A registry holds its built language
//! ([`FlmRegistry::lang`](crate::core::registry::FlmRegistry::lang)); a test or a
//! program that needs a language without a registry calls [`build_language`]
//! directly.
//!
//! # What the build does
//!
//! 1. **Builds the packages.** [Minting](crate::lang::mint) builds techy
//!    packages and specifications from the declarations: one package per
//!    declaring feature, per weakness of its declarations
//!    ([`ElementDef::weak`]) and per set of parsing modes they are available
//!    in, the scoped packages, the package holding the fallback
//!    specifications, and the package holding the specifications of the field
//!    macros (such as `\label`) that a tack-on argument absorbs. A tack-on
//!    argument is the argument of a construct that absorbs the field macros
//!    written at its position in a call, after the arguments declared before
//!    it (see [fields: data a construct
//!    reads](crate::guide::concepts_overview#fields-data-a-construct-reads)).
//! 2. **Derives the parsing state every parse starts from**
//!    ([`BuiltLang::initial_state`]) in one step from the language's initial
//!    parsing state (techy's `ParsingState::lang_initial`, built from
//!    [`Flm::initial_state_data`](crate::techy::core::Lang::initial_state_data)):
//!    the changes to the tokenizer rules that the parsing settings
//!    ([`FlmParsing`]) ask for, a state extension holding the registry's
//!    [structural elements](crate::lang::structural) and the parsing settings,
//!    and a new scope stack holding, outermost first, the fallback provider
//!    ([`FlmFallbackProvider`], which resolves every name no declaration
//!    defines), techy's built-in package that handles `\begin` and `\end`, the
//!    features' packages of weak declarations in registration order, and the
//!    features' packages of ordinary declarations in registration order.
//! 3. **Builds the driver** ([`FlmDriver`]) and installs the [recursion
//!    guard](crate::lang::guard) of the policy that the inputs specify
//!    ([`LangInputs::guard`]).
//!
//! The fallback provider is at the bottom of the scope stack, so every defined
//! name takes precedence over it. Below every fallback a feature declares, the
//! provider holds the language's own two fallbacks: one for an unknown macro and one for
//! an unknown environment. Every name therefore resolves, in every parsing mode,
//! to a specification that minting built, and every node receives an element.
//!
//! # Errors are collected, never fatal
//!
//! [`build_language`] always returns a [`BuiltLang`]. Each problem in the
//! declarations (two features defining one name, an environment referring to a
//! scoped package nobody declared, a state that could not be derived) is
//! collected into [`BuiltLang::errors`] as a [`LangBuildError`], and the
//! language is built from the declarations that have no problem. The caller
//! decides whether to proceed; [`BuiltLang::is_sound`] tells whether there was
//! any problem.
//!
//! # Parsing from a state of one's own
//!
//! The built language keeps the parts a program needs to build a state of its
//! own for a parse: [`BuiltLang::base_scope`], the entries every scope stack
//! keeps, and [`BuiltLang::scoped_package`], the package of a scoped package by
//! its name. A state derived with [`BuiltLang::derive_state`] is passed to
//! [`parse_fragment_with_state`](crate::lang::parse_fragment_with_state) or to
//! [`assemble_with_state`](crate::model::assemble::assemble_with_state).

use std::any::Any;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::{Arc, Mutex};

use techy::core::specs::{ScopeOp, SpecsProvider};
use techy::core::{DeriveError, Language, ParsingState, ParsingStateDelta};
use techy::error::Recovery;

use crate::model::names::{FeatureName, Name};
use crate::lang::driver::FlmDriver;
use crate::lang::ext::FlmStateExt;
use crate::lang::flm::Flm;
use crate::lang::input::{InputResolver, Placements};
use crate::lang::guard::{self, GuardPolicy};
use crate::lang::mint::{
    mint_packages, ElementDef, FallbackDef, FlmFallbackProvider, MintError, OverrideDef,
    ScopedPackageDef, Symbol,
};
use crate::lang::rules::FlmParsing;
use crate::lang::structural::StructuralElements;

/// Everything [`build_language`] takes: the declarations of every feature, and
/// the settings that apply to every parse.
///
/// The registry fills this in. A test or a program that builds a language
/// without a registry starts from [`LangInputs::new`] and adds declarations to
/// the vectors.
pub struct LangInputs {
    /// The features' element declarations: each element with the syntax it is
    /// written in, in registration order. Where two features define the same
    /// name in one parsing mode, the later feature's package takes precedence
    /// among the ordinary declarations of the name in that mode, or among its
    /// weak ones ([`ElementDef::weak`]) where it has no ordinary one; the
    /// weak ones play no part where an ordinary one exists. Two definitions
    /// that decide in one mode are also reported as a [`LangBuildError::Mint`]
    /// unless the later feature is explicitly after the other
    /// ([`explicitly_before`](Self::explicitly_before)) or its override
    /// declares the redefinition ([`overrides`](Self::overrides)). The
    /// [module documentation of `packages`](crate::lang::mint::packages)
    /// states the rule.
    pub elements: Vec<ElementDef>,
    /// The features' fallbacks: policies for callables that no declaration
    /// defines, each limited to the parsing modes it applies in.
    pub fallbacks: Vec<FallbackDef>,
    /// The [scoped packages](crate::lang::mint::ScopedPackageDef): sets of
    /// element declarations that can be written only inside the environment
    /// bodies and the arguments whose declarations refer to them.
    pub scoped_packages: Vec<ScopedPackageDef>,
    /// The scoped packages that a feature expects another feature to declare,
    /// as pairs (the expecting feature, the package's name). Each pair is a
    /// [peer declaration](crate::core::registry::PeerName) of a scoped package.
    ///
    /// A body or an argument of the expecting feature's declarations may refer
    /// to such a package when no feature declares it: the reference then makes
    /// no command available, and it is not a
    /// [`MintError::UnknownScopedPackage`]. When some feature does declare the
    /// package, the pair has no effect. A registry fills this from its
    /// features' peer declarations and reports each one that no feature
    /// declares.
    pub peer_scoped_packages: Vec<(FeatureName, Name)>,
    /// The explicit redefinitions of a name another feature defines. Without
    /// one, two features defining the same name in one parsing mode is an
    /// error that identifies both features, unless
    /// [`explicitly_before`](Self::explicitly_before) places the feature
    /// registered last after the others. The features concerned are those
    /// that declare the name ordinarily in the mode, or weakly where none
    /// declares it ordinarily. Only the override of the feature registered
    /// last among them is consulted, in that mode; an override never makes a
    /// weak declaration apply over an ordinary one.
    pub overrides: Vec<OverrideDef>,
    /// The pairs `(a, b)` of features such that the feature order places `a`
    /// explicitly before `b` ([`crate::core::registry::order`]). Where features
    /// define one name in one parsing mode (ordinarily, or weakly where none
    /// defines it ordinarily), the definition of the feature registered last
    /// among them applies there without an error when every other of those
    /// features is explicitly before it ([`crate::lang::mint::packages`]); no
    /// pair makes a weak declaration apply over an ordinary one. The registry
    /// fills this from the chains of its feature order; it is empty by
    /// default.
    pub explicitly_before: BTreeSet<(FeatureName, FeatureName)>,
    /// The document's parsing settings: comment recognition, the comment
    /// prefix, and whether `$` delimits mathematics.
    pub parsing: FlmParsing,
    /// The structural elements: the registry's set, with the aspects the
    /// features attached to them.
    pub structural: Arc<StructuralElements>,
    /// The recursion-guard policy of every parse: the stack budget for normal
    /// use, a limit on open descents for tests ([`GuardPolicy`]).
    pub guard: GuardPolicy,
    /// How many diagnostics a parse keeps; `None` keeps techy's own default. One
    /// parse may set another cap through
    /// [`ParseOptions`](crate::lang::ParseOptions).
    pub diagnostics_limit: Option<usize>,
    /// The input resolver: the object, supplied by the embedding program, that
    /// finds and reads the file an `\input` command refers to
    /// ([`crate::lang::input`]). The library performs no input or output of its
    /// own; with `None`, `\input` includes no file and is reported.
    pub input_resolver: Option<Arc<dyn InputResolver>>,
}

impl LangInputs {
    /// Returns inputs with nothing declared: the default parsing settings, the
    /// default structural elements, the stack-budget guard, no cap on
    /// diagnostics of their own, and no input resolver.
    ///
    /// A language built from these recognizes FLM's own structure (text,
    /// comments, groups, mathematics) and no command of any feature.
    pub fn new() -> LangInputs {
        LangInputs {
            elements: Vec::new(),
            fallbacks: Vec::new(),
            scoped_packages: Vec::new(),
            peer_scoped_packages: Vec::new(),
            overrides: Vec::new(),
            explicitly_before: BTreeSet::new(),
            parsing: FlmParsing::default(),
            structural: Arc::new(StructuralElements::default()),
            guard: GuardPolicy::StackBudget,
            diagnostics_limit: None,
            input_resolver: None,
        }
    }
}

impl Default for LangInputs {
    fn default() -> LangInputs {
        LangInputs::new()
    }
}

impl fmt::Debug for LangInputs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LangInputs")
            .field("elements", &self.elements.len())
            .field("fallbacks", &self.fallbacks.len())
            .field("scoped_packages", &self.scoped_packages.len())
            .field("peer_scoped_packages", &self.peer_scoped_packages)
            .field("overrides", &self.overrides)
            .field("explicitly_before", &self.explicitly_before)
            .field("parsing", &self.parsing)
            .field("guard", &self.guard)
            .field("diagnostics_limit", &self.diagnostics_limit)
            .finish_non_exhaustive()
    }
}

/// A problem the language build found in its inputs. Problems are collected in
/// [`BuiltLang::errors`] and never stop the build: see the [module
/// documentation](self#errors-are-collected-never-fatal).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LangBuildError {
    /// Minting could not build every declaration: for example, two features
    /// define one name without an override, or a body or an argument refers to
    /// a scoped package that nobody declared and its feature did not declare as
    /// a peer. [`MintError`] lists every case.
    Mint(MintError),
    /// The parsing state every parse starts from could not be derived exactly
    /// as the inputs asked. The language was built from the state techy recovered, without
    /// the scope changes that failed.
    State {
        /// techy's description of what failed.
        detail: String,
    },
}

impl fmt::Display for LangBuildError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LangBuildError::Mint(error) => fmt::Display::fmt(error, f),
            LangBuildError::State { detail } => {
                write!(f, "the initial parsing state could not be derived: {detail}")
            }
        }
    }
}

impl std::error::Error for LangBuildError {}

/// A built language: what every parse of a document under one registry runs
/// under.
///
/// It holds the techy `Language` value, the parsing state every parse of a
/// document starts from, the providers and the structural elements that
/// state refers to, the scoped packages ([`BuiltLang::scoped_package`]) and
/// the base scope ([`BuiltLang::base_scope`]) from which a program builds a
/// state of its own, the table of every registered callable name, and the
/// problems the build collected. Pass it to
/// [`parse_fragment`](crate::lang::parse_fragment).
///
/// [`build_language`] creates it; a registry holds its own
/// ([`FlmRegistry::lang`](crate::core::registry::FlmRegistry::lang)). A
/// `BuiltLang` never changes after it is built.
pub struct BuiltLang {
    language: Language<Flm>,
    initial_state: Arc<ParsingState<Flm>>,
    providers: Vec<Arc<dyn SpecsProvider<Flm>>>,
    base_scope: Vec<Arc<dyn SpecsProvider<Flm>>>,
    scoped: BTreeMap<Name, Arc<dyn SpecsProvider<Flm>>>,
    fallback: Arc<FlmFallbackProvider>,
    structural: Arc<StructuralElements>,
    symbols: BTreeMap<Symbol, FeatureName>,
    errors: Vec<LangBuildError>,
    parsing: FlmParsing,
    guard: GuardPolicy,
    driver: FlmDriver,
    /// The values built against this language for its elements, which read
    /// them through a [`LangOwned`](super::LangOwned) cell. They are freed
    /// with the language.
    owned: Mutex<Vec<Arc<dyn Any + Send + Sync>>>,
}

impl BuiltLang {
    /// Makes this language the owner of `value`, the value of a
    /// [`LangOwned`](super::LangOwned) cell.
    pub(super) fn own(&self, value: Arc<dyn Any + Send + Sync>) {
        self.owned.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push(value);
    }

    /// Returns the techy language value: the driver, the initial state and the
    /// recursion guard, ready to parse.
    pub fn language(&self) -> &Language<Flm> {
        &self.language
    }

    /// Returns the parsing state every parse of a document starts from, which
    /// [`build_language`] derived from the language's initial parsing state
    /// (techy's `ParsingState::lang_initial`). To parse under other conditions, derive a state from it with
    /// [`BuiltLang::derive_state`].
    pub fn initial_state(&self) -> &Arc<ParsingState<Flm>> {
        &self.initial_state
    }

    /// Returns every provider of specifications that minting built, in one
    /// list: the fallback provider; the package holding the fallback
    /// specifications, which the fallback specifications' provenance stamps
    /// (the record of the package that holds a specification, used to
    /// serialize it by identity; see [`crate::lang::serialize`]) refer to; the
    /// package holding the specifications of the field macros that tack-on
    /// arguments absorb
    /// ([`ArgStdKind::TackOn`](crate::lang::mint::ArgStdKind::TackOn)); the
    /// declaring features' packages (one per feature, per weakness of its
    /// declarations and per set of parsing modes they are available in), in
    /// the order of the scope stack: every package of weak declarations
    /// ([`ElementDef::weak`]), then every package of ordinary declarations,
    /// each part in registration order; and the scoped packages.
    ///
    /// A [reading session](crate::dump::session) needs this list to rebuild a
    /// serialized parse, in which a specification is referred to by identity and
    /// looked up in the package it came from. techy's built-in package that
    /// handles `\begin` and `\end` is not in the list; it is reachable through
    /// the initial state's scope stack and through [`BuiltLang::base_scope`].
    /// A scoped package is in the list under its declared name, which can
    /// also be the name of a feature's package; [`BuiltLang::scoped_package`]
    /// finds a scoped package by its name.
    pub fn providers(&self) -> &[Arc<dyn SpecsProvider<Flm>>] {
        &self.providers
    }

    /// Returns the techy package of the [scoped
    /// package](crate::lang::mint::ScopedPackageDef) declared under `name`, or
    /// `None` when no feature declares a scoped package of that name. The
    /// package of a feature is not a scoped package: its name gives `None`.
    ///
    /// A program adds the package to a state with
    /// `derive_state(&ParsingStateDelta::new().push_provider(package))`
    /// ([`BuiltLang::derive_state`]), so that the names it declares resolve in
    /// the parse that starts from that state, or puts it in a scope stack of
    /// its own (see [`BuiltLang::base_scope`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
    /// use flm_core::stdlib::features::lists;
    /// use flm_core::stdlib::{self, StdlibConfig};
    /// use flm_core::techy::core::ParsingStateDelta;
    ///
    /// let mut builder = RegistryBuilder::new();
    /// builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
    /// let registry = builder.build(&RegistryInputs::new())?;
    /// let lang = registry.lang();
    ///
    /// // The package that defines `\item`, added to a state of the program's own.
    /// let items = lang.scoped_package(lists::PACKAGE).expect("declared by the lists feature");
    /// let state = lang.derive_state(&ParsingStateDelta::new().push_provider(items))?;
    /// assert!(state.scopes().providers().iter().any(|p| p.name() == lists::PACKAGE));
    /// let standard = lang.initial_state().scopes().providers();
    /// assert!(!standard.iter().any(|p| p.name() == lists::PACKAGE));
    ///
    /// // A name under which no feature declares a scoped package.
    /// assert!(lang.scoped_package("no.such.package").is_none());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn scoped_package(&self, name: &str) -> Option<Arc<dyn SpecsProvider<Flm>>> {
        self.scoped.get(name).cloned()
    }

    /// Returns the entries that every scope stack keeps, outermost first: the
    /// fallback provider ([`BuiltLang::fallback`]), then techy's built-in
    /// package that handles `\begin` and `\end`. The standard stack
    /// (`lang.initial_state().scopes().providers()`) is these entries followed
    /// by the features' packages of weak declarations
    /// ([`ElementDef::weak`]), in registration order, then the features'
    /// packages of ordinary declarations, in registration order.
    ///
    /// A program builds a reduced scope stack of its own from them, for
    /// instance followed by one [scoped package](BuiltLang::scoped_package),
    /// and installs it with a scope operation (techy's
    /// `ScopeOp::ReplaceStack`) in a state derived with
    /// [`BuiltLang::derive_state`]. A parse from that state
    /// ([`parse_fragment_with_state`](crate::lang::parse_fragment_with_state),
    /// [`assemble_with_state`](crate::model::assemble::assemble_with_state))
    /// then follows these rules:
    ///
    /// - text, groups, comments, mathematics delimiters and paragraph breaks
    ///   are rules of the tokenizer, not packages, and stay available;
    /// - a command that no package of the stack defines is reported as unknown;
    /// - `\input` is declared by a feature (the standard feature
    ///   [`input`](crate::stdlib::features::input)), so a reduced stack hides it
    ///   unless a scoped package of the stack declares an inclusion macro;
    /// - an argument and an environment's body are read in the scope that
    ///   applies at their command, or in the scope of the standard state when
    ///   their declaration carries an event that restores it
    ///   ([`FlmEvent`](crate::lang::FlmEvent), declared with
    ///   [`ArgDef::event`](crate::lang::mint::ArgDef::event) and
    ///   [`BodyDef::event`](crate::lang::mint::BodyDef::event)), with the
    ///   scoped packages that their declaration names added
    ///   ([`ArgDef::scoped`](crate::lang::mint::ArgDef::scoped),
    ///   [`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped));
    /// - `\begin{name}` needs groups to be enabled in the state's rules.
    ///
    /// # Examples
    ///
    /// ```
    /// use flm_core::lang::{build_language, LangInputs};
    /// use flm_core::techy::core::specs::ScopeOp;
    /// use flm_core::techy::core::ParsingStateDelta;
    ///
    /// let lang = build_language(LangInputs::new());
    /// // The base scope opens the standard stack.
    /// let standard = lang.initial_state().scopes().providers();
    /// assert_eq!(lang.base_scope().len(), 2);
    /// assert!(lang.base_scope().iter().zip(standard).all(|(a, b)| a.name() == b.name()));
    ///
    /// // A state whose stack holds the base scope alone.
    /// let stack = ScopeOp::ReplaceStack(lang.base_scope().to_vec());
    /// let reduced = lang
    ///     .derive_state(&ParsingStateDelta::new().scope_op(stack))
    ///     .expect("a stack replacement applies outside a parse");
    /// assert_eq!(reduced.scopes().providers().len(), 2);
    /// ```
    pub fn base_scope(&self) -> &[Arc<dyn SpecsProvider<Flm>>] {
        &self.base_scope
    }

    /// Returns the fallback provider: the provider at the bottom of the scope
    /// stack that resolves a callable no declaration defines, applying each
    /// feature's fallback in the parsing modes that fallback declares. The
    /// specifications it returns are held in its own package
    /// ([`FlmFallbackProvider::package`]).
    pub fn fallback(&self) -> &Arc<FlmFallbackProvider> {
        &self.fallback
    }

    /// Returns the structural elements of this language: the elements of every
    /// node shape no feature declares. The initial state's extension holds the
    /// same set.
    pub fn structural(&self) -> &Arc<StructuralElements> {
        &self.structural
    }

    /// Returns every callable name the features' packages register, with the
    /// feature whose definition applies: the last registered among those that
    /// declare the name ordinarily, since a later feature's package takes
    /// precedence over an earlier one's and an ordinary declaration over a
    /// weak one ([`ElementDef::weak`]); the last registered when every
    /// declaration of the name is weak. A name that two features define in
    /// parsing modes that do not overlap is listed once, under the feature
    /// these rules give over all its modes.
    pub fn symbols(&self) -> &BTreeMap<Symbol, FeatureName> {
        &self.symbols
    }

    /// Returns the problems the build found; empty for a language without
    /// problems. See [`LangBuildError`].
    pub fn errors(&self) -> &[LangBuildError] {
        &self.errors
    }

    /// Returns whether the build found no problem at all
    /// ([`BuiltLang::errors`] is empty).
    pub fn is_sound(&self) -> bool {
        self.errors.is_empty()
    }

    /// Returns the parsing settings the language was built with
    /// ([`LangInputs::parsing`]).
    pub fn parsing(&self) -> &FlmParsing {
        &self.parsing
    }

    /// Returns the recursion-guard policy every parse under this language runs
    /// with.
    pub fn guard(&self) -> GuardPolicy {
        self.guard
    }

    /// Returns the parse driver: the behavior and the settings of a running
    /// parse. [`BuiltLang::language_for_parse`] builds its language from a copy
    /// of it.
    pub fn driver(&self) -> &FlmDriver {
        &self.driver
    }

    /// Returns a parsing state derived from the initial one by applying
    /// `delta`.
    ///
    /// Use it to parse under other conditions than a document's while keeping
    /// what the build installed (the features' packages, the structural
    /// elements). The library's own use is the parse of a [user
    /// definition](crate::lang::rewrites::userdefs::Definition)'s template, which
    /// runs with the [`Template`](crate::lang::RestrictedInterior::Template)
    /// restricted-interior policy and the package of placeholders added. A
    /// program can add a [scoped package](BuiltLang::scoped_package), or
    /// replace the scope stack with one of its own that starts with
    /// [`BuiltLang::base_scope`]. Pass the result to
    /// [`parse_fragment_with_state`](crate::lang::parse_fragment_with_state),
    /// or to [`assemble_with_state`](crate::model::assemble::assemble_with_state)
    /// for a whole document.
    ///
    /// # Errors
    ///
    /// techy's `DeriveError` when `delta` cannot be applied: a scope change the
    /// stack refuses, or an event that can only be interpreted during a parse.
    /// The error carries the state techy recovered.
    #[allow(clippy::result_large_err)]
    pub fn derive_state(
        &self,
        delta: &ParsingStateDelta<Flm>,
    ) -> Result<Arc<ParsingState<Flm>>, DeriveError<Flm>> {
        self.initial_state.derived(delta).map(Arc::new)
    }

    /// Returns a language with the same initial state and guard that keeps at
    /// most `diagnostics_limit` diagnostics per parse; `None` restores techy's
    /// own default. This is [`language_for_parse`](Self::language_for_parse)
    /// with this language's input resolver. Cheap: the state is shared and only
    /// the driver is copied.
    pub fn language_with(&self, diagnostics_limit: Option<usize>) -> Language<Flm> {
        self.language_for_parse(diagnostics_limit, None)
    }

    /// Returns a language with the same initial state and guard that keeps at
    /// most `diagnostics_limit` diagnostics per parse (`None` restores techy's
    /// own default) and reads included files with `input_resolver` when one is
    /// given (with this language's input resolver otherwise). A parse whose
    /// options ([`ParseOptions`](crate::lang::ParseOptions)) set no standard
    /// state runs with such a language. Cheap: the state is shared and only
    /// the driver is copied.
    pub fn language_for_parse(
        &self,
        diagnostics_limit: Option<usize>,
        input_resolver: Option<Arc<dyn InputResolver>>,
    ) -> Language<Flm> {
        self.language_recording(diagnostics_limit, input_resolver, None, None)
    }

    /// Builds every per-parse language:
    /// [`language_for_parse`](Self::language_for_parse), with the driver also
    /// carrying `standard_state` when given (the standard state of the parse,
    /// [`ParseOptions::standard_state`](crate::lang::ParseOptions::standard_state))
    /// and `placements` when given (the record of heading inputs that the
    /// assembly of a document reads back, [`crate::model::assemble`]).
    pub(crate) fn language_recording(
        &self,
        diagnostics_limit: Option<usize>,
        input_resolver: Option<Arc<dyn InputResolver>>,
        standard_state: Option<Arc<ParsingState<Flm>>>,
        placements: Option<Arc<Placements>>,
    ) -> Language<Flm> {
        let mut driver = self.driver.clone().with_diagnostics_limit(diagnostics_limit);
        if let Some(resolver) = input_resolver {
            driver = driver.with_input_resolver(resolver);
        }
        if let Some(state) = standard_state {
            driver = driver.with_standard_state(state);
        }
        if let Some(placements) = placements {
            driver = driver.with_placements(placements);
        }
        guard::language(Language::new(driver, Arc::clone(&self.initial_state)), self.guard)
    }
}

impl fmt::Debug for BuiltLang {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BuiltLang")
            .field("providers", &self.providers.iter().map(|p| p.name()).collect::<Vec<_>>())
            .field("symbols", &self.symbols.len())
            .field("errors", &self.errors)
            .field("parsing", &self.parsing)
            .field("guard", &self.guard)
            .finish()
    }
}

/// Builds the language from the declarations and settings in `inputs`.
///
/// The [module documentation](self) describes the three steps of the build and
/// how problems are collected. A [`BuiltLang`] is always returned; check
/// [`BuiltLang::is_sound`] before relying on it, and read the problems in
/// [`BuiltLang::errors`]. A registry calls this function when it is built; most
/// callers take the result from
/// [`FlmRegistry::lang`](crate::core::registry::FlmRegistry::lang).
///
/// # Examples
///
/// ```
/// use flm_core::lang::{build_language, LangInputs};
///
/// // Nothing declared: FLM's own structure and no feature.
/// let lang = build_language(LangInputs::new());
/// assert!(lang.is_sound());
/// assert!(lang.symbols().is_empty());
/// // The fallback provider is always installed, so an unknown name still resolves.
/// assert!(lang.providers().iter().any(|p| p.name() == "_fallback.gate"));
/// ```
pub fn build_language(inputs: LangInputs) -> BuiltLang {
    let LangInputs {
        elements,
        fallbacks,
        scoped_packages,
        peer_scoped_packages,
        overrides,
        explicitly_before,
        parsing,
        structural,
        guard: policy,
        diagnostics_limit,
        input_resolver,
    } = inputs;

    let minted = mint_packages(
        &elements,
        &fallbacks,
        &scoped_packages,
        &overrides,
        &explicitly_before,
        &peer_scoped_packages,
        &structural,
    );
    let mut errors: Vec<LangBuildError> =
        minted.errors.into_iter().map(LangBuildError::Mint).collect();
    let fallback = minted.fallback;

    // FLM's seed cannot fail (its data are in-crate constants); the `expect`
    // states that invariant.
    let seed = ParsingState::<Flm>::lang_initial()
        .expect("the initial parsing state is built from constants and cannot fail");

    // The scope stack, outermost first: the fallback gate at the bottom (so every
    // defined name shadows it), the seed's builtin dispatch package, then the
    // features' packages in the order minting gives: the weak declarations'
    // under the ordinary declarations', each part in registration order.
    let mut stack: Vec<Arc<dyn SpecsProvider<Flm>>> = Vec::new();
    let mut providers: Vec<Arc<dyn SpecsProvider<Flm>>> = Vec::new();
    let gate: Arc<dyn SpecsProvider<Flm>> = fallback.clone();
    stack.push(Arc::clone(&gate));
    providers.push(gate);
    let fallback_package: Arc<dyn SpecsProvider<Flm>> = fallback.package().clone();
    providers.push(fallback_package);
    let fields_package: Arc<dyn SpecsProvider<Flm>> = minted.fields.clone();
    providers.push(fields_package);
    stack.extend(seed.scopes().providers().iter().cloned());
    let base_scope = stack.clone();
    for package in &minted.packages {
        let provider: Arc<dyn SpecsProvider<Flm>> = package.clone();
        stack.push(Arc::clone(&provider));
        providers.push(provider);
    }
    let mut scoped: BTreeMap<Name, Arc<dyn SpecsProvider<Flm>>> = BTreeMap::new();
    for (name, package) in minted.scoped {
        let provider: Arc<dyn SpecsProvider<Flm>> = package;
        providers.push(Arc::clone(&provider));
        scoped.insert(name, provider);
    }

    let delta = ParsingStateDelta::new()
        .rules(parsing.token_rules_overrides(seed.rules()))
        .ext(FlmStateExt::new(Arc::clone(&structural)).with_parsing(parsing.clone()))
        .scope_op(ScopeOp::ReplaceStack(stack));
    let initial_state = match seed.derived(&delta) {
        Ok(state) => Arc::new(state),
        Err(error) => {
            errors.push(LangBuildError::State { detail: error.to_string() });
            Arc::new(error.recovered)
        }
    };

    let mut driver =
        FlmDriver::new(Recovery::Tolerant, diagnostics_limit, Arc::clone(&initial_state));
    if let Some(resolver) = input_resolver {
        driver = driver.with_input_resolver(resolver);
    }
    let language =
        guard::language(Language::new(driver.clone(), Arc::clone(&initial_state)), policy);

    BuiltLang {
        language,
        initial_state,
        providers,
        base_scope,
        scoped,
        fallback,
        structural,
        symbols: minted.symbols,
        errors,
        parsing,
        guard: policy,
        driver,
        owned: Mutex::new(Vec::new()),
    }
}