Skip to main content

flm_core/lang/mint/
parsers.rs

1//! The parser objects that argument and body declarations hold:
2//! [`FlmArgumentParser`], which reads one argument, with the standard argument
3//! kinds ([`ArgStdKind`]) as its standard implementations, and
4//! [`FlmBodyParser`], which reads an environment's body.
5//!
6//! A declaration is data ([`super::decl`]), and its parser is one of its
7//! fields. An argument declaration ([`ArgDef`]) holds the parser that reads
8//! the argument beside everything else it declares: its name, its parsing
9//! mode, its layout, the scoped packages available inside it, the state
10//! events it is read under, and its documentation. Minting applies all of
11//! those around the parser, so a parser of a feature's own receives them
12//! exactly as a standard kind does. A body declaration
13//! ([`BodyDef`](super::BodyDef)) may likewise hold the parser that reads the
14//! body, with its layout, mode, scoped packages and state events declared
15//! beside it.
16//!
17//! techy, the parser toolkit FLM is built on, defines the traits that read the
18//! source ([`ArgumentParser`], [`EnvironmentBehavior`]). The two traits here
19//! extend them with what FLM needs to know about an argument or a body beyond
20//! reading it: what identifies the parser in the [registry
21//! digest](crate::model::digest) (the hash of everything about a registry that
22//! can change what processing produces), and a short description. For an argument, they also return which tack-on fields it
23//! declares, and how the [recomposed LaTeX
24//! backend](crate::stdlib::backends::latex_recomposed) takes the argument
25//! when it keeps a [user definition](crate::lang::rewrites::userdefs::Definition)
26//! as a LaTeX command instead of expanding its uses. The library reads a
27//! parser only through these methods and never tests which parser type it
28//! is.
29
30use std::fmt;
31use std::sync::Arc;
32
33use techy::core::constructs::{
34    ArgumentParser, ConstructParserResult, EmbellishmentsArgumentParser, GroupArgumentParser,
35    MarkerArgumentParser, OptionalGroupArgumentParser, ParseContext, ParsedArgumentNodes,
36    TackOnFieldsArgumentParser, TerminatedArgumentParser,
37};
38use techy::core::specs::ArgumentSpec;
39use techy::core::token::GroupRule;
40use techy::latexlike::{argument_specs, EnvironmentBehavior};
41
42use crate::lang::chars_group::FlmCharsGroupArgumentParser;
43use crate::lang::flm::{Flm, FlmCallableType, FlmGroupType};
44use crate::lang::mint::decl::{ArgDef, TackOnField};
45use crate::lang::mint::opaque::OpaqueWrapperReader;
46use crate::lang::verbatim::{
47    FlmRawTerminatedArgumentParser, FlmVerbatimArgumentParser, FlmVerbatimBehavior,
48};
49
50// --- the argument parser ---------------------------------------------------------------------
51
52/// The parser of one argument of a macro, an environment or a special
53/// character sequence, together with what FLM needs to know about the
54/// argument beyond reading it.
55///
56/// techy's [`ArgumentParser`] reads the argument from the source: it stages
57/// (builds into the parsed tree) the argument's nodes and says which of them
58/// are its content, or reports the argument absent. This trait adds the
59/// questions that minting, the registry build, the JSON schema of the
60/// settings and the `userdefs` feature ask of an argument, one method each:
61/// its identity, its tack-on fields, the shape of a definition written back,
62/// and its description. The standard kinds ([`ArgStdKind`]) implement them; a
63/// feature whose syntax the standard kinds cannot express writes a parser of
64/// its own and implements them itself.
65///
66/// An argument declaration ([`ArgDef`]) holds the parser as a shared object,
67/// `Arc<dyn FlmArgumentParser>`. Minting applies what the declaration holds
68/// beside it, the parsing mode ([`ArgDef::mode`]), the scoped packages
69/// ([`ArgDef::scoped`]) and the state events ([`ArgDef::events`]), as a change
70/// of parsing state over the whole argument, before
71/// [`parse_argument`](ArgumentParser::parse_argument) is called: the parser
72/// finds them already in `cx.state` and does nothing to obtain them. A parser
73/// that reads part of its input under another state asks for an event itself,
74/// with [`cx.derive_state`](ParseContext::derive_state) and a change that
75/// carries it (`ParsingStateDelta::new().event(FlmEvent::StandardState)`).
76/// Whether the content is kept as written is the declaration's choice too
77/// ([`ArgDef::opaque_wrapper`]): where the declaration asks for it, minting
78/// places what the parser read under an opaque wrapper, whatever the parser.
79///
80/// techy's own trait has one more method that matters here:
81/// [`can_match_empty`](ArgumentParser::can_match_empty) returns whether a use
82/// site may leave the argument out (`true` for an optional group or a `*`
83/// marker, `false` for a mandatory group). When the recomposed LaTeX backend
84/// keeps a user definition, it calls this method to decide whether a call
85/// must tell the definition whether the argument was written. techy's default returns
86/// `true`, so a parser that always reads something, and never reports the
87/// argument absent, overrides it to return `false`.
88///
89/// # Implementing FlmArgumentParser
90///
91/// One parser object serves every use of the command: it takes `&self`,
92/// holds no state of one parse, and receives what one use needs through its
93/// arguments (techy's requirement for [`ArgumentParser`]).
94/// It must never panic or loop on any input: an argument that reads nothing,
95/// and the end of the input reached before the argument, are ordinary inputs.
96/// Report a problem through `cx.recover` and return what was read.
97///
98/// ```
99/// use flm_core::lang::Flm;
100/// use flm_core::lang::mint::{DefinitionShape, FlmArgumentParser};
101/// use flm_core::techy::core::constructs::{
102///     ArgumentParser, ConstructParserResult, OptionalGroupArgumentParser, ParseContext,
103///     ParsedArgumentNodes,
104/// };
105/// use flm_core::techy::core::specs::ArgumentSpec;
106/// use flm_core::techy::core::token::GroupRule;
107/// use flm_core::lang::FlmGroupType;
108/// use std::sync::Arc;
109///
110/// /// An optional `<…>` group.
111/// #[derive(Debug)]
112/// struct Angles(OptionalGroupArgumentParser<Flm>);
113///
114/// impl Angles {
115///     fn new() -> Angles {
116///         let rule = Arc::new(GroupRule {
117///             group_type: FlmGroupType::Content,
118///             open: String::from("<"),
119///             close: String::from(">"),
120///         });
121///         Angles(OptionalGroupArgumentParser::new(rule))
122///     }
123/// }
124///
125/// impl ArgumentParser<Flm> for Angles {
126///     fn parse_argument(
127///         &self,
128///         cx: &mut ParseContext<'_, '_, Flm>,
129///         spec: &ArgumentSpec<Flm>,
130///     ) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
131///         self.0.parse_argument(cx, spec)
132///     }
133/// }
134///
135/// impl FlmArgumentParser for Angles {
136///     fn identity(&self) -> Vec<u8> {
137///         b"example.angles".to_vec()
138///     }
139///     fn definition_shape(&self) -> DefinitionShape {
140///         DefinitionShape::NoShape { token: "angles" }
141///     }
142///     fn description(&self) -> String {
143///         String::from("an optional `<…>` group")
144///     }
145/// }
146///
147/// let arg = flm_core::lang::mint::ArgDef::named("extra", Angles::new());
148/// assert_eq!(arg.kind.description(), "an optional `<…>` group");
149/// ```
150pub trait FlmArgumentParser: ArgumentParser<Flm> + Send + Sync {
151    /// Returns the bytes that identify this parser in the [registry
152    /// digest](crate::model::digest) (the hash of everything about a registry
153    /// that can change what processing produces) and in the digest that the
154    /// `userdefs` feature computes over its configuration
155    /// ([`UserdefsConfig::digest_bytes`](crate::stdlib::features::userdefs::UserdefsConfig::digest_bytes)).
156    ///
157    /// Two parsers that read differently must return different bytes (a
158    /// standard kind returns bytes per kind and per delimiter pair), and one
159    /// parser must return the same bytes in every run and every process. Build
160    /// them from data the parser holds, never from an address or a randomized
161    /// hash. The digests take the bytes as one string, preceded by its length,
162    /// so the bytes need no terminator. A parser of a feature's own begins its
163    /// bytes with a name no other parser uses, such as the feature's name.
164    fn identity(&self) -> Vec<u8>;
165
166    /// Returns the [tack-on fields](TackOnField) the argument declares, when
167    /// it is a **tack-on argument**: the argument that absorbs the field macros
168    /// written at its position in a call, after the arguments declared before
169    /// it, such as the `\label{…}` after a heading. The default returns `None`,
170    /// for every other argument.
171    ///
172    /// A parser of a feature's own keeps the default; declare a tack-on
173    /// argument with [`ArgStdKind::TackOn`]. For any argument whose parser
174    /// returns fields, minting builds the argument's reader itself, and that
175    /// reader replaces the object's
176    /// [`parse_argument`](ArgumentParser::parse_argument).
177    ///
178    /// The reason is that each tack-on field is a declaration of its own, with
179    /// its own arguments. Minting builds the field's specification
180    /// into the techy package of fields
181    /// ([`FIELDS_PACKAGE_NAME`](super::FIELDS_PACKAGE_NAME)), which records
182    /// where the specification is held so that a serialized tree can find it
183    /// again (the [provenance stamp](super::packages)). That package is
184    /// created during the language build, after every parser object has been
185    /// created, so a parser object cannot hold those specifications.
186    fn tack_on_fields(&self) -> Option<&[TackOnField]> {
187        None
188    }
189
190    /// Returns how a user definition that declares this argument is written
191    /// back as a LaTeX definition, when the [recomposed LaTeX
192    /// backend](crate::stdlib::backends::latex_recomposed) keeps the
193    /// definition rather than expanding it. See [`DefinitionShape`].
194    fn definition_shape(&self) -> DefinitionShape;
195
196    /// Returns a description of the argument's syntax in a short phrase, such
197    /// as "an optional `[…]` group".
198    ///
199    /// The JSON schema of the settings shows it for each argument code that a
200    /// settings file may write
201    /// ([`arg_def_from_code`](crate::lang::mint::arg_def_from_code)). Nothing
202    /// else in the library reads it.
203    fn description(&self) -> String;
204
205    /// Returns the [standard kind](ArgStdKind) this parser reads, for a
206    /// program that describes the registry's declarations, such as a
207    /// generator of documentation pages; `None`, the default, for a parser of
208    /// a feature's own.
209    fn std_kind(&self) -> Option<&ArgStdKind> {
210        None
211    }
212}
213
214/// How the [recomposed LaTeX backend](crate::stdlib::backends::latex_recomposed)
215/// takes one declared argument when it keeps a [user
216/// definition](crate::lang::rewrites::userdefs::Definition) as a LaTeX command
217/// instead of expanding its uses, as returned by
218/// [`FlmArgumentParser::definition_shape`].
219///
220/// When the recomposed LaTeX backend keeps a user definition, it writes the
221/// definition once, as a LaTeX command, and each use of the definition as a
222/// call of that command.
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
224pub enum DefinitionShape {
225    /// The definition takes the argument as a value: each call writes, in one
226    /// brace group, what the use site wrote for the argument, so the
227    /// argument's delimiters in the source never reach LaTeX. A tack-on
228    /// argument, which no template may refer to, contributes no group. Every
229    /// standard kind returns this, except
230    /// [`ArgStdKind::Terminated`].
231    Value,
232    /// No shape of a kept definition expresses the argument. A user
233    /// definition that declares it is not kept: the recomposed LaTeX backend
234    /// expands its uses instead, and gives `token` as the reason the
235    /// definition was not kept
236    /// ([`NotRecomposable::ArgumentShape`](crate::lang::rewrites::userdefs::NotRecomposable::ArgumentShape)).
237    NoShape {
238        /// The shape's name in one stable word, given as the reason the
239        /// definition was not kept.
240        token: &'static str,
241    },
242}
243
244/// Conversion into an argument's shared parser object: the parameter type of
245/// [`ArgDef::new`] and [`ArgDef::named`], so that a standard kind and a parser
246/// of one's own are passed the same way.
247///
248/// Three types convert: an [`ArgStdKind`], wrapped into the object that reads
249/// it; any [`FlmArgumentParser`], passed by value and shared from then on; and
250/// an already shared `Arc<dyn FlmArgumentParser>`, passed through unchanged,
251/// so that one parser reused by several declarations stays one value.
252pub trait IntoFlmArgumentParser {
253    /// Returns the shared parser object an [`ArgDef`] holds.
254    fn into_flm_argument_parser(self) -> Arc<dyn FlmArgumentParser>;
255}
256
257impl IntoFlmArgumentParser for ArgStdKind {
258    fn into_flm_argument_parser(self) -> Arc<dyn FlmArgumentParser> {
259        Arc::new(StdArgumentParser::new(self))
260    }
261}
262
263impl<P: FlmArgumentParser + 'static> IntoFlmArgumentParser for P {
264    fn into_flm_argument_parser(self) -> Arc<dyn FlmArgumentParser> {
265        Arc::new(self)
266    }
267}
268
269impl IntoFlmArgumentParser for Arc<dyn FlmArgumentParser> {
270    fn into_flm_argument_parser(self) -> Arc<dyn FlmArgumentParser> {
271        self
272    }
273}
274
275// --- the standard kinds ----------------------------------------------------------------------
276
277/// The standard argument kinds: the forms of argument that FLM provides,
278/// each describing, as data, what one argument looks like in the source.
279///
280/// An argument declaration takes a kind as its parser
281/// (`ArgDef::named("title", ArgStdKind::Mandatory)`, see [`ArgDef::named`]);
282/// each kind is read by a parser of techy's or of FLM's own and implements
283/// [`FlmArgumentParser`]. An argument that no standard kind expresses holds a
284/// parser of its own instead.
285///
286/// # The kind as data
287///
288/// A kind is written to data and read from it (`serde::Serialize`,
289/// `serde::Deserialize`) as a map: the key `syntax` holds the kind's name, in
290/// lowercase with hyphens, and the kind's parameters stand beside it, as in
291/// `{"syntax": "delimited-group", "delimiters": ["(", ")"]}`. This map is the
292/// **structured syntax** of an argument in settings given as data, which the
293/// [`codes`](crate::lang::mint::codes) module reads together with the
294/// argument codes, the shorthands that stand for the same kinds. The names
295/// and the parameters:
296///
297/// | kind | `syntax` | parameters |
298/// |---|---|---|
299/// | [`Mandatory`](ArgStdKind::Mandatory) | `mandatory` | none |
300/// | [`Optional`](ArgStdKind::Optional) | `optional` | none |
301/// | [`Star`](ArgStdKind::Star) | `star` | none |
302/// | [`Marker`](ArgStdKind::Marker) | `marker` | `marker`: the marker's characters, one or more (`*` reads as `star`) |
303/// | [`DelimitedGroup`](ArgStdKind::DelimitedGroup) | `delimited-group` | `delimiters`: the opening and the closing character, as a list of two (`["(", ")"]`) |
304/// | [`OptionalDelimitedGroup`](ArgStdKind::OptionalDelimitedGroup) | `optional-delimited-group` | `delimiters`, as for `delimited-group` |
305/// | [`AnyDelimitedGroup`](ArgStdKind::AnyDelimitedGroup) | `any-delimited-group` | none |
306/// | [`OptionalAnyDelimitedGroup`](ArgStdKind::OptionalAnyDelimitedGroup) | `optional-any-delimited-group` | none |
307/// | [`BracedOnly`](ArgStdKind::BracedOnly) | `braced-only` | none |
308/// | [`Embellishments`](ArgStdKind::Embellishments) | `embellishments` | `markers`: the marker characters, a list of at least one (`["^", "_"]`) |
309/// | [`KeyVals`](ArgStdKind::KeyVals) | `key-vals` | none |
310/// | [`CharsGroup`](ArgStdKind::CharsGroup) | `chars-group` | none |
311/// | [`Verbatim`](ArgStdKind::Verbatim) | `verbatim` | `delimiters`: the prescribed pair, as for `delimited-group`; absent for a closing delimiter matched to whichever opening one is found |
312/// | [`TackOn`](ArgStdKind::TackOn) | `tack-on` | `fields`: a list of maps `{"name", "args", "repeatable", "docs"}`, one per field: `name`, the field's name without the backslash; `args`, the field's arguments as an argument list ([`ArgListData`](crate::lang::mint::ArgListData)), none by default; `repeatable`, `false` by default; `docs`, empty by default |
313/// | [`Terminated`](ArgStdKind::Terminated) | `terminated` | `terminator`: text; `repeat_char`: one character, absent for none; `opener`: text, empty by default; `head`: text, empty by default; `raw`: `true` or `false`, `false` by default |
314///
315/// Each character is written as a text of one character, and a marker as a
316/// text of one or more characters; none of them may be whitespace, as in the
317/// argument codes. A parameter that has no default must be written. Reading a
318/// kind refuses, with a message that states the condition broken:
319///
320/// - a key that is not one of the kind's parameters, and a name that is no
321///   kind's;
322/// - a character written as a text of another length, or as whitespace, and
323///   a marker written as an empty text or with whitespace;
324/// - `delimiters` that are not two, and an empty list of `markers`;
325/// - the two configurations of `terminated` that can never work (see
326///   [`Terminated`](ArgStdKind::Terminated)): a terminator that is always
327///   empty, and an `opener` that begins with `repeat_char`;
328/// - a `tack-on` field's argument that cannot be read (its position and the
329///   field's name are given); that the fields' names are distinct is checked
330///   by the minting (see [`TackOn`](ArgStdKind::TackOn)).
331///
332/// Three kinds have no argument code ([`KeyVals`](ArgStdKind::KeyVals),
333/// [`CharsGroup`](ArgStdKind::CharsGroup), [`TackOn`](ArgStdKind::TackOn)),
334/// and the codes of [`Terminated`](ArgStdKind::Terminated) set neither its
335/// opener nor its terminator head: settings write those with the structured
336/// syntax.
337///
338/// Two kinds are equal (`PartialEq`) when they are the same kind with equal
339/// parameters; two tack-on fields are equal when their names, arguments,
340/// repetition and documentation are.
341#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
342#[derive(schemars::JsonSchema)]
343#[serde(
344    into = "crate::lang::mint::codes::ArgStdKindData",
345    try_from = "crate::lang::mint::codes::ArgStdKindData"
346)]
347pub enum ArgStdKind {
348    /// A mandatory `{…}` group. A single token also counts, as in TeX:
349    /// `\frac12` is `\frac{1}{2}`.
350    Mandatory,
351    /// An optional `[…]` group. When the whole content is one `{…}` group,
352    /// the argument's content is that group's content, so it may hold the
353    /// closing character: `[{a]b}]` reads `a]b`.
354    Optional,
355    /// An optional `*` marker: whether the command was written in its starred
356    /// form.
357    Star,
358    /// An optional marker made of one or more characters, as the `!` of
359    /// `\name!`: whether the command was written with it. The marker's
360    /// characters are matched as they are written in the source, even a
361    /// character that elsewhere begins a command, a group or a special
362    /// character sequence: a marker `\big` matches the four characters `\big`
363    /// in `\name\big`, which are then not read as the command `\big`. The
364    /// characters after the marker are not checked, so the marker `\big` also
365    /// matches the beginning of `\name\bigg`. The `*` marker is
366    /// [`ArgStdKind::Star`].
367    Marker {
368        /// The marker's characters, one or more.
369        marker: String,
370    },
371    /// A mandatory group between a prescribed pair of characters, as the
372    /// `(…)` of `\name(arg)`. Nothing else is accepted: no `{…}` group and no
373    /// single token. The two characters delimit a group only at this
374    /// argument's position; everywhere else they are ordinary characters.
375    DelimitedGroup {
376        /// The opening character.
377        open: char,
378        /// The closing character.
379        close: char,
380    },
381    /// An optional group between a prescribed pair of characters, as the
382    /// `<…>` of `\name<arg>`. As for [`ArgStdKind::Optional`], when the
383    /// whole content is one `{…}` group, the argument's content is that
384    /// group's content: `<{a>b}>` reads `a>b`.
385    OptionalDelimitedGroup {
386        /// The opening character.
387        open: char,
388        /// The closing character.
389        close: char,
390    },
391    /// A mandatory group between any of the pairs `{…}`, `[…]`, `(…)` and
392    /// `<…>`, whichever the use site opens; the parsed group records which
393    /// pair delimits it. No single token counts.
394    AnyDelimitedGroup,
395    /// An optional group between any of the pairs of
396    /// [`ArgStdKind::AnyDelimitedGroup`].
397    OptionalAnyDelimitedGroup,
398    /// A mandatory `{…}` group and nothing else: unlike
399    /// [`ArgStdKind::Mandatory`], a single token does not count, so a use
400    /// site that writes no group is told that the argument is missing.
401    BracedOnly,
402    /// **Embellishments**: a run of pairs, each a marker character followed by
403    /// one expression (a group, a command with its arguments, or one
404    /// character), in any order, each marker at most once, as the subscript
405    /// and the superscript of `\name_{a}^{b}` or `\name^{b}_{a}`. A marker is
406    /// matched as written, as the marker of [`ArgStdKind::Marker`] is. The
407    /// argument is absent when no marker follows the command. techy's
408    /// [`split_embellishments`](techy::extract::split_embellishments) reads
409    /// the pairs back by marker.
410    Embellishments {
411        /// The marker characters, at least one.
412        markers: Vec<char>,
413    },
414    /// An optional `[key=value,…]` group.
415    ///
416    /// Parsed like [`ArgStdKind::Optional`]; the element that declares the
417    /// argument reads the keys and values out of it. Declaring this kind
418    /// rather than [`ArgStdKind::Optional`] records what the argument is for.
419    /// The values are FLM markup. A group whose values the document shows (an
420    /// item's tag, a heading's `alt=`) is laid out by the [block-structure
421    /// pass](crate::lang::rewrites::blocks) as any content. An element that
422    /// reads the values as data declares the argument with
423    /// [`ArgDef::with_opaque_wrapper`], so that they are kept as written.
424    KeyVals,
425    /// A mandatory `{…}` group read as plain characters, as in
426    /// `\label{sec:intro}`. An escape character and a special character
427    /// sequence are ordinary characters inside it; comments and nested groups
428    /// are still recognized, and when a user definition's template is parsed,
429    /// its placeholders (`#1`, `#{name}`) are still recognized inside it
430    /// ([`crate::lang::chars_group`]). The reader places the group under an
431    /// opaque wrapper ([`FlmGroupType::OpaqueWrapper`]), so the
432    /// [block-structure pass](crate::lang::rewrites::blocks) carries the
433    /// characters over as written.
434    CharsGroup,
435    /// A verbatim argument delimited by a pair of characters
436    /// (`\verbcode|…|`, `\verbcode{…}`): raw text up to the closing delimiter,
437    /// wrapped in a group of the verbatim class like every other verbatim run
438    /// ([`crate::lang::verbatim`], which also states how this shape differs
439    /// from [`ArgStdKind::CharsGroup`]). The [block-structure
440    /// pass](crate::lang::rewrites::blocks) carries the text over as written.
441    Verbatim {
442        /// `None` matches the closing delimiter to whichever opening character
443        /// is found (`{}`, `[]`, `<>`, `()`, and otherwise the same character
444        /// again); `Some((open, close))` prescribes the pair.
445        delimiters: Option<(char, char)>,
446    },
447    /// The [tack-on fields](TackOnField) a command accepts: the argument
448    /// absorbs the run of field macros written where it stands, and anything
449    /// else ends the run, after which the next declared argument is read.
450    /// Declared last, as a heading declares it, it absorbs the fields written
451    /// after the command's other arguments (`\section{…}\label{…}`). Each
452    /// field written there becomes a macro node named as the field is
453    /// written, carrying the language's field element
454    /// ([`FIELD`](crate::lang::structural::FIELD)).
455    ///
456    /// Its fields must have distinct names. Minting reports a declaration that
457    /// breaks this rule
458    /// ([`MintError::FieldDeclaredTwice`](crate::lang::mint::MintError::FieldDeclaredTwice)).
459    TackOn {
460        /// The fields this command accepts, in no particular order: they may be
461        /// written in any order after the command.
462        fields: Vec<TackOnField>,
463    },
464    // One general kind over the toolkit's parser serves every construct that runs up to
465    // a terminator: the parsing state decides how the content is read, and a longer run
466    // of the repeat character lets any content hold the terminator.
467    /// A mandatory argument that runs up to a fixed character sequence, its
468    /// **terminator**, as in `\phf … \endphf` or a code span `` `…` ``.
469    ///
470    /// The argument is written as three consecutive parts:
471    ///
472    /// 1. the **prefix**: a run of copies of `repeat_char`, as many as the use
473    ///    site writes, possibly none (only when `repeat_char` is set),
474    ///    followed by `opener` (empty when not needed);
475    /// 2. the **content**;
476    /// 3. the terminator: `head`, then as many copies of `repeat_char` as the
477    ///    prefix had, then `terminator`.
478    ///
479    /// | syntax | declaration |
480    /// |---|---|
481    /// | `\phf … \endphf`, content parsed | a macro `\phf` with `Terminated { terminator: "\\endphf", repeat_char: None, opener: "", head: "", raw: false }` |
482    /// | `` `x` `` and ``` ``a`b`` ```, raw text | a special character sequence `` ` `` with `` Terminated { terminator: "`", repeat_char: Some('`'), opener: "", head: "", raw: true } `` |
483    /// | `\fenced+++…+++`, raw text | a macro `\fenced` with `Terminated { terminator: "", repeat_char: Some('+'), opener: "", head: "", raw: true }` |
484    ///
485    /// In the code span row, the special character sequence has already read
486    /// the first backtick, and the argument counts the backticks that follow
487    /// it: the terminator is one backtick for each counted one, then the
488    /// final backtick, as many backticks as opened the span.
489    ///
490    /// Nothing is skipped before the prefix: a space at the start is content,
491    /// as in the code span `` ` x` ``, except the spaces that the source
492    /// reader counts as part of the preceding command name (`\phf a\endphf`
493    /// has the content `a`). The terminator is matched character for
494    /// character wherever it appears, before any other markup: inside parsed
495    /// content, `\endphf` is never read as a command, and a run of three
496    /// backticks ends a code span opened with two at its first two, the third
497    /// following the argument. Nothing is trimmed from the content. The
498    /// toolkit's [`TerminatedArgumentParser`]
499    /// reads the argument; its documentation gives the complete rules.
500    ///
501    /// With `raw: false`, the content is parsed as document content: commands,
502    /// groups and comments inside it are read as usual, and the terminator is
503    /// not recognized inside a nested `{…}` group. With `raw: true`, the
504    /// content is raw text, read under the same parsing state as a verbatim
505    /// argument's interior and held by a group of the verbatim class, like
506    /// every verbatim run ([`crate::lang::verbatim`]); the [block-structure
507    /// pass](crate::lang::rewrites::blocks) carries it over as written.
508    ///
509    /// When the terminator never appears, the argument keeps the content read
510    /// up to the end of the input (or up to a closing delimiter that nothing
511    /// in it opened) and the toolkit's
512    /// [`MissingArgumentTerminator`](techy::core::constructs::MissingArgumentTerminator)
513    /// is reported. When the prefix is incomplete (the opener does not follow
514    /// the run, or the run is the whole terminator and the use site writes
515    /// none of it), the toolkit's
516    /// [`ExpectedArgumentOpener`](techy::core::constructs::ExpectedArgumentOpener)
517    /// is reported and the argument is absent.
518    ///
519    /// Two configurations can never work, and the toolkit stops every parse
520    /// that reaches such an argument with an implementation error: a
521    /// terminator that is always empty (`repeat_char`, `head` and
522    /// `terminator` all empty), and an `opener` that begins with
523    /// `repeat_char`. Reading the kind from data refuses both.
524    ///
525    /// Settings given as data write this kind with the structured syntax
526    /// `terminated`, which sets each of the five fields, or with the codes
527    /// `u`, `U`, `f` and `F`, which set neither `opener` nor `head`
528    /// ([`crate::lang::mint::codes`]). The recomposed LaTeX backend cannot
529    /// keep a user definition that declares such an argument
530    /// ([`DefinitionShape::NoShape`]).
531    Terminated {
532        /// The end of the terminator, after the repeated characters: the
533        /// whole terminator unless `repeat_char` or `head` is set. It may be
534        /// empty only when `repeat_char` is set.
535        terminator: String,
536        /// The character whose run starts the prefix and is repeated in the
537        /// terminator, or `None`.
538        repeat_char: Option<char>,
539        /// The fixed text that follows the run of `repeat_char` in the
540        /// prefix; empty for none.
541        opener: String,
542        /// The fixed text that begins the terminator, before the repeated
543        /// characters; empty for none.
544        head: String,
545        /// Whether the content is raw text (`true`) or parsed document
546        /// content (`false`).
547        raw: bool,
548    },
549}
550
551impl ArgStdKind {
552    /// Returns the parser that reads this kind: one of techy's argument
553    /// presets (`m`, `o`, `s`); one of techy's group, marker or embellishments
554    /// parsers, built as techy's table of argument codes builds it for the
555    /// same code; FLM's characters-only group or verbatim argument; techy's
556    /// terminated parser, run under the raw-text state for raw content
557    /// ([`FlmRawTerminatedArgumentParser`]); or, for a tack-on argument,
558    /// techy's tack-on reader with no field, which absorbs nothing. The specifications of the fields exist only once minting has
559    /// built them, and minting then builds the reader of a tack-on argument
560    /// itself ([`FlmArgumentParser::tack_on_fields`]). The reader of a
561    /// characters-only group places what it reads under an opaque wrapper
562    /// ([`OpaqueWrapperReader`]).
563    fn reader(&self) -> Arc<dyn ArgumentParser<Flm>> {
564        match self {
565            ArgStdKind::Mandatory => preset("m"),
566            ArgStdKind::Optional | ArgStdKind::KeyVals => preset("o"),
567            ArgStdKind::Star => preset("s"),
568            ArgStdKind::Marker { marker } => Arc::new(MarkerArgumentParser::new(marker.clone())),
569            ArgStdKind::DelimitedGroup { open, close } => {
570                Arc::new(GroupArgumentParser::with_rule(group_rule(*open, *close)))
571            }
572            ArgStdKind::OptionalDelimitedGroup { open, close } => Arc::new(
573                OptionalGroupArgumentParser::new(group_rule(*open, *close))
574                    .with_unwrap_lone_group(FlmGroupType::Content),
575            ),
576            ArgStdKind::AnyDelimitedGroup => Arc::new(GroupArgumentParser::any_of(any_delimited_rules())),
577            ArgStdKind::OptionalAnyDelimitedGroup => Arc::new(
578                OptionalGroupArgumentParser::any_of(any_delimited_rules())
579                    .with_unwrap_lone_group(FlmGroupType::Content),
580            ),
581            ArgStdKind::BracedOnly => Arc::new(
582                GroupArgumentParser::<Flm>::new(FlmGroupType::Content).with_expression_fallback(false),
583            ),
584            ArgStdKind::Embellishments { markers } => {
585                Arc::new(EmbellishmentsArgumentParser::new(markers.iter().map(|marker| String::from(*marker))))
586            }
587            ArgStdKind::CharsGroup => {
588                Arc::new(OpaqueWrapperReader::new(Arc::new(FlmCharsGroupArgumentParser::new())))
589            }
590            ArgStdKind::Verbatim { delimiters: Some((open, close)) } => {
591                Arc::new(FlmVerbatimArgumentParser::new().with_delimiters(*open, *close))
592            }
593            ArgStdKind::Verbatim { delimiters: None } => Arc::new(FlmVerbatimArgumentParser::new()),
594            ArgStdKind::TackOn { .. } => {
595                Arc::new(TackOnFieldsArgumentParser::<Flm>::new(FlmCallableType::Macro))
596            }
597            ArgStdKind::Terminated { terminator, repeat_char, opener, head, raw } => {
598                let group_type = if *raw { FlmGroupType::Verbatim } else { FlmGroupType::Content };
599                let mut parser = TerminatedArgumentParser::<Flm>::new(group_type, terminator.as_str())
600                    .with_opener(opener.as_str())
601                    .with_terminator_head(head.as_str());
602                if let Some(repeat_char) = repeat_char {
603                    parser = parser.with_repeat_char(*repeat_char);
604                }
605                if *raw {
606                    Arc::new(FlmRawTerminatedArgumentParser::new(parser))
607                } else {
608                    Arc::new(parser)
609                }
610            }
611        }
612    }
613
614    /// Returns the identity bytes of [`FlmArgumentParser::identity`]: the
615    /// kind's word, then the characters the kind holds (a marker, a pair, the
616    /// markers of embellishments), a verbatim argument's prescribed pair, a
617    /// tack-on argument's fields (each field's name, its arguments' names and
618    /// identities, and whether it may repeat), or a terminated argument's
619    /// configuration (its terminator, its repeat character or none, its
620    /// opener, its terminator head, and whether it is raw).
621    fn identity(&self) -> Vec<u8> {
622        let mut out = Vec::new();
623        match self {
624            ArgStdKind::Mandatory => put(&mut out, "mandatory"),
625            ArgStdKind::Optional => put(&mut out, "optional"),
626            ArgStdKind::Star => put(&mut out, "star"),
627            ArgStdKind::Marker { marker } => {
628                put(&mut out, "marker");
629                put(&mut out, marker);
630            }
631            ArgStdKind::DelimitedGroup { open, close } => {
632                put(&mut out, "delimited");
633                put(&mut out, &format!("{open}{close}"));
634            }
635            ArgStdKind::OptionalDelimitedGroup { open, close } => {
636                put(&mut out, "optional-delimited");
637                put(&mut out, &format!("{open}{close}"));
638            }
639            ArgStdKind::AnyDelimitedGroup => put(&mut out, "any-delimited"),
640            ArgStdKind::OptionalAnyDelimitedGroup => put(&mut out, "optional-any-delimited"),
641            ArgStdKind::BracedOnly => put(&mut out, "braced-only"),
642            ArgStdKind::Embellishments { markers } => {
643                put(&mut out, "embellishments");
644                put(&mut out, &markers.iter().collect::<String>());
645            }
646            ArgStdKind::KeyVals => put(&mut out, "keyvals"),
647            ArgStdKind::CharsGroup => put(&mut out, "chars"),
648            ArgStdKind::Verbatim { delimiters } => {
649                put(&mut out, "verbatim");
650                match delimiters {
651                    None => put(&mut out, "-"),
652                    Some((open, close)) => put(&mut out, &format!("+{open}{close}")),
653                }
654            }
655            ArgStdKind::TackOn { fields } => {
656                put(&mut out, "tack-on");
657                put_count(&mut out, fields.len());
658                for field in fields {
659                    put(&mut out, &field.name);
660                    put_count(&mut out, field.args.len());
661                    for arg in &field.args {
662                        put_arg_identity(&mut out, arg);
663                    }
664                    put_count(&mut out, usize::from(field.repeatable));
665                }
666            }
667            ArgStdKind::Terminated { terminator, repeat_char, opener, head, raw } => {
668                put(&mut out, "terminated");
669                put(&mut out, terminator);
670                match repeat_char {
671                    None => put(&mut out, "-"),
672                    Some(repeat_char) => put(&mut out, &format!("+{repeat_char}")),
673                }
674                put(&mut out, opener);
675                put(&mut out, head);
676                put_count(&mut out, usize::from(*raw));
677            }
678        }
679        out
680    }
681
682    /// Returns the phrase of [`FlmArgumentParser::description`].
683    fn description(&self) -> String {
684        match self {
685            ArgStdKind::Mandatory => String::from("a mandatory `{…}` group"),
686            ArgStdKind::Optional => String::from("an optional `[…]` group"),
687            ArgStdKind::Star => String::from("an optional `*` marker"),
688            ArgStdKind::Marker { marker } => format!("an optional `{marker}` marker"),
689            ArgStdKind::DelimitedGroup { open, close } => format!("a mandatory `{open}…{close}` group"),
690            ArgStdKind::OptionalDelimitedGroup { open, close } => {
691                format!("an optional `{open}…{close}` group")
692            }
693            ArgStdKind::AnyDelimitedGroup => {
694                String::from("a mandatory group in `{…}`, `[…]`, `(…)` or `<…>`")
695            }
696            ArgStdKind::OptionalAnyDelimitedGroup => {
697                String::from("an optional group in `{…}`, `[…]`, `(…)` or `<…>`")
698            }
699            ArgStdKind::BracedOnly => String::from("a mandatory `{…}` group, never a single token"),
700            ArgStdKind::Embellishments { markers } => {
701                let names: Vec<String> = markers.iter().map(|marker| format!("`{marker}`")).collect();
702                format!(
703                    "optional embellishments {}, each followed by one expression, in any order",
704                    names.join(", ")
705                )
706            }
707            ArgStdKind::KeyVals => String::from("an optional `[key=value,…]` group"),
708            ArgStdKind::CharsGroup => {
709                String::from("a `{…}` group read as plain characters, kept as written")
710            }
711            ArgStdKind::Verbatim { delimiters: None } => {
712                String::from("verbatim text between a pair of delimiters")
713            }
714            ArgStdKind::Verbatim { delimiters: Some((open, close)) } => {
715                format!("verbatim text between `{open}` and `{close}`")
716            }
717            ArgStdKind::TackOn { fields } => {
718                let names: Vec<String> =
719                    fields.iter().map(|field| format!("`\\{}`", field.name)).collect();
720                format!("the fields {} written after the command", names.join(", "))
721            }
722            ArgStdKind::Terminated { terminator, repeat_char, opener, head, raw } => {
723                let what = if *raw { "raw text" } else { "content" };
724                let mut prefix = Vec::new();
725                if let Some(repeat_char) = repeat_char {
726                    prefix.push(format!("a run of {}", code_span(&String::from(*repeat_char))));
727                }
728                if !opener.is_empty() {
729                    prefix.push(code_span(opener));
730                }
731                let after = if prefix.is_empty() {
732                    String::new()
733                } else {
734                    format!(" after {},", prefix.join(" then "))
735                };
736                let until = match repeat_char {
737                    None => code_span(&format!("{head}{terminator}")),
738                    Some(_) => {
739                        let mut parts = Vec::new();
740                        if !head.is_empty() {
741                            parts.push(code_span(head));
742                        }
743                        parts.push(String::from("the same run"));
744                        if !terminator.is_empty() {
745                            parts.push(code_span(terminator));
746                        }
747                        parts.join(" then ")
748                    }
749                };
750                format!("{what}{after} up to {until}")
751            }
752        }
753    }
754}
755
756/// Writes `text` as a code span of a documentation text: between single
757/// backticks, or, when `text` holds a backtick, between runs of backticks
758/// longer than any run in `text`, with a space inside each end.
759pub(crate) fn code_span(text: &str) -> String {
760    let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
761    if longest == 0 {
762        return format!("`{text}`");
763    }
764    let fence = "`".repeat(longest + 1);
765    format!("{fence} {text} {fence}")
766}
767
768/// The parser object of a standard kind: the kind, and the parser that reads
769/// it.
770///
771/// The reading parser is built **once**, when the kind is wrapped into its
772/// shared object ([`IntoFlmArgumentParser`]), and shared by every invocation.
773/// Building it at each parse instead would let the kind be the object by
774/// itself, but it would repeat, for every argument of every invocation, the
775/// allocations some of the parsers make when they are built (the group rule of
776/// an optional group, the text of a marker). A declaration is wrapped once per
777/// registry, so building once adds no work to a parse.
778struct StdArgumentParser {
779    kind: ArgStdKind,
780    reader: Arc<dyn ArgumentParser<Flm>>,
781}
782
783impl StdArgumentParser {
784    fn new(kind: ArgStdKind) -> StdArgumentParser {
785        let reader = kind.reader();
786        StdArgumentParser { kind, reader }
787    }
788}
789
790impl fmt::Debug for StdArgumentParser {
791    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792        fmt::Debug::fmt(&self.kind, f)
793    }
794}
795
796impl ArgumentParser<Flm> for StdArgumentParser {
797    fn parse_argument(
798        &self,
799        cx: &mut ParseContext<'_, '_, Flm>,
800        spec: &ArgumentSpec<Flm>,
801    ) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
802        self.reader.parse_argument(cx, spec)
803    }
804
805    fn can_match_empty(&self) -> bool {
806        self.reader.can_match_empty()
807    }
808}
809
810impl FlmArgumentParser for StdArgumentParser {
811    fn identity(&self) -> Vec<u8> {
812        self.kind.identity()
813    }
814
815    fn tack_on_fields(&self) -> Option<&[TackOnField]> {
816        match &self.kind {
817            ArgStdKind::TackOn { fields } => Some(fields),
818            _ => None,
819        }
820    }
821
822    /// Every standard kind but one is taken as a value: a key-value argument
823    /// is a value like any other (the recomposed definition does not read its
824    /// keys separately), and a verbatim argument is the characters the use
825    /// site wrote between its delimiters. A terminated argument has no shape:
826    /// a LaTeX command defined by the recomposed definition cannot read an
827    /// argument up to a terminator.
828    fn definition_shape(&self) -> DefinitionShape {
829        match self.kind {
830            ArgStdKind::Terminated { .. } => DefinitionShape::NoShape { token: "terminated" },
831            _ => DefinitionShape::Value,
832        }
833    }
834
835    fn description(&self) -> String {
836        self.kind.description()
837    }
838
839    fn std_kind(&self) -> Option<&ArgStdKind> {
840        Some(&self.kind)
841    }
842}
843
844/// Returns the parser of one of techy's argument codes (`m`, `o`, `s`). The
845/// codes are constants of this module, so the conversion cannot fail; the
846/// `expect` records that.
847fn preset(code: &str) -> Arc<dyn ArgumentParser<Flm>> {
848    argument_specs::<Flm, _>([code])
849        .expect("the preset argument codes listed here are valid")
850        .into_iter()
851        .next()
852        .expect("one code yields one argument specification")
853        .parser
854        .clone()
855}
856
857/// Returns the rule of a group delimited by `open` and `close` at one
858/// argument's position: a group of the content class, as techy's table of
859/// argument codes builds it for the codes `r` and `d`.
860fn group_rule(open: char, close: char) -> Arc<GroupRule<Flm>> {
861    Arc::new(GroupRule {
862        group_type: FlmGroupType::Content,
863        open: String::from(open),
864        close: String::from(close),
865    })
866}
867
868/// The pairs a group of [`ArgStdKind::AnyDelimitedGroup`] may be written in,
869/// in the order techy's table of argument codes lists them for the code
870/// `AnyDelimited`.
871const ANY_DELIMITED_PAIRS: [(char, char); 4] = [('{', '}'), ('[', ']'), ('(', ')'), ('<', '>')];
872
873/// The rules of [`ANY_DELIMITED_PAIRS`].
874fn any_delimited_rules() -> Vec<Arc<GroupRule<Flm>>> {
875    ANY_DELIMITED_PAIRS.into_iter().map(|(open, close)| group_rule(open, close)).collect()
876}
877
878// --- identity bytes --------------------------------------------------------------------------
879
880/// Writes a string, its length first.
881fn put(out: &mut Vec<u8>, text: &str) {
882    put_count(out, text.len());
883    out.extend_from_slice(text.as_bytes());
884}
885
886/// Writes a count or a flag as eight little-endian bytes.
887fn put_count(out: &mut Vec<u8>, count: usize) {
888    out.extend_from_slice(&(count as u64).to_le_bytes());
889}
890
891/// Writes one argument declaration's name (`-` when it has none, `+` and the
892/// name otherwise), its parser's identity, its length first, and what minting
893/// applies around the parser: its parsing mode, its layout, whether it is
894/// declared with an opaque wrapper, its scoped packages and its state events,
895/// each list preceded by its number of entries. Its documentation and its role
896/// change nothing that a parse or the processing produces, and are left out.
897fn put_arg_identity(out: &mut Vec<u8>, arg: &ArgDef) {
898    match &arg.name {
899        None => put(out, "-"),
900        Some(name) => put(out, &format!("+{name}")),
901    }
902    let identity = arg.kind.identity();
903    put_count(out, identity.len());
904    out.extend_from_slice(&identity);
905    put(out, &format!("{:?}", arg.mode));
906    put(out, &format!("{:?}", arg.layout));
907    put_count(out, usize::from(arg.opaque_wrapper));
908    put_count(out, arg.scoped.len());
909    for package in &arg.scoped {
910        put(out, package.as_str());
911    }
912    put_count(out, arg.events.len());
913    for event in &arg.events {
914        put(out, &format!("{event:?}"));
915    }
916}
917
918// --- the body parser -------------------------------------------------------------------------
919
920/// The parser of an environment's body that is not read the ordinary way,
921/// together with what FLM needs to know about the body beyond reading it.
922///
923/// techy's [`EnvironmentBehavior`] reads the body through
924/// [`make_body_parser`](EnvironmentBehavior::make_body_parser): FLM's verbatim
925/// reader reads raw text up to `\end{name}`, and a feature's parser may read
926/// the ordinary content and then check it. A body declaration
927/// ([`BodyDef::parser`](super::BodyDef::parser)) holds such an object;
928/// [`BodyDef::verbatim`](super::BodyDef::verbatim) installs the verbatim
929/// reader. A body that declares none is read the ordinary way: content up to
930/// and including `\end{name}`.
931///
932/// Only `make_body_parser` is called. The environment's arguments are those
933/// of the declaration ([`SyntaxDef::Environment`](super::SyntaxDef::Environment)),
934/// and the body is read under the parsing state the body declaration asks
935/// for, its parsing mode ([`BodyDef::mode`](super::BodyDef::mode)), its
936/// scoped packages ([`BodyDef::scoped`](super::BodyDef::scoped)) and its state
937/// events ([`BodyDef::events`](super::BodyDef::events)), which minting applies
938/// around the body parse. The object's own
939/// [`arguments`](EnvironmentBehavior::arguments) and
940/// [`body_state_delta`](EnvironmentBehavior::body_state_delta) are not
941/// called.
942///
943/// Like an argument parser, a body parser is shared by every invocation and
944/// must never panic or loop: the end of the input reached before `\end{name}`
945/// is an ordinary input.
946pub trait FlmBodyParser: EnvironmentBehavior<Flm> + Send + Sync {
947    /// Returns the bytes that identify this body parser in the [registry
948    /// digest](crate::model::digest), under the same rules as
949    /// [`FlmArgumentParser::identity`].
950    fn identity(&self) -> Vec<u8>;
951
952    /// Returns a description of how the body is read, in a short phrase. The
953    /// library does not act on it; a program that describes the registry's
954    /// declarations
955    /// ([`FlmRegistry::declarations`](crate::core::registry::FlmRegistry::declarations))
956    /// shows it.
957    fn description(&self) -> String;
958}
959
960/// Conversion into a body's shared parser object: the parameter type of
961/// [`BodyDef::parser`](super::BodyDef::parser), as [`IntoFlmArgumentParser`]
962/// is for an argument.
963///
964/// Two types convert: any [`FlmBodyParser`], passed by value and shared from
965/// then on, and an already shared `Arc<dyn FlmBodyParser>`, passed through
966/// unchanged, so that one parser reused by several environments stays one
967/// value. The body declaration always holds the parser as
968/// `Option<Arc<dyn FlmBodyParser>>` (the field `BodyDef::parser`).
969pub trait IntoFlmBodyParser {
970    /// Returns the shared parser object a [`BodyDef`](super::BodyDef) holds.
971    fn into_flm_body_parser(self) -> Arc<dyn FlmBodyParser>;
972}
973
974impl<P: FlmBodyParser + 'static> IntoFlmBodyParser for P {
975    fn into_flm_body_parser(self) -> Arc<dyn FlmBodyParser> {
976        Arc::new(self)
977    }
978}
979
980impl IntoFlmBodyParser for Arc<dyn FlmBodyParser> {
981    fn into_flm_body_parser(self) -> Arc<dyn FlmBodyParser> {
982        self
983    }
984}
985
986impl FlmBodyParser for FlmVerbatimBehavior {
987    fn identity(&self) -> Vec<u8> {
988        let mut out = Vec::new();
989        put(&mut out, "verbatim");
990        out
991    }
992
993    fn description(&self) -> String {
994        String::from("raw text up to `\\end{name}`")
995    }
996}
997
998#[cfg(test)]
999mod tests {
1000    use super::*;
1001    use crate::lang::flm::FlmEvent;
1002    use crate::lang::mint::decl::ArgLayout;
1003    use techy::latexlike::Mode;
1004
1005    fn object(kind: ArgStdKind) -> Arc<dyn FlmArgumentParser> {
1006        kind.into_flm_argument_parser()
1007    }
1008
1009    fn terminated(terminator: &str, repeat_char: Option<char>, raw: bool) -> ArgStdKind {
1010        ArgStdKind::Terminated {
1011            terminator: String::from(terminator),
1012            repeat_char,
1013            opener: String::new(),
1014            head: String::new(),
1015            raw,
1016        }
1017    }
1018
1019    #[test]
1020    fn every_standard_kind_answers_a_distinct_identity() {
1021        let kinds = [
1022            ArgStdKind::Mandatory,
1023            ArgStdKind::Optional,
1024            ArgStdKind::Star,
1025            ArgStdKind::KeyVals,
1026            ArgStdKind::CharsGroup,
1027            ArgStdKind::Verbatim { delimiters: None },
1028            ArgStdKind::Verbatim { delimiters: Some(('{', '}')) },
1029            ArgStdKind::Verbatim { delimiters: Some(('|', '|')) },
1030            ArgStdKind::TackOn { fields: Vec::new() },
1031            ArgStdKind::TackOn {
1032                fields: vec![TackOnField::new("label", vec![ArgDef::new(ArgStdKind::CharsGroup)])],
1033            },
1034            // What minting applies around a field's argument is part of the identity.
1035            ArgStdKind::TackOn {
1036                fields: vec![TackOnField::new(
1037                    "label",
1038                    vec![ArgDef::new(ArgStdKind::CharsGroup).mode(Mode::Math)],
1039                )],
1040            },
1041            ArgStdKind::TackOn {
1042                fields: vec![TackOnField::new(
1043                    "label",
1044                    vec![ArgDef::new(ArgStdKind::CharsGroup).layout(ArgLayout::Blocks)],
1045                )],
1046            },
1047            ArgStdKind::TackOn {
1048                fields: vec![TackOnField::new(
1049                    "label",
1050                    vec![ArgDef::new(ArgStdKind::CharsGroup).with_opaque_wrapper()],
1051                )],
1052            },
1053            ArgStdKind::TackOn {
1054                fields: vec![TackOnField::new(
1055                    "label",
1056                    vec![ArgDef::new(ArgStdKind::CharsGroup).scoped("t.package")],
1057                )],
1058            },
1059            ArgStdKind::TackOn {
1060                fields: vec![TackOnField::new(
1061                    "label",
1062                    vec![ArgDef::new(ArgStdKind::CharsGroup).event(FlmEvent::StandardState)],
1063                )],
1064            },
1065            ArgStdKind::Marker { marker: String::from("!") },
1066            ArgStdKind::Marker { marker: String::from("+") },
1067            ArgStdKind::Marker { marker: String::from("!+") },
1068            ArgStdKind::DelimitedGroup { open: '(', close: ')' },
1069            ArgStdKind::DelimitedGroup { open: '<', close: '>' },
1070            ArgStdKind::OptionalDelimitedGroup { open: '(', close: ')' },
1071            ArgStdKind::AnyDelimitedGroup,
1072            ArgStdKind::OptionalAnyDelimitedGroup,
1073            ArgStdKind::BracedOnly,
1074            ArgStdKind::Embellishments { markers: vec!['^'] },
1075            ArgStdKind::Embellishments { markers: vec!['^', '_'] },
1076            ArgStdKind::Embellishments { markers: vec!['_', '^'] },
1077            terminated("\\endphf", None, false),
1078            terminated("\\endphf", None, true),
1079            terminated("\\endph", None, false),
1080            terminated("`", Some('`'), true),
1081            terminated("`", Some('+'), true),
1082            terminated("", Some('`'), true),
1083            ArgStdKind::Terminated {
1084                terminator: String::from("]"),
1085                repeat_char: Some('='),
1086                opener: String::from("["),
1087                head: String::new(),
1088                raw: true,
1089            },
1090            ArgStdKind::Terminated {
1091                terminator: String::from("]"),
1092                repeat_char: Some('='),
1093                opener: String::new(),
1094                head: String::from("["),
1095                raw: true,
1096            },
1097        ];
1098        let identities: Vec<Vec<u8>> = kinds.into_iter().map(|kind| object(kind).identity()).collect();
1099        for (i, a) in identities.iter().enumerate() {
1100            for b in &identities[i + 1..] {
1101                assert_ne!(a, b);
1102            }
1103        }
1104    }
1105
1106    #[test]
1107    fn a_kind_with_a_code_reads_as_the_toolkit_s_table_of_codes_builds_it() {
1108        // The two verbatim codes, `v` and `v<c1><c2>`, are left out: they name
1109        // the library's own verbatim reader, so their parser is not the
1110        // toolkit's.
1111        let kinds = [
1112            ("m", ArgStdKind::Mandatory),
1113            ("o", ArgStdKind::Optional),
1114            ("s", ArgStdKind::Star),
1115            ("t!", ArgStdKind::Marker { marker: String::from("!") }),
1116            ("r()", ArgStdKind::DelimitedGroup { open: '(', close: ')' }),
1117            ("d<>", ArgStdKind::OptionalDelimitedGroup { open: '<', close: '>' }),
1118            ("AnyDelimited", ArgStdKind::AnyDelimitedGroup),
1119            ("AnyDelimitedOptional", ArgStdKind::OptionalAnyDelimitedGroup),
1120            ("BracedOnly", ArgStdKind::BracedOnly),
1121            ("e{^_}", ArgStdKind::Embellishments { markers: vec!['^', '_'] }),
1122        ];
1123        for (code, kind) in kinds {
1124            let toolkit = argument_specs::<Flm, _>([code]).unwrap();
1125            assert_eq!(format!("{:?}", kind.reader()), format!("{:?}", toolkit[0].parser), "{code}");
1126        }
1127    }
1128
1129    #[test]
1130    fn a_use_site_may_leave_out_exactly_the_optional_shapes() {
1131        assert!(object(ArgStdKind::Optional).can_match_empty());
1132        assert!(object(ArgStdKind::KeyVals).can_match_empty());
1133        assert!(object(ArgStdKind::Star).can_match_empty());
1134        assert!(!object(ArgStdKind::Mandatory).can_match_empty());
1135        assert!(!object(ArgStdKind::CharsGroup).can_match_empty());
1136        assert!(!object(ArgStdKind::Verbatim { delimiters: None }).can_match_empty());
1137        assert!(object(ArgStdKind::Marker { marker: String::from("!") }).can_match_empty());
1138        assert!(object(ArgStdKind::OptionalDelimitedGroup { open: '<', close: '>' }).can_match_empty());
1139        assert!(object(ArgStdKind::OptionalAnyDelimitedGroup).can_match_empty());
1140        assert!(object(ArgStdKind::Embellishments { markers: vec!['^'] }).can_match_empty());
1141        assert!(!object(ArgStdKind::DelimitedGroup { open: '(', close: ')' }).can_match_empty());
1142        assert!(!object(ArgStdKind::AnyDelimitedGroup).can_match_empty());
1143        assert!(!object(ArgStdKind::BracedOnly).can_match_empty());
1144        assert!(!object(terminated("\\endphf", None, false)).can_match_empty());
1145        assert!(!object(terminated("`", Some('`'), true)).can_match_empty());
1146    }
1147
1148    #[test]
1149    fn only_a_tack_on_argument_declares_fields() {
1150        let field = TackOnField::new("label", Vec::new());
1151        let tack_on = object(ArgStdKind::TackOn { fields: vec![field] });
1152        assert_eq!(tack_on.tack_on_fields().map(<[TackOnField]>::len), Some(1));
1153        assert!(object(ArgStdKind::Mandatory).tack_on_fields().is_none());
1154    }
1155
1156    #[test]
1157    fn a_standard_kind_describes_itself() {
1158        assert_eq!(object(ArgStdKind::Optional).description(), "an optional `[…]` group");
1159        let field = TackOnField::new("label", Vec::new());
1160        assert_eq!(
1161            object(ArgStdKind::TackOn { fields: vec![field] }).description(),
1162            "the fields `\\label` written after the command"
1163        );
1164        assert_eq!(object(ArgStdKind::Star).definition_shape(), DefinitionShape::Value);
1165    }
1166
1167    /// An optional `!` marker: a parser of the test's own, standing for the
1168    /// parser a feature defines for itself.
1169    #[derive(Debug)]
1170    struct Bang(MarkerArgumentParser);
1171
1172    impl ArgumentParser<Flm> for Bang {
1173        fn parse_argument(
1174            &self,
1175            cx: &mut ParseContext<'_, '_, Flm>,
1176            spec: &ArgumentSpec<Flm>,
1177        ) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
1178            self.0.parse_argument(cx, spec)
1179        }
1180        fn can_match_empty(&self) -> bool {
1181            true
1182        }
1183    }
1184
1185    impl FlmArgumentParser for Bang {
1186        fn identity(&self) -> Vec<u8> {
1187            b"test.bang".to_vec()
1188        }
1189        fn definition_shape(&self) -> DefinitionShape {
1190            DefinitionShape::NoShape { token: "bang" }
1191        }
1192        fn description(&self) -> String {
1193            String::from("an optional `!` marker")
1194        }
1195    }
1196
1197    #[test]
1198    fn only_a_standard_parser_tells_its_kind() {
1199        let kind = object(ArgStdKind::Marker { marker: String::from("!") });
1200        assert!(matches!(kind.std_kind(), Some(ArgStdKind::Marker { marker }) if marker == "!"));
1201        let own: Arc<dyn FlmArgumentParser> =
1202            Arc::new(Bang(MarkerArgumentParser::new(String::from("!"))));
1203        assert!(own.std_kind().is_none());
1204    }
1205
1206    #[test]
1207    fn a_terminated_kind_describes_itself_and_has_no_definition_shape() {
1208        assert_eq!(object(terminated("\\endphf", None, false)).description(), "content up to `\\endphf`");
1209        assert_eq!(
1210            object(terminated("`", Some('`'), true)).description(),
1211            "raw text after a run of `` ` ``, up to the same run then `` ` ``"
1212        );
1213        assert_eq!(
1214            object(terminated("", Some('+'), true)).description(),
1215            "raw text after a run of `+`, up to the same run"
1216        );
1217        let raw_string = ArgStdKind::Terminated {
1218            terminator: String::new(),
1219            repeat_char: Some('#'),
1220            opener: String::from("\""),
1221            head: String::from("\""),
1222            raw: true,
1223        };
1224        assert_eq!(
1225            object(raw_string.clone()).description(),
1226            "raw text after a run of `#` then `\"`, up to `\"` then the same run"
1227        );
1228        assert_eq!(
1229            object(raw_string).definition_shape(),
1230            DefinitionShape::NoShape { token: "terminated" }
1231        );
1232        assert_eq!(
1233            object(terminated("\\endphf", None, false)).definition_shape(),
1234            DefinitionShape::NoShape { token: "terminated" }
1235        );
1236    }
1237
1238    #[test]
1239    fn a_code_span_holds_the_backticks_of_its_text() {
1240        assert_eq!(code_span("ab"), "`ab`");
1241        assert_eq!(code_span("`"), "`` ` ``");
1242        assert_eq!(code_span("a``b`"), "``` a``b` ```");
1243    }
1244
1245    #[test]
1246    fn the_verbatim_body_has_an_identity_of_its_own() {
1247        let body = FlmVerbatimBehavior::new();
1248        assert_ne!(body.identity(), object(ArgStdKind::Verbatim { delimiters: None }).identity());
1249    }
1250}