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