flm-core 0.7.0

FLM semantic markup framework — core library, built on techy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! The FLM language type, [`Flm`]: the type parameter techy's parser and node
//! trees take when they handle FLM.
//!
//! techy is generic over a **language**: a set of types, fixed at compile time,
//! that says which kinds of groups and of callables exist, which data is
//! attached to parsing states and to nodes, and which object holds the behavior
//! of a running parse. [`Flm`] is FLM's language. It is built on techy's
//! LaTeX-like preset (techy's ready-made specification types, argument parsers
//! and parse behavior for markup in the style of LaTeX), so the preset's parts
//! work with [`Flm`] directly.
//!
//! This module defines:
//!
//! - [`FlmGroupType`] — the group classes: content groups, mathematics,
//!   verbatim text, opaque wrappers and paragraphs.
//! - [`FlmCallableType`] — the forms a callable node takes: macro, environment,
//!   special character sequence, and two forms the library creates itself.
//! - [`FlmEvent`] — the state events: the requests, carried by a change of
//!   parsing state, whose effect depends on where the change is applied
//!   during a parse. The parse driver ([`FlmDriver`]) resolves them.
//! - [`FlmNodeExts`] — which data is attached to nodes, to arguments and to
//!   node slots (techy's `ParsedSlot`, the parts of a node's content outside
//!   its arguments, such as an environment's body).
//! - [`Flm`] itself. Its required method
//!   [`make_node_ext`](Lang::make_node_ext) gives every node its
//!   [element](crate::model::element::ElementSpec).
//!
//! Every node receives an element, and finding it needs no lookup by name. A
//! callable node's specification is always one of the wrapper types that
//! [minting](crate::lang::mint) builds, each carrying its element; every other
//! node shape takes its element from the [structural
//! elements](crate::lang::structural) the parsing state carries. See
//! [`resolve_element`] for the full rule.

use std::sync::Arc;

use techy::core::node::{NodeBuildError, NodeKind, StagedChildren};
use techy::core::specs::ScopeStack;
use techy::core::token::{SpecialsMatch, SpecialsScanError, StdTokenization, TriggerChars};
use techy::core::{
    AllLangFeatures, ClosedVocabulary, FinalizeError, Lang, NodeExtTypes, ParsingState,
    StateData,
};
use techy::latexlike::{
    builtin_package, default_token_rules, BodyMarker, InvocationSyntaxData,
    LatexlikeCallableType, LatexlikeEvent, LatexlikeGroupType, LatexlikeLang, MathGroupForm,
    Mode, StdEnvironmentSyntax,
};
use techy::serialize::{DeserializableValue, SerializableValue};
use techy::source::SourceSpan;

use crate::lang::driver::FlmDriver;
use crate::lang::ext::{FlmNodeExt, FlmStateExt};
use crate::lang::mint::resolve_element;
use crate::lang::origin::FlmOrigin;

/// The group classes: what a group node holds (content, mathematics, raw text,
/// content kept as written, or a paragraph).
///
/// A group node records its class separately from the delimiters it was
/// written with. Which delimiter pairs exist is a setting of the tokenizer
/// ([`crate::lang::rules`]), and several delimiter pairs may open groups of the
/// same class (`\(…\)` opens inline mathematics, and so does `$…$` when `$`
/// is enabled as a delimiter). Because the class is recorded on the node, code
/// anywhere in the library can ask whether a node is mathematics, verbatim text,
/// an opaque wrapper or a paragraph without looking at its delimiters.
///
/// The content of a verbatim group and of an opaque wrapper is an [opaque
/// region](crate::guide::concepts_overview#opaque-regions) whatever the parsing
/// mode of anything inside it
/// ([`is_opaque_in_any_mode`](FlmGroupType::is_opaque_in_any_mode)).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(SerializableValue, DeserializableValue)]
pub enum FlmGroupType {
    /// A plain `{…}` content group, and the group an argument parser creates
    /// around a braced argument.
    #[serial(name = "content")]
    Content,
    /// A mathematics group, inline or display.
    #[serial(name = "math")]
    Math(MathGroupForm),
    /// A group of raw text. Every run of verbatim content is a child of a group
    /// of this class; see [`crate::lang::verbatim`].
    #[serial(name = "verbatim")]
    Verbatim,
    /// A group with no delimiters of its own that holds parsed content kept as
    /// written.
    ///
    /// Minting stages one around the content of an argument or a body whose
    /// declaration asks for it
    /// ([`ArgDef::opaque_wrapper`](crate::lang::mint::ArgDef::opaque_wrapper),
    /// [`BodyDef::opaque_wrapper`](crate::lang::mint::BodyDef::opaque_wrapper)),
    /// and around every characters-only group, whose reader always places one
    /// ([`ArgStdKind::CharsGroup`](crate::lang::mint::ArgStdKind::CharsGroup)).
    /// A feature's own reader may also place one around content it keeps as
    /// written: on a theorem kind whose class reads back-references, such as
    /// a proof, the title's reader places one around a title that begins with
    /// a star
    /// ([`theorems`](crate::stdlib::features::theorems::elements#a-starred-title-is-kept-as-typed)).
    /// The block-structure pass ([`crate::lang::rewrites::blocks`]) carries
    /// its content over untouched: no whitespace is collapsed and no
    /// typographic substitution is made inside it, so the element that
    /// declared the argument reads it as typed.
    #[serial(name = "opaque-wrapper")]
    OpaqueWrapper,
    /// A paragraph. Paragraphs are created by the block-structure rewrite pass
    /// ([`crate::lang::rewrites::blocks`]); no delimiter in the source opens one.
    #[serial(name = "paragraph")]
    Paragraph,
}

impl FlmGroupType {
    /// Returns whether the content of a group of this class is an [opaque
    /// region](crate::guide::concepts_overview#opaque-regions) whatever the
    /// parsing mode of anything inside it: `true` for
    /// [`Verbatim`](FlmGroupType::Verbatim) and
    /// [`OpaqueWrapper`](FlmGroupType::OpaqueWrapper).
    ///
    /// A mathematics group is opaque too, but not in every mode: inside it, a
    /// region read in text mode, such as the argument of `\text{…}`, is
    /// document content
    /// ([`reads_text_in_math`](crate::lang::mint::reads_text_in_math)). Inside
    /// a group of a class for which this method returns `true`, no region is
    /// content, whatever mode it was read in.
    pub fn is_opaque_in_any_mode(self) -> bool {
        matches!(self, FlmGroupType::Verbatim | FlmGroupType::OpaqueWrapper)
    }
}

impl LatexlikeGroupType for FlmGroupType {
    fn content_group() -> FlmGroupType {
        FlmGroupType::Content
    }

    fn math_group(form: MathGroupForm) -> FlmGroupType {
        FlmGroupType::Math(form)
    }

    fn verbatim_group() -> FlmGroupType {
        FlmGroupType::Verbatim
    }

    fn math_form(self) -> Option<MathGroupForm> {
        match self {
            FlmGroupType::Math(form) => Some(form),
            _ => None,
        }
    }
}

impl ClosedVocabulary for FlmGroupType {
    const ALL: &'static [FlmGroupType] = &[
        FlmGroupType::Content,
        FlmGroupType::Math(MathGroupForm::Inline),
        FlmGroupType::Math(MathGroupForm::Display),
        FlmGroupType::Verbatim,
        FlmGroupType::OpaqueWrapper,
        FlmGroupType::Paragraph,
    ];
}

/// The callable forms: how a callable node was written in the source (macro,
/// environment, special character sequence), or one of two forms that only the
/// library creates (placeholder, presentation).
///
/// An author can write the first three forms. The last two are created by the
/// library only: no source text parses to them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(SerializableValue, DeserializableValue)]
pub enum FlmCallableType {
    /// A macro invocation (`\emph{…}`).
    #[serial(name = "macro")]
    Macro,
    /// An environment (`\begin{…}…\end{…}`).
    #[serial(name = "environment")]
    Environment,
    /// A special character sequence, recognized wherever it appears rather than
    /// after an escape character (`~`, `---`). Paragraph-break nodes have this
    /// form too, and so do the nodes of synthesized elements, which the library
    /// creates ([`FlmSynthesizedSpec`](crate::lang::mint::FlmSynthesizedSpec)).
    #[serial(name = "specials")]
    Specials,
    /// A placeholder in the template of a [user
    /// definition](crate::lang::rewrites::userdefs::Definition) (`#1`,
    /// `#{name}`): the place where the content of an argument is inserted when
    /// the definition is used. Placeholder nodes are created when a template is
    /// compiled, never by the parse of a document.
    #[serial(name = "placeholder")]
    Placeholder,
    /// A node of a presentation tree, the tree that lowering builds from a
    /// frozen document tree for one backend. Such a node carries its typed
    /// payload in its node extension
    /// ([`FlmNodeExt::payload`](crate::lang::ext::FlmNodeExt::payload)). No
    /// source text parses to this form.
    #[serial(name = "presentation")]
    Presentation,
}

impl LatexlikeCallableType for FlmCallableType {
    fn macro_callable() -> FlmCallableType {
        FlmCallableType::Macro
    }

    fn environment_callable() -> FlmCallableType {
        FlmCallableType::Environment
    }

    fn specials_callable() -> FlmCallableType {
        FlmCallableType::Specials
    }
}

impl ClosedVocabulary for FlmCallableType {
    const ALL: &'static [FlmCallableType] = &[
        FlmCallableType::Macro,
        FlmCallableType::Environment,
        FlmCallableType::Specials,
        FlmCallableType::Placeholder,
        FlmCallableType::Presentation,
    ];
}

/// The state events of FLM: requests, carried by a change of parsing state,
/// whose effect depends on where the change is applied.
///
/// A change of parsing state (techy's `ParsingStateDelta`) states rules,
/// a mode, scope operations and the state's data, which apply wherever the
/// change is applied. An event states instead what the change should reach,
/// and the parse driver ([`FlmDriver`]) computes, at the point where the
/// change is applied, the change that reaches it. An argument's or an
/// environment body's declaration carries events in this way
/// ([`ArgDef::event`](crate::lang::mint::ArgDef::event),
/// [`BodyDef::event`](crate::lang::mint::BodyDef::event)): the argument
/// of `\text{…}` leaves mathematics with
/// [`ExitMathContext`](FlmEvent::ExitMathContext), whatever mathematics
/// encloses it.
///
/// [`StandardScope`](FlmEvent::StandardScope) and
/// [`StandardState`](FlmEvent::StandardState) restore the *standard state of
/// the parse*: the initial state of the built language
/// ([`BuiltLang::initial_state`](crate::lang::BuiltLang::initial_state)),
/// unless the parse sets another one
/// ([`ParseOptions::standard_state`](crate::lang::ParseOptions::standard_state)).
/// A program that parses a document from a state of its own, for instance
/// one whose scope stack holds only the [base
/// scope](crate::lang::BuiltLang::base_scope) and one [scoped
/// package](crate::lang::BuiltLang::scoped_package), uses them to read the
/// content of an element of that package as standard content. Under such a
/// reduced stack:
///
/// - text, groups, comments, mathematics delimiters and paragraph breaks are
///   tokenizer rules, not packages, and stay available;
/// - a command that no package of the stack defines is reported as unknown;
/// - `\input` is declared by a feature, so a reduced stack hides it unless a
///   scoped package of the stack declares an inclusion macro;
/// - an argument and an environment's body are read in the scope that
///   applies at their command, or in the scope of the standard state when
///   their declaration carries an event that restores it
///   ([`StandardScope`](FlmEvent::StandardScope),
///   [`StandardState`](FlmEvent::StandardState)), with the scoped packages
///   that their declaration names added;
/// - `\begin{name}` needs groups to be enabled.
///
/// An event is resolved only during a parse, where the driver knows the
/// enclosing parsing states and the standard state. A state derived outside a
/// parse, with [`BuiltLang::derive_state`](crate::lang::BuiltLang::derive_state),
/// cannot carry an event: the derivation fails.
///
/// An event is written everywhere by one name: `exit-math-context`,
/// `standard-scope` and `standard-state`, in techy's serialization, in
/// `serde`'s and in the JSON schema. More events may be added in a later
/// version, so a `match` on this type needs a wildcard arm.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[derive(SerializableValue, DeserializableValue)]
#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
#[schemars(description = "A state event, listed in the `events` of the declaration of an \
    argument or of an environment's body: a change of parsing state that applies where the \
    argument or the body is read, and whose effect depends on that place. The standard state \
    is the state a document starts in, unless the program that parses the document sets \
    another.")]
pub enum FlmEvent {
    /// Restores the innermost enclosing context that is not mathematics: its
    /// tokenizer rules and its mode, or those of the outermost context when
    /// every enclosing context is mathematics. The scope stack and the state's
    /// data are kept.
    ///
    /// An argument or a body declared in text mode carries this event
    /// ([`ArgDef::mode`](crate::lang::mint::ArgDef::mode)), so that the argument
    /// of `\text{…}` is read with the rules of the text around the
    /// mathematics.
    #[schemars(description = "Reads the content with the rules and the mode of the innermost \
        enclosing text outside mathematics, as the argument of `\\text{…}` is read. The \
        commands and environments available are kept.")]
    #[serial(name = "exit-math-context")]
    ExitMathContext,
    /// Replaces the scope stack by that of the standard state of the parse.
    ///
    /// The tokenizer rules, the mode and the state's data are those of the
    /// state where the change is applied: only the commands and environments
    /// that resolve change.
    #[serial(name = "standard-scope")]
    StandardScope,
    /// Restores the standard state of the parse: its scope stack, its
    /// tokenizer rules, its mode and its data
    /// ([`FlmStateExt`]).
    ///
    /// The parsing settings of the file being read are kept. An included file
    /// with parsing settings of its own, such as its own comment prefix, keeps
    /// them inside a region that declares this event: the state restored is
    /// the standard state with these settings applied, as `\input` applies
    /// them ([`crate::lang::input`]).
    ///
    /// The settings of a file are those that its parsing state records
    /// ([`FlmStateExt::parsing`]). A program that changes the tokenizer rules
    /// of the state it parses a document from does so with rule overrides and
    /// leaves the recorded parsing settings as they are; under that state,
    /// this event restores the rules of the standard state.
    #[schemars(description = "Reads the content in the standard state: its commands and \
        environments, its rules and its mode. An included file with parsing settings of its \
        own, such as its own comment prefix, keeps them.")]
    #[serial(name = "standard-state")]
    StandardState,
}

impl LatexlikeEvent for FlmEvent {
    fn exit_math_context() -> FlmEvent {
        FlmEvent::ExitMathContext
    }

    fn is_exit_math_context(&self) -> bool {
        matches!(self, FlmEvent::ExitMathContext)
    }
}

/// The data FLM attaches to the three parts of a tree where techy lets a
/// language attach data: nodes, arguments and node slots (techy's
/// `ParsedSlot`, the parts of a node's content outside its arguments, such as
/// an environment's body). (The data attached to
/// parsing states is [`FlmStateExt`].)
///
/// - Nodes carry [`FlmNodeExt`], which holds the node's element.
/// - Arguments carry nothing (`()`), as the preset's argument parsers expect.
/// - Slots carry the preset's body marker, with which the preset marks the slot
///   that holds an environment's body; asking a node for its body relies on it.
#[derive(Debug, Clone, Copy)]
pub struct FlmNodeExts;

impl NodeExtTypes for FlmNodeExts {
    type NodeExt = FlmNodeExt;
    type ArgumentExt = ();
    type SlotExt = BodyMarker;
}

/// The FLM language: the type parameter of every techy type that handles FLM.
///
/// This type holds no data. Its implementation of techy's `Lang` trait states
/// FLM's choices (the group classes, the callable forms, the attached data, the
/// parse driver), and every techy type that depends on a language (parsing
/// states, node trees, tokens, diagnostics) takes it as its type parameter:
/// `NodeTree<Flm>` is a tree of FLM nodes. The [module documentation](self)
/// lists the choices.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Flm;

impl Lang for Flm {
    type Features = AllLangFeatures;
    type GroupTypeId = FlmGroupType;
    type CallableTypeId = FlmCallableType;
    type ModeId = Mode;
    type StateExt = FlmStateExt;
    type Event = FlmEvent;
    type SessionExt = ();
    type SourceOrigin = FlmOrigin;
    type Tokenization = StdTokenization;
    type NodeExts = FlmNodeExts;
    type InvocationSyntax = InvocationSyntaxData<StdEnvironmentSyntax<Flm>>;
    type Driver = FlmDriver;

    /// Returns the data of the language's initial parsing state (techy's
    /// `ParsingState::lang_initial`), before anything is configured: the
    /// preset's standard tokenizer rules, techy's built-in package that handles
    /// `\begin` and `\end`, text mode, and the default state extension.
    ///
    /// No document is parsed from this state. [`crate::lang::build`] derives
    /// the state every parse starts from, in one step: it applies the parsing
    /// settings, the features' packages, the fallback provider and the
    /// registry's structural elements.
    ///
    /// # Errors
    ///
    /// `FinalizeError` if the state cannot be finalized. This state is built
    /// from constants of this crate and always finalizes.
    fn initial_state_data() -> Result<StateData<Self>, FinalizeError> {
        let mut scopes = ScopeStack::new();
        scopes.push(builtin_package());
        Ok(StateData {
            rules: default_token_rules(),
            scopes,
            mode: Mode::Text,
            ext: FlmStateExt::default(),
        })
    }

    /// Checks the events that come with a change of parsing state made outside
    /// a parse.
    ///
    /// Every event of FLM ([`FlmEvent`]) is resolved by the parse driver
    /// ([`FlmDriver`]), from the stack of enclosing parsing states and from
    /// the standard state of the parse. Outside a parse there is neither, so
    /// this method refuses every event with an error instead of dropping it.
    /// Outside a parse, the standard state is the initial state of the built
    /// language itself, which a program derives from directly.
    ///
    /// # Errors
    ///
    /// `FinalizeError` when `events` is not empty. A state whose change
    /// carries an event can only be derived during a parse.
    fn finalize_transition(
        new: &mut StateData<Self>,
        prev: &ParsingState<Self>,
        events: &[FlmEvent],
    ) -> Result<(), FinalizeError> {
        let _ = (new, prev);
        if let Some(event) = events.first() {
            let name = match event {
                FlmEvent::ExitMathContext => "exit-math-context",
                FlmEvent::StandardScope => "standard-scope",
                FlmEvent::StandardState => "standard-state",
            };
            return Err(FinalizeError::new(format!(
                "Unresolved state event ‘{name}’: derive the state with \
                 ‘ParseContext::derive_state’ during a parse"
            )));
        }
        Ok(())
    }

    /// Looks for a special character sequence at byte position `pos` in
    /// `content`, and returns the match if there is one. Every provider on the
    /// state's scope stack is consulted, from the innermost outwards, and the
    /// longest match wins.
    ///
    /// # Errors
    ///
    /// `SpecialsScanError` when a provider fails while it looks for a match.
    fn scan_specials(
        state: &ParsingState<Self>,
        content: &str,
        pos: usize,
    ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
        state.scopes().scan_specials(state, content, pos)
    }

    /// The characters that can start a special character sequence under this
    /// state: the union over every provider on its scope stack. The tokenizer
    /// uses this set to skip the scan at any other character.
    fn specials_trigger_chars(data: &StateData<Self>) -> TriggerChars {
        data.scopes.specials_trigger_chars()
    }

    /// Builds the extension ([`FlmNodeExt`]) of a node that techy is about to
    /// add to a tree. This is the only place where a node receives its
    /// [element](crate::model::element::ElementSpec).
    ///
    /// Every node receives an element: a callable node the one its
    /// specification carries, every other node one of the structural elements
    /// the parsing state carries. [`resolve_element`] states the full rule. The
    /// extension's source map and payload are left empty here: the
    /// block-structure rewrite pass sets the source map on the text nodes it
    /// rewrites, and the code that builds a presentation node, a synthesized
    /// node or a rebuilt node sets its payload ([`FlmNodeExt::payload`]).
    ///
    /// # Errors
    ///
    /// `NodeBuildError::ExtMintFailed` when the node is a callable whose
    /// specification is none of the wrapper types that
    /// [minting](crate::lang::mint) builds, and therefore carries no element.
    /// No document can cause this: it requires a caller that builds a tree by
    /// hand with a specification of its own. See
    /// [`UnmintedSpec`](crate::lang::mint::UnmintedSpec).
    fn make_node_ext(
        kind: &NodeKind<Self>,
        _span: &SourceSpan<FlmOrigin>,
        state: &Arc<ParsingState<Self>>,
        _children: StagedChildren<'_, Self>,
    ) -> Result<FlmNodeExt, NodeBuildError> {
        // The one failing case is a caller-contract violation, unreachable from
        // document input: a consumer-built node whose spec is not flm-minted
        // (`UnmintedSpec`). techy's `ExtMintFailed` is the channel that exists
        // for exactly that, and it never panics.
        match resolve_element(kind, state.ext()) {
            Ok(element) => Ok(FlmNodeExt::new(element)),
            Err(error) => Err(NodeBuildError::ExtMintFailed { detail: error.to_string() }),
        }
    }
}

/// FLM keeps every default of the language family: in particular, no check runs
/// when a parse starts ([`LatexlikeLang::check_parse_start`]).
impl LatexlikeLang for Flm {}

#[cfg(test)]
mod tests {
    use super::*;
    use techy::core::ParsingStateDelta;

    #[test]
    fn the_vocabularies_play_the_preset_roles() {
        assert_eq!(FlmGroupType::content_group(), FlmGroupType::Content);
        assert_eq!(FlmGroupType::verbatim_group(), FlmGroupType::Verbatim);
        assert!(FlmGroupType::Math(MathGroupForm::Display).is_math());
        assert!(!FlmGroupType::Paragraph.is_math());
        assert!(FlmCallableType::Macro.is_macro());
        assert!(!FlmCallableType::Placeholder.is_specials());
    }

    #[test]
    fn the_seed_is_finalize_coherent() {
        let seed = ParsingState::<Flm>::lang_initial().expect("seed state");
        let rederived = seed.derived(&ParsingStateDelta::new()).unwrap();
        assert_eq!(seed.rules(), rederived.rules());
        assert_eq!(seed.mode(), rederived.mode());
        assert_eq!(seed.scopes().provider_names().collect::<Vec<_>>(), ["_builtin"]);
    }

    #[test]
    fn each_event_is_refused_out_of_parse() {
        let seed = ParsingState::<Flm>::lang_initial().expect("seed state");
        for event in [FlmEvent::ExitMathContext, FlmEvent::StandardScope, FlmEvent::StandardState] {
            assert!(seed.derived(&ParsingStateDelta::new().event(event.clone())).is_err(), "{event:?}");
        }
    }
}