Skip to main content

flm_core/lang/mint/
codes.rs

1//! The syntax of an argument in settings given as data, and the only reader
2//! of it: the structured syntax, a standard argument kind written as a map,
3//! and the argument codes, the short texts that stand for the kinds.
4//!
5//! [Settings given as data](crate::core::settings) cannot hold a parser object,
6//! so when they declare a macro or an environment they write the syntax of
7//! each of its arguments as data, in one of two forms:
8//!
9//! - the **structured syntax**: a map whose key `syntax` holds the name of a
10//!   standard argument kind ([`ArgStdKind`]) and whose other keys hold the
11//!   kind's parameters, as in `{syntax: delimited-group, delimiters: ["(",
12//!   ")"]}` for a group in parentheses;
13//! - an **argument code**, a short text that stands for one kind with its
14//!   parameters: `{` for a mandatory group, `[` for an optional one, `r()`
15//!   for a group in parentheses.
16//!
17//! This module reads both forms, and no other part of the library does:
18//! [`ArgData`] reads one argument in either form, [`ArgListData`] reads a
19//! whole argument list written in any of the three shapes that settings may
20//! use, [`ArgCode::read`] reads one code, which keeps its text with the
21//! standard kind it stands for, and [`arg_def_from_code`] turns one code into
22//! an argument declaration ([`ArgDef`]). Every feature whose settings declare
23//! macros or environments reads its argument lists through these, so that one
24//! syntax means one form of argument in every settings file; the `userdefs`
25//! feature is one of them ([`deserialize_arg_list`] reads its `args` settings
26//! key).
27//!
28//! # The structured syntax
29//!
30//! The structured syntax is a standard kind written as data: its map is the
31//! kind's serialized form, so the kinds of the settings and of the Rust
32//! interface are one vocabulary. The key `syntax` holds the kind's name in
33//! lowercase with hyphens (`mandatory`, `delimited-group`, `chars-group`),
34//! and the kind's parameters stand beside it (`delimiters`, `markers`,
35//! `terminator`). The [documentation of `ArgStdKind`](ArgStdKind#the-kind-as-data)
36//! lists each kind's name and parameters, and what reading a kind refuses.
37//!
38//! Every kind can be written this way. Four of the forms that the structured
39//! syntax writes have no code: a group read as plain characters
40//! (`chars-group`), a group of `key=value` pairs (`key-vals`), a tack-on
41//! argument with its fields (`tack-on`, [`TackOn`](ArgStdKind::TackOn)), and
42//! a terminated argument with an opener or a terminator head (`terminated`
43//! with `opener` or `head`).
44//!
45//! A tack-on argument lists its fields under `fields`, each a map of the
46//! field's `name` (without the backslash), its `args` (an argument list in any
47//! of the three shapes below), whether it is `repeatable` (`false` by
48//! default) and its `docs` (empty by default): `{syntax: tack-on, fields:
49//! [{name: label, args: [{syntax: chars-group}], repeatable: true}]}` accepts
50//! any number of `\label{…}` after the command.
51//!
52//! # The codes
53//!
54//! The codes are those of techy's table of argument codes
55//! ([`argument_specs`](techy::latexlike::argument_specs)), plus FLM's own:
56//! `t{<chars>}`, a marker made of the characters between the braces, and four
57//! codes for a terminated argument (`u`, `U`, `f` and `F`, described below
58//! the table); techy is the parser toolkit FLM is built on. Each code is a
59//! shorthand for one structured syntax, a standard kind with its parameters,
60//! which the last column of the table gives. Every code of techy's table
61//! means what it means there, except the code `v` alone: it selects FLM's own
62//! verbatim reader, the one FLM's verbatim commands use, which closes `{` with
63//! `}`, `[` with `]`, `(` with `)`, `<` with `>` and any other character with
64//! itself, whereas techy's `v` closes on the same character that opened. Each
65//! example shows a use of a macro `\m` declared with that code as its only
66//! argument.
67//!
68//! | code | the argument | example | structured syntax |
69//! |---|---|---|---|
70//! | `{` or `m` | a mandatory `{…}` group; a single token also counts | `\m{arg}`, `\m1` | [`mandatory`](ArgStdKind::Mandatory) |
71//! | `[` or `o` | an optional `[…]` group | `\m[arg]` | [`optional`](ArgStdKind::Optional) |
72//! | `*` or `s` | an optional `*` marker | `\m*` | [`star`](ArgStdKind::Star) |
73//! | `t<c>` | an optional marker made of the one character `<c>` (`t*` is the same as `*`) | `t!` reads `\m!` | [`marker`](ArgStdKind::Marker) with `marker: <c>` |
74//! | `t{<chars>}` | an optional marker made of the characters `<chars>`, one or more, matched as written (`t{*}` is the same as `*`) | `t{\big}` reads `\m\big` | [`marker`](ArgStdKind::Marker) with `marker: <chars>` |
75//! | `r<c1><c2>` | a mandatory group between `<c1>` and `<c2>` | `r()` reads `\m(arg)` | [`delimited-group`](ArgStdKind::DelimitedGroup) with `delimiters: [<c1>, <c2>]` |
76//! | `d<c1><c2>` | an optional group between `<c1>` and `<c2>` | `d<>` reads `\m<arg>` | [`optional-delimited-group`](ArgStdKind::OptionalDelimitedGroup) with `delimiters: [<c1>, <c2>]` |
77//! | `v` | verbatim text between two delimiters, matched to the opening one | `\m+raw %text+` | [`verbatim`](ArgStdKind::Verbatim) |
78//! | `v<c1><c2>` | verbatim text between `<c1>` and `<c2>` | `v+-` reads `\m+raw %text-` | [`verbatim`](ArgStdKind::Verbatim) with `delimiters: [<c1>, <c2>]` |
79//! | `e{<chars>}` | embellishments: each character between the braces is a marker that is followed by one expression; the markers may be written in any order, each at most once | `e{^_}` reads `\m^{a}_{b}` | [`embellishments`](ArgStdKind::Embellishments) with `markers`, one entry per character of `<chars>` |
80//! | `AnyDelimited` | a mandatory group in `{…}`, `[…]`, `(…)` or `<…>` | `\m<arg>` | [`any-delimited-group`](ArgStdKind::AnyDelimitedGroup) |
81//! | `AnyDelimitedOptional` | the same pairs, optional | `\m(arg)` | [`optional-any-delimited-group`](ArgStdKind::OptionalAnyDelimitedGroup) |
82//! | `BracedOnly` | a mandatory `{…}` group, never a single token | `\m{arg}` | [`braced-only`](ArgStdKind::BracedOnly) |
83//! | `u<terminator>` | document content up to `<terminator>`, one or more characters | `u\endm` reads `\m some \emph{text}\endm` | [`terminated`](ArgStdKind::Terminated) with `terminator: <terminator>` |
84//! | `U<terminator>` | raw text up to `<terminator>` | `U\endm` reads `\m raw %text\endm` | [`terminated`](ArgStdKind::Terminated) with `terminator: <terminator>`, `raw: true` |
85//! | `f<c><terminator>` | document content after a run of the character `<c>`, up to the same run followed by `<terminator>`, which may be empty | `f+` reads `\m++some text++` | [`terminated`](ArgStdKind::Terminated) with `repeat_char: <c>`, `terminator: <terminator>` |
86//! | `F<c><terminator>` | raw text after a run of the character `<c>`, up to the same run followed by `<terminator>` | `F+` reads `\m+++raw %text+++` | [`terminated`](ArgStdKind::Terminated) with `repeat_char: <c>`, `terminator: <terminator>`, `raw: true` |
87//!
88//! A code is written exactly, with no space around it. The characters a code
89//! takes (`<c>`, `<c1><c2>`, `<chars>`, `<terminator>`) follow its letter
90//! immediately, and none of them may be a space. An optional argument the use
91//! site does not write is absent; a mandatory one is reported missing.
92//!
93//! The four codes `u`, `U`, `f` and `F` are FLM's own: techy's table has no
94//! code for a terminated argument. In their content, the terminator is
95//! matched before any other markup, wherever its characters appear; with `f`
96//! and `F`, the run of `<c>` that opens the argument may hold any number of
97//! copies, and the terminator repeats the same number of copies before
98//! `<terminator>`. A code span written with backticks, `` `x` `` or
99//! ``` ``a`b`` ```, is read by a special character sequence `` ` `` declared
100//! with one argument of the code ``` F`` ```: the sequence reads the first
101//! backtick, the argument reads the run of backticks that follows, and the
102//! terminator is that run followed by one more backtick. The [terminated
103//! kind](ArgStdKind::Terminated) also has an opener (text after the run) and a
104//! terminator head (text before the repeated copies), which no code sets: a
105//! declaration that needs them writes the structured syntax.
106//!
107//! # The three shapes of an argument list
108//!
109//! An argument list ([`ArgListData`]) is written in one of three shapes:
110//!
111//! - one text in which each character is one code (`"[{{"`: an optional group,
112//!   then two mandatory ones); only the codes of one character can be written
113//!   this way;
114//! - a list of codes (`["[", "r()"]`);
115//! - a list whose entries are each a code or an argument's map (below):
116//!   `[{syntax: optional, name: size}, "{"]`.
117//!
118//! # An argument's map
119//!
120//! An argument's map ([`ArgDataFields`]) gives the argument's syntax in
121//! exactly one of the two forms: a structured syntax (`syntax` and the
122//! kind's parameters) or a code (the key `code`). A map that gives both, and
123//! one that gives neither, is refused. Beside the syntax, the map may give
124//! the argument's own keys, each optional: `name`, `mode` (`text` or
125//! `math`), `layout`, `opaque_wrapper`, `scoped` (scoped packages), `docs`
126//! and `role`. For example, `{syntax: delimited-group, delimiters: ["(",
127//! ")"], name: size}` and `{code: "r()", name: size}` declare the same
128//! argument; `{code: "{", mode: "math"}`, `{syntax: chars-group, name:
129//! "key"}` and `{code: "{", name: "target", role: "flm.refs.target"}` are
130//! maps too.
131//
132// An argument's syntax in data is the standard kind itself, so that settings
133// and the Rust interface share one vocabulary and every kind can be declared
134// from settings; the codes are shorthands, for short declarations.
135
136use std::fmt;
137
138use serde::de::{Error as _, MapAccess, SeqAccess, Visitor};
139use serde::{Deserialize, Deserializer};
140use serde_json::Value;
141
142use techy::latexlike::Mode;
143
144use crate::lang::mint::decl::{ArgDef, ArgLayout, TackOnField};
145use crate::lang::mint::parsers::ArgStdKind;
146use crate::model::names::Name;
147
148// --- an argument and a list of arguments, as data ------------------------------------------------
149
150/// One argument of a macro or environment declared in settings given as data:
151/// either its argument code alone (`"{"`), or an argument's map, which gives
152/// its syntax (a structured syntax or a code) with the argument's name,
153/// parsing mode, layout, opaque wrapper, scoped packages, documentation and
154/// role.
155///
156/// It converts into an argument declaration ([`ArgDef`]) through `TryFrom`,
157/// which reads a code with [`arg_def_from_code`]; the [module
158/// documentation](self) describes both forms of a syntax.
159//
160// It is also written to data (`Serialize`): a code as its text, a map as
161// [`ArgDataFields`] writes it.
162#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
163#[derive(schemars::JsonSchema)]
164#[serde(untagged)]
165pub enum ArgData {
166    /// The argument code alone: the argument has no name and its content is
167    /// laid out inline.
168    Code(#[schemars(schema_with = "arg_code_schema")] String),
169    /// The argument's syntax with the argument's name, parsing mode, layout,
170    /// opaque wrapper, scoped packages, documentation and role.
171    Declared(ArgDataFields),
172}
173
174// An argument is a text or a map, and is read as the one or the other, so
175// that a problem inside a map is reported with its own message.
176impl<'de> Deserialize<'de> for ArgData {
177    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<ArgData, D::Error> {
178        struct Entry;
179
180        impl<'de> Visitor<'de> for Entry {
181            type Value = ArgData;
182
183            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184                f.write_str("an argument code or a map")
185            }
186
187            fn visit_str<E: serde::de::Error>(self, code: &str) -> Result<ArgData, E> {
188                Ok(ArgData::Code(code.to_string()))
189            }
190
191            fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<ArgData, A::Error> {
192                ArgDataFields::deserialize(serde::de::value::MapAccessDeserializer::new(map))
193                    .map(ArgData::Declared)
194            }
195        }
196
197        deserializer.deserialize_any(Entry)
198    }
199}
200
201/// An argument written as a map in settings given as data: its syntax, given
202/// as a code or as a structured syntax, exactly one of the two, and its name,
203/// parsing mode, layout, opaque wrapper, scoped packages, documentation and
204/// role (see [`ArgData`]).
205//
206// It is also written to data (`Serialize`), with every field present except
207// the form of the syntax it does not give, and reads back as the same value:
208// see the registry's "Serialized forms" (`crate::core::registry`). The
209// structured syntax is flattened into the map: `deserialize_syntax` reads
210// the keys that are not the map's own, and `arg_map_schema` gives the schema
211// one alternative per form of the syntax. This is a plain comment, not
212// documentation, because the documentation of this type is the description
213// of a settings key in the settings' JSON Schema.
214#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
215#[derive(schemars::JsonSchema)]
216#[schemars(transform = arg_map_schema)]
217pub struct ArgDataFields {
218    /// The argument code, which says what form the argument takes in one
219    /// short text (the codes are those [`arg_def_from_code`] reads). A map
220    /// gives either a code or a structured syntax.
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    #[schemars(schema_with = "arg_code_schema")]
223    pub code: Option<String>,
224    /// The structured syntax: the standard kind ([`ArgStdKind`]) written as
225    /// data, its name under the key `syntax` and its parameters beside it, in
226    /// the map itself. A map gives either a code or a structured syntax.
227    #[serde(flatten, deserialize_with = "deserialize_syntax")]
228    #[schemars(schema_with = "syntax_schema")]
229    pub syntax: Option<ArgStdKind>,
230    /// The argument's name, by which a user definition's template refers to
231    /// it. No name by default.
232    #[serde(default)]
233    pub name: Option<String>,
234    /// How the argument's content is laid out: `inline` (running text with
235    /// no paragraph, the default), `blocks` (paragraphs and other blocks), or
236    /// `inline-or-blocks` (decided by the content); see [`ArgLayout`].
237    #[serde(default)]
238    pub layout: ArgLayout,
239    /// Whether the argument's content is placed under an opaque wrapper, so
240    /// that it is kept as written: no whitespace is collapsed and no
241    /// typographic substitution is made inside it. `false` by default; see
242    /// [`ArgDef::with_opaque_wrapper`](ArgDef::with_opaque_wrapper()).
243    #[serde(default)]
244    pub opaque_wrapper: bool,
245    /// Documentation of the argument. Empty by default.
246    #[serde(default)]
247    pub docs: String,
248    /// The parsing mode the argument is read in: `text` or `math`. Without
249    /// it, the argument is read in the mode the command is written in; see
250    /// [`ArgDef::mode`](ArgDef::mode()).
251    #[serde(default)]
252    #[schemars(schema_with = "mode_schema")]
253    pub mode: Option<Mode>,
254    /// The names of the [scoped packages](super::ScopedPackageDef) whose
255    /// declarations are available inside the argument. None by default; see
256    /// [`ArgDef::scoped`](ArgDef::scoped()).
257    #[serde(default)]
258    pub scoped: Vec<Name>,
259    /// The argument's role: the registered name of what the argument holds,
260    /// such as `flm.refs.target` for a label that a reference points to. No
261    /// role by default; see [`ArgDef::role`](ArgDef::role()).
262    #[serde(default)]
263    pub role: Option<Name>,
264}
265
266/// Writes a declaration as an argument's map, as [`ArgDef::code`] states a
267/// declaration is written back: with the code it was read from, when it has
268/// one; otherwise with the structured syntax of its parser's standard kind
269/// ([`FlmArgumentParser::std_kind`](super::FlmArgumentParser::std_kind));
270/// otherwise with neither, for a parser of a feature's own. A map written
271/// with neither does not read back. The declaration's other fields are
272/// copied.
273impl From<&ArgDef> for ArgDataFields {
274    fn from(arg: &ArgDef) -> ArgDataFields {
275        let code = arg.code().map(str::to_string);
276        let syntax = match (&code, arg.kind.std_kind()) {
277            (None, Some(kind)) => Some(kind.clone()),
278            _ => None,
279        };
280        ArgDataFields {
281            code,
282            syntax,
283            name: arg.name.clone(),
284            layout: arg.layout,
285            opaque_wrapper: arg.opaque_wrapper,
286            docs: arg.docs.clone(),
287            mode: arg.mode,
288            scoped: arg.scoped.clone(),
289            role: arg.role.clone(),
290        }
291    }
292}
293
294impl TryFrom<ArgData> for ArgDef {
295    type Error = ArgDataError;
296
297    fn try_from(data: ArgData) -> Result<ArgDef, ArgDataError> {
298        match data {
299            ArgData::Code(code) => Ok(arg_def_from_code(&code)?),
300            ArgData::Declared(fields) => {
301                let arg = match (fields.code, fields.syntax) {
302                    (Some(code), None) => arg_def_from_code(&code)?,
303                    (None, Some(kind)) => ArgDef::new(kind),
304                    (Some(_), Some(_)) => return Err(ArgDataError::BothCodeAndSyntax),
305                    (None, None) => return Err(ArgDataError::NeitherCodeNorSyntax),
306                };
307                let mut arg = arg.layout(fields.layout).docs(fields.docs);
308                arg.name = fields.name;
309                arg.opaque_wrapper = fields.opaque_wrapper;
310                arg.mode = fields.mode;
311                arg.scoped = fields.scoped;
312                arg.role = fields.role;
313                Ok(arg)
314            }
315        }
316    }
317}
318
319/// What is wrong with an argument written as data: the error of converting
320/// an [`ArgData`] into an argument declaration ([`ArgDef`], through
321/// `TryFrom`), which an [`ArgListError`] holds with the argument's position.
322///
323/// Its `Display` text states the problem for the person who wrote the
324/// settings.
325#[derive(Debug, Clone, PartialEq, Eq)]
326pub enum ArgDataError {
327    /// The argument's code is not a complete argument code.
328    Code(ArgCodeError),
329    /// The argument's map gives both a code (`code`) and a structured syntax
330    /// (`syntax`).
331    BothCodeAndSyntax,
332    /// The argument's map gives neither a code nor a structured syntax.
333    NeitherCodeNorSyntax,
334}
335
336impl From<ArgCodeError> for ArgDataError {
337    fn from(error: ArgCodeError) -> ArgDataError {
338        ArgDataError::Code(error)
339    }
340}
341
342impl fmt::Display for ArgDataError {
343    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344        match self {
345            ArgDataError::Code(error) => fmt::Display::fmt(error, f),
346            ArgDataError::BothCodeAndSyntax => f.write_str(
347                "an argument written as a map must hold exactly one of the keys `code` and `syntax`, \
348                 and this one holds both",
349            ),
350            ArgDataError::NeitherCodeNorSyntax => f.write_str(
351                "an argument written as a map must hold the key `code` or the key `syntax`, which \
352                 gives its syntax",
353            ),
354        }
355    }
356}
357
358impl std::error::Error for ArgDataError {
359    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
360        match self {
361            ArgDataError::Code(error) => Some(error),
362            _ => None,
363        }
364    }
365}
366
367/// What is wrong with an argument list written as data: the error of
368/// [`ArgListData::arg_defs`], the [`ArgDataError`] of one of its arguments
369/// with the argument's position in the list. A reader that converts the
370/// entries of a list one by one gives its errors the same form.
371///
372/// Its `Display` text states the problem for the person who wrote the
373/// settings: the argument's position counted from 1, then the
374/// [`ArgDataError`]'s text (`argument 2: ` followed by that text).
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct ArgListError {
377    /// The argument's index in the list, from 0: the index of its entry in a
378    /// list, or of its character in one text of codes.
379    pub index: usize,
380    /// What is wrong with the argument.
381    pub error: ArgDataError,
382}
383
384impl fmt::Display for ArgListError {
385    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386        write!(f, "argument {}: {}", self.index + 1, self.error)
387    }
388}
389
390impl std::error::Error for ArgListError {
391    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
392        Some(&self.error)
393    }
394}
395
396/// The argument list of a macro or environment declared in settings given as
397/// data, written either as one text in which each character is one argument
398/// code (`"[{"`), or as a list whose entries are each a code or an argument's
399/// map ([`ArgData`]).
400///
401/// [`arg_defs`](ArgListData::arg_defs) converts it into argument declarations;
402/// [`deserialize_arg_list`] reads a settings field of type `Vec<ArgDef>` in any
403/// of the shapes. The [module documentation](self) describes the shapes and
404/// the forms of an argument's syntax.
405//
406// It is also written to data (`Serialize`), in the shape it holds; the
407// fields of a tack-on argument write their arguments as a list of maps.
408#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
409#[derive(schemars::JsonSchema)]
410#[serde(untagged)]
411pub enum ArgListData {
412    /// One text in which each character is one argument code: `"[{{"`.
413    Codes(#[schemars(schema_with = "arg_codes_text_schema")] String),
414    /// A list of arguments, each an argument code or a map.
415    List(Vec<ArgData>),
416}
417
418// A list is a text or a list, and is read as the one or the other, so that a
419// problem in one of its entries is reported with its own message, at the
420// entry's position.
421impl<'de> Deserialize<'de> for ArgListData {
422    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<ArgListData, D::Error> {
423        struct List;
424
425        impl<'de> Visitor<'de> for List {
426            type Value = ArgListData;
427
428            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429                f.write_str(LIST_EXPECTED)
430            }
431
432            fn visit_str<E: serde::de::Error>(self, codes: &str) -> Result<ArgListData, E> {
433                Ok(ArgListData::Codes(codes.to_string()))
434            }
435
436            fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<ArgListData, A::Error> {
437                entries(seq).map(ArgListData::List)
438            }
439        }
440
441        deserializer.deserialize_any(List)
442    }
443}
444
445impl ArgListData {
446    /// Converts the list into argument declarations, in the order the
447    /// arguments are written.
448    ///
449    /// # Errors
450    ///
451    /// An [`ArgListError`] for the first entry that is not an argument code,
452    /// that lacks the characters its code letter requires, or that is a map
453    /// giving both a code and a structured syntax, or neither: the entry's
454    /// [`ArgDataError`] with its position.
455    pub fn arg_defs(self) -> Result<Vec<ArgDef>, ArgListError> {
456        match self {
457            ArgListData::Codes(codes) => codes
458                .chars()
459                .enumerate()
460                .map(|(index, code)| {
461                    arg_def_from_code(&String::from(code)).map_err(|error| ArgListError { index, error: error.into() })
462                })
463                .collect(),
464            ArgListData::List(args) => args
465                .into_iter()
466                .enumerate()
467                .map(|(index, arg)| ArgDef::try_from(arg).map_err(|error| ArgListError { index, error }))
468                .collect(),
469        }
470    }
471}
472
473/// What an argument list is, for the message of a value of another form.
474const LIST_EXPECTED: &str = "a text of argument codes or a list of arguments";
475
476/// Reads every entry of a list.
477fn entries<'de, A: SeqAccess<'de>, T: Deserialize<'de>>(mut seq: A) -> Result<Vec<T>, A::Error> {
478    let mut entries = Vec::new();
479    while let Some(entry) = seq.next_element()? {
480        entries.push(entry);
481    }
482    Ok(entries)
483}
484
485/// Deserializes an argument list written in any of the shapes of
486/// [`ArgListData`] into argument declarations.
487///
488/// Use it as the deserializer of a settings field of type `Vec<ArgDef>`, and
489/// give the field [`ArgListData`]'s schema, as in the example. Each entry of
490/// a list is converted as it is read, so the error of an entry is reported at
491/// the entry's position in the list.
492///
493/// ```
494/// use flm_core::lang::mint::{deserialize_arg_list, ArgDef, ArgListData};
495///
496/// #[derive(serde::Deserialize, schemars::JsonSchema)]
497/// struct MyMacro {
498///     #[serde(deserialize_with = "deserialize_arg_list")]
499///     #[schemars(with = "ArgListData")]
500///     args: Vec<ArgDef>,
501/// }
502///
503/// let declared: MyMacro = serde_json::from_value(serde_json::json!({ "args": "[{" })).unwrap();
504/// assert_eq!(declared.args.len(), 2);
505/// let declared: MyMacro = serde_json::from_value(serde_json::json!({
506///     "args": [{ "syntax": "delimited-group", "delimiters": ["(", ")"], "name": "size" }],
507/// }))
508/// .unwrap();
509/// assert_eq!(declared.args[0].kind.description(), "a mandatory `(…)` group");
510/// ```
511///
512/// # Errors
513///
514/// The deserializer's error when the data has none of the shapes of
515/// [`ArgListData`], or when an entry is not an argument; the error then
516/// carries the [`ArgListError`]'s message for a code of one text of codes,
517/// the [`ArgDataError`]'s message for an entry of a list, or the message of
518/// the structured syntax that cannot be read.
519pub fn deserialize_arg_list<'de, D>(deserializer: D) -> Result<Vec<ArgDef>, D::Error>
520where
521    D: Deserializer<'de>,
522{
523    struct Args;
524
525    impl<'de> Visitor<'de> for Args {
526        type Value = Vec<ArgDef>;
527
528        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529            f.write_str(LIST_EXPECTED)
530        }
531
532        fn visit_str<E: serde::de::Error>(self, codes: &str) -> Result<Vec<ArgDef>, E> {
533            ArgListData::Codes(codes.to_string()).arg_defs().map_err(E::custom)
534        }
535
536        fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Vec<ArgDef>, A::Error> {
537            entries(seq)
538        }
539    }
540
541    deserializer.deserialize_any(Args)
542}
543
544// --- the structured syntax -----------------------------------------------------------------------
545
546/// The keys of a standard kind written as data: the form in which
547/// [`ArgStdKind`] is serialized and deserialized (its `into` and `try_from`
548/// type). Each variant holds the parameters as data writes them, a character
549/// as a text and a pair of delimiters as a list; the conversion into the kind
550/// checks them. A kind without parameters is a variant with no field, so
551/// that a key written beside its name is refused. A parameter's key must
552/// differ from the keys of an argument's map ([`ArgDataFields`]), which the
553/// map reads itself before the kind reads the keys left. The documentation of
554/// the variants and of their fields is the description of each kind in the
555/// settings' JSON Schema.
556#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
557#[serde(tag = "syntax", rename_all = "kebab-case", deny_unknown_fields)]
558pub(crate) enum ArgStdKindData {
559    /// A mandatory `{…}` group; a single token also counts.
560    Mandatory {},
561    /// An optional `[…]` group.
562    Optional {},
563    /// An optional `*` marker.
564    Star {},
565    /// An optional marker made of one or more characters.
566    Marker {
567        /// The marker's characters.
568        #[schemars(pattern(CHARACTERS))]
569        marker: String,
570    },
571    /// A mandatory group between a pair of characters.
572    DelimitedGroup {
573        /// The opening and the closing character.
574        #[schemars(length(equal = 2), inner(pattern(ONE_CHARACTER)))]
575        delimiters: Vec<String>,
576    },
577    /// An optional group between a pair of characters.
578    OptionalDelimitedGroup {
579        /// The opening and the closing character.
580        #[schemars(length(equal = 2), inner(pattern(ONE_CHARACTER)))]
581        delimiters: Vec<String>,
582    },
583    /// A mandatory group in `{…}`, `[…]`, `(…)` or `<…>`.
584    AnyDelimitedGroup {},
585    /// An optional group in `{…}`, `[…]`, `(…)` or `<…>`.
586    OptionalAnyDelimitedGroup {},
587    /// A mandatory `{…}` group, never a single token.
588    BracedOnly {},
589    /// Embellishments: each marker character is followed by one expression;
590    /// the markers may be written in any order, each at most once.
591    Embellishments {
592        /// The marker characters, at least one.
593        #[schemars(length(min = 1), inner(pattern(ONE_CHARACTER)))]
594        markers: Vec<String>,
595    },
596    /// An optional `[key=value,…]` group.
597    KeyVals {},
598    /// A `{…}` group read as plain characters, kept as written.
599    CharsGroup {},
600    /// Verbatim text between a pair of delimiters.
601    Verbatim {
602        /// The opening and the closing delimiter. Without it, the closing
603        /// delimiter matches whichever opening one is found: `}` for `{`, `]`
604        /// for `[`, `)` for `(`, `>` for `<`, and any other character for
605        /// itself.
606        #[serde(default, skip_serializing_if = "Option::is_none")]
607        #[schemars(length(equal = 2), inner(pattern(ONE_CHARACTER)))]
608        delimiters: Option<Vec<String>>,
609    },
610    /// The fields a command accepts at this argument's position in a call:
611    /// macros written after the arguments declared before it, which the
612    /// command reads as data.
613    TackOn {
614        /// The fields, each with a distinct name.
615        fields: Vec<TackOnFieldData>,
616    },
617    /// An argument that runs up to a terminator: an optional run of a
618    /// repeated character and an opener, the content, then the terminator,
619    /// which is the head, as many copies of the repeated character as the
620    /// run had, and the rest of the terminator.
621    Terminated {
622        /// The end of the terminator, after the repeated characters.
623        terminator: String,
624        /// The character whose run starts the argument and is repeated in
625        /// the terminator. None by default.
626        #[serde(default, skip_serializing_if = "Option::is_none")]
627        #[schemars(pattern(ONE_CHARACTER))]
628        repeat_char: Option<String>,
629        /// The text that follows the run of the repeated character. Empty by
630        /// default.
631        #[serde(default)]
632        opener: String,
633        /// The text that begins the terminator, before the repeated
634        /// characters. Empty by default.
635        #[serde(default)]
636        head: String,
637        /// Whether the content is raw text (`true`) or parsed document
638        /// content (`false`, the default).
639        #[serde(default)]
640        raw: bool,
641    },
642}
643
644/// A field that the command accepts at the position of its `tack-on`
645/// argument: a macro, which the command reads as data.
646//
647// A tack-on field ([`TackOnField`]) written as data, in the structured syntax
648// `tack-on`: its name, its arguments, whether it may repeat, and its
649// documentation. This is a plain comment, not documentation, because the
650// documentation of this type and of its fields is the description of each
651// key in the settings' JSON Schema.
652#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
653#[serde(deny_unknown_fields)]
654pub(crate) struct TackOnFieldData {
655    /// The field's name, without the backslash: `label` for a field written
656    /// `\label{…}`.
657    name: String,
658    /// The field's own arguments, an argument list in any of its shapes. None
659    /// by default.
660    #[serde(default = "no_arguments")]
661    args: ArgListData,
662    /// Whether the field may be written more than once after one command.
663    /// `false` by default.
664    #[serde(default)]
665    repeatable: bool,
666    /// The field's documentation. Empty by default.
667    #[serde(default)]
668    docs: String,
669}
670
671/// The argument list of a field that gives none: no argument.
672fn no_arguments() -> ArgListData {
673    ArgListData::List(Vec::new())
674}
675
676/// The pattern of a character in a structured syntax: one character, not
677/// whitespace.
678const ONE_CHARACTER: &str = r"^\S$";
679
680/// The pattern of a run of characters in a structured syntax: one or more
681/// characters, none of them whitespace.
682const CHARACTERS: &str = r"^\S+$";
683
684impl From<ArgStdKind> for ArgStdKindData {
685    fn from(kind: ArgStdKind) -> ArgStdKindData {
686        let pair = |open: char, close: char| vec![String::from(open), String::from(close)];
687        match kind {
688            ArgStdKind::Mandatory => ArgStdKindData::Mandatory {},
689            ArgStdKind::Optional => ArgStdKindData::Optional {},
690            ArgStdKind::Star => ArgStdKindData::Star {},
691            ArgStdKind::Marker { marker } => ArgStdKindData::Marker { marker },
692            ArgStdKind::DelimitedGroup { open, close } => {
693                ArgStdKindData::DelimitedGroup { delimiters: pair(open, close) }
694            }
695            ArgStdKind::OptionalDelimitedGroup { open, close } => {
696                ArgStdKindData::OptionalDelimitedGroup { delimiters: pair(open, close) }
697            }
698            ArgStdKind::AnyDelimitedGroup => ArgStdKindData::AnyDelimitedGroup {},
699            ArgStdKind::OptionalAnyDelimitedGroup => ArgStdKindData::OptionalAnyDelimitedGroup {},
700            ArgStdKind::BracedOnly => ArgStdKindData::BracedOnly {},
701            ArgStdKind::Embellishments { markers } => {
702                ArgStdKindData::Embellishments { markers: markers.into_iter().map(String::from).collect() }
703            }
704            ArgStdKind::KeyVals => ArgStdKindData::KeyVals {},
705            ArgStdKind::CharsGroup => ArgStdKindData::CharsGroup {},
706            ArgStdKind::Verbatim { delimiters } => ArgStdKindData::Verbatim {
707                delimiters: delimiters.map(|(open, close)| pair(open, close)),
708            },
709            ArgStdKind::TackOn { fields } => ArgStdKindData::TackOn {
710                fields: fields
711                    .iter()
712                    .map(|field: &TackOnField| TackOnFieldData {
713                        name: field.name.clone(),
714                        args: ArgListData::List(
715                            field.args.iter().map(|arg| ArgData::Declared(ArgDataFields::from(arg))).collect(),
716                        ),
717                        repeatable: field.repeatable,
718                        docs: field.docs.clone(),
719                    })
720                    .collect(),
721            },
722            ArgStdKind::Terminated { terminator, repeat_char, opener, head, raw } => ArgStdKindData::Terminated {
723                terminator,
724                repeat_char: repeat_char.map(String::from),
725                opener,
726                head,
727                raw,
728            },
729        }
730    }
731}
732
733impl TryFrom<ArgStdKindData> for ArgStdKind {
734    type Error = String;
735
736    fn try_from(data: ArgStdKindData) -> Result<ArgStdKind, String> {
737        Ok(match data {
738            ArgStdKindData::Mandatory {} => ArgStdKind::Mandatory,
739            ArgStdKindData::Optional {} => ArgStdKind::Optional,
740            ArgStdKindData::Star {} => ArgStdKind::Star,
741            ArgStdKindData::Marker { marker } => {
742                if marker.is_empty() || marker.chars().any(char::is_whitespace) {
743                    return Err(format!(
744                        "`marker` must be one or more characters other than whitespace, not {marker:?}"
745                    ));
746                }
747                marker_kind(marker)
748            }
749            ArgStdKindData::DelimitedGroup { delimiters } => {
750                let (open, close) = delimiter_pair(&delimiters)?;
751                ArgStdKind::DelimitedGroup { open, close }
752            }
753            ArgStdKindData::OptionalDelimitedGroup { delimiters } => {
754                let (open, close) = delimiter_pair(&delimiters)?;
755                ArgStdKind::OptionalDelimitedGroup { open, close }
756            }
757            ArgStdKindData::AnyDelimitedGroup {} => ArgStdKind::AnyDelimitedGroup,
758            ArgStdKindData::OptionalAnyDelimitedGroup {} => ArgStdKind::OptionalAnyDelimitedGroup,
759            ArgStdKindData::BracedOnly {} => ArgStdKind::BracedOnly,
760            ArgStdKindData::Embellishments { markers } => {
761                if markers.is_empty() {
762                    return Err(String::from("`markers` must list at least one marker character"));
763                }
764                let markers = markers
765                    .iter()
766                    .map(|marker| character("each of the `markers`", marker))
767                    .collect::<Result<Vec<char>, String>>()?;
768                ArgStdKind::Embellishments { markers }
769            }
770            ArgStdKindData::KeyVals {} => ArgStdKind::KeyVals,
771            ArgStdKindData::CharsGroup {} => ArgStdKind::CharsGroup,
772            ArgStdKindData::Verbatim { delimiters } => ArgStdKind::Verbatim {
773                delimiters: delimiters.as_deref().map(delimiter_pair).transpose()?,
774            },
775            ArgStdKindData::TackOn { fields } => ArgStdKind::TackOn { fields: tack_on_fields(fields)? },
776            ArgStdKindData::Terminated { terminator, repeat_char, opener, head, raw } => {
777                let repeat_char = repeat_char.as_deref().map(|text| character("`repeat_char`", text)).transpose()?;
778                match repeat_char {
779                    None if terminator.is_empty() && head.is_empty() => {
780                        return Err(String::from(
781                            "a `terminated` argument must give a non-empty `terminator` or `head`, or a \
782                             `repeat_char`, so that its terminator is never empty",
783                        ));
784                    }
785                    Some(repeat_char) if opener.starts_with(repeat_char) => {
786                        return Err(format!(
787                            "the `opener` of a `terminated` argument must not begin with its \
788                             `repeat_char` `{repeat_char}`"
789                        ));
790                    }
791                    _ => {}
792                }
793                ArgStdKind::Terminated { terminator, repeat_char, opener, head, raw }
794            }
795        })
796    }
797}
798
799/// Reads the fields of a structured syntax `tack-on`: each field's name; its
800/// arguments, read as an argument list ([`ArgListData::arg_defs`]); whether it
801/// repeats; and its documentation. That the fields' names are distinct is
802/// checked by the minting, as for fields declared in Rust
803/// ([`MintError::FieldDeclaredTwice`](crate::lang::mint::MintError::FieldDeclaredTwice)).
804fn tack_on_fields(fields: Vec<TackOnFieldData>) -> Result<Vec<TackOnField>, String> {
805    fields
806        .into_iter()
807        .map(|data| {
808            let args = data.args.arg_defs().map_err(|error| format!("in the field `{}`, {error}", data.name))?;
809            let field = TackOnField::new(data.name, args).docs(data.docs);
810            Ok(if data.repeatable { field.repeatable() } else { field })
811        })
812        .collect()
813}
814
815/// The kind of an optional marker made of the characters `marker`: as with
816/// the code `t*`, the `*` marker is the star kind, so that one form has one
817/// kind.
818fn marker_kind(marker: String) -> ArgStdKind {
819    if marker == "*" {
820        ArgStdKind::Star
821    } else {
822        ArgStdKind::Marker { marker }
823    }
824}
825
826/// Reads a character of a structured syntax, written as `text`: one
827/// character, not whitespace. `what` names the parameter in the message.
828fn character(what: &str, text: &str) -> Result<char, String> {
829    let mut chars = text.chars();
830    match (chars.next(), chars.next()) {
831        (Some(c), None) if !c.is_whitespace() => Ok(c),
832        _ => Err(format!("{what} must be one character other than whitespace, not {text:?}")),
833    }
834}
835
836/// Reads the `delimiters` of a structured syntax: an opening and a closing
837/// character.
838fn delimiter_pair(delimiters: &[String]) -> Result<(char, char), String> {
839    let [open, close] = delimiters else {
840        return Err(format!(
841            "`delimiters` must list two characters, the opening one and the closing one, and it lists {}",
842            delimiters.len()
843        ));
844    };
845    Ok((character("each of the `delimiters`", open)?, character("each of the `delimiters`", close)?))
846}
847
848/// Reads the structured syntax of an argument's map ([`ArgDataFields`]): the
849/// keys of the map that are not the map's own, which the map's other fields
850/// read. With the key `syntax`, they are read as a standard kind; without it,
851/// they must be none. When the kind cannot be read, the message states the
852/// condition from the forms of the map's schema where they show it
853/// ([`syntax_problem`]): a name that is no kind's, a key that is neither one
854/// of the map's own nor a parameter of the kind, and a parameter's value of
855/// another type.
856fn deserialize_syntax<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<ArgStdKind>, D::Error> {
857    let keys = serde_json::Map::<String, Value>::deserialize(deserializer)?;
858    let Some(syntax) = keys.get("syntax") else {
859        return match keys.keys().next() {
860            Some(key) => Err(D::Error::custom(unknown_key(key, None, map_form(&map_forms(), None)))),
861            None => Ok(None),
862        };
863    };
864    ArgStdKind::deserialize(Value::Object(keys.clone())).map(Some).map_err(|error| {
865        // The kind's own message for a name that is no kind's lists the names
866        // without stating the condition; for a key it does not take, it lists
867        // the kind's parameters alone, not the keys of the map around them;
868        // for a parameter's value of another type, it does not name the
869        // parameter.
870        D::Error::custom(syntax_problem(syntax, &keys).unwrap_or_else(|| error.to_string()))
871    })
872}
873
874/// States what keeps the structured syntax of an argument's map from being
875/// read, when the forms of the map's schema show it ([`map_forms`]):
876/// `syntax`, the value of the key `syntax`, that names no kind settings may
877/// write ([`unknown_syntax`]); a key of `keys`, the map's keys that are not
878/// its own, that is neither `syntax` nor a parameter of the kind
879/// ([`unknown_key`]); or a parameter whose value has a type the kind does not
880/// take ([`mistyped`]). `None` for any other condition, which the kind's own
881/// message states.
882fn syntax_problem(syntax: &Value, keys: &serde_json::Map<String, Value>) -> Option<String> {
883    let forms = map_forms();
884    let name = syntax.as_str();
885    let Some(form) = name.and_then(|name| map_form(&forms, Some(name))) else {
886        return Some(unknown_syntax(syntax, &forms));
887    };
888    if let Some(key) = keys.keys().find(|key| !form.contains_key(*key)) {
889        return Some(unknown_key(key, name, Some(form)));
890    }
891    keys.iter().find_map(|(key, value)| mistyped(key, form.get(key)?, value))
892}
893
894/// The message that refuses `syntax`, the value of the key `syntax` of an
895/// argument's map, which names no kind that settings may write. It lists the
896/// names of the kinds of `forms` ([`map_forms`]).
897fn unknown_syntax(syntax: &Value, forms: &[MapForm]) -> String {
898    let names: Vec<String> = forms.iter().filter_map(form_syntax).map(|name| format!("`{name}`")).collect();
899    format!("{syntax} is not a syntax of an argument; the syntaxes are {}", names.join(", "))
900}
901
902/// The message that refuses the key `key` of an argument's map, a key that is
903/// neither one of the map's own nor a parameter of the kind named `syntax`
904/// (`None` for a map without the key `syntax`). It lists the keys of `form`,
905/// the form of the map ([`map_form`]).
906fn unknown_key(key: &str, syntax: Option<&str>, form: Option<&MapForm>) -> String {
907    let listed = |code: bool| {
908        let known = form.into_iter().flat_map(MapForm::keys).filter(|known| code || known.as_str() != "code");
909        known.map(|known| format!("`{known}`")).collect::<Vec<_>>().join(", ")
910    };
911    match (syntax, form) {
912        (_, None) => format!("`{key}` is not a key of an argument's map"),
913        (Some(name), Some(_)) => format!(
914            "`{key}` is not a key of an argument's map with the syntax `{name}`; its keys are {}",
915            listed(true)
916        ),
917        (None, Some(_)) => format!(
918            "`{key}` is not a key of an argument's map; its keys are {}, and `code` or `syntax` with the \
919             syntax's parameters",
920            listed(false)
921        ),
922    }
923}
924
925/// The message that refuses `value`, the value of the parameter `key` of a
926/// structured syntax, when the parameter's schema `schema` does not admit its
927/// JSON type, or, for a list, the JSON type of one of its entries; `None`
928/// when it admits them, or when its type is not one a parameter takes
929/// ([`expected`]).
930fn mistyped(key: &str, schema: &Value, value: &Value) -> Option<String> {
931    if !admits(schema, value) {
932        return Some(format!("`{key}` must be {}, not {value}", expected(schema)?));
933    }
934    let (Some(items), Value::Array(entries)) = (schema.get("items"), value) else {
935        return None;
936    };
937    let entry = entries.iter().find(|entry| !admits(items, entry))?;
938    Some(format!("each of the `{key}` must be {}, not {entry}", expected(items)?))
939}
940
941/// Whether the JSON schema `schema` admits the JSON type of `value`: whether
942/// its key `type`, one name or a list of names, names that type. A schema
943/// without the key admits every type.
944fn admits(schema: &Value, value: &Value) -> bool {
945    let name = match value {
946        Value::Null => "null",
947        Value::Bool(_) => "boolean",
948        Value::Number(_) => "number",
949        Value::String(_) => "string",
950        Value::Array(_) => "array",
951        Value::Object(_) => "object",
952    };
953    match schema.get("type") {
954        Some(Value::Array(names)) => names.iter().any(|admitted| admitted == name),
955        Some(admitted) => admitted == name,
956        None => true,
957    }
958}
959
960/// What a value that the schema `schema` of a parameter of a structured
961/// syntax admits is, in a message: one character (a text of the pattern
962/// [`ONE_CHARACTER`]), one or more characters (a text of the pattern
963/// [`CHARACTERS`]), a text, a list, or `true` or `false`. `None` for a schema
964/// of another type.
965fn expected(schema: &Value) -> Option<&'static str> {
966    let name = match schema.get("type")? {
967        Value::Array(names) => names.iter().filter_map(Value::as_str).find(|name| *name != "null")?,
968        name => name.as_str()?,
969    };
970    let pattern = schema.get("pattern").and_then(Value::as_str);
971    match name {
972        "string" if pattern == Some(ONE_CHARACTER) => Some("one character other than whitespace"),
973        "string" if pattern == Some(CHARACTERS) => Some("one or more characters other than whitespace"),
974        "string" => Some("a text"),
975        "array" => Some("a list"),
976        "boolean" => Some("`true` or `false`"),
977        _ => None,
978    }
979}
980
981/// One form of an argument's map in the map's JSON schema: the keys the map
982/// may hold, each with the schema of its value.
983type MapForm = serde_json::Map<String, Value>;
984
985/// The forms of an argument's map ([`ArgDataFields`]), read from the map's
986/// JSON schema, whose alternatives list each form's keys
987/// ([`arg_map_schema`]): the form with the key `code`, then one per kind that
988/// settings may write, with the key `syntax`, the kind's parameters, and the
989/// map's own keys. The messages that refuse a map are read from them, so that
990/// the messages and the schema name the same kinds, keys and types.
991fn map_forms() -> Vec<MapForm> {
992    let schema = schemars::SchemaGenerator::default().into_root_schema_for::<ArgDataFields>();
993    let alternatives = schema.get("oneOf").and_then(Value::as_array).into_iter().flatten();
994    alternatives.filter_map(|alternative| alternative.get("properties").and_then(Value::as_object)).cloned().collect()
995}
996
997/// The form among `forms` ([`map_forms`]) of an argument's map with the
998/// structured syntax named `syntax`, or with a code for `None`. A name that
999/// no kind settings may write has none.
1000fn map_form<'a>(forms: &'a [MapForm], syntax: Option<&str>) -> Option<&'a MapForm> {
1001    forms.iter().find(|form| form_syntax(form) == syntax)
1002}
1003
1004/// The name of the kind of the form `form` of an argument's map
1005/// ([`map_forms`]), which its key `syntax` holds as its `const`; `None` for
1006/// the form with a code.
1007fn form_syntax(form: &MapForm) -> Option<&str> {
1008    form.get("syntax")?.get("const")?.as_str()
1009}
1010
1011// --- the reader ----------------------------------------------------------------------------------
1012
1013/// What is wrong with a text read as an argument code; part of
1014/// [`ArgCodeError`].
1015#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1016pub enum ArgCodeProblem {
1017    /// The text is not an argument code.
1018    Unknown,
1019    /// The text begins with a code letter that requires characters after it
1020    /// (`t`, `r`, `d`, `v`, `e`, `u`, `U`, `f`, `F`), and they are missing or
1021    /// include a space.
1022    Incomplete,
1023}
1024
1025/// The error of reading a text that is not a complete argument code, returned
1026/// by [`ArgCode::read`] and [`arg_def_from_code`] and held by an
1027/// [`ArgDataError`].
1028///
1029/// Its `Display` text states the problem for the person who wrote the
1030/// settings: for an unknown code it lists every code.
1031#[derive(Debug, Clone, PartialEq, Eq)]
1032pub struct ArgCodeError {
1033    /// The code as written.
1034    pub code: String,
1035    /// What is wrong with it.
1036    pub problem: ArgCodeProblem,
1037}
1038
1039impl fmt::Display for ArgCodeError {
1040    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041        match self.problem {
1042            ArgCodeProblem::Unknown => {
1043                let codes: Vec<String> = FIXED_CODES
1044                    .iter()
1045                    .map(|(code, _)| *code)
1046                    .chain(CODE_FORMS.iter().flat_map(|form| form.written.iter().copied()))
1047                    .map(|code| format!("`{code}`"))
1048                    .collect();
1049                write!(f, "`{}` is not an argument code; the codes are {}", self.code, codes.join(", "))
1050            }
1051            ArgCodeProblem::Incomplete => {
1052                let letter = self.code.chars().next();
1053                match CODE_FORMS.iter().find(|form| Some(form.letter) == letter) {
1054                    Some(form) => write!(
1055                        f,
1056                        "in the argument code `{}`, `{}` must be followed by {}, as in `{}`",
1057                        self.code, form.letter, form.takes, form.example
1058                    ),
1059                    None => write!(f, "`{}` is not a complete argument code", self.code),
1060                }
1061            }
1062        }
1063    }
1064}
1065
1066impl std::error::Error for ArgCodeError {}
1067
1068/// An argument code that has been read: the code's text, as written, and the
1069/// standard argument kind ([`ArgStdKind`]) it stands for. An argument code is
1070/// a short text, such as `{` or `r()`, that settings given as data write for
1071/// the syntax of an argument; the [module documentation](self) lists the
1072/// codes.
1073///
1074/// [`ArgCode::read`] is the only way to make one, so its text and its kind
1075/// always agree. An argument declaration ([`ArgDef`]) is made from it through
1076/// `From`, without reading the code again, and keeps it: [`ArgDef::code`]
1077/// gives the code's text and [`ArgDef::arg_code`] the `ArgCode` itself. A
1078/// declaration keeps the text as well as the kind because several codes
1079/// stand for one kind (`{` and `m`, `*` and `t*`), and a declaration written
1080/// back as data shows the code its author wrote.
1081#[derive(Debug, Clone, PartialEq, Eq)]
1082pub struct ArgCode {
1083    /// The code as written.
1084    code: String,
1085    /// The standard kind the code stands for.
1086    kind: ArgStdKind,
1087}
1088
1089impl ArgCode {
1090    /// Reads `code` as an argument code, one of those listed in the [module
1091    /// documentation](self).
1092    ///
1093    /// This is the only reader of the codes: [`arg_def_from_code`], and
1094    /// through it every reader of settings given as data, reads its codes
1095    /// with it.
1096    ///
1097    /// # Errors
1098    ///
1099    /// An [`ArgCodeError`] for a text that is no code
1100    /// ([`ArgCodeProblem::Unknown`]) and for a code lacking the characters it
1101    /// takes ([`ArgCodeProblem::Incomplete`]: `r(`, `t`, `e{}`).
1102    ///
1103    /// # Examples
1104    ///
1105    /// ```
1106    /// use flm_core::lang::mint::{ArgCode, ArgCodeProblem, ArgDef, ArgStdKind};
1107    ///
1108    /// let code = ArgCode::read("r()").unwrap();
1109    /// assert_eq!(code.as_str(), "r()");
1110    /// assert_eq!(code.kind(), &ArgStdKind::DelimitedGroup { open: '(', close: ')' });
1111    /// assert_eq!(ArgDef::from(code).code(), Some("r()"));
1112    /// assert_eq!(ArgCode::read("q").unwrap_err().problem, ArgCodeProblem::Unknown);
1113    /// assert_eq!(ArgCode::read("r(").unwrap_err().problem, ArgCodeProblem::Incomplete);
1114    /// ```
1115    pub fn read(code: &str) -> Result<ArgCode, ArgCodeError> {
1116        let read = |kind: ArgStdKind| ArgCode { code: code.to_string(), kind };
1117        if let Some((_, kind)) = FIXED_CODES.iter().find(|(known, _)| *known == code) {
1118            return Ok(read(kind.clone()));
1119        }
1120        let error = |problem| ArgCodeError { code: code.to_string(), problem };
1121        let mut chars = code.chars();
1122        let Some(letter) = chars.next() else {
1123            return Err(error(ArgCodeProblem::Unknown));
1124        };
1125        let Some(form) = CODE_FORMS.iter().find(|form| form.letter == letter) else {
1126            return Err(error(ArgCodeProblem::Unknown));
1127        };
1128        let rest: Vec<char> = chars.collect();
1129        (form.read)(&rest).map(read).map_err(error)
1130    }
1131
1132    /// The code as written: `"["`, `"r()"`.
1133    pub fn as_str(&self) -> &str {
1134        &self.code
1135    }
1136
1137    /// The standard kind the code stands for.
1138    pub fn kind(&self) -> &ArgStdKind {
1139        &self.kind
1140    }
1141}
1142
1143/// The declaration of an argument read by the standard kind `code` stands
1144/// for, with no name, inline layout and no scoped package, which keeps the
1145/// code ([`ArgDef::code`], [`ArgDef::arg_code`]). The code is not read again.
1146impl From<ArgCode> for ArgDef {
1147    fn from(code: ArgCode) -> ArgDef {
1148        let mut arg = ArgDef::new(code.kind.clone());
1149        arg.code = Some(code);
1150        arg
1151    }
1152}
1153
1154/// Converts one argument code into an argument declaration ([`ArgDef`]) with
1155/// no name, inline layout and no scoped package, which keeps the code it was
1156/// read from ([`ArgDef::code`]): the code is read by [`ArgCode::read`], and
1157/// the declaration made from it through `From`.
1158///
1159/// # Errors
1160///
1161/// An [`ArgCodeError`] for a text that is no code ([`ArgCodeProblem::Unknown`])
1162/// and for a code lacking the characters it takes
1163/// ([`ArgCodeProblem::Incomplete`]: `r(`, `t`, `e{}`).
1164///
1165/// # Examples
1166///
1167/// ```
1168/// use flm_core::lang::mint::{arg_def_from_code, ArgCodeProblem};
1169///
1170/// let arg = arg_def_from_code("r()").unwrap();
1171/// assert!(arg.name.is_none());
1172/// assert_eq!(arg.code(), Some("r()"));
1173/// assert_eq!(arg.kind.description(), "a mandatory `(…)` group");
1174/// assert_eq!(arg_def_from_code("q").unwrap_err().problem, ArgCodeProblem::Unknown);
1175/// assert_eq!(arg_def_from_code("r(").unwrap_err().problem, ArgCodeProblem::Incomplete);
1176/// ```
1177pub fn arg_def_from_code(code: &str) -> Result<ArgDef, ArgCodeError> {
1178    ArgCode::read(code).map(ArgDef::from)
1179}
1180
1181/// The codes written as one fixed text, each with its standard kind.
1182const FIXED_CODES: [(&str, ArgStdKind); 10] = [
1183    ("{", ArgStdKind::Mandatory),
1184    ("m", ArgStdKind::Mandatory),
1185    ("[", ArgStdKind::Optional),
1186    ("o", ArgStdKind::Optional),
1187    ("*", ArgStdKind::Star),
1188    ("s", ArgStdKind::Star),
1189    ("v", ArgStdKind::Verbatim { delimiters: None }),
1190    ("AnyDelimited", ArgStdKind::AnyDelimitedGroup),
1191    ("AnyDelimitedOptional", ArgStdKind::OptionalAnyDelimitedGroup),
1192    ("BracedOnly", ArgStdKind::BracedOnly),
1193];
1194
1195/// A code made of a letter and the characters it takes: how it is written,
1196/// matched and read.
1197struct CodeForm {
1198    /// The code's letter.
1199    letter: char,
1200    /// The code's shapes as the documentation and the messages show them
1201    /// (`r<c1><c2>`; `t<c>` and `t{<chars>}`).
1202    written: &'static [&'static str],
1203    /// What the letter must be followed by, for the message of an incomplete
1204    /// code.
1205    takes: &'static str,
1206    /// A complete code of the form.
1207    example: &'static str,
1208    /// The regular expression a complete code of the form matches, in any of
1209    /// its shapes, for the schema of the settings.
1210    pattern: &'static str,
1211    /// What the argument is, for the schema of the settings.
1212    description: &'static str,
1213    /// Reads the characters after the letter.
1214    read: fn(&[char]) -> Result<ArgStdKind, ArgCodeProblem>,
1215}
1216
1217/// The codes made of a letter and the characters it takes. The letter `v`
1218/// alone is the fixed code `v` ([`FIXED_CODES`]).
1219const CODE_FORMS: [CodeForm; 9] = [
1220    CodeForm {
1221        letter: 't',
1222        written: &["t<c>", "t{<chars>}"],
1223        takes: "one marker character, or by `{`, one or more marker characters and `}`",
1224        example: "t!",
1225        pattern: r"^t(\S|\{[^\s}]+\})$",
1226        description: "an optional marker made of the one character after `t`, or of the characters \
1227                      between the braces after `t`",
1228        read: |rest| {
1229            let marker: String = match rest {
1230                ['{', _, ..] => braced(rest)?.iter().collect(),
1231                _ => parameters::<1>(rest)?.iter().collect(),
1232            };
1233            Ok(marker_kind(marker))
1234        },
1235    },
1236    CodeForm {
1237        letter: 'r',
1238        written: &["r<c1><c2>"],
1239        takes: "an opening and a closing character",
1240        example: "r()",
1241        pattern: r"^r\S\S$",
1242        description: "a mandatory group between the two characters after `r`",
1243        read: |rest| {
1244            let [open, close] = parameters::<2>(rest)?;
1245            Ok(ArgStdKind::DelimitedGroup { open, close })
1246        },
1247    },
1248    CodeForm {
1249        letter: 'd',
1250        written: &["d<c1><c2>"],
1251        takes: "an opening and a closing character",
1252        example: "d<>",
1253        pattern: r"^d\S\S$",
1254        description: "an optional group between the two characters after `d`",
1255        read: |rest| {
1256            let [open, close] = parameters::<2>(rest)?;
1257            Ok(ArgStdKind::OptionalDelimitedGroup { open, close })
1258        },
1259    },
1260    CodeForm {
1261        letter: 'v',
1262        written: &["v<c1><c2>"],
1263        takes: "an opening and a closing character",
1264        example: "v||",
1265        pattern: r"^v\S\S$",
1266        description: "verbatim text between the two characters after `v`",
1267        read: |rest| {
1268            let [open, close] = parameters::<2>(rest)?;
1269            Ok(ArgStdKind::Verbatim { delimiters: Some((open, close)) })
1270        },
1271    },
1272    CodeForm {
1273        letter: 'e',
1274        written: &["e{<chars>}"],
1275        takes: "`{`, one or more marker characters and `}`",
1276        example: "e{_^}",
1277        pattern: r"^e\{[^\s}]+\}$",
1278        description: "embellishments: each character between the braces is a marker that is \
1279                      followed by one expression; the markers may be written in any order, \
1280                      each at most once",
1281        read: |rest| Ok(ArgStdKind::Embellishments { markers: braced(rest)?.to_vec() }),
1282    },
1283    CodeForm {
1284        letter: 'u',
1285        written: &["u<terminator>"],
1286        takes: "the terminator, one or more characters",
1287        example: "u\\endm",
1288        pattern: r"^u\S+$",
1289        description: "document content up to the characters after `u`, its terminator",
1290        read: |rest| terminated(rest, false, false),
1291    },
1292    CodeForm {
1293        letter: 'U',
1294        written: &["U<terminator>"],
1295        takes: "the terminator, one or more characters",
1296        example: "U\\endm",
1297        pattern: r"^U\S+$",
1298        description: "raw text up to the characters after `U`, its terminator",
1299        read: |rest| terminated(rest, false, true),
1300    },
1301    CodeForm {
1302        letter: 'f',
1303        written: &["f<c><terminator>"],
1304        takes: "a repeated character, then the rest of the terminator, if any",
1305        example: "f+",
1306        pattern: r"^f\S+$",
1307        description: "document content after a run of the character after `f`, up to the same run \
1308                      followed by the characters after that character",
1309        read: |rest| terminated(rest, true, false),
1310    },
1311    CodeForm {
1312        letter: 'F',
1313        written: &["F<c><terminator>"],
1314        takes: "a repeated character, then the rest of the terminator, if any",
1315        example: "F+",
1316        pattern: r"^F\S+$",
1317        description: "raw text after a run of the character after `F`, up to the same run \
1318                      followed by the characters after that character",
1319        read: |rest| terminated(rest, true, true),
1320    },
1321];
1322
1323/// Reads the characters after the letter of a terminated code (`u`, `U`,
1324/// `f`, `F`): with `repeated`, the repeat character and then the rest of the
1325/// terminator, which may be empty; without it, the whole terminator, at
1326/// least one character. A space among them makes the code incomplete.
1327fn terminated(rest: &[char], repeated: bool, raw: bool) -> Result<ArgStdKind, ArgCodeProblem> {
1328    if rest.is_empty() || rest.iter().any(|c| c.is_whitespace()) {
1329        return Err(ArgCodeProblem::Incomplete);
1330    }
1331    let (repeat_char, terminator) = if repeated { (Some(rest[0]), &rest[1..]) } else { (None, rest) };
1332    Ok(ArgStdKind::Terminated {
1333        terminator: terminator.iter().collect(),
1334        repeat_char,
1335        opener: String::new(),
1336        head: String::new(),
1337        raw,
1338    })
1339}
1340
1341/// The characters between the braces of a code that takes `{<chars>}` after
1342/// its letter (`e{<chars>}`, `t{<chars>}`), given the characters after the
1343/// letter: a missing `{` or `}`, nothing between them, or a space among the
1344/// characters is an incomplete code; more after the `}` is no code.
1345fn braced(rest: &[char]) -> Result<&[char], ArgCodeProblem> {
1346    let Some(('{', inner)) = rest.split_first().map(|(first, inner)| (*first, inner)) else {
1347        return Err(ArgCodeProblem::Incomplete);
1348    };
1349    let Some(end) = inner.iter().position(|c| *c == '}') else {
1350        return Err(ArgCodeProblem::Incomplete);
1351    };
1352    let chars = &inner[..end];
1353    if chars.is_empty() || chars.iter().any(|c| c.is_whitespace()) {
1354        return Err(ArgCodeProblem::Incomplete);
1355    }
1356    if end + 1 != inner.len() {
1357        return Err(ArgCodeProblem::Unknown);
1358    }
1359    Ok(chars)
1360}
1361
1362/// The `N` characters a code takes after its letter: fewer, or one of them a
1363/// space, is an incomplete code; more is no code.
1364fn parameters<const N: usize>(rest: &[char]) -> Result<[char; N], ArgCodeProblem> {
1365    if rest.len() > N {
1366        return Err(ArgCodeProblem::Unknown);
1367    }
1368    match <[char; N]>::try_from(rest) {
1369        Ok(chars) if !chars.iter().any(|c| c.is_whitespace()) => Ok(chars),
1370        _ => Err(ArgCodeProblem::Incomplete),
1371    }
1372}
1373
1374// --- the schemas ---------------------------------------------------------------------------------
1375
1376/// The JSON schema of an argument code in settings given as data: one of the
1377/// fixed codes, each described by the phrase its parser returns
1378/// ([`FlmArgumentParser::description`](super::FlmArgumentParser::description)),
1379/// or a code of one of the forms that take characters, each matched by its
1380/// pattern.
1381fn arg_code_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1382    let fixed = FIXED_CODES.iter().map(|(code, kind)| {
1383        let parser = ArgDef::new(kind.clone()).kind;
1384        serde_json::json!({ "const": code, "description": parser.description() })
1385    });
1386    let forms = CODE_FORMS.iter().map(|form| {
1387        serde_json::json!({
1388            "type": "string",
1389            "pattern": form.pattern,
1390            "description": format!("{}: {}", shapes(form), form.description),
1391        })
1392    });
1393    let codes: Vec<serde_json::Value> = fixed.chain(forms).collect();
1394    schemars::json_schema!({
1395        "description": "The argument code, which says what form the argument takes.",
1396        "anyOf": codes,
1397    })
1398}
1399
1400/// The shapes of the code form `form`, each in backticks, joined by "or":
1401/// `` `t<c>` or `t{<chars>}` ``.
1402fn shapes(form: &CodeForm) -> String {
1403    form.written.iter().map(|shape| format!("`{shape}`")).collect::<Vec<_>>().join(" or ")
1404}
1405
1406/// The JSON schema of an argument's parsing mode in settings given as data:
1407/// `text` or `math` (techy's names of the two modes), or nothing.
1408fn mode_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1409    schemars::json_schema!({
1410        "description": "The parsing mode the argument is read in: `text` or `math`. Without it, \
1411                        the argument is read in the mode the command is written in.",
1412        "enum": ["text", "math", null],
1413    })
1414}
1415
1416/// The JSON schema of an argument list written as one text: each character is
1417/// one of the fixed codes of one character.
1418fn arg_codes_text_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1419    let singles: String = FIXED_CODES
1420        .iter()
1421        .map(|(code, _)| *code)
1422        .filter(|code| code.chars().count() == 1)
1423        .map(|code| match code {
1424            "[" | "]" | "\\" | "^" | "-" => format!("\\{code}"),
1425            _ => code.to_string(),
1426        })
1427        .collect();
1428    schemars::json_schema!({
1429        "type": "string",
1430        "pattern": format!("^[{singles}]*$"),
1431        "description": "The arguments written as one text, in which each character is one \
1432                        argument code.",
1433    })
1434}
1435
1436/// The JSON schema of the structured syntax that an argument's map holds
1437/// beside its own keys: one alternative per standard kind that settings may
1438/// write, each the kind's name under `syntax` with the kind's parameters, as
1439/// [`ArgStdKind`]'s schema lists them. [`arg_map_schema`] completes each
1440/// alternative into a whole map.
1441fn syntax_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1442    let kinds = <ArgStdKind as schemars::JsonSchema>::json_schema(generator);
1443    let alternatives = kinds.get("oneOf").cloned().unwrap_or_else(|| Value::Array(Vec::new()));
1444    schemars::json_schema!({ "oneOf": alternatives })
1445}
1446
1447/// Completes the JSON schema that `schemars` derives for an argument's map
1448/// ([`ArgDataFields`]), which lists the map's own keys under `properties`,
1449/// `code` among them, and the kinds of the structured syntax under `oneOf`
1450/// ([`syntax_schema`]).
1451///
1452/// The completed schema has one alternative per form of the syntax: the code
1453/// with the map's other keys, then each kind's name and parameters with the
1454/// same keys. Each alternative is a whole map that admits no other key, so a
1455/// map that gives both a code and a structured syntax, or neither, matches
1456/// none. A schema of another shape is left as it is.
1457fn arg_map_schema(schema: &mut schemars::Schema) {
1458    let Some(object) = schema.as_object_mut() else { return };
1459    let (Some(Value::Array(kinds)), Some(Value::Object(properties))) = (object.get("oneOf"), object.get("properties"))
1460    else {
1461        return;
1462    };
1463    let mut own = properties.clone();
1464    let Some(code) = own.shift_remove("code") else { return };
1465    let whole = |mut keys: serde_json::Map<String, Value>, required: Value, description: Option<&Value>| {
1466        keys.extend(own.clone());
1467        let mut map = serde_json::Map::new();
1468        map.insert(String::from("type"), Value::from("object"));
1469        if let Some(description) = description {
1470            map.insert(String::from("description"), description.clone());
1471        }
1472        map.insert(String::from("properties"), Value::Object(keys));
1473        map.insert(String::from("required"), required);
1474        map.insert(String::from("additionalProperties"), Value::Bool(false));
1475        Value::Object(map)
1476    };
1477    let mut alternatives = vec![whole(
1478        serde_json::Map::from_iter([(String::from("code"), code)]),
1479        serde_json::json!(["code"]),
1480        None,
1481    )];
1482    for kind in kinds {
1483        let parameters = kind.get("properties").and_then(Value::as_object).cloned().unwrap_or_default();
1484        // The kind's name first, then its parameters.
1485        let mut keys = serde_json::Map::new();
1486        if let Some(name) = parameters.get("syntax") {
1487            keys.insert(String::from("syntax"), name.clone());
1488        }
1489        keys.extend(parameters);
1490        let required = kind.get("required").cloned().unwrap_or_else(|| serde_json::json!(["syntax"]));
1491        alternatives.push(whole(keys, required, kind.get("description")));
1492    }
1493    for key in ["oneOf", "properties", "type", "required", "additionalProperties"] {
1494        object.shift_remove(key);
1495    }
1496    object.insert(String::from("oneOf"), Value::Array(alternatives));
1497}
1498
1499#[cfg(test)]
1500mod tests {
1501    use super::*;
1502
1503    fn kind(code: &str) -> Result<String, ArgCodeProblem> {
1504        ArgCode::read(code).map(|code| format!("{:?}", code.kind())).map_err(|error| error.problem)
1505    }
1506
1507    #[test]
1508    fn each_form_reads_its_characters() {
1509        assert_eq!(kind("t!").unwrap(), r#"Marker { marker: "!" }"#);
1510        assert_eq!(kind("t*").unwrap(), "Star");
1511        assert_eq!(kind("t{").unwrap(), r#"Marker { marker: "{" }"#);
1512        assert_eq!(kind("t{\\big}").unwrap(), r#"Marker { marker: "\\big" }"#);
1513        assert_eq!(kind("t{*}").unwrap(), "Star");
1514        assert_eq!(kind("r()").unwrap(), "DelimitedGroup { open: '(', close: ')' }");
1515        assert_eq!(kind("d<>").unwrap(), "OptionalDelimitedGroup { open: '<', close: '>' }");
1516        assert_eq!(kind("v").unwrap(), "Verbatim { delimiters: None }");
1517        assert_eq!(kind("v||").unwrap(), "Verbatim { delimiters: Some(('|', '|')) }");
1518        assert_eq!(kind("e{_^}").unwrap(), "Embellishments { markers: ['_', '^'] }");
1519        assert_eq!(kind("e{`}").unwrap(), "Embellishments { markers: ['`'] }");
1520        assert_eq!(
1521            kind("u\\endphf").unwrap(),
1522            r#"Terminated { terminator: "\\endphf", repeat_char: None, opener: "", head: "", raw: false }"#
1523        );
1524        assert_eq!(
1525            kind("U!!").unwrap(),
1526            r#"Terminated { terminator: "!!", repeat_char: None, opener: "", head: "", raw: true }"#
1527        );
1528        assert_eq!(
1529            kind("f+").unwrap(),
1530            r#"Terminated { terminator: "", repeat_char: Some('+'), opener: "", head: "", raw: false }"#
1531        );
1532        assert_eq!(
1533            kind("F``").unwrap(),
1534            r#"Terminated { terminator: "`", repeat_char: Some('`'), opener: "", head: "", raw: true }"#
1535        );
1536    }
1537
1538    #[test]
1539    fn a_terminated_code_round_trips_through_its_declaration() {
1540        for code in ["u\\endphf", "U\\endverb", "f+", "F``", "F=]]"] {
1541            let arg = arg_def_from_code(code).unwrap();
1542            assert_eq!(arg.code(), Some(code));
1543            let again = arg_def_from_code(arg.code().unwrap()).unwrap();
1544            assert_eq!(again.kind.identity(), arg.kind.identity(), "{code}");
1545        }
1546        assert_ne!(
1547            arg_def_from_code("u\\endphf").unwrap().kind.identity(),
1548            arg_def_from_code("U\\endphf").unwrap().kind.identity()
1549        );
1550        assert_ne!(
1551            arg_def_from_code("f+").unwrap().kind.identity(),
1552            arg_def_from_code("u+").unwrap().kind.identity()
1553        );
1554    }
1555
1556    #[test]
1557    fn a_code_lacking_characters_is_incomplete_and_one_with_more_is_unknown() {
1558        for code in [
1559            "t", "t ", "t{}", "t{ab", "t{a b}", "r", "r(", "r( ", "d<", "v|", "e", "e{", "e{}", "e{_", "e^", "e{ }",
1560            "u", "U", "f", "F", "u ", "ua b", "F` ",
1561        ] {
1562            assert_eq!(kind(code), Err(ArgCodeProblem::Incomplete), "{code:?}");
1563        }
1564        for code in ["", "q", " m", "m ", "mo", "t!!", "t{ab}x", "r()x", "e{^}x", "anydelimited"] {
1565            assert_eq!(kind(code), Err(ArgCodeProblem::Unknown), "{code:?}");
1566        }
1567    }
1568
1569    #[test]
1570    fn each_form_s_example_reads_and_matches_its_pattern() {
1571        for form in &CODE_FORMS {
1572            assert!(ArgCode::read(form.example).is_ok(), "{}", form.example);
1573            assert!(form.pattern.starts_with(&format!("^{}", form.letter)));
1574        }
1575    }
1576
1577    #[test]
1578    fn the_data_form_reads_the_role_and_leaves_it_absent_by_default() {
1579        let list: ArgListData = serde_json::from_value(serde_json::json!([
1580            { "code": "{", "name": "target", "role": "flm.refs.target" },
1581            { "code": "[" },
1582            "m",
1583        ]))
1584        .unwrap();
1585        let args = list.arg_defs().unwrap();
1586        assert_eq!(args[0].role.as_ref().map(Name::as_str), Some("flm.refs.target"));
1587        assert_eq!(args[0].name.as_deref(), Some("target"));
1588        assert!(args[1].role.is_none());
1589        assert!(args[2].role.is_none());
1590    }
1591
1592    #[test]
1593    fn a_structured_syntax_declares_what_its_code_does_and_a_map_gives_exactly_one() {
1594        let arg = |data| ArgDef::try_from(serde_json::from_value::<ArgData>(data).unwrap());
1595        let structured = arg(serde_json::json!({
1596            "syntax": "delimited-group", "delimiters": ["(", ")"], "name": "size",
1597        }))
1598        .unwrap();
1599        let mut coded = arg(serde_json::json!({ "code": "r()", "name": "size" })).unwrap();
1600        // The same declaration, but for the code a declaration read from one
1601        // keeps.
1602        assert_eq!(coded.code(), Some("r()"));
1603        coded.code = None;
1604        assert_eq!(structured, coded);
1605        let both = serde_json::json!({ "code": "r()", "syntax": "delimited-group", "delimiters": ["(", ")"] });
1606        assert_eq!(arg(both).unwrap_err(), ArgDataError::BothCodeAndSyntax);
1607        assert_eq!(arg(serde_json::json!({ "name": "size" })).unwrap_err(), ArgDataError::NeitherCodeNorSyntax);
1608    }
1609
1610    #[test]
1611    fn the_data_form_serializes_every_field_and_reads_back_the_same() {
1612        let fields: ArgDataFields = serde_json::from_value(serde_json::json!({
1613            "code": "{", "name": "path", "mode": "text", "scoped": ["my.package"], "role": "my.path",
1614        }))
1615        .unwrap();
1616        let written = serde_json::to_value(&fields).unwrap();
1617        assert_eq!(
1618            written,
1619            serde_json::json!({
1620                "code": "{", "name": "path", "layout": "inline", "opaque_wrapper": false, "docs": "",
1621                "mode": "text", "scoped": ["my.package"], "role": "my.path",
1622            })
1623        );
1624        let read: ArgDataFields = serde_json::from_value(written).unwrap();
1625        assert_eq!(read, fields);
1626    }
1627
1628    #[test]
1629    fn a_tack_on_kind_reads_its_fields_and_writes_back_the_same() {
1630        let arg = |data| ArgDef::try_from(serde_json::from_value::<ArgData>(data).unwrap()).unwrap();
1631        let declared = arg(serde_json::json!({
1632            "syntax": "tack-on",
1633            "name": "fields",
1634            "fields": [
1635                { "name": "label", "args": [{ "syntax": "chars-group", "name": "target" }], "repeatable": true },
1636                { "name": "nolink", "docs": "No link." },
1637            ],
1638        }));
1639        assert_eq!(declared.name.as_deref(), Some("fields"));
1640        let fields = declared.kind.tack_on_fields().expect("a tack-on argument");
1641        assert_eq!(
1642            fields,
1643            [
1644                TackOnField::new("label", vec![ArgDef::named("target", ArgStdKind::CharsGroup)]).repeatable(),
1645                TackOnField::new("nolink", Vec::new()).docs("No link."),
1646            ]
1647        );
1648        let written = serde_json::to_value(ArgDataFields::from(&declared)).unwrap();
1649        assert_eq!(arg(written), declared);
1650    }
1651}