Skip to main content

flm_core/stdlib/backends/latex_rendered/
contract.rs

1//! The contract of the `latex-rendered` backend: what LaTeX is written for
2//! each element of the [presentation vocabulary](crate::stdlib::backends::pres),
3//! as data.
4//!
5//! One command or environment per presentation element, named `flmx` and the
6//! element's name in camel case ([`Row::form`]); every field of the
7//! element's payload is a key of an optional key-value argument written first
8//! ([`Row::keys`]), or a mandatory argument ([`Row::args`]), or listed as not
9//! written with the reason ([`Row::not_written`]). The emitter reads the row of
10//! every element it writes, writes the keys in the row's order, and requires
11//! the row's definition piece ([`Row::chunk`]), so that the style file holds
12//! the definitions of every command the document uses. [`print_rows`] prints
13//! the table for the documentation; a test pins the rows against the payload
14//! types.
15//!
16//! The style file defines each command and environment once
17//! (the chunks [`CORE_CHUNK`] to [`MARKS_CHUNK`]); a definition dispatches on
18//! the element's keys, so that a template registers a look per role, kind
19//! token, style, heading kind or level, or link kind (see the header comment of
20//! the core chunk, `sty/flmx-core.sty`).
21
22use crate::stdlib::backends::pres;
23
24// --- the chunks -------------------------------------------------------------------------
25
26/// `flm.latex.def.flmx.core`: the dispatch machinery, every `\flmxDefine…`
27/// command that registers a look or replaces a default, `\flmxKey`,
28/// `\flmxIfKey`, `\flmxTarget`, the lengths `\flmxTabWidth` and
29/// `\flmxRuninSep`, the colors, `flmxBlock`, `\flmxSpan` with its nine style
30/// defaults, and the three decorations. Every style file holds it.
31pub const CORE_CHUNK: &str = "flm.latex.def.flmx.core";
32/// `flm.latex.def.flmx.headings`: `\flmxHeading` and `\flmxRuninHeading`.
33pub const HEADINGS_CHUNK: &str = "flm.latex.def.flmx.headings";
34/// `flm.latex.def.flmx.links`: `\flmxLink`.
35pub const LINKS_CHUNK: &str = "flm.latex.def.flmx.links";
36/// `flm.latex.def.flmx.lists`: `flmxList` and `\flmxItem`.
37pub const LISTS_CHUNK: &str = "flm.latex.def.flmx.lists";
38/// `flm.latex.def.flmx.lines`: `flmxLines` and `\flmxLine`.
39pub const LINES_CHUNK: &str = "flm.latex.def.flmx.lines";
40/// `flm.latex.def.flmx.verbatim`: `\flmxVerbatim`, `flmxVerbatimBlock`,
41/// `\flmxVerbLine`, and `\flmxDefineVerbatimFont`, which registers the font
42/// of each verbatim kind.
43pub const VERBATIM_CHUNK: &str = "flm.latex.def.flmx.verbatim";
44/// `flm.latex.def.flmx.cells`: `flmxCells`.
45pub const CELLS_CHUNK: &str = "flm.latex.def.flmx.cells";
46/// `flm.latex.def.flmx.images`: `\flmxImage`.
47pub const IMAGES_CHUNK: &str = "flm.latex.def.flmx.images";
48/// `flm.latex.def.flmx.marks`: `\flmxDropped`, `\flmxUnsupported` and
49/// `\flmxUnknown`.
50pub const MARKS_CHUNK: &str = "flm.latex.def.flmx.marks";
51
52/// Every chunk of the backend, the core chunk first.
53pub const CHUNKS: [&str; 9] = [
54    CORE_CHUNK,
55    HEADINGS_CHUNK,
56    LINKS_CHUNK,
57    LISTS_CHUNK,
58    LINES_CHUNK,
59    VERBATIM_CHUNK,
60    CELLS_CHUNK,
61    IMAGES_CHUNK,
62    MARKS_CHUNK,
63];
64
65// --- the row's parts ----------------------------------------------------------------------
66
67/// The LaTeX form an element is written in.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Form {
70    /// A LaTeX paragraph between blank lines, with no command of its own.
71    Paragraph,
72    /// An environment `\begin{<name>}[…]` … `\end{<name>}`.
73    Environment(&'static str),
74    /// A command `\<name>[…]{…}`.
75    Command(&'static str),
76    /// An inline command or, for a block, an environment, chosen by the
77    /// payload's `display`.
78    CommandOrEnvironment {
79        /// The inline command's name.
80        command: &'static str,
81        /// The block environment's name.
82        environment: &'static str,
83    },
84    /// The mathematics delimiters around the source, byte for byte.
85    Formula,
86    /// Content written inside a formula's source.
87    FormulaText,
88    /// The decoration the mark refers to, written at the mark's place.
89    AtMark,
90    /// The placed tree's LaTeX, written in the node's place.
91    Placed,
92}
93
94/// Where a key's value comes from.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum Origin {
97    /// A field of the element's payload.
98    Field(&'static str),
99    /// A field of the payload holding one value per list entry, written as a
100    /// key of that entry's `\flmxItem`.
101    EntryField(&'static str),
102    /// A content slot of the node, lowered content.
103    Slot(&'static str),
104    /// A content slot of each list entry, written as a key of that entry's
105    /// `\flmxItem`.
106    EntrySlot(&'static str),
107    /// Computed by the emitter (a heading's plain title, a link's target, a
108    /// list's depth, the stop after a run-in title).
109    Computed,
110}
111
112/// How a key's value is written (see [`super::emit`]).
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum Value {
115    /// A name (a role, a kind, an anchor, a word), written bare.
116    Name,
117    /// Kind tokens, separated by a space, braced.
118    Words,
119    /// Lowered content, braced.
120    Content,
121    /// Document text computed by the emitter, braced.
122    Text,
123    /// An address, escaped for LaTeX, braced.
124    Address,
125    /// A length, spelled for LaTeX ([`super::length::latex_length`]).
126    Length,
127    /// A number, bare.
128    Number,
129    /// `true` or `false`.
130    Bool,
131    /// One braced key-value list per cell.
132    Specs,
133}
134
135/// One key of an element's key-value argument.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub struct Key {
138    /// The key as written (`doc-role`).
139    pub key: &'static str,
140    /// Where its value comes from.
141    pub origin: Origin,
142    /// How its value is written.
143    pub value: Value,
144}
145
146impl Key {
147    /// The payload field the key is written from, where it comes from one.
148    pub fn field(&self) -> Option<&'static str> {
149        match self.origin {
150            Origin::Field(field) | Origin::EntryField(field) => Some(field),
151            _ => None,
152        }
153    }
154
155    /// Whether the key belongs to each entry of a list (`\flmxItem`) rather
156    /// than to the element itself.
157    pub fn is_entry(&self) -> bool {
158        matches!(self.origin, Origin::EntryField(_) | Origin::EntrySlot(_))
159    }
160
161    /// Whether the key is not the field's name with `_` replaced by `-`: a
162    /// heading's `name` written `kind` and its `in_toc` written `toc`, and a
163    /// list entry's anchor.
164    pub fn is_renamed(&self) -> bool {
165        self.field().is_some_and(|field| field.replace('_', "-") != self.key)
166    }
167}
168
169/// One row of the contract: everything this backend writes for one
170/// presentation element.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub struct Row {
173    /// The presentation element's name (`flm.pres.span`).
174    pub element: &'static str,
175    /// The LaTeX form.
176    pub form: Form,
177    /// The keys of the key-value argument, in the order they are written.
178    pub keys: &'static [Key],
179    /// The payload fields written as mandatory arguments, in order, as text.
180    pub args: &'static [&'static str],
181    /// The payload fields written as nothing, each with the reason.
182    pub not_written: &'static [(&'static str, &'static str)],
183    /// The definition piece the emitter requires where it writes the
184    /// element; `None` for a node that writes no command of its own.
185    pub chunk: Option<&'static str>,
186}
187
188impl Row {
189    /// The key named `key`, where the row has one.
190    pub fn key(&self, key: &str) -> Option<&Key> {
191        self.keys.iter().find(|entry| entry.key == key)
192    }
193}
194
195const fn field(key: &'static str, field: &'static str, value: Value) -> Key {
196    Key { key, origin: Origin::Field(field), value }
197}
198
199const fn computed(key: &'static str, value: Value) -> Key {
200    Key { key, origin: Origin::Computed, value }
201}
202
203/// The keys of both heading elements, block and run in.
204const HEADING_KEYS: [Key; 7] = [
205    field("kind", "name", Value::Name),
206    field("level", "level", Value::Number),
207    field("toc", "in_toc", Value::Bool),
208    field("anchor", "anchor", Value::Name),
209    field("number", "number", Value::Text),
210    computed("plain", Value::Text),
211    Key { key: "alt", origin: Origin::Slot(pres::ALT_SLOT), value: Value::Content },
212];
213
214/// The keys of a run-in heading: [`HEADING_KEYS`] and the stop.
215const RUNIN_HEADING_KEYS: [Key; 8] = [
216    HEADING_KEYS[0],
217    HEADING_KEYS[1],
218    HEADING_KEYS[2],
219    HEADING_KEYS[3],
220    HEADING_KEYS[4],
221    HEADING_KEYS[5],
222    HEADING_KEYS[6],
223    computed("stop", Value::Text),
224];
225
226/// The contract, one row per element of the presentation vocabulary, in the
227/// vocabulary's own order. Every name of [`pres::ALL`] has exactly one row,
228/// which a test holds; [`row`] is the lookup the emitter uses.
229pub static ROWS: &[Row] = &[
230    Row {
231        element: pres::PAR,
232        form: Form::Paragraph,
233        keys: &[],
234        args: &[],
235        not_written: &[("anchor", "written as `\\flmxTarget{<anchor>}` at the paragraph's start")],
236        chunk: Some(CORE_CHUNK),
237    },
238    Row {
239        element: pres::BLOCK,
240        form: Form::Environment("flmxBlock"),
241        keys: &[
242            field("role", "role", Value::Name),
243            field("kinds", "kinds", Value::Words),
244            field("anchor", "anchor", Value::Name),
245            field("doc-role", "doc_role", Value::Name),
246        ],
247        args: &[],
248        not_written: &[],
249        chunk: Some(CORE_CHUNK),
250    },
251    Row {
252        element: pres::BLOCK_HEADING,
253        form: Form::Command("flmxHeading"),
254        keys: &HEADING_KEYS,
255        args: &[],
256        not_written: &[],
257        chunk: Some(HEADINGS_CHUNK),
258    },
259    Row {
260        element: pres::RUNIN_HEADING,
261        form: Form::Command("flmxRuninHeading"),
262        keys: &RUNIN_HEADING_KEYS,
263        args: &[],
264        not_written: &[],
265        chunk: Some(HEADINGS_CHUNK),
266    },
267    Row {
268        element: pres::SPAN,
269        form: Form::Command("flmxSpan"),
270        keys: &[
271            field("style", "style", Value::Name),
272            field("role", "role", Value::Name),
273            field("kinds", "kinds", Value::Words),
274            field("anchor", "anchor", Value::Name),
275            field("doc-role", "doc_role", Value::Name),
276        ],
277        args: &[],
278        not_written: &[],
279        chunk: Some(CORE_CHUNK),
280    },
281    Row {
282        element: pres::LIST,
283        form: Form::Environment("flmxList"),
284        keys: &[
285            field("kinds", "kinds", Value::Words),
286            field("anchor", "anchor", Value::Name),
287            computed("depth", Value::Number),
288            Key { key: "label", origin: Origin::EntrySlot(pres::LABEL_SLOT), value: Value::Content },
289            Key {
290                key: "anchor",
291                origin: Origin::EntryField("entry_anchors"),
292                value: Value::Name,
293            },
294        ],
295        args: &[],
296        not_written: &[(
297            "entry_levels",
298            "an entry's level selects its looks in a page's stylesheet; the document's LaTeX sets \
299             the entries of a list alike, a nested list by its `depth`",
300        )],
301        chunk: Some(LISTS_CHUNK),
302    },
303    Row {
304        element: pres::CELLS,
305        form: Form::Environment("flmxCells"),
306        keys: &[
307            field("rows", "rows", Value::Number),
308            field("cols", "cols", Value::Number),
309            field("cells", "cells", Value::Specs),
310        ],
311        args: &[],
312        not_written: &[],
313        chunk: Some(CELLS_CHUNK),
314    },
315    Row {
316        element: pres::LINES,
317        form: Form::Environment("flmxLines"),
318        keys: &[],
319        args: &[],
320        not_written: &[],
321        chunk: Some(LINES_CHUNK),
322    },
323    Row {
324        element: pres::LINE,
325        form: Form::Command("flmxLine"),
326        keys: &[
327            field("indent-left", "indent_left", Value::Length),
328            field("indent-right", "indent_right", Value::Length),
329            field("align", "align", Value::Name),
330        ],
331        args: &[],
332        not_written: &[],
333        chunk: Some(LINES_CHUNK),
334    },
335    Row {
336        element: pres::VERBATIM,
337        form: Form::CommandOrEnvironment {
338            command: "flmxVerbatim",
339            environment: "flmxVerbatimBlock",
340        },
341        keys: &[field("kind", "kind", Value::Name), field("lang", "lang", Value::Name)],
342        args: &[],
343        not_written: &[(
344            "display",
345            "chooses the form: the command `\\flmxVerbatim` inline, the environment \
346             `flmxVerbatimBlock` for a block",
347        )],
348        chunk: Some(VERBATIM_CHUNK),
349    },
350    Row {
351        element: pres::MATH_PASSTHROUGH,
352        form: Form::Formula,
353        keys: &[],
354        args: &[],
355        not_written: &[
356            ("display", "chooses the delimiters: `\\(…\\)` inline, `\\[…\\]` or an environment displayed"),
357            ("env", "the environment written, starred, around a displayed formula's source"),
358        ],
359        chunk: None,
360    },
361    Row {
362        element: pres::MATH_TEXT,
363        form: Form::FormulaText,
364        keys: &[],
365        args: &[],
366        not_written: &[
367            ("command", "the command written around the content inside the formula, `\\text` by default"),
368            ("anchor", "written as `\\flmxTarget{<anchor>}` inside the formula"),
369            ("at_tag", "at a tag the content is written alone, since the source holds `\\tag*{` around it"),
370        ],
371        chunk: None,
372    },
373    Row {
374        element: pres::LINK,
375        form: Form::Command("flmxLink"),
376        keys: &[
377            field("kind", "kind", Value::Name),
378            field("href", "href", Value::Address),
379            computed("target", Value::Name),
380            field("doc-role", "doc_role", Value::Name),
381            field("label", "label", Value::Text),
382            field("shows-target", "shows_target", Value::Bool),
383        ],
384        args: &[],
385        not_written: &[],
386        chunk: Some(LINKS_CHUNK),
387    },
388    Row {
389        element: pres::IMAGE,
390        form: Form::Command("flmxImage"),
391        keys: &[
392            field("width", "width", Value::Length),
393            field("height", "height", Value::Length),
394            field("alt", "alt", Value::Text),
395            field("display", "display", Value::Name),
396            field("anchor", "anchor", Value::Name),
397        ],
398        args: &[],
399        not_written: &[
400            ("src", "the path is the command's mandatory argument"),
401            ("srcset", "the candidates a browser chooses among; LaTeX includes the one file"),
402        ],
403        chunk: Some(IMAGES_CHUNK),
404    },
405    Row {
406        element: pres::UNSUPPORTED,
407        form: Form::Command("flmxUnsupported"),
408        keys: &[],
409        args: &["element", "message"],
410        not_written: &[],
411        chunk: Some(MARKS_CHUNK),
412    },
413    Row {
414        element: pres::DROPPED,
415        form: Form::Command("flmxDropped"),
416        keys: &[],
417        args: &["condition", "detail"],
418        not_written: &[],
419        chunk: Some(MARKS_CHUNK),
420    },
421    Row {
422        element: pres::UNKNOWN,
423        form: Form::Command("flmxUnknown"),
424        keys: &[field("kind", "kind", Value::Name)],
425        args: &["name", "spelling"],
426        not_written: &[],
427        chunk: Some(MARKS_CHUNK),
428    },
429    Row {
430        element: pres::DECO_RUNIN,
431        form: Form::Command("flmxDecoRunin"),
432        keys: &[computed("stop", Value::Text)],
433        args: &[],
434        not_written: &[],
435        chunk: Some(CORE_CHUNK),
436    },
437    Row {
438        element: pres::DECO_FINAL,
439        form: Form::Command("flmxDecoFinal"),
440        keys: &[],
441        args: &[],
442        not_written: &[],
443        chunk: Some(CORE_CHUNK),
444    },
445    Row {
446        element: pres::DECO_MARGIN,
447        form: Form::Command("flmxDecoMargin"),
448        keys: &[],
449        args: &[],
450        not_written: &[],
451        chunk: Some(CORE_CHUNK),
452    },
453    Row {
454        element: pres::DECO_MARK,
455        form: Form::AtMark,
456        keys: &[],
457        args: &[],
458        not_written: &[("slot", "identifies the decoration written in the mark's place")],
459        chunk: None,
460    },
461    Row {
462        element: pres::SUBTREE,
463        form: Form::Placed,
464        keys: &[],
465        args: &[],
466        not_written: &[("tree", "identifies the document tree written in the node's place")],
467        chunk: None,
468    },
469];
470
471/// The row of the presentation element `element`, or `None` for a name
472/// outside the vocabulary.
473///
474/// # Examples
475///
476/// ```
477/// use flm_core::stdlib::backends::latex_rendered::contract::{Form, row};
478/// use flm_core::stdlib::backends::pres;
479///
480/// let span = row(pres::SPAN).expect("a row");
481/// assert_eq!(span.form, Form::Command("flmxSpan"));
482/// assert_eq!(span.keys.iter().map(|key| key.key).collect::<Vec<_>>(),
483///            ["style", "role", "kinds", "anchor", "doc-role"]);
484/// ```
485pub fn row(element: &str) -> Option<&'static Row> {
486    ROWS.iter().find(|row| row.element == element)
487}
488
489/// The table printed for the documentation: one line per element, its LaTeX
490/// form, its keys (a renamed key with its field, `kind (name)`), its
491/// mandatory arguments and its chunk.
492///
493/// # Examples
494///
495/// ```
496/// use flm_core::stdlib::backends::latex_rendered::contract::print_rows;
497///
498/// let table = print_rows();
499/// assert!(table.lines().any(|line| line.starts_with("flm.pres.span: \\flmxSpan[style, role")));
500/// ```
501pub fn print_rows() -> String {
502    let mut out = String::new();
503    for row in ROWS {
504        let keys: Vec<String> = row
505            .keys
506            .iter()
507            .map(|key| match key.origin {
508                Origin::Field(field) if key.is_renamed() => format!("{} ({field})", key.key),
509                Origin::EntryField(field) => format!("item {} ({field})", key.key),
510                Origin::EntrySlot(slot) => format!("item {} (slot {slot})", key.key),
511                Origin::Slot(slot) => format!("{} (slot {slot})", key.key),
512                _ => String::from(key.key),
513            })
514            .collect();
515        let keys = if keys.is_empty() { String::new() } else { format!("[{}]", keys.join(", ")) };
516        let args: String = row.args.iter().map(|arg| format!("{{{arg}}}")).collect();
517        let form = match row.form {
518            Form::Paragraph => String::from("a paragraph"),
519            Form::Environment(name) => format!("\\begin{{{name}}}{keys}{args} … \\end{{{name}}}"),
520            Form::Command(name) => format!("\\{name}{keys}{args}"),
521            Form::CommandOrEnvironment { command, environment } => {
522                format!("\\{command}{keys} or \\begin{{{environment}}}{keys} … \\end{{{environment}}}")
523            }
524            Form::Formula => String::from("the formula's delimiters around its source"),
525            Form::FormulaText => String::from("content inside the formula's source"),
526            Form::AtMark => String::from("the decoration at the mark's place"),
527            Form::Placed => String::from("the placed tree in place"),
528        };
529        let chunk = row.chunk.map(|chunk| format!(" ({chunk})")).unwrap_or_default();
530        out.push_str(&format!("{}: {form}{chunk}\n", row.element));
531    }
532    out
533}
534
535#[cfg(test)]
536mod tests {
537    use std::sync::Arc;
538
539    use techy::serialize::SerialValue;
540
541    use super::*;
542    use crate::lang::PresPayload;
543    use crate::model::addr::TreeId;
544    use crate::model::names::{ElementName, Name};
545    use crate::stdlib::backends::pres::{
546        BlockPayload, CellSpec, CellsPayload, DecoMarkPayload, DecorationPayload, DocRole,
547        DroppedPayload, HeadingPayload, ImageDisplay, ImagePayload, Length, LineAlign,
548        LinePayload, LinesPayload, LinkPayload, ListPayload, MathDisplay, MathPassthroughPayload,
549        MathTextPayload, ParPayload, SpanPayload, SpanStyle, SrcsetCandidate, SubtreePayload,
550        UnknownKind, UnknownPayload, UnsupportedPayload, VerbatimDisplay, VerbatimKind,
551        VerbatimPayload,
552    };
553
554    fn name(text: &str) -> Name {
555        Name::from(text)
556    }
557
558    /// Every payload of the vocabulary, fully populated, beside its element.
559    fn populated_payloads() -> Vec<(&'static str, Arc<dyn PresPayload>)> {
560        let anchor = || Some(String::from("a-1"));
561        let heading = || HeadingPayload { name: name("section"), level: 1, in_toc: true, anchor: anchor(), number: Some(String::from("1")) };
562        let mut cell = CellSpec::at(1, 1);
563        cell.styles = vec![name("green")];
564        vec![
565            (pres::PAR, Arc::new(ParPayload { anchor: anchor() }) as Arc<dyn PresPayload>),
566            (
567                pres::BLOCK,
568                Arc::new(BlockPayload {
569                    role: Some(name("flm.theorems.theorem")),
570                    kinds: vec![name("theorem")],
571                    anchor: anchor(),
572                    doc_role: Some(DocRole::Endnotes),
573                }),
574            ),
575            (pres::BLOCK_HEADING, Arc::new(heading())),
576            (pres::RUNIN_HEADING, Arc::new(heading())),
577            (
578                pres::SPAN,
579                Arc::new(SpanPayload {
580                    style: Some(SpanStyle::Bold),
581                    role: Some(name("flm.defterm.term")),
582                    kinds: vec![name("primary")],
583                    anchor: anchor(),
584                    doc_role: Some(DocRole::Footnote),
585                }),
586            ),
587            (
588                pres::LIST,
589                Arc::new(ListPayload {
590                    kinds: vec![name("numbered")],
591                    anchor: anchor(),
592                    entry_anchors: vec![Some(String::from("item-a"))],
593                    entry_levels: vec![Some(1)],
594                }),
595            ),
596            (pres::CELLS, Arc::new(CellsPayload { rows: 1, cols: 1, cells: vec![cell] })),
597            (pres::LINES, Arc::new(LinesPayload)),
598            (
599                pres::LINE,
600                Arc::new(LinePayload {
601                    indent_left: Length::tabs(1),
602                    indent_right: Length::tabs(2),
603                    align: LineAlign::Center,
604                }),
605            ),
606            (
607                pres::VERBATIM,
608                Arc::new(VerbatimPayload {
609                    kind: VerbatimKind::Code,
610                    display: VerbatimDisplay::Block,
611                    lang: Some(String::from("rust")),
612                }),
613            ),
614            (
615                pres::MATH_PASSTHROUGH,
616                Arc::new(MathPassthroughPayload {
617                    display: MathDisplay::Display,
618                    env: Some(String::from("align")),
619                    role: None,
620                }),
621            ),
622            (
623                pres::MATH_TEXT,
624                Arc::new(MathTextPayload { command: Some(String::from("text")), anchor: anchor(), at_tag: true }),
625            ),
626            (
627                pres::LINK,
628                Arc::new(LinkPayload {
629                    href: String::from("#a-1"),
630                    kind: name("ref"),
631                    doc_role: Some(DocRole::NoteRef),
632                    label: Some(String::from("Footnote 1")),
633                    shows_target: true,
634                }),
635            ),
636            (
637                pres::IMAGE,
638                Arc::new(ImagePayload {
639                    src: String::from("a.png"),
640                    display: ImageDisplay::Block,
641                    alt: Some(String::from("a")),
642                    width: Some(Length::tabs(1)),
643                    height: Some(Length::tabs(1)),
644                    srcset: vec![SrcsetCandidate { src: String::from("b.png"), descriptor: String::from("2x") }],
645                    anchor: anchor(),
646                }),
647            ),
648            (
649                pres::UNSUPPORTED,
650                Arc::new(UnsupportedPayload { element: ElementName::from("x.box"), message: String::from("why") }),
651            ),
652            (
653                pres::DROPPED,
654                Arc::new(DroppedPayload { condition: name("x.left-out"), detail: String::from("what") }),
655            ),
656            (
657                pres::UNKNOWN,
658                Arc::new(UnknownPayload {
659                    kind: UnknownKind::Macro,
660                    name: String::from("foo"),
661                    spelling: String::from("\\foo"),
662                }),
663            ),
664            (pres::DECO_RUNIN, Arc::new(DecorationPayload)),
665            (pres::DECO_FINAL, Arc::new(DecorationPayload)),
666            (pres::DECO_MARGIN, Arc::new(DecorationPayload)),
667            (pres::DECO_MARK, Arc::new(DecoMarkPayload { slot: 1 })),
668            (pres::SUBTREE, Arc::new(SubtreePayload { tree: TreeId::tree(1) })),
669        ]
670    }
671
672    #[test]
673    fn every_element_of_the_vocabulary_has_exactly_one_row() {
674        let mut elements: Vec<&str> = ROWS.iter().map(|row| row.element).collect();
675        elements.sort_unstable();
676        let mut all = pres::ALL.to_vec();
677        all.sort_unstable();
678        assert_eq!(elements, all);
679        assert_eq!(populated_payloads().len(), ROWS.len());
680    }
681
682    #[test]
683    fn every_payload_field_is_a_key_an_argument_or_not_written_with_a_reason() {
684        for (element, payload) in populated_payloads() {
685            let row = row(element).expect("a row for every element");
686            let SerialValue::Map(entries) = payload.project() else {
687                panic!("`{element}` projects as something other than a map");
688            };
689            let projected: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
690            for key in &projected {
691                let known = row.keys.iter().any(|entry| entry.field() == Some(key))
692                    || row.args.contains(key)
693                    || row.not_written.iter().any(|(field, _)| field == key);
694                assert!(known, "`{element}`'s field `{key}` is not in its row");
695            }
696            let named = row
697                .keys
698                .iter()
699                .filter_map(Key::field)
700                .chain(row.args.iter().copied())
701                .chain(row.not_written.iter().map(|(field, _)| *field));
702            for field in named {
703                assert!(projected.contains(&field), "`{element}`'s row names `{field}`, not projected");
704            }
705        }
706    }
707
708    #[test]
709    fn the_keys_of_a_row_are_the_field_names_with_hyphens_but_the_two_heading_renames() {
710        let renamed: Vec<(&str, &str)> = ROWS
711            .iter()
712            .flat_map(|row| row.keys.iter())
713            .filter(|key| key.is_renamed())
714            .map(|key| (key.key, key.field().unwrap_or_default()))
715            .collect();
716        assert_eq!(
717            renamed,
718            [("kind", "name"), ("toc", "in_toc"), ("kind", "name"), ("toc", "in_toc"), ("anchor", "entry_anchors")]
719        );
720    }
721
722    #[test]
723    fn the_printed_table_holds_one_line_per_element() {
724        let table = print_rows();
725        assert_eq!(table.lines().count(), ROWS.len());
726        assert!(table.contains(
727            "flm.pres.block-heading: \\flmxHeading[kind (name), level, toc (in_toc), anchor, number, plain, alt (slot alt)] (flm.latex.def.flmx.headings)"
728        ), "{table}");
729        assert!(table.contains("flm.pres.dropped: \\flmxDropped{condition}{detail} (flm.latex.def.flmx.marks)"), "{table}");
730    }
731}