flm_core/lang/flm.rs
1//! The FLM language type, [`Flm`]: the type parameter techy's parser and node
2//! trees take when they handle FLM.
3//!
4//! techy is generic over a **language**: a set of types, fixed at compile time,
5//! that says which kinds of groups and of callables exist, which data is
6//! attached to parsing states and to nodes, and which object holds the behavior
7//! of a running parse. [`Flm`] is FLM's language. It is built on techy's
8//! LaTeX-like preset (techy's ready-made specification types, argument parsers
9//! and parse behavior for markup in the style of LaTeX), so the preset's parts
10//! work with [`Flm`] directly.
11//!
12//! This module defines:
13//!
14//! - [`FlmGroupType`] — the group classes: content groups, mathematics,
15//! verbatim text, opaque wrappers and paragraphs.
16//! - [`FlmCallableType`] — the forms a callable node takes: macro, environment,
17//! special character sequence, and two forms the library creates itself.
18//! - [`FlmEvent`] — the state events: the requests, carried by a change of
19//! parsing state, whose effect depends on where the change is applied
20//! during a parse. The parse driver ([`FlmDriver`]) resolves them.
21//! - [`FlmNodeExts`] — which data is attached to nodes, to arguments and to
22//! node slots (techy's `ParsedSlot`, the parts of a node's content outside
23//! its arguments, such as an environment's body).
24//! - [`Flm`] itself. Its required method
25//! [`make_node_ext`](Lang::make_node_ext) gives every node its
26//! [element](crate::model::element::ElementSpec).
27//!
28//! Every node receives an element, and finding it needs no lookup by name. A
29//! callable node's specification is always one of the wrapper types that
30//! [minting](crate::lang::mint) builds, each carrying its element; every other
31//! node shape takes its element from the [structural
32//! elements](crate::lang::structural) the parsing state carries. See
33//! [`resolve_element`] for the full rule.
34
35use std::sync::Arc;
36
37use techy::core::node::{NodeBuildError, NodeKind, StagedChildren};
38use techy::core::specs::ScopeStack;
39use techy::core::token::{SpecialsMatch, SpecialsScanError, StdTokenization, TriggerChars};
40use techy::core::{
41 AllLangFeatures, ClosedVocabulary, FinalizeError, Lang, NodeExtTypes, ParsingState,
42 StateData,
43};
44use techy::latexlike::{
45 builtin_package, default_token_rules, BodyMarker, InvocationSyntaxData,
46 LatexlikeCallableType, LatexlikeEvent, LatexlikeGroupType, LatexlikeLang, MathGroupForm,
47 Mode, StdEnvironmentSyntax,
48};
49use techy::serialize::{DeserializableValue, SerializableValue};
50use techy::source::SourceSpan;
51
52use crate::lang::driver::FlmDriver;
53use crate::lang::ext::{FlmNodeExt, FlmStateExt};
54use crate::lang::mint::resolve_element;
55use crate::lang::origin::FlmOrigin;
56
57/// The group classes: what a group node holds (content, mathematics, raw text,
58/// content kept as written, or a paragraph).
59///
60/// A group node records its class separately from the delimiters it was
61/// written with. Which delimiter pairs exist is a setting of the tokenizer
62/// ([`crate::lang::rules`]), and several delimiter pairs may open groups of the
63/// same class (`\(…\)` opens inline mathematics, and so does `$…$` when `$`
64/// is enabled as a delimiter). Because the class is recorded on the node, code
65/// anywhere in the library can ask whether a node is mathematics, verbatim text,
66/// an opaque wrapper or a paragraph without looking at its delimiters.
67///
68/// The content of a verbatim group and of an opaque wrapper is an [opaque
69/// region](crate::guide::concepts_overview#opaque-regions) whatever the parsing
70/// mode of anything inside it
71/// ([`is_opaque_in_any_mode`](FlmGroupType::is_opaque_in_any_mode)).
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73#[derive(SerializableValue, DeserializableValue)]
74pub enum FlmGroupType {
75 /// A plain `{…}` content group, and the group an argument parser creates
76 /// around a braced argument.
77 #[serial(name = "content")]
78 Content,
79 /// A mathematics group, inline or display.
80 #[serial(name = "math")]
81 Math(MathGroupForm),
82 /// A group of raw text. Every run of verbatim content is a child of a group
83 /// of this class; see [`crate::lang::verbatim`].
84 #[serial(name = "verbatim")]
85 Verbatim,
86 /// A group with no delimiters of its own that holds parsed content kept as
87 /// written.
88 ///
89 /// Minting stages one around the content of an argument or a body whose
90 /// declaration asks for it
91 /// ([`ArgDef::opaque_wrapper`](crate::lang::mint::ArgDef::opaque_wrapper),
92 /// [`BodyDef::opaque_wrapper`](crate::lang::mint::BodyDef::opaque_wrapper)),
93 /// and around every characters-only group, whose reader always places one
94 /// ([`ArgStdKind::CharsGroup`](crate::lang::mint::ArgStdKind::CharsGroup)).
95 /// A feature's own reader may also place one around content it keeps as
96 /// written: on a theorem kind whose class reads back-references, such as
97 /// a proof, the title's reader places one around a title that begins with
98 /// a star
99 /// ([`theorems`](crate::stdlib::features::theorems::elements#a-starred-title-is-kept-as-typed)).
100 /// The block-structure pass ([`crate::lang::rewrites::blocks`]) carries
101 /// its content over untouched: no whitespace is collapsed and no
102 /// typographic substitution is made inside it, so the element that
103 /// declared the argument reads it as typed.
104 #[serial(name = "opaque-wrapper")]
105 OpaqueWrapper,
106 /// A paragraph. Paragraphs are created by the block-structure rewrite pass
107 /// ([`crate::lang::rewrites::blocks`]); no delimiter in the source opens one.
108 #[serial(name = "paragraph")]
109 Paragraph,
110}
111
112impl FlmGroupType {
113 /// Returns whether the content of a group of this class is an [opaque
114 /// region](crate::guide::concepts_overview#opaque-regions) whatever the
115 /// parsing mode of anything inside it: `true` for
116 /// [`Verbatim`](FlmGroupType::Verbatim) and
117 /// [`OpaqueWrapper`](FlmGroupType::OpaqueWrapper).
118 ///
119 /// A mathematics group is opaque too, but not in every mode: inside it, a
120 /// region read in text mode, such as the argument of `\text{…}`, is
121 /// document content
122 /// ([`reads_text_in_math`](crate::lang::mint::reads_text_in_math)). Inside
123 /// a group of a class for which this method returns `true`, no region is
124 /// content, whatever mode it was read in.
125 pub fn is_opaque_in_any_mode(self) -> bool {
126 matches!(self, FlmGroupType::Verbatim | FlmGroupType::OpaqueWrapper)
127 }
128}
129
130impl LatexlikeGroupType for FlmGroupType {
131 fn content_group() -> FlmGroupType {
132 FlmGroupType::Content
133 }
134
135 fn math_group(form: MathGroupForm) -> FlmGroupType {
136 FlmGroupType::Math(form)
137 }
138
139 fn verbatim_group() -> FlmGroupType {
140 FlmGroupType::Verbatim
141 }
142
143 fn math_form(self) -> Option<MathGroupForm> {
144 match self {
145 FlmGroupType::Math(form) => Some(form),
146 _ => None,
147 }
148 }
149}
150
151impl ClosedVocabulary for FlmGroupType {
152 const ALL: &'static [FlmGroupType] = &[
153 FlmGroupType::Content,
154 FlmGroupType::Math(MathGroupForm::Inline),
155 FlmGroupType::Math(MathGroupForm::Display),
156 FlmGroupType::Verbatim,
157 FlmGroupType::OpaqueWrapper,
158 FlmGroupType::Paragraph,
159 ];
160}
161
162/// The callable forms: how a callable node was written in the source (macro,
163/// environment, special character sequence), or one of two forms that only the
164/// library creates (placeholder, presentation).
165///
166/// An author can write the first three forms. The last two are created by the
167/// library only: no source text parses to them.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
169#[derive(SerializableValue, DeserializableValue)]
170pub enum FlmCallableType {
171 /// A macro invocation (`\emph{…}`).
172 #[serial(name = "macro")]
173 Macro,
174 /// An environment (`\begin{…}…\end{…}`).
175 #[serial(name = "environment")]
176 Environment,
177 /// A special character sequence, recognized wherever it appears rather than
178 /// after an escape character (`~`, `---`). Paragraph-break nodes have this
179 /// form too, and so do the nodes of synthesized elements, which the library
180 /// creates ([`FlmSynthesizedSpec`](crate::lang::mint::FlmSynthesizedSpec)).
181 #[serial(name = "specials")]
182 Specials,
183 /// A placeholder in the template of a [user
184 /// definition](crate::lang::rewrites::userdefs::Definition) (`#1`,
185 /// `#{name}`): the place where the content of an argument is inserted when
186 /// the definition is used. Placeholder nodes are created when a template is
187 /// compiled, never by the parse of a document.
188 #[serial(name = "placeholder")]
189 Placeholder,
190 /// A node of a presentation tree, the tree that lowering builds from a
191 /// frozen document tree for one backend. Such a node carries its typed
192 /// payload in its node extension
193 /// ([`FlmNodeExt::payload`](crate::lang::ext::FlmNodeExt::payload)). No
194 /// source text parses to this form.
195 #[serial(name = "presentation")]
196 Presentation,
197}
198
199impl LatexlikeCallableType for FlmCallableType {
200 fn macro_callable() -> FlmCallableType {
201 FlmCallableType::Macro
202 }
203
204 fn environment_callable() -> FlmCallableType {
205 FlmCallableType::Environment
206 }
207
208 fn specials_callable() -> FlmCallableType {
209 FlmCallableType::Specials
210 }
211}
212
213impl ClosedVocabulary for FlmCallableType {
214 const ALL: &'static [FlmCallableType] = &[
215 FlmCallableType::Macro,
216 FlmCallableType::Environment,
217 FlmCallableType::Specials,
218 FlmCallableType::Placeholder,
219 FlmCallableType::Presentation,
220 ];
221}
222
223/// The state events of FLM: requests, carried by a change of parsing state,
224/// whose effect depends on where the change is applied.
225///
226/// A change of parsing state (techy's `ParsingStateDelta`) states rules,
227/// a mode, scope operations and the state's data, which apply wherever the
228/// change is applied. An event states instead what the change should reach,
229/// and the parse driver ([`FlmDriver`]) computes, at the point where the
230/// change is applied, the change that reaches it. An argument's or an
231/// environment body's declaration carries events in this way
232/// ([`ArgDef::event`](crate::lang::mint::ArgDef::event),
233/// [`BodyDef::event`](crate::lang::mint::BodyDef::event)): the argument
234/// of `\text{…}` leaves mathematics with
235/// [`ExitMathContext`](FlmEvent::ExitMathContext), whatever mathematics
236/// encloses it.
237///
238/// [`StandardScope`](FlmEvent::StandardScope) and
239/// [`StandardState`](FlmEvent::StandardState) restore the *standard state of
240/// the parse*: the initial state of the built language
241/// ([`BuiltLang::initial_state`](crate::lang::BuiltLang::initial_state)),
242/// unless the parse sets another one
243/// ([`ParseOptions::standard_state`](crate::lang::ParseOptions::standard_state)).
244/// A program that parses a document from a state of its own, for instance
245/// one whose scope stack holds only the [base
246/// scope](crate::lang::BuiltLang::base_scope) and one [scoped
247/// package](crate::lang::BuiltLang::scoped_package), uses them to read the
248/// content of an element of that package as standard content. Under such a
249/// reduced stack:
250///
251/// - text, groups, comments, mathematics delimiters and paragraph breaks are
252/// tokenizer rules, not packages, and stay available;
253/// - a command that no package of the stack defines is reported as unknown;
254/// - `\input` is declared by a feature, so a reduced stack hides it unless a
255/// scoped package of the stack declares an inclusion macro;
256/// - an argument and an environment's body are read in the scope that
257/// applies at their command, or in the scope of the standard state when
258/// their declaration carries an event that restores it
259/// ([`StandardScope`](FlmEvent::StandardScope),
260/// [`StandardState`](FlmEvent::StandardState)), with the scoped packages
261/// that their declaration names added;
262/// - `\begin{name}` needs groups to be enabled.
263///
264/// An event is resolved only during a parse, where the driver knows the
265/// enclosing parsing states and the standard state. A state derived outside a
266/// parse, with [`BuiltLang::derive_state`](crate::lang::BuiltLang::derive_state),
267/// cannot carry an event: the derivation fails.
268///
269/// An event is written everywhere by one name: `exit-math-context`,
270/// `standard-scope` and `standard-state`, in techy's serialization, in
271/// `serde`'s and in the JSON schema. More events may be added in a later
272/// version, so a `match` on this type needs a wildcard arm.
273#[non_exhaustive]
274#[derive(Debug, Clone, PartialEq, Eq, Hash)]
275#[derive(SerializableValue, DeserializableValue)]
276#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
277#[serde(rename_all = "kebab-case")]
278#[schemars(description = "A state event, listed in the `events` of the declaration of an \
279 argument or of an environment's body: a change of parsing state that applies where the \
280 argument or the body is read, and whose effect depends on that place. The standard state \
281 is the state a document starts in, unless the program that parses the document sets \
282 another.")]
283pub enum FlmEvent {
284 /// Restores the innermost enclosing context that is not mathematics: its
285 /// tokenizer rules and its mode, or those of the outermost context when
286 /// every enclosing context is mathematics. The scope stack and the state's
287 /// data are kept.
288 ///
289 /// An argument or a body declared in text mode carries this event
290 /// ([`ArgDef::mode`](crate::lang::mint::ArgDef::mode)), so that the argument
291 /// of `\text{…}` is read with the rules of the text around the
292 /// mathematics.
293 #[schemars(description = "Reads the content with the rules and the mode of the innermost \
294 enclosing text outside mathematics, as the argument of `\\text{…}` is read. The \
295 commands and environments available are kept.")]
296 #[serial(name = "exit-math-context")]
297 ExitMathContext,
298 /// Replaces the scope stack by that of the standard state of the parse.
299 ///
300 /// The tokenizer rules, the mode and the state's data are those of the
301 /// state where the change is applied: only the commands and environments
302 /// that resolve change.
303 #[serial(name = "standard-scope")]
304 StandardScope,
305 /// Restores the standard state of the parse: its scope stack, its
306 /// tokenizer rules, its mode and its data
307 /// ([`FlmStateExt`]).
308 ///
309 /// The parsing settings of the file being read are kept. An included file
310 /// with parsing settings of its own, such as its own comment prefix, keeps
311 /// them inside a region that declares this event: the state restored is
312 /// the standard state with these settings applied, as `\input` applies
313 /// them ([`crate::lang::input`]).
314 ///
315 /// The settings of a file are those that its parsing state records
316 /// ([`FlmStateExt::parsing`]). A program that changes the tokenizer rules
317 /// of the state it parses a document from does so with rule overrides and
318 /// leaves the recorded parsing settings as they are; under that state,
319 /// this event restores the rules of the standard state.
320 #[schemars(description = "Reads the content in the standard state: its commands and \
321 environments, its rules and its mode. An included file with parsing settings of its \
322 own, such as its own comment prefix, keeps them.")]
323 #[serial(name = "standard-state")]
324 StandardState,
325}
326
327impl LatexlikeEvent for FlmEvent {
328 fn exit_math_context() -> FlmEvent {
329 FlmEvent::ExitMathContext
330 }
331
332 fn is_exit_math_context(&self) -> bool {
333 matches!(self, FlmEvent::ExitMathContext)
334 }
335}
336
337/// The data FLM attaches to the three parts of a tree where techy lets a
338/// language attach data: nodes, arguments and node slots (techy's
339/// `ParsedSlot`, the parts of a node's content outside its arguments, such as
340/// an environment's body). (The data attached to
341/// parsing states is [`FlmStateExt`].)
342///
343/// - Nodes carry [`FlmNodeExt`], which holds the node's element.
344/// - Arguments carry nothing (`()`), as the preset's argument parsers expect.
345/// - Slots carry the preset's body marker, with which the preset marks the slot
346/// that holds an environment's body; asking a node for its body relies on it.
347#[derive(Debug, Clone, Copy)]
348pub struct FlmNodeExts;
349
350impl NodeExtTypes for FlmNodeExts {
351 type NodeExt = FlmNodeExt;
352 type ArgumentExt = ();
353 type SlotExt = BodyMarker;
354}
355
356/// The FLM language: the type parameter of every techy type that handles FLM.
357///
358/// This type holds no data. Its implementation of techy's `Lang` trait states
359/// FLM's choices (the group classes, the callable forms, the attached data, the
360/// parse driver), and every techy type that depends on a language (parsing
361/// states, node trees, tokens, diagnostics) takes it as its type parameter:
362/// `NodeTree<Flm>` is a tree of FLM nodes. The [module documentation](self)
363/// lists the choices.
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub struct Flm;
366
367impl Lang for Flm {
368 type Features = AllLangFeatures;
369 type GroupTypeId = FlmGroupType;
370 type CallableTypeId = FlmCallableType;
371 type ModeId = Mode;
372 type StateExt = FlmStateExt;
373 type Event = FlmEvent;
374 type SessionExt = ();
375 type SourceOrigin = FlmOrigin;
376 type Tokenization = StdTokenization;
377 type NodeExts = FlmNodeExts;
378 type InvocationSyntax = InvocationSyntaxData<StdEnvironmentSyntax<Flm>>;
379 type Driver = FlmDriver;
380
381 /// Returns the data of the language's initial parsing state (techy's
382 /// `ParsingState::lang_initial`), before anything is configured: the
383 /// preset's standard tokenizer rules, techy's built-in package that handles
384 /// `\begin` and `\end`, text mode, and the default state extension.
385 ///
386 /// No document is parsed from this state. [`crate::lang::build`] derives
387 /// the state every parse starts from, in one step: it applies the parsing
388 /// settings, the features' packages, the fallback provider and the
389 /// registry's structural elements.
390 ///
391 /// # Errors
392 ///
393 /// `FinalizeError` if the state cannot be finalized. This state is built
394 /// from constants of this crate and always finalizes.
395 fn initial_state_data() -> Result<StateData<Self>, FinalizeError> {
396 let mut scopes = ScopeStack::new();
397 scopes.push(builtin_package());
398 Ok(StateData {
399 rules: default_token_rules(),
400 scopes,
401 mode: Mode::Text,
402 ext: FlmStateExt::default(),
403 })
404 }
405
406 /// Checks the events that come with a change of parsing state made outside
407 /// a parse.
408 ///
409 /// Every event of FLM ([`FlmEvent`]) is resolved by the parse driver
410 /// ([`FlmDriver`]), from the stack of enclosing parsing states and from
411 /// the standard state of the parse. Outside a parse there is neither, so
412 /// this method refuses every event with an error instead of dropping it.
413 /// Outside a parse, the standard state is the initial state of the built
414 /// language itself, which a program derives from directly.
415 ///
416 /// # Errors
417 ///
418 /// `FinalizeError` when `events` is not empty. A state whose change
419 /// carries an event can only be derived during a parse.
420 fn finalize_transition(
421 new: &mut StateData<Self>,
422 prev: &ParsingState<Self>,
423 events: &[FlmEvent],
424 ) -> Result<(), FinalizeError> {
425 let _ = (new, prev);
426 if let Some(event) = events.first() {
427 let name = match event {
428 FlmEvent::ExitMathContext => "exit-math-context",
429 FlmEvent::StandardScope => "standard-scope",
430 FlmEvent::StandardState => "standard-state",
431 };
432 return Err(FinalizeError::new(format!(
433 "Unresolved state event ‘{name}’: derive the state with \
434 ‘ParseContext::derive_state’ during a parse"
435 )));
436 }
437 Ok(())
438 }
439
440 /// Looks for a special character sequence at byte position `pos` in
441 /// `content`, and returns the match if there is one. Every provider on the
442 /// state's scope stack is consulted, from the innermost outwards, and the
443 /// longest match wins.
444 ///
445 /// # Errors
446 ///
447 /// `SpecialsScanError` when a provider fails while it looks for a match.
448 fn scan_specials(
449 state: &ParsingState<Self>,
450 content: &str,
451 pos: usize,
452 ) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
453 state.scopes().scan_specials(state, content, pos)
454 }
455
456 /// The characters that can start a special character sequence under this
457 /// state: the union over every provider on its scope stack. The tokenizer
458 /// uses this set to skip the scan at any other character.
459 fn specials_trigger_chars(data: &StateData<Self>) -> TriggerChars {
460 data.scopes.specials_trigger_chars()
461 }
462
463 /// Builds the extension ([`FlmNodeExt`]) of a node that techy is about to
464 /// add to a tree. This is the only place where a node receives its
465 /// [element](crate::model::element::ElementSpec).
466 ///
467 /// Every node receives an element: a callable node the one its
468 /// specification carries, every other node one of the structural elements
469 /// the parsing state carries. [`resolve_element`] states the full rule. The
470 /// extension's source map and payload are left empty here: the
471 /// block-structure rewrite pass sets the source map on the text nodes it
472 /// rewrites, and the code that builds a presentation node, a synthesized
473 /// node or a rebuilt node sets its payload ([`FlmNodeExt::payload`]).
474 ///
475 /// # Errors
476 ///
477 /// `NodeBuildError::ExtMintFailed` when the node is a callable whose
478 /// specification is none of the wrapper types that
479 /// [minting](crate::lang::mint) builds, and therefore carries no element.
480 /// No document can cause this: it requires a caller that builds a tree by
481 /// hand with a specification of its own. See
482 /// [`UnmintedSpec`](crate::lang::mint::UnmintedSpec).
483 fn make_node_ext(
484 kind: &NodeKind<Self>,
485 _span: &SourceSpan<FlmOrigin>,
486 state: &Arc<ParsingState<Self>>,
487 _children: StagedChildren<'_, Self>,
488 ) -> Result<FlmNodeExt, NodeBuildError> {
489 // The one failing case is a caller-contract violation, unreachable from
490 // document input: a consumer-built node whose spec is not flm-minted
491 // (`UnmintedSpec`). techy's `ExtMintFailed` is the channel that exists
492 // for exactly that, and it never panics.
493 match resolve_element(kind, state.ext()) {
494 Ok(element) => Ok(FlmNodeExt::new(element)),
495 Err(error) => Err(NodeBuildError::ExtMintFailed { detail: error.to_string() }),
496 }
497 }
498}
499
500/// FLM keeps every default of the language family: in particular, no check runs
501/// when a parse starts ([`LatexlikeLang::check_parse_start`]).
502impl LatexlikeLang for Flm {}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507 use techy::core::ParsingStateDelta;
508
509 #[test]
510 fn the_vocabularies_play_the_preset_roles() {
511 assert_eq!(FlmGroupType::content_group(), FlmGroupType::Content);
512 assert_eq!(FlmGroupType::verbatim_group(), FlmGroupType::Verbatim);
513 assert!(FlmGroupType::Math(MathGroupForm::Display).is_math());
514 assert!(!FlmGroupType::Paragraph.is_math());
515 assert!(FlmCallableType::Macro.is_macro());
516 assert!(!FlmCallableType::Placeholder.is_specials());
517 }
518
519 #[test]
520 fn the_seed_is_finalize_coherent() {
521 let seed = ParsingState::<Flm>::lang_initial().expect("seed state");
522 let rederived = seed.derived(&ParsingStateDelta::new()).unwrap();
523 assert_eq!(seed.rules(), rederived.rules());
524 assert_eq!(seed.mode(), rederived.mode());
525 assert_eq!(seed.scopes().provider_names().collect::<Vec<_>>(), ["_builtin"]);
526 }
527
528 #[test]
529 fn each_event_is_refused_out_of_parse() {
530 let seed = ParsingState::<Flm>::lang_initial().expect("seed state");
531 for event in [FlmEvent::ExitMathContext, FlmEvent::StandardScope, FlmEvent::StandardState] {
532 assert!(seed.derived(&ParsingStateDelta::new().event(event.clone())).is_err(), "{event:?}");
533 }
534 }
535}