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