Skip to main content

flm_core/lang/mint/
decl.rs

1//! The declaration types a feature fills in to say what can be written in a
2//! document: elements and their syntax, fallbacks, scoped packages and
3//! overrides.
4//!
5//! A declaration is plain data. [`mint_packages`](super::mint_packages) builds
6//! the techy packages and specifications that a parse uses from the
7//! declarations (see the [module documentation](super) for this work, called
8//! minting). A feature constructs its declarations itself and hands them to
9//! its feature builder, which records the feature as their owner:
10//!
11//! - [`ElementDef`], an element and the syntax it is written in
12//!   ([`SyntaxDef`]), passed to
13//!   [`FeatureBuilder::element`](crate::core::registry::FeatureBuilder::element);
14//!   a declaration is available in text mode unless it lists its parsing
15//!   modes ([`ElementDef::modes`]);
16//! - [`FallbackDef`], what a macro or an environment that no declaration
17//!   defines means in given parsing modes, passed to
18//!   [`FeatureBuilder::fallback`](crate::core::registry::FeatureBuilder::fallback);
19//! - [`ScopedPackageDef`], a set of element declarations that is on no scope
20//!   stack until the declaration of an environment body or an argument, or a
21//!   program, adds it, passed to
22//!   [`FeatureBuilder::scoped_package`](crate::core::registry::FeatureBuilder::scoped_package);
23//! - [`OverrideDef`], a feature's statement that its definition of a name
24//!   replaces another feature's, made with
25//!   [`FeatureBuilder::override_callable`](crate::core::registry::FeatureBuilder::override_callable).
26//!
27//! The two types to read first are [`SyntaxDef`], which says how an element is
28//! written, and [`ArgDef`], which declares one argument: the parser that reads
29//! it ([`FlmArgumentParser`], most often one of the standard kinds of
30//! [`ArgStdKind`]) and what the declaration says around the parser (name,
31//! parsing mode, layout, opaque wrapper, scoped packages, state events,
32//! documentation).
33//! [`BodyDef`] does the
34//! same for an environment's body. Settings given as data write an argument
35//! declaration as a map, whose syntax is a standard kind written as data or a
36//! short text standing for one, an argument code; see [`super::codes`].
37
38use std::fmt;
39use std::sync::Arc;
40
41use techy::latexlike::Mode;
42
43use crate::model::element::ElementSpec;
44use crate::model::names::{FeatureName, Name};
45use crate::lang::flm::{FlmCallableType, FlmEvent};
46use crate::lang::mint::codes::{ArgCode, ArgData};
47use crate::lang::mint::parsers::{
48    ArgStdKind, FlmArgumentParser, FlmBodyParser, IntoFlmArgumentParser, IntoFlmBodyParser,
49};
50use crate::lang::verbatim::FlmVerbatimBehavior;
51
52/// A callable kind: one of the three forms in which an element can be written
53/// in a document, a macro, an environment or a special character sequence.
54///
55/// [`SyntaxDef::kind`] returns it for a syntax; [`OverrideDef`] and
56/// [`Symbol`](super::Symbol) use it to say which form a name belongs to. Its
57/// `Display` text (`macro`, `environment`, `specials`) appears in error
58/// messages and in the [registry digest](crate::model::digest) (the hash of
59/// everything about a registry that can change what processing produces).
60///
61/// It is written to data with `Serialize`; see [serialized
62/// forms](crate::core::registry#serialized-forms).
63#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
64#[derive(serde::Serialize, schemars::JsonSchema)]
65#[serde(rename_all = "lowercase")]
66pub enum CallableKind {
67    /// A macro: `\name{…}`.
68    Macro,
69    /// An environment: `\begin{name}…\end{name}`.
70    Environment,
71    /// A special character sequence, recognized wherever it appears rather than
72    /// after an escape character (`~`, `---`).
73    Specials,
74}
75
76impl CallableKind {
77    /// Returns the callable type of the FLM language ([`FlmCallableType`])
78    /// under which a name of this kind is registered in a techy package.
79    pub fn callable_type(self) -> FlmCallableType {
80        match self {
81            CallableKind::Macro => FlmCallableType::Macro,
82            CallableKind::Environment => FlmCallableType::Environment,
83            CallableKind::Specials => FlmCallableType::Specials,
84        }
85    }
86}
87
88impl fmt::Display for CallableKind {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.write_str(match self {
91            CallableKind::Macro => "macro",
92            CallableKind::Environment => "environment",
93            CallableKind::Specials => "specials",
94        })
95    }
96}
97
98/// The declaration of one **tack-on field**: a macro that a construct absorbs
99/// as data after its own arguments, as `\section{…}` absorbs the `\label{…}`
100/// written after it.
101///
102/// A construct accepts its tack-on fields through its tack-on argument, an
103/// argument declared as [`ArgStdKind::TackOn`] with the list of fields,
104/// usually its last. A field is written like a macro, but its name is not
105/// defined as a command anywhere: only the construct that declares the field
106/// accepts it, and only where that construct's tack-on argument stands.
107///
108/// A field is **data that the declaring construct reads**, not content: its
109/// node is a macro node named as the field is written, carrying the language's
110/// field element ([`FIELD`](crate::lang::structural::FIELD)), the same element
111/// for every field, and the construct that declared the field is its only
112/// reader. The declaration is data only: a name, arguments, whether the field
113/// repeats, and documentation. See the [`field`](super::field) module and
114/// [fields](crate::guide::concepts_overview#fields-data-a-construct-reads).
115///
116/// Settings given as data declare a field in the structured syntax `tack-on`
117/// of its tack-on argument ([the kind as data](ArgStdKind#the-kind-as-data)).
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct TackOnField {
120    /// The field's name, without the escape character (`label`), distinct
121    /// from the names of the other fields of its tack-on argument.
122    pub name: String,
123    /// The field's own arguments, in the order they are written.
124    pub args: Vec<ArgDef>,
125    /// Whether the field may be written more than once after one construct.
126    pub repeatable: bool,
127    /// Documentation of the field. The library does not act on it; the
128    /// registry keeps it with the declaration
129    /// ([`FlmRegistry::declarations`](crate::core::registry::FlmRegistry::declarations))
130    /// for a program that describes what an author may write.
131    pub docs: String,
132}
133
134impl TackOnField {
135    /// Declares a field written `\name`, taking the given arguments, which may
136    /// be written at most once after the construct;
137    /// [`TackOnField::repeatable`] allows it more than once.
138    pub fn new(name: impl Into<String>, args: Vec<ArgDef>) -> TackOnField {
139        TackOnField { name: name.into(), args, repeatable: false, docs: String::new() }
140    }
141
142    /// Builder: the field may be written more than once after one construct.
143    pub fn repeatable(mut self) -> TackOnField {
144        self.repeatable = true;
145        self
146    }
147
148    /// Builder: sets the field's documentation.
149    pub fn docs(mut self, docs: impl Into<String>) -> TackOnField {
150        self.docs = crate::kept_docs(docs);
151        self
152    }
153}
154
155/// How the [block-structure pass](crate::lang::rewrites::blocks) lays out an
156/// argument's content: as inline
157/// content, as a region of blocks, or as whichever of the two the content
158/// calls for.
159///
160/// Inline content is running text (words, formulas, commands such as
161/// `\emph{…}`) with no paragraph inside it. A region of blocks holds
162/// paragraphs and block-level constructs such as lists. The layout belongs to
163/// the command's declaration ([`ArgDef::layout`]); an author cannot choose it
164/// where the command is written.
165///
166/// An argument declared with an opaque wrapper ([`ArgDef::opaque_wrapper`])
167/// takes only [`Inline`](ArgLayout::Inline): the block-structure pass carries
168/// its content over as written, so no other layout could take effect. An
169/// argument read in mathematics mode is an [opaque
170/// region](crate::guide::concepts_overview#opaque-regions), which the
171/// block-structure pass carries over untouched, so it may not be declared
172/// [`Blocks`](ArgLayout::Blocks). Minting reports a declaration that breaks
173/// either rule
174/// ([`MintError::LayoutOnOpaqueWrappedArgument`](super::MintError::LayoutOnOpaqueWrappedArgument),
175/// [`MintError::BlocksOnMathArgument`](super::MintError::BlocksOnMathArgument)).
176/// A layout declared on an argument whose reader yields raw text or places
177/// its content under an opaque wrapper by construction (a verbatim argument, a
178/// characters-only group) is not reported; it has no effect, since the
179/// argument's content is an opaque region.
180///
181/// [`arg_layout_of`](super::arg_layout_of) returns the declared layout of an
182/// argument of a parsed node;
183/// [`argument_holds_blocks`](crate::lang::rewrites::blocks::argument_holds_blocks)
184/// returns whether an argument holds blocks, before and after the
185/// block-structure pass alike.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize)]
187#[derive(schemars::JsonSchema)]
188#[serde(rename_all = "kebab-case")]
189pub enum ArgLayout {
190    /// Inline content: no paragraph is built inside it, and a blank line in it
191    /// is an error, reported and read as one space. The default.
192    #[default]
193    Inline,
194    /// A region of blocks: paragraphs are built inside it, exactly as in an
195    /// environment body declared [`BodyLayout::Blocks`]. Content written on
196    /// one line becomes one paragraph.
197    Blocks,
198    /// Inferred from the content: a region of blocks when the content holds a
199    /// blank line (a paragraph break) or a block-level construct such as a
200    /// list, inline content otherwise. This is the rule a fragment laid out
201    /// [`InlineOrBlocks`](crate::model::doc::FragmentLayout::InlineOrBlocks)
202    /// applies to its top level.
203    InlineOrBlocks,
204}
205
206/// The declaration of one argument of a macro, an environment or a special
207/// character sequence: the parser that reads it, the name it can be read by,
208/// the parsing mode it is read in, how its content is laid out, whether its
209/// content is kept as written under an opaque wrapper, the scoped packages
210/// available inside it, the state events it is read under, documentation, and
211/// what it holds (its role).
212///
213/// The parser is one field among the others ([`ArgDef::kind`]): one of the
214/// standard argument kinds ([`ArgStdKind`]) for the forms FLM provides, or a
215/// parser of a feature's own ([`FlmArgumentParser`]) for a syntax they cannot
216/// express. Either way, minting applies the name, mode, layout, opaque
217/// wrapper, scoped packages and events declared here around the parser.
218///
219/// Give an argument a name whenever anything reads it: reading by name keeps
220/// working when the argument list changes later, reading by position does not.
221///
222/// An argument may also state its **role**: what the text written for it
223/// holds (a label, a citation key, the path of a file), as a dotted name
224/// that a feature registers in the registry's namespace of argument roles.
225/// The role describes the argument for a reader of the registry; parsing and
226/// processing do not read it. See [`ArgDef::role`].
227///
228/// [`ArgDef::new`], [`ArgDef::named`], [`ArgDef::mandatory`] and
229/// [`ArgDef::optional`] create a declaration; the builder methods
230/// [`mode`](ArgDef::mode), [`layout`](ArgDef::layout),
231/// [`blocks`](ArgDef::blocks), [`with_opaque_wrapper`](ArgDef::with_opaque_wrapper),
232/// [`scoped`](ArgDef::scoped), [`event`](ArgDef::event),
233/// [`docs`](ArgDef::docs) and [`role`](ArgDef::role) each change one thing.
234/// Settings given as data write an argument as its argument code, or as a map
235/// of its syntax (a structured syntax, the standard kind written as data, or a
236/// code) with the argument's name, parsing mode, layout, opaque wrapper,
237/// scoped packages, state events, documentation and role ([`ArgData`], which
238/// converts into an `ArgDef` through `TryFrom`; see [`super::codes`]).
239///
240/// Two declarations are equal (`PartialEq`) when every field is equal, the
241/// code they were read from included ([`ArgDef::code`]). Their parsers are
242/// compared by the bytes that identify them
243/// ([`FlmArgumentParser::identity`]), which differ for any two parsers that
244/// read differently.
245#[derive(Debug, Clone, serde::Deserialize)]
246#[derive(schemars::JsonSchema)]
247#[serde(try_from = "ArgData")]
248#[schemars(with = "ArgData")]
249pub struct ArgDef {
250    /// The name the argument can be read by, when it has one.
251    pub name: Option<String>,
252    /// The parser that reads the argument and tells FLM what it needs to know
253    /// about the argument beyond reading it ([`FlmArgumentParser`]). It is a
254    /// shared object, so cloning a declaration shares its parser.
255    /// [`ArgDef::new`] and [`ArgDef::named`] build it from a standard kind or
256    /// from a parser of one's own.
257    pub kind: Arc<dyn FlmArgumentParser>,
258    /// The parsing mode the argument is read in; `None` reads it in the mode
259    /// the command itself is written in. See [`ArgDef::mode`].
260    pub mode: Option<Mode>,
261    /// How the [block-structure pass](crate::lang::rewrites::blocks) lays out
262    /// the argument's content; inline by default. See [`ArgDef::layout`].
263    pub layout: ArgLayout,
264    /// Whether minting places the argument's content under an **opaque
265    /// wrapper**: a group of the class
266    /// [`FlmGroupType::OpaqueWrapper`](crate::lang::FlmGroupType::OpaqueWrapper),
267    /// with no delimiters of its own, staged over what the argument's reader
268    /// read. The [block-structure pass](crate::lang::rewrites::blocks) carries
269    /// the content of such a group over as written, with no whitespace
270    /// collapsed and no typographic substitution made, so the element that
271    /// declared the argument reads it as typed; it reads it through the same
272    /// content nodes as without the wrapper. `false` by default; set it with
273    /// [`ArgDef::with_opaque_wrapper`].
274    ///
275    /// The wrapper is placed around whatever the argument's reader read, for
276    /// every kind and for a parser of one's own. The reader of a
277    /// characters-only group ([`ArgStdKind::CharsGroup`]) places one by
278    /// construction, whatever this field says. A verbatim argument places its
279    /// content under a verbatim group, which the block-structure pass carries
280    /// over in the same way.
281    ///
282    /// An argument declared with an opaque wrapper may not take a layout other
283    /// than [`ArgLayout::Inline`]; minting reports one as
284    /// [`MintError::LayoutOnOpaqueWrappedArgument`](super::MintError::LayoutOnOpaqueWrappedArgument).
285    /// A scoped package declared on it is attached as on any argument
286    /// ([`ArgDef::scoped`]).
287    pub opaque_wrapper: bool,
288    /// The names of the [scoped packages](ScopedPackageDef) whose
289    /// declarations are available inside this argument. See
290    /// [`ArgDef::scoped`].
291    pub scoped: Vec<Name>,
292    /// The state events the argument is read under ([`FlmEvent`]), in the
293    /// order they are declared; empty by default. See [`ArgDef::event`].
294    pub events: Vec<FlmEvent>,
295    /// Documentation of the argument. The library does not act on it; the
296    /// registry keeps it with the declaration
297    /// ([`FlmRegistry::declarations`](crate::core::registry::FlmRegistry::declarations))
298    /// for a program that describes what an author may write.
299    pub docs: String,
300    /// The **argument role**: what the argument holds, beyond how it is
301    /// written, as a registered dotted name such as `flm.refs.target` (the
302    /// label a reference points to). `None`, the default, says nothing about
303    /// what the argument holds. See [`ArgDef::role`].
304    pub role: Option<Name>,
305    /// The argument code the declaration was read from, with the kind it
306    /// stands for; see [`ArgDef::code`].
307    pub(super) code: Option<ArgCode>,
308}
309
310impl ArgDef {
311    /// Creates the declaration of an argument read by `kind`, with no name, so
312    /// that it can be read only by position. Its content is inline
313    /// ([`ArgLayout::Inline`]) and not placed under an opaque wrapper by the
314    /// declaration, it is read in the mode the command is written in, no
315    /// scoped package is available inside it, and it declares no event.
316    ///
317    /// `kind` is a standard kind (`ArgDef::new(ArgStdKind::Star)`), a parser
318    /// of one's own passed by value, or a parser already shared as
319    /// `Arc<dyn FlmArgumentParser>`; [`IntoFlmArgumentParser`] converts all
320    /// three.
321    pub fn new(kind: impl IntoFlmArgumentParser) -> ArgDef {
322        ArgDef {
323            name: None,
324            kind: kind.into_flm_argument_parser(),
325            mode: None,
326            layout: ArgLayout::Inline,
327            opaque_wrapper: false,
328            scoped: Vec::new(),
329            events: Vec::new(),
330            docs: String::new(),
331            role: None,
332            code: None,
333        }
334    }
335
336    /// The argument code this declaration was read from: `"["`, `"r()"`. A
337    /// declaration has one when it was made from a code, by
338    /// [`arg_def_from_code`](super::arg_def_from_code) (every reader of
339    /// settings given as data reads its codes through it) or from a code
340    /// read already ([`ArgCode`], through `From`). `None` for a declaration
341    /// built from a standard kind or a parser ([`ArgDef::new`] and the
342    /// constructors built on it), and for one read from a structured syntax,
343    /// whose standard kind the parser returns
344    /// ([`FlmArgumentParser::std_kind`]).
345    ///
346    /// A program that writes a declaration back as data writes it in the
347    /// form it was read from, so that it reads back the same:
348    ///
349    /// - a declaration read from a code writes this code: the parser object
350    ///   alone does not say which code chose it (`{` and `m` choose the same
351    ///   parser);
352    /// - any other declaration whose parser is a standard kind writes the
353    ///   structured syntax, the kind written as data under the key `syntax`
354    ///   (see [`ArgStdKind`]); this covers a declaration read from a
355    ///   structured syntax and one built in Rust from a standard kind;
356    /// - a declaration whose parser is a feature's own writes neither, and
357    ///   does not read back.
358    ///
359    /// [`ArgDataFields`](super::ArgDataFields)' conversion from an `ArgDef`
360    /// follows this rule. The builder methods leave the code as it is; a
361    /// caller that replaces [`kind`](ArgDef::kind) after reading a code makes
362    /// the code describe a parser the declaration no longer holds.
363    ///
364    /// ```
365    /// use flm_core::lang::mint::{arg_def_from_code, ArgDef, ArgStdKind};
366    ///
367    /// assert_eq!(arg_def_from_code("m").unwrap().code(), Some("m"));
368    /// assert_eq!(ArgDef::new(ArgStdKind::Mandatory).code(), None);
369    /// ```
370    pub fn code(&self) -> Option<&str> {
371        self.code.as_ref().map(ArgCode::as_str)
372    }
373
374    /// The argument code this declaration was read from, with the standard
375    /// kind it stands for ([`ArgCode`]); `None` where [`ArgDef::code`] is
376    /// `None`. A program that holds declarations in a form of its own takes
377    /// the code from here, already read, and makes the declaration again from
378    /// it through `From`, without reading the code again.
379    pub fn arg_code(&self) -> Option<&ArgCode> {
380        self.code.as_ref()
381    }
382
383    /// Creates the declaration of an argument read by `kind`, which can be
384    /// read by `name`. Everything else is as for [`ArgDef::new`].
385    pub fn named(name: impl Into<String>, kind: impl IntoFlmArgumentParser) -> ArgDef {
386        ArgDef { name: Some(name.into()), ..ArgDef::new(kind) }
387    }
388
389    /// Creates the declaration of a mandatory `{…}` argument named `name`;
390    /// shorthand for `ArgDef::named(name, ArgStdKind::Mandatory)`.
391    pub fn mandatory(name: impl Into<String>) -> ArgDef {
392        ArgDef::named(name, ArgStdKind::Mandatory)
393    }
394
395    /// Creates the declaration of an optional `[…]` argument named `name`;
396    /// shorthand for `ArgDef::named(name, ArgStdKind::Optional)`.
397    pub fn optional(name: impl Into<String>) -> ArgDef {
398        ArgDef::named(name, ArgStdKind::Optional)
399    }
400
401    /// Builder: sets the parsing mode the argument is read in. Without it,
402    /// the argument is read in the mode the command is written in.
403    ///
404    /// `Mode::Math` reads the argument as mathematics wherever the command is
405    /// written. `Mode::Text` restores the innermost non-mathematics context
406    /// that encloses the command, with its mode and its token rules; this is
407    /// how `\text{…}` inside mathematics holds ordinary document content.
408    /// Outside mathematics, `Mode::Text` changes nothing. The two values mean
409    /// the same on an environment's body ([`BodyDef::mode`]).
410    pub fn mode(mut self, mode: Mode) -> ArgDef {
411        self.mode = Some(mode);
412        self
413    }
414
415    /// Builder: sets how the [block-structure
416    /// pass](crate::lang::rewrites::blocks) lays out the argument's content: inline
417    /// content (the default), a region of blocks, or whichever of the two the content
418    /// calls for. See [`ArgLayout`].
419    ///
420    /// An argument declared with an opaque wrapper
421    /// ([`ArgDef::with_opaque_wrapper`]) may not take a layout other than
422    /// [`ArgLayout::Inline`], and an argument read in mathematics mode may not
423    /// take [`ArgLayout::Blocks`]. Minting reports a declaration that breaks
424    /// either rule
425    /// ([`MintError::LayoutOnOpaqueWrappedArgument`](super::MintError::LayoutOnOpaqueWrappedArgument),
426    /// [`MintError::BlocksOnMathArgument`](super::MintError::BlocksOnMathArgument))
427    /// and lays the argument out inline.
428    ///
429    /// ```
430    /// use flm_core::lang::mint::{ArgDef, ArgLayout};
431    ///
432    /// // A note whose text may be one line of running text or several
433    /// // paragraphs, as the author writes it.
434    /// let text = ArgDef::mandatory("text").layout(ArgLayout::InlineOrBlocks);
435    /// assert_eq!(text.layout, ArgLayout::InlineOrBlocks);
436    /// ```
437    pub fn layout(mut self, layout: ArgLayout) -> ArgDef {
438        self.layout = layout;
439        self
440    }
441
442    /// Builder: the argument's content is a region of blocks; shorthand for
443    /// `.layout(ArgLayout::Blocks)`.
444    pub fn blocks(self) -> ArgDef {
445        self.layout(ArgLayout::Blocks)
446    }
447
448    /// Builder: places the argument's content under an opaque wrapper
449    /// ([`ArgDef::opaque_wrapper`], which states what the wrapper does and
450    /// what the declaration then admits), for an argument whose text the
451    /// element reads as typed, such as a citation key or the target of a
452    /// link.
453    pub fn with_opaque_wrapper(mut self) -> ArgDef {
454        self.opaque_wrapper = true;
455        self
456    }
457
458    /// Builder: makes the declarations of one more [scoped
459    /// package](ScopedPackageDef), given by name, available inside this
460    /// argument, as [`BodyDef::scoped`] does for an environment's body.
461    ///
462    /// This is how a command gives one of its arguments commands of its own:
463    /// a note whose optional argument accepts `\label{…}`, while `\label` is
464    /// not defined in the running text. While the argument is parsed, the
465    /// scoped package is the innermost techy package of the parsing state's
466    /// scope stack, so its declarations shadow any other definition of the
467    /// same names inside the argument.
468    ///
469    /// Some feature must declare a scoped package of that name; the order in
470    /// which the features register does not matter. A name that no feature
471    /// declares is reported as
472    /// [`MintError::UnknownScopedPackage`](super::MintError::UnknownScopedPackage),
473    /// unless the feature that refers to it declared the name as a peer
474    /// ([`FeatureBuilder::peer_scoped_package`](crate::core::registry::FeatureBuilder::peer_scoped_package)).
475    /// A package that another feature owns may be absent from a registry; the
476    /// argument then makes no command available through it, and a command
477    /// the package would define is an unknown command there. Scoped packages
478    /// that refer to each other in a cycle are reported as
479    /// [`MintError::ScopedPackageCycle`](super::MintError::ScopedPackageCycle).
480    ///
481    /// The package is attached to the parsing state of the argument whatever
482    /// its reader. Inside a reading that recognizes no command, such as a
483    /// characters-only group or a verbatim argument, its declarations are not
484    /// reachable, and nothing is reported.
485    ///
486    /// ```
487    /// use flm_core::lang::mint::ArgDef;
488    ///
489    /// let labels = ArgDef::optional("labels").scoped("my.labels");
490    /// assert_eq!(labels.scoped, ["my.labels"]);
491    /// ```
492    pub fn scoped(mut self, package: impl Into<Name>) -> ArgDef {
493        self.scoped.push(package.into());
494        self
495    }
496
497    /// Builder: adds one more state event ([`FlmEvent`]) that the argument
498    /// is read under, after those declared before.
499    ///
500    /// An event asks the parse for a state computed where the command is
501    /// written: [`FlmEvent::StandardState`] reads the argument under the
502    /// standard state of the parse, whatever state the command is written
503    /// in, and [`FlmEvent::StandardScope`] under the standard scope with the
504    /// token rules of the place of the command. The three fields that
505    /// declare a change of state are applied as one change: what the events
506    /// resolve to first, in the order listed, then the [mode](ArgDef::mode)
507    /// and the [scoped packages](ArgDef::scoped). So an argument can be read
508    /// under the standard state, in mathematics, with a scoped package of
509    /// its own.
510    ///
511    /// [`FlmEvent::ExitMathContext`] asks for what `.mode(Mode::Text)` asks
512    /// for; the mode is the documented way to leave mathematics, and
513    /// declaring both changes nothing more.
514    ///
515    /// ```
516    /// use flm_core::lang::FlmEvent;
517    /// use flm_core::lang::mint::ArgDef;
518    ///
519    /// // A caption that holds ordinary document content wherever the
520    /// // command is written.
521    /// let caption = ArgDef::mandatory("caption").event(FlmEvent::StandardState);
522    /// assert_eq!(caption.events, [FlmEvent::StandardState]);
523    /// ```
524    pub fn event(mut self, event: FlmEvent) -> ArgDef {
525        self.events.push(event);
526        self
527    }
528
529    /// Builder: sets the argument's documentation.
530    pub fn docs(mut self, docs: impl Into<String>) -> ArgDef {
531        self.docs = crate::kept_docs(docs);
532        self
533    }
534
535    /// Builder: sets the argument's **role**, the registered name of what the
536    /// argument holds, replacing any role set before.
537    ///
538    /// The syntax of an argument says how it is written (a group of
539    /// characters, raw text up to a closing brace); its role says what the
540    /// written text is: a label, a citation key, the path of an image file. A
541    /// program that describes the language reads the role, for example to
542    /// show that the argument of `\ref` and the argument of `\eqref` hold the
543    /// same kind of thing. Parsing and processing do not read it, and the
544    /// role is not an input of the [registry digest](crate::model::digest).
545    ///
546    /// A role is an entity of the registry, in a namespace of its own, the
547    /// *argument roles*. A feature declares a role with
548    /// [`FeatureBuilder::argument_role`](crate::core::registry::FeatureBuilder::argument_role),
549    /// giving its name and a description. A feature may set a role that
550    /// another feature declares; when that feature may be absent from a
551    /// registry, the feature using the role declares it as a peer
552    /// ([`FeatureBuilder::peer_argument_role`](crate::core::registry::FeatureBuilder::peer_argument_role)).
553    /// When the registry is built, a role that no feature declares, and that
554    /// the feature setting it did not declare as a peer, is refused as a
555    /// [`BuildError::UndeclaredArgumentRole`](crate::core::registry::BuildError::UndeclaredArgumentRole).
556    ///
557    /// ```
558    /// use flm_core::lang::mint::{ArgDef, ArgStdKind};
559    ///
560    /// let target = ArgDef::named("target", ArgStdKind::CharsGroup).role("flm.refs.target");
561    /// assert_eq!(target.role.as_ref().map(|name| name.as_str()), Some("flm.refs.target"));
562    /// assert!(ArgDef::mandatory("text").role.is_none());
563    /// ```
564    // A role is a fact of the declaration, which the declaring feature knows; a
565    // registered name gives each role an owner, a description and a listing.
566    pub fn role(mut self, name: impl Into<Name>) -> ArgDef {
567        self.role = Some(name.into());
568        self
569    }
570}
571
572impl PartialEq for ArgDef {
573    fn eq(&self, other: &ArgDef) -> bool {
574        self.name == other.name
575            && self.kind.identity() == other.kind.identity()
576            && self.mode == other.mode
577            && self.layout == other.layout
578            && self.opaque_wrapper == other.opaque_wrapper
579            && self.scoped == other.scoped
580            && self.events == other.events
581            && self.docs == other.docs
582            && self.role == other.role
583            && self.code == other.code
584    }
585}
586
587impl Eq for ArgDef {}
588
589/// How the [block-structure pass](crate::lang::rewrites::blocks) lays out an
590/// environment's body: as inline content, as a region of blocks, or according
591/// to the element's block role.
592///
593/// [`Inline`](BodyLayout::Inline) and [`Blocks`](BodyLayout::Blocks) take
594/// precedence over the element's block role; [`FromRole`](BodyLayout::FromRole)
595/// follows it. A verbatim body ([`BodyDef::verbatim`]), a body declared with
596/// an opaque wrapper ([`BodyDef::opaque_wrapper`]) and a body read in
597/// mathematics mode are [opaque
598/// regions](crate::guide::concepts_overview#opaque-regions): the
599/// block-structure pass carries them over untouched, regardless of their
600/// layout. A body declared with an opaque wrapper may not declare a layout
601/// other than [`FromRole`](BodyLayout::FromRole)
602/// ([`MintError::LayoutOnOpaqueWrappedBody`](super::MintError::LayoutOnOpaqueWrappedBody)).
603///
604/// It is written to data with `Serialize`; see [serialized
605/// forms](crate::core::registry#serialized-forms).
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
607#[derive(serde::Serialize, schemars::JsonSchema)]
608#[serde(rename_all = "kebab-case")]
609pub enum BodyLayout {
610    /// The body is inline content: no paragraph is built inside it, and a blank
611    /// line in it is an error.
612    Inline,
613    /// The body is a region of blocks: paragraphs are built inside it.
614    Blocks,
615    /// The body follows the element's block role: a region of blocks for an
616    /// element whose role is [`BlockRole::Block`](crate::model::aspects::BlockRole::Block),
617    /// inline content otherwise. This is the default, so that a body's layout
618    /// follows from what the element is.
619    #[default]
620    FromRole,
621}
622
623/// The declaration of an environment's body: how it is laid out, which parser
624/// reads it, which parsing mode it is read in, whether its content is kept as
625/// written under an opaque wrapper, which scoped packages are available
626/// inside it, and which state events it is read under.
627///
628/// [`BodyDef::new`] (the same as `BodyDef::default()`) declares a body laid
629/// out by the element's block role, read the ordinary way, read in the mode
630/// the environment is written in, with no opaque wrapper, with no scoped
631/// package and with no event; each builder method changes one of these.
632///
633/// The body parser is one field among the others ([`BodyDef::parser`]): a body
634/// that is not read the ordinary way (raw text, or content a feature checks as
635/// it reads it) holds the object that reads it, and minting applies the
636/// layout, mode, opaque wrapper, scoped packages and events declared here
637/// around that object.
638#[derive(Debug, Clone, Default)]
639pub struct BodyDef {
640    /// How the [block-structure pass](crate::lang::rewrites::blocks) lays out
641    /// the body.
642    pub layout: BodyLayout,
643    /// The parser that reads the body, when the body is not read the ordinary
644    /// way (content up to and including `\end{name}`). See
645    /// [`BodyDef::parser`].
646    pub parser: Option<Arc<dyn FlmBodyParser>>,
647    /// The parsing mode the body is read in: `Some(Mode::Math)` for an
648    /// equation-like environment, `Some(Mode::Text)` to restore the
649    /// non-mathematics context that encloses the mathematics, `None` to read
650    /// the body in the mode the environment is written in.
651    pub mode: Option<Mode>,
652    /// Whether minting places the body's content under an opaque wrapper, as
653    /// [`ArgDef::opaque_wrapper`] does for an argument: a group of the class
654    /// [`FlmGroupType::OpaqueWrapper`](crate::lang::FlmGroupType::OpaqueWrapper),
655    /// whose content the [block-structure pass](crate::lang::rewrites::blocks)
656    /// carries over as written. The wrapper is placed around whatever reads
657    /// the body, the declared parser or the ordinary reading, and the content
658    /// designated as the body's stays the same nodes. `false` by default; set
659    /// it with [`BodyDef::with_opaque_wrapper`].
660    ///
661    /// A body declared with an opaque wrapper may not declare a layout other
662    /// than [`BodyLayout::FromRole`]; minting reports one as
663    /// [`MintError::LayoutOnOpaqueWrappedBody`](super::MintError::LayoutOnOpaqueWrappedBody).
664    /// A scoped package declared on it is attached as on any body
665    /// ([`BodyDef::scoped`]).
666    pub opaque_wrapper: bool,
667    /// The names of the [scoped packages](ScopedPackageDef) whose
668    /// declarations are available inside this body, such as the package that
669    /// defines `\item` inside a list environment. See [`BodyDef::scoped`].
670    pub scoped: Vec<Name>,
671    /// The state events the body is read under ([`FlmEvent`]), in the order
672    /// they are declared; empty by default. See [`BodyDef::event`].
673    pub events: Vec<FlmEvent>,
674}
675
676impl BodyDef {
677    /// Creates the declaration of a body read the ordinary way, laid out by
678    /// the element's block role ([`BodyLayout::FromRole`]), read in the mode
679    /// the environment is written in, with no opaque wrapper, no scoped
680    /// package and no event. The same as `BodyDef::default()`.
681    pub fn new() -> BodyDef {
682        BodyDef::default()
683    }
684
685    /// Builder: sets how the body is laid out.
686    pub fn layout(mut self, layout: BodyLayout) -> BodyDef {
687        self.layout = layout;
688        self
689    }
690
691    /// Builder: the body is a region of blocks; shorthand for
692    /// `.layout(BodyLayout::Blocks)`.
693    pub fn blocks(self) -> BodyDef {
694        self.layout(BodyLayout::Blocks)
695    }
696
697    /// Builder: the body is raw text, read by FLM's verbatim reader
698    /// ([`crate::lang::verbatim`]), which places the content under a group of
699    /// the verbatim class; shorthand for
700    /// `.parser(FlmVerbatimBehavior::new())`.
701    pub fn verbatim(self) -> BodyDef {
702        self.parser(FlmVerbatimBehavior::new())
703    }
704
705    /// Builder: sets the parser that reads the body ([`FlmBodyParser`]), for
706    /// a body not read the ordinary way: FLM's verbatim reader
707    /// ([`BodyDef::verbatim`]), or a feature's own parser, such as one that
708    /// reads the ordinary content and then checks it.
709    ///
710    /// Only the parser's reading of the body is used: the environment's
711    /// arguments are those of the declaration, the body is read under the
712    /// mode, the scoped packages and the events declared here, and what the
713    /// parser read is placed under an opaque wrapper when the declaration asks for one
714    /// ([`BodyDef::with_opaque_wrapper`]).
715    ///
716    /// `parser` is a parser passed by value, or one already shared as
717    /// `Arc<dyn FlmBodyParser>` by several declarations; [`IntoFlmBodyParser`]
718    /// converts both.
719    pub fn parser(mut self, parser: impl IntoFlmBodyParser) -> BodyDef {
720        self.parser = Some(parser.into_flm_body_parser());
721        self
722    }
723
724    /// Builder: sets the parsing mode the body is read in. `Mode::Math` and
725    /// `Mode::Text` mean what they mean for an argument ([`ArgDef::mode`]).
726    pub fn mode(mut self, mode: Mode) -> BodyDef {
727        self.mode = Some(mode);
728        self
729    }
730
731    /// Builder: places the body's content under an opaque wrapper
732    /// ([`BodyDef::opaque_wrapper`], which states what the wrapper does and
733    /// what the declaration then admits).
734    pub fn with_opaque_wrapper(mut self) -> BodyDef {
735        self.opaque_wrapper = true;
736        self
737    }
738
739    /// Builder: makes the declarations of one more scoped package, given by
740    /// name, available inside the body. Some feature must declare a
741    /// [`ScopedPackageDef`] of that name; the rules are those of
742    /// [`ArgDef::scoped`].
743    pub fn scoped(mut self, package: impl Into<Name>) -> BodyDef {
744        self.scoped.push(package.into());
745        self
746    }
747
748    /// Builder: adds one more state event ([`FlmEvent`]) that the body is
749    /// read under, after those declared before; the rules are those of
750    /// [`ArgDef::event`].
751    ///
752    /// An environment whose body declares [`FlmEvent::StandardState`] holds
753    /// ordinary document content wherever it is written, even in a document
754    /// parsed from a restricted state:
755    ///
756    /// ```
757    /// use flm_core::lang::FlmEvent;
758    /// use flm_core::lang::mint::BodyDef;
759    ///
760    /// let body = BodyDef::new().blocks().event(FlmEvent::StandardState);
761    /// assert_eq!(body.events, [FlmEvent::StandardState]);
762    /// ```
763    pub fn event(mut self, event: FlmEvent) -> BodyDef {
764        self.events.push(event);
765        self
766    }
767}
768
769/// How an element is written in the source: as a macro, an environment, a
770/// file-inclusion macro, a special character sequence, or not at all.
771///
772/// Each form holds its list of argument declarations ([`ArgDef`]), and an
773/// environment also holds a body declaration ([`BodyDef`]). A syntax the
774/// standard argument kinds cannot express is still one of these forms: its
775/// argument, or its body, holds a parser of the feature's own
776/// ([`FlmArgumentParser`], [`FlmBodyParser`]), with its name, layout,
777/// documentation, mode and scoped packages declared like any other. Only these
778/// declarations reach techy: minting builds every specification from them.
779#[derive(Debug, Clone)]
780pub enum SyntaxDef {
781    /// A macro taking the given arguments, registered under each of the
782    /// declaration's names.
783    Macro {
784        /// The arguments, in the order they are written.
785        args: Vec<ArgDef>,
786    },
787    /// An environment taking the given arguments, written after `\begin{name}`,
788    /// and the given body; registered under each of the declaration's names.
789    Environment {
790        /// The arguments, in the order they are written.
791        args: Vec<ArgDef>,
792        /// What the body is.
793        body: BodyDef,
794    },
795    /// A macro that brings the content of another file into the document,
796    /// written `\input{reference}`. One of the given arguments must be named
797    /// [`REFERENCE_ARGUMENT`](crate::lang::input::REFERENCE_ARGUMENT); it holds
798    /// the reference as plain characters, and minting reports a declaration
799    /// without it as
800    /// [`MintError::NoReferenceArgument`](super::MintError::NoReferenceArgument).
801    /// The macro is registered under each of the declaration's names and
802    /// parsed by the language's own inclusion parser ([`crate::lang::input`]),
803    /// which asks the [input resolver](crate::lang::InputResolver) on the
804    /// [parse driver](crate::lang::FlmDriver) for the file and parses the
805    /// file's content where the command is written.
806    Inclusion {
807        /// The arguments, in the order they are written.
808        args: Vec<ArgDef>,
809    },
810    /// A special character sequence with the given trigger and arguments. The
811    /// declaration lists no name: the trigger is how the sequence is written.
812    Specials {
813        /// The character sequence that triggers it.
814        trigger: String,
815        /// The arguments, in the order they are written.
816        args: Vec<ArgDef>,
817    },
818    /// No syntax: the element is never parsed, and only a rewrite or a
819    /// lowering stage creates nodes of it, such as a heading's number or a
820    /// pointer to another node's argument. The declaration lists no name.
821    Synthesized,
822}
823
824impl SyntaxDef {
825    /// Returns the callable kind this syntax is registered under (a
826    /// file-inclusion macro is a macro); `None` for
827    /// [`SyntaxDef::Synthesized`], which is not registered.
828    pub fn kind(&self) -> Option<CallableKind> {
829        match self {
830            SyntaxDef::Macro { .. } | SyntaxDef::Inclusion { .. } => Some(CallableKind::Macro),
831            SyntaxDef::Environment { .. } => Some(CallableKind::Environment),
832            SyntaxDef::Specials { .. } => Some(CallableKind::Specials),
833            SyntaxDef::Synthesized => None,
834        }
835    }
836
837    /// Returns the argument declarations of this syntax, in the order they are
838    /// written; empty for [`SyntaxDef::Synthesized`], which takes none.
839    ///
840    /// ```
841    /// use flm_core::lang::mint::{ArgDef, SyntaxDef};
842    ///
843    /// let syntax = SyntaxDef::Macro { args: vec![ArgDef::mandatory("text")] };
844    /// assert_eq!(syntax.args().len(), 1);
845    /// assert!(SyntaxDef::Synthesized.args().is_empty());
846    /// ```
847    pub fn args(&self) -> &[ArgDef] {
848        match self {
849            SyntaxDef::Macro { args }
850            | SyntaxDef::Environment { args, .. }
851            | SyntaxDef::Inclusion { args }
852            | SyntaxDef::Specials { args, .. } => args,
853            SyntaxDef::Synthesized => &[],
854        }
855    }
856}
857
858/// An element declaration: the plain data a feature gives for an element, the
859/// syntax it is written in (macro, environment or special character sequence),
860/// its arguments (each with a parser, a layout, a parsing mode and the scoped
861/// packages available inside it) and its body.
862///
863/// Besides the syntax ([`SyntaxDef`]), the declaration holds the feature that
864/// declares it, the names the element is written under, the element value its
865/// nodes carry, the parsing modes it is available in, and documentation. A
866/// feature passes it to
867/// [`FeatureBuilder::element`](crate::core::registry::FeatureBuilder::element),
868/// or places it in a [`ScopedPackageDef`].
869///
870/// A declaration is available in text mode unless it lists its parsing modes
871/// with [`ElementDef::modes`]: a feature that defines a command of mathematics
872/// lists `[Mode::Math]`, and one that defines a command for both modes lists
873/// both. Two declarations of one name whose modes do not overlap never clash,
874/// whether they come from one feature or from two: a text-mode `\textbf` and
875/// a mathematics-mode `\textbf` are two different commands. A declaration
876/// with no syntax ([`SyntaxDef::Synthesized`]) carries the field and ignores
877/// it.
878///
879/// A declaration is ordinary unless it is marked weak with
880/// [`ElementDef::weak`]. A weak declaration of a name applies in a parsing
881/// mode only where no feature gives that name an ordinary declaration in that
882/// mode, whatever the order of the features: a mathematics processor declares
883/// its notation weakly, so that a package or a document that defines `\ket`
884/// replaces the processor's `\ket` without naming the processor in a feature
885/// order. The [module documentation of minting](super::packages) states the
886/// rule. A declaration in a [`ScopedPackageDef`] may not be weak
887/// ([`MintError::WeakInScopedPackage`](super::MintError::WeakInScopedPackage)),
888/// and a declaration with no syntax ignores the mark.
889#[derive(Clone)]
890pub struct ElementDef {
891    /// The feature that declares the element. Error messages identify the
892    /// declaration by it, and the symbol table
893    /// ([`MintedProviders::symbols`](super::MintedProviders::symbols)) records
894    /// it. The feature builder sets it to the feature being built, so a
895    /// feature need not set it; a caller of
896    /// [`build_language`](crate::lang::build_language) that builds the
897    /// declarations by hand sets it here.
898    pub owner: FeatureName,
899    /// The names this element is written under, without the escape
900    /// character. Several names may share one element value: the headings
901    /// feature, for instance, declares all the commands of one heading kind
902    /// under one element value. Empty for a special
903    /// character sequence and for an element with no syntax
904    /// ([`SyntaxDef::Synthesized`]).
905    pub names: Vec<Name>,
906    /// How the element is written.
907    pub syntax: SyntaxDef,
908    /// The element value every node of this declaration carries.
909    pub element: Arc<ElementSpec>,
910    /// Documentation of the declaration. The library does not act on it; the
911    /// registry keeps it with the declaration
912    /// ([`FlmRegistry::declarations`](crate::core::registry::FlmRegistry::declarations))
913    /// for a program that describes what an author may write.
914    pub docs: String,
915    /// The parsing modes the declaration is available in: `[Mode::Text]`
916    /// unless the feature lists others with [`ElementDef::modes`]. Ignored for
917    /// [`SyntaxDef::Synthesized`], which no document writes.
918    pub modes: Vec<Mode>,
919    /// Whether the declaration is weak: it then applies in a parsing mode only
920    /// where no feature declares the name ordinarily in that mode. Off unless
921    /// the feature sets it with [`ElementDef::weak`]. Ignored for
922    /// [`SyntaxDef::Synthesized`], which no document writes.
923    pub weak: bool,
924}
925
926impl ElementDef {
927    /// Creates the declaration, by `owner`, that `element` is written as
928    /// `syntax` under `names`, with no documentation and available in text
929    /// mode only.
930    pub fn new(
931        owner: impl Into<FeatureName>,
932        names: impl IntoIterator<Item = impl Into<Name>>,
933        syntax: SyntaxDef,
934        element: Arc<ElementSpec>,
935    ) -> ElementDef {
936        ElementDef {
937            owner: owner.into(),
938            names: names.into_iter().map(Into::into).collect(),
939            syntax,
940            element,
941            docs: String::new(),
942            modes: vec![Mode::Text],
943            weak: false,
944        }
945    }
946
947    /// Builder: sets the declaration's documentation.
948    pub fn docs(mut self, docs: impl Into<String>) -> ElementDef {
949        self.docs = crate::kept_docs(docs);
950        self
951    }
952
953    /// Builder: sets the parsing modes the declaration is available in,
954    /// replacing the default, text mode. A feature that defines a command of
955    /// mathematics passes `[Mode::Math]`; one that defines a command for both
956    /// modes passes `[Mode::Text, Mode::Math]`.
957    pub fn modes(mut self, modes: impl IntoIterator<Item = Mode>) -> ElementDef {
958        self.modes = modes.into_iter().collect();
959        self
960    }
961
962    /// Builder: marks the declaration weak. In each of its parsing modes, it
963    /// then applies only where no feature declares the same name ordinarily
964    /// in that mode, whatever the order of the features; where several
965    /// features declare the name weakly and none ordinarily, the feature order
966    /// decides among the weak declarations as among ordinary ones (see the
967    /// [module documentation of minting](super::packages)).
968    pub fn weak(mut self) -> ElementDef {
969        self.weak = true;
970        self
971    }
972}
973
974impl fmt::Debug for ElementDef {
975    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976        f.debug_struct("ElementDef")
977            .field("owner", &self.owner)
978            .field("names", &self.names)
979            .field("syntax", &self.syntax)
980            .field("element", &self.element.name)
981            .field("modes", &self.modes)
982            .field("weak", &self.weak)
983            .finish()
984    }
985}
986
987/// The callable kinds a fallback can be declared for: macros and
988/// environments.
989///
990/// There is no fallback for special character sequences: a sequence of
991/// characters that no declaration defines is not a special character
992/// sequence, and is read as ordinary text.
993#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
994pub enum FallbackKind {
995    /// Macros that no declaration defines.
996    Macro,
997    /// Environments that no declaration defines.
998    Environment,
999}
1000
1001impl FallbackKind {
1002    /// Returns the callable kind ([`CallableKind`]) this fallback kind
1003    /// applies to.
1004    pub fn callable_kind(self) -> CallableKind {
1005        match self {
1006            FallbackKind::Macro => CallableKind::Macro,
1007            FallbackKind::Environment => CallableKind::Environment,
1008        }
1009    }
1010
1011    /// Returns the callable type of the FLM language ([`FlmCallableType`])
1012    /// this fallback kind applies to.
1013    pub fn callable_type(self) -> FlmCallableType {
1014        self.callable_kind().callable_type()
1015    }
1016}
1017
1018impl fmt::Display for FallbackKind {
1019    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1020        f.write_str(match self {
1021            FallbackKind::Macro => "macro",
1022            FallbackKind::Environment => "environment",
1023        })
1024    }
1025}
1026
1027/// A fallback: a feature's declaration of what a macro or an environment that
1028/// no declaration defines means, in the parsing modes the fallback lists.
1029///
1030/// In those modes, such a command of the fallback's kind
1031/// ([`kind`](Self::kind)) resolves to a specification that takes no argument
1032/// and carries `element`, and the parse reports nothing. A mathematics feature
1033/// uses a fallback to accept any command name inside `\(…\)` as content for
1034/// the mathematics renderer, while text mode still reports an unknown command.
1035///
1036/// Only one fallback may apply to one kind in one parsing mode across a
1037/// registry: a later fallback that overlaps an earlier one is reported as a
1038/// [`MintError::Clash`](super::MintError::Clash) and not installed. The
1039/// language has its own two fallbacks, consulted after every fallback a
1040/// feature declares, which apply in every mode and report the unknown command;
1041/// their nodes carry [`UNKNOWN_MACRO`](crate::lang::structural::UNKNOWN_MACRO) or
1042/// [`UNKNOWN_ENVIRONMENT`](crate::lang::structural::UNKNOWN_ENVIRONMENT). A feature
1043/// declares a fallback with
1044/// [`FeatureBuilder::fallback`](crate::core::registry::FeatureBuilder::fallback);
1045/// [`FlmFallbackProvider`](super::FlmFallbackProvider) applies them.
1046#[derive(Clone)]
1047pub struct FallbackDef {
1048    /// The feature that declares the fallback; the feature builder sets it.
1049    pub owner: FeatureName,
1050    /// The parsing modes in which the fallback applies.
1051    pub modes: Vec<Mode>,
1052    /// The callable kind the fallback applies to.
1053    pub kind: FallbackKind,
1054    /// The element that the node of such a command carries.
1055    pub element: Arc<ElementSpec>,
1056}
1057
1058impl fmt::Debug for FallbackDef {
1059    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1060        f.debug_struct("FallbackDef")
1061            .field("owner", &self.owner)
1062            .field("modes", &self.modes)
1063            .field("kind", &self.kind)
1064            .field("element", &self.element.name)
1065            .finish()
1066    }
1067}
1068
1069/// A scoped package: a set of element declarations that can be written only
1070/// inside the environment bodies and arguments whose declarations refer to the
1071/// package by name, for instance `\item` inside a list's body or `\caption`
1072/// inside a float's body.
1073///
1074/// A body refers to a scoped package with [`BodyDef::scoped`], an argument
1075/// with [`ArgDef::scoped`]. While such a body or argument is parsed, the
1076/// package's declarations are available there and shadow any other definition
1077/// of the same names; outside, they do not exist.
1078///
1079/// Minting builds one techy package per scoped package. That package is not
1080/// on the document's scope stack: it is added as the innermost techy package
1081/// only while a body or an argument that refers to it is parsed. Minting never
1082/// checks the declarations of a scoped package for clashes with those of
1083/// another scoped package or of a feature; only two scoped packages of one
1084/// name clash ([`ClashKind::ScopedPackage`](super::ClashKind::ScopedPackage)).
1085///
1086/// A feature declares a scoped package with
1087/// [`FeatureBuilder::scoped_package`](crate::core::registry::FeatureBuilder::scoped_package).
1088/// A body or an argument may refer to a scoped package that another feature
1089/// declares. The referring feature then declares the name as a peer
1090/// ([`FeatureBuilder::peer_scoped_package`](crate::core::registry::FeatureBuilder::peer_scoped_package)),
1091/// so that a registry without the owning feature still builds: the referring
1092/// bodies and arguments then make no command available through the package.
1093/// See also [scoped packages](crate::guide::concepts_overview#scoped-packages).
1094#[derive(Clone)]
1095pub struct ScopedPackageDef {
1096    /// The feature that declares the package; the feature builder sets it,
1097    /// and sets it on each of the package's element declarations too.
1098    pub owner: FeatureName,
1099    /// The name by which a body or an argument refers to the package. It must
1100    /// be unique across the registry: minting reports a second package of the
1101    /// same name as a [`MintError::Clash`](super::MintError::Clash) and builds
1102    /// only the first.
1103    pub name: Name,
1104    /// The element declarations the package holds.
1105    pub elements: Vec<ElementDef>,
1106    /// Documentation of the package. The library does not act on it; the
1107    /// registry keeps it with the declaration
1108    /// ([`FlmRegistry::declarations`](crate::core::registry::FlmRegistry::declarations))
1109    /// for a program that describes what an author may write.
1110    pub docs: String,
1111}
1112
1113impl fmt::Debug for ScopedPackageDef {
1114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1115        f.debug_struct("ScopedPackageDef")
1116            .field("owner", &self.owner)
1117            .field("name", &self.name)
1118            .field("elements", &self.elements)
1119            .finish()
1120    }
1121}
1122
1123/// An override: the statement, by the feature `owner`, that its definition of
1124/// `name` replaces the definitions other features give that name.
1125///
1126/// Registration order decides which of several definitions of one name
1127/// applies, because a later feature's techy package is innermost on the scope
1128/// stack. Two features that define one name in one parsing mode are reported
1129/// as a [`MintError::Clash`](super::MintError::Clash), unless the feature
1130/// order places the feature registered last explicitly after the others
1131/// ([`crate::core::registry::order`]), or that feature declares an override.
1132/// An override thus prevents that report in each mode where `owner` is the
1133/// feature registered last among those that define the name; elsewhere it is
1134/// not consulted and has no effect. These rules decide among the ordinary
1135/// definitions of the name in a mode, or among its weak ones
1136/// ([`ElementDef::weak`]) where it has no ordinary one; an override never
1137/// makes a weak definition apply over an ordinary one. A feature declares an
1138/// override with
1139/// [`FeatureBuilder::override_callable`](crate::core::registry::FeatureBuilder::override_callable).
1140#[derive(Debug, Clone, PartialEq, Eq)]
1141pub struct OverrideDef {
1142    /// The feature whose definition replaces the others.
1143    pub owner: FeatureName,
1144    /// The callable kind of the redefined name.
1145    pub kind: CallableKind,
1146    /// The redefined name, without the escape character, or the trigger of a
1147    /// special character sequence.
1148    pub name: Name,
1149}