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