Skip to main content

flm_core/lang/
build.rs

1//! Building the language that every parse of a document runs under:
2//! [`build_language`], its inputs ([`LangInputs`]) and its result
3//! ([`BuiltLang`]).
4//!
5//! The registry collects what every [feature](crate::core::registry::FlmFeature)
6//! declares and passes it to [`build_language`] as [`LangInputs`].
7//! [`build_language`] turns the inputs into a [`BuiltLang`]: one techy
8//! `Language` value, the parsing state every parse starts from, and the
9//! providers and elements that state refers to. Everything a parse needs is decided here, once;
10//! [`crate::lang::parse`] only runs it. A registry holds its built language
11//! ([`FlmRegistry::lang`](crate::core::registry::FlmRegistry::lang)); a test or a
12//! program that needs a language without a registry calls [`build_language`]
13//! directly.
14//!
15//! # What the build does
16//!
17//! 1. **Builds the packages.** [Minting](crate::lang::mint) builds techy
18//!    packages and specifications from the declarations: one package per
19//!    declaring feature and per set of parsing modes its declarations are
20//!    available in, the scoped packages, the package holding the fallback
21//!    specifications, and the package holding the specifications of the field
22//!    macros (such as `\label`) that a tack-on argument absorbs. A tack-on
23//!    argument is the argument of a construct that absorbs the field macros
24//!    written at its position in a call, after the arguments declared before
25//!    it (see [fields: data a construct
26//!    reads](crate::guide::concepts_overview#fields-data-a-construct-reads)).
27//! 2. **Derives the parsing state every parse starts from**
28//!    ([`BuiltLang::initial_state`]) in one step from the language's initial
29//!    parsing state (techy's `ParsingState::lang_initial`, built from
30//!    [`Flm::initial_state_data`](crate::techy::core::Lang::initial_state_data)):
31//!    the changes to the tokenizer rules that the parsing settings
32//!    ([`FlmParsing`]) ask for, a state extension holding the registry's
33//!    [structural elements](crate::lang::structural) and the parsing settings,
34//!    and a new scope stack holding, outermost first, the fallback provider
35//!    ([`FlmFallbackProvider`], which resolves every name no declaration
36//!    defines), techy's built-in package that handles `\begin` and `\end`, and the features'
37//!    packages in registration order.
38//! 3. **Builds the driver** ([`FlmDriver`]) and installs the [recursion
39//!    guard](crate::lang::guard) of the policy that the inputs specify
40//!    ([`LangInputs::guard`]).
41//!
42//! The fallback provider is at the bottom of the scope stack, so every defined
43//! name takes precedence over it. Below every fallback a feature declares, the
44//! provider holds the language's own two fallbacks: one for an unknown macro and one for
45//! an unknown environment. Every name therefore resolves, in every parsing mode,
46//! to a specification that minting built, and every node receives an element.
47//!
48//! # Errors are collected, never fatal
49//!
50//! [`build_language`] always returns a [`BuiltLang`]. Each problem in the
51//! declarations (two features defining one name, an environment referring to a
52//! scoped package nobody declared, a state that could not be derived) is
53//! collected into [`BuiltLang::errors`] as a [`LangBuildError`], and the
54//! language is built from the declarations that have no problem. The caller
55//! decides whether to proceed; [`BuiltLang::is_sound`] tells whether there was
56//! any problem.
57
58use std::any::Any;
59use std::collections::{BTreeMap, BTreeSet};
60use std::fmt;
61use std::sync::{Arc, Mutex};
62
63use techy::core::specs::{ScopeOp, SpecsProvider};
64use techy::core::{DeriveError, Language, ParsingState, ParsingStateDelta};
65use techy::error::Recovery;
66
67use crate::model::names::{FeatureName, Name};
68use crate::lang::driver::FlmDriver;
69use crate::lang::ext::FlmStateExt;
70use crate::lang::flm::Flm;
71use crate::lang::input::{InputResolver, Placements};
72use crate::lang::guard::{self, GuardPolicy};
73use crate::lang::mint::{
74    mint_packages, ElementDef, FallbackDef, FlmFallbackProvider, MintError, OverrideDef,
75    ScopedPackageDef, Symbol,
76};
77use crate::lang::rules::FlmParsing;
78use crate::lang::structural::StructuralElements;
79
80/// Everything [`build_language`] takes: the declarations of every feature, and
81/// the settings that apply to every parse.
82///
83/// The registry fills this in. A test or a program that builds a language
84/// without a registry starts from [`LangInputs::new`] and adds declarations to
85/// the vectors.
86pub struct LangInputs {
87    /// The features' element declarations: each element with the syntax it is
88    /// written in, in registration order. Where two features define the same
89    /// name, the later feature's package takes precedence; two definitions in
90    /// one parsing mode are also reported as a [`LangBuildError::Mint`] unless
91    /// the later feature is explicitly after the other
92    /// ([`explicitly_before`](Self::explicitly_before)) or its override
93    /// declares the redefinition ([`overrides`](Self::overrides)).
94    pub elements: Vec<ElementDef>,
95    /// The features' fallbacks: policies for callables that no declaration
96    /// defines, each limited to the parsing modes it applies in.
97    pub fallbacks: Vec<FallbackDef>,
98    /// The [scoped packages](crate::lang::mint::ScopedPackageDef): sets of
99    /// element declarations that can be written only inside the environment
100    /// bodies and the arguments whose declarations refer to them.
101    pub scoped_packages: Vec<ScopedPackageDef>,
102    /// The scoped packages that a feature expects another feature to declare,
103    /// as pairs (the expecting feature, the package's name). Each pair is a
104    /// [peer declaration](crate::core::registry::PeerName) of a scoped package.
105    ///
106    /// A body or an argument of the expecting feature's declarations may refer
107    /// to such a package when no feature declares it: the reference then makes
108    /// no command available, and it is not a
109    /// [`MintError::UnknownScopedPackage`]. When some feature does declare the
110    /// package, the pair has no effect. A registry fills this from its
111    /// features' peer declarations and reports each one that no feature
112    /// declares.
113    pub peer_scoped_packages: Vec<(FeatureName, Name)>,
114    /// The explicit redefinitions of a name another feature defines. Without
115    /// one, two features defining the same name in one parsing mode is an
116    /// error that identifies both features, unless
117    /// [`explicitly_before`](Self::explicitly_before) places the feature
118    /// registered last after the others. Only the override of the feature
119    /// registered last among those that define the name in a mode is
120    /// consulted, in that mode.
121    pub overrides: Vec<OverrideDef>,
122    /// The pairs `(a, b)` of features such that the feature order places `a`
123    /// explicitly before `b` ([`crate::core::registry::order`]). Where features
124    /// define one name in one parsing mode, the definition of the feature
125    /// registered last applies there without an error when every other of
126    /// those features is explicitly before it
127    /// ([`crate::lang::mint::packages`]). The registry fills this from the
128    /// chains of its feature order; it is empty by default.
129    pub explicitly_before: BTreeSet<(FeatureName, FeatureName)>,
130    /// The document's parsing settings: comment recognition, the comment
131    /// prefix, and whether `$` delimits mathematics.
132    pub parsing: FlmParsing,
133    /// The structural elements: the registry's set, with the aspects the
134    /// features attached to them.
135    pub structural: Arc<StructuralElements>,
136    /// The recursion-guard policy of every parse: the stack budget for normal
137    /// use, a limit on open descents for tests ([`GuardPolicy`]).
138    pub guard: GuardPolicy,
139    /// How many diagnostics a parse keeps; `None` keeps techy's own default. One
140    /// parse may set another cap through
141    /// [`ParseOptions`](crate::lang::ParseOptions).
142    pub diagnostics_limit: Option<usize>,
143    /// The input resolver: the object, supplied by the embedding program, that
144    /// finds and reads the file an `\input` command refers to
145    /// ([`crate::lang::input`]). The library performs no input or output of its
146    /// own; with `None`, `\input` includes no file and is reported.
147    pub input_resolver: Option<Arc<dyn InputResolver>>,
148}
149
150impl LangInputs {
151    /// Returns inputs with nothing declared: the default parsing settings, the
152    /// default structural elements, the stack-budget guard, no cap on
153    /// diagnostics of their own, and no input resolver.
154    ///
155    /// A language built from these recognizes FLM's own structure (text,
156    /// comments, groups, mathematics) and no command of any feature.
157    pub fn new() -> LangInputs {
158        LangInputs {
159            elements: Vec::new(),
160            fallbacks: Vec::new(),
161            scoped_packages: Vec::new(),
162            peer_scoped_packages: Vec::new(),
163            overrides: Vec::new(),
164            explicitly_before: BTreeSet::new(),
165            parsing: FlmParsing::default(),
166            structural: Arc::new(StructuralElements::default()),
167            guard: GuardPolicy::StackBudget,
168            diagnostics_limit: None,
169            input_resolver: None,
170        }
171    }
172}
173
174impl Default for LangInputs {
175    fn default() -> LangInputs {
176        LangInputs::new()
177    }
178}
179
180impl fmt::Debug for LangInputs {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        f.debug_struct("LangInputs")
183            .field("elements", &self.elements.len())
184            .field("fallbacks", &self.fallbacks.len())
185            .field("scoped_packages", &self.scoped_packages.len())
186            .field("peer_scoped_packages", &self.peer_scoped_packages)
187            .field("overrides", &self.overrides)
188            .field("explicitly_before", &self.explicitly_before)
189            .field("parsing", &self.parsing)
190            .field("guard", &self.guard)
191            .field("diagnostics_limit", &self.diagnostics_limit)
192            .finish_non_exhaustive()
193    }
194}
195
196/// A problem the language build found in its inputs. Problems are collected in
197/// [`BuiltLang::errors`] and never stop the build: see the [module
198/// documentation](self#errors-are-collected-never-fatal).
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub enum LangBuildError {
201    /// Minting could not build every declaration: for example, two features
202    /// define one name without an override, or a body or an argument refers to
203    /// a scoped package that nobody declared and its feature did not declare as
204    /// a peer. [`MintError`] lists every case.
205    Mint(MintError),
206    /// The parsing state every parse starts from could not be derived exactly
207    /// as the inputs asked. The language was built from the state techy recovered, without
208    /// the scope changes that failed.
209    State {
210        /// techy's description of what failed.
211        detail: String,
212    },
213}
214
215impl fmt::Display for LangBuildError {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        match self {
218            LangBuildError::Mint(error) => fmt::Display::fmt(error, f),
219            LangBuildError::State { detail } => {
220                write!(f, "the initial parsing state could not be derived: {detail}")
221            }
222        }
223    }
224}
225
226impl std::error::Error for LangBuildError {}
227
228/// A built language: what every parse of a document under one registry runs
229/// under.
230///
231/// It holds the techy `Language` value, the parsing state every parse of a
232/// document starts from, the providers and the structural elements that
233/// state refers to, the table of every registered callable name, and the
234/// problems the build collected. Pass it to
235/// [`parse_fragment`](crate::lang::parse_fragment).
236///
237/// [`build_language`] creates it; a registry holds its own
238/// ([`FlmRegistry::lang`](crate::core::registry::FlmRegistry::lang)). A
239/// `BuiltLang` never changes after it is built.
240pub struct BuiltLang {
241    language: Language<Flm>,
242    initial_state: Arc<ParsingState<Flm>>,
243    providers: Vec<Arc<dyn SpecsProvider<Flm>>>,
244    fallback: Arc<FlmFallbackProvider>,
245    structural: Arc<StructuralElements>,
246    symbols: BTreeMap<Symbol, FeatureName>,
247    errors: Vec<LangBuildError>,
248    parsing: FlmParsing,
249    guard: GuardPolicy,
250    driver: FlmDriver,
251    /// The values built against this language for its elements, which read
252    /// them through a [`LangOwned`](super::LangOwned) cell. They are freed
253    /// with the language.
254    owned: Mutex<Vec<Arc<dyn Any + Send + Sync>>>,
255}
256
257impl BuiltLang {
258    /// Makes this language the owner of `value`, the value of a
259    /// [`LangOwned`](super::LangOwned) cell.
260    pub(super) fn own(&self, value: Arc<dyn Any + Send + Sync>) {
261        self.owned.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push(value);
262    }
263
264    /// Returns the techy language value: the driver, the initial state and the
265    /// recursion guard, ready to parse.
266    pub fn language(&self) -> &Language<Flm> {
267        &self.language
268    }
269
270    /// Returns the parsing state every parse of a document starts from, which
271    /// [`build_language`] derived from the language's initial parsing state
272    /// (techy's `ParsingState::lang_initial`). To parse under other conditions, derive a state from it with
273    /// [`BuiltLang::derive_state`].
274    pub fn initial_state(&self) -> &Arc<ParsingState<Flm>> {
275        &self.initial_state
276    }
277
278    /// Returns every provider of specifications that minting built, in one
279    /// list: the fallback provider; the package holding the fallback
280    /// specifications, which the fallback specifications' provenance stamps
281    /// (the record of the package that holds a specification, used to
282    /// serialize it by identity; see [`crate::lang::serialize`]) refer to; the
283    /// package holding the specifications of the field macros that tack-on
284    /// arguments absorb
285    /// ([`ArgStdKind::TackOn`](crate::lang::mint::ArgStdKind::TackOn)); the
286    /// declaring features' packages (one per feature and per set of parsing
287    /// modes its declarations are available in); and the scoped packages.
288    ///
289    /// A [reading session](crate::dump::session) needs this list to rebuild a
290    /// serialized parse, in which a specification is referred to by identity and
291    /// looked up in the package it came from. techy's built-in package that
292    /// handles `\begin` and `\end` is not in the list; it is reachable through
293    /// the initial state's scope stack.
294    pub fn providers(&self) -> &[Arc<dyn SpecsProvider<Flm>>] {
295        &self.providers
296    }
297
298    /// Returns the fallback provider: the provider at the bottom of the scope
299    /// stack that resolves a callable no declaration defines, applying each
300    /// feature's fallback in the parsing modes that fallback declares. The
301    /// specifications it returns are held in its own package
302    /// ([`FlmFallbackProvider::package`]).
303    pub fn fallback(&self) -> &Arc<FlmFallbackProvider> {
304        &self.fallback
305    }
306
307    /// Returns the structural elements of this language: the elements of every
308    /// node shape no feature declares. The initial state's extension holds the
309    /// same set.
310    pub fn structural(&self) -> &Arc<StructuralElements> {
311        &self.structural
312    }
313
314    /// Returns every callable name the features' packages register, with the
315    /// feature whose definition applies: the last registered, since a later
316    /// feature's package takes precedence over an earlier one's. A name that two
317    /// features define in parsing modes that do not overlap is listed once,
318    /// also under the last registered.
319    pub fn symbols(&self) -> &BTreeMap<Symbol, FeatureName> {
320        &self.symbols
321    }
322
323    /// Returns the problems the build found; empty for a language without
324    /// problems. See [`LangBuildError`].
325    pub fn errors(&self) -> &[LangBuildError] {
326        &self.errors
327    }
328
329    /// Returns whether the build found no problem at all
330    /// ([`BuiltLang::errors`] is empty).
331    pub fn is_sound(&self) -> bool {
332        self.errors.is_empty()
333    }
334
335    /// Returns the parsing settings the language was built with
336    /// ([`LangInputs::parsing`]).
337    pub fn parsing(&self) -> &FlmParsing {
338        &self.parsing
339    }
340
341    /// Returns the recursion-guard policy every parse under this language runs
342    /// with.
343    pub fn guard(&self) -> GuardPolicy {
344        self.guard
345    }
346
347    /// Returns the parse driver: the behavior and the settings of a running
348    /// parse. [`BuiltLang::language_for_parse`] builds its language from a copy
349    /// of it.
350    pub fn driver(&self) -> &FlmDriver {
351        &self.driver
352    }
353
354    /// Returns a parsing state derived from the initial one by applying
355    /// `delta`.
356    ///
357    /// Use it to parse under other conditions than a document's while keeping
358    /// what the build installed (the features' packages, the structural
359    /// elements). The library's own use is the parse of a [user
360    /// definition](crate::lang::rewrites::userdefs::Definition)'s template, which
361    /// runs with the [`Template`](crate::lang::RestrictedInterior::Template)
362    /// restricted-interior policy and the package of placeholders added. Pass
363    /// the result to
364    /// [`parse_fragment_with_state`](crate::lang::parse_fragment_with_state).
365    ///
366    /// # Errors
367    ///
368    /// techy's `DeriveError` when `delta` cannot be applied: a scope change the
369    /// stack refuses, or an event that can only be interpreted during a parse.
370    /// The error carries the state techy recovered.
371    #[allow(clippy::result_large_err)]
372    pub fn derive_state(
373        &self,
374        delta: &ParsingStateDelta<Flm>,
375    ) -> Result<Arc<ParsingState<Flm>>, DeriveError<Flm>> {
376        self.initial_state.derived(delta).map(Arc::new)
377    }
378
379    /// Returns a language with the same initial state and guard that keeps at
380    /// most `diagnostics_limit` diagnostics per parse; `None` restores techy's
381    /// own default. This is [`language_for_parse`](Self::language_for_parse)
382    /// with this language's input resolver. Cheap: the state is shared and only
383    /// the driver is copied.
384    pub fn language_with(&self, diagnostics_limit: Option<usize>) -> Language<Flm> {
385        self.language_for_parse(diagnostics_limit, None)
386    }
387
388    /// Returns a language with the same initial state and guard that keeps at
389    /// most `diagnostics_limit` diagnostics per parse (`None` restores techy's
390    /// own default) and reads included files with `input_resolver` when one is
391    /// given (with this language's input resolver otherwise). A parse with
392    /// options of its own ([`ParseOptions`](crate::lang::ParseOptions)) runs
393    /// with such a language. Cheap: the state is shared and only the driver is
394    /// copied.
395    pub fn language_for_parse(
396        &self,
397        diagnostics_limit: Option<usize>,
398        input_resolver: Option<Arc<dyn InputResolver>>,
399    ) -> Language<Flm> {
400        self.language_recording(diagnostics_limit, input_resolver, None)
401    }
402
403    /// Builds every per-parse language:
404    /// [`language_for_parse`](Self::language_for_parse), with the driver also
405    /// carrying `placements` when given (the record of heading inputs that the
406    /// assembly of a document reads back, [`crate::model::assemble`]).
407    pub(crate) fn language_recording(
408        &self,
409        diagnostics_limit: Option<usize>,
410        input_resolver: Option<Arc<dyn InputResolver>>,
411        placements: Option<Arc<Placements>>,
412    ) -> Language<Flm> {
413        let mut driver = self.driver.clone().with_diagnostics_limit(diagnostics_limit);
414        if let Some(resolver) = input_resolver {
415            driver = driver.with_input_resolver(resolver);
416        }
417        if let Some(placements) = placements {
418            driver = driver.with_placements(placements);
419        }
420        guard::language(Language::new(driver, Arc::clone(&self.initial_state)), self.guard)
421    }
422}
423
424impl fmt::Debug for BuiltLang {
425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426        f.debug_struct("BuiltLang")
427            .field("providers", &self.providers.iter().map(|p| p.name()).collect::<Vec<_>>())
428            .field("symbols", &self.symbols.len())
429            .field("errors", &self.errors)
430            .field("parsing", &self.parsing)
431            .field("guard", &self.guard)
432            .finish()
433    }
434}
435
436/// Builds the language from the declarations and settings in `inputs`.
437///
438/// The [module documentation](self) describes the three steps of the build and
439/// how problems are collected. A [`BuiltLang`] is always returned; check
440/// [`BuiltLang::is_sound`] before relying on it, and read the problems in
441/// [`BuiltLang::errors`]. A registry calls this function when it is built; most
442/// callers take the result from
443/// [`FlmRegistry::lang`](crate::core::registry::FlmRegistry::lang).
444///
445/// # Examples
446///
447/// ```
448/// use flm_core::lang::{build_language, LangInputs};
449///
450/// // Nothing declared: FLM's own structure and no feature.
451/// let lang = build_language(LangInputs::new());
452/// assert!(lang.is_sound());
453/// assert!(lang.symbols().is_empty());
454/// // The fallback provider is always installed, so an unknown name still resolves.
455/// assert!(lang.providers().iter().any(|p| p.name() == "_fallback.gate"));
456/// ```
457pub fn build_language(inputs: LangInputs) -> BuiltLang {
458    let LangInputs {
459        elements,
460        fallbacks,
461        scoped_packages,
462        peer_scoped_packages,
463        overrides,
464        explicitly_before,
465        parsing,
466        structural,
467        guard: policy,
468        diagnostics_limit,
469        input_resolver,
470    } = inputs;
471
472    let minted = mint_packages(
473        &elements,
474        &fallbacks,
475        &scoped_packages,
476        &overrides,
477        &explicitly_before,
478        &peer_scoped_packages,
479        &structural,
480    );
481    let mut errors: Vec<LangBuildError> =
482        minted.errors.into_iter().map(LangBuildError::Mint).collect();
483    let fallback = minted.fallback;
484
485    // FLM's seed cannot fail (its data are in-crate constants); the `expect`
486    // states that invariant.
487    let seed = ParsingState::<Flm>::lang_initial()
488        .expect("the initial parsing state is built from constants and cannot fail");
489
490    // The scope stack, outermost first: the fallback gate at the bottom (so every
491    // defined name shadows it), the seed's builtin dispatch package, then the
492    // features' packages in registration order.
493    let mut stack: Vec<Arc<dyn SpecsProvider<Flm>>> = Vec::new();
494    let mut providers: Vec<Arc<dyn SpecsProvider<Flm>>> = Vec::new();
495    let gate: Arc<dyn SpecsProvider<Flm>> = fallback.clone();
496    stack.push(Arc::clone(&gate));
497    providers.push(gate);
498    let fallback_package: Arc<dyn SpecsProvider<Flm>> = fallback.package().clone();
499    providers.push(fallback_package);
500    let fields_package: Arc<dyn SpecsProvider<Flm>> = minted.fields.clone();
501    providers.push(fields_package);
502    stack.extend(seed.scopes().providers().iter().cloned());
503    for package in &minted.packages {
504        let provider: Arc<dyn SpecsProvider<Flm>> = package.clone();
505        stack.push(Arc::clone(&provider));
506        providers.push(provider);
507    }
508    for package in minted.scoped.values() {
509        let provider: Arc<dyn SpecsProvider<Flm>> = package.clone();
510        providers.push(provider);
511    }
512
513    let delta = ParsingStateDelta::new()
514        .rules(parsing.token_rules_overrides(seed.rules()))
515        .ext(FlmStateExt::new(Arc::clone(&structural)).with_parsing(parsing.clone()))
516        .scope_op(ScopeOp::ReplaceStack(stack));
517    let initial_state = match seed.derived(&delta) {
518        Ok(state) => Arc::new(state),
519        Err(error) => {
520            errors.push(LangBuildError::State { detail: error.to_string() });
521            Arc::new(error.recovered)
522        }
523    };
524
525    let mut driver = FlmDriver::new(Recovery::Tolerant, diagnostics_limit);
526    if let Some(resolver) = input_resolver {
527        driver = driver.with_input_resolver(resolver);
528    }
529    let language =
530        guard::language(Language::new(driver.clone(), Arc::clone(&initial_state)), policy);
531
532    BuiltLang {
533        language,
534        initial_state,
535        providers,
536        fallback,
537        structural,
538        symbols: minted.symbols,
539        errors,
540        parsing,
541        guard: policy,
542        driver,
543        owned: Mutex::new(Vec::new()),
544    }
545}