flm_core/stdlib/backends/pres/payload.rs
1//! The typed payloads of the presentation elements, their projections and
2//! their readers.
3//!
4//! Every presentation node (a node of a presentation element; see
5//! [`super`]) carries exactly one payload value, of the type its element
6//! declares, and that value holds every fact the node states beyond its
7//! element and its children. This module defines one payload type per
8//! element, together with the small enumerations they use ([`SpanStyle`],
9//! [`DocRole`], [`VerbatimKind`], [`VerbatimDisplay`], [`MathDisplay`],
10//! [`ImageDisplay`], [`LineAlign`], [`UnknownKind`], and for a table of cells
11//! [`CellAlign`], [`CellHeader`], [`CellEdge`] and [`GridPosition`]).
12//!
13//! # Roles, kinds and document roles
14//!
15//! A **role** is a feature-owned dotted name on a presentation payload that
16//! says what a container is (a theorem's heading, a quotation's attribution),
17//! and **kinds** (kind tokens) are feature-owned names that classify it
18//! further, so that a stylesheet or a host's lowering rule can select on
19//! them. Both are [`Name`]s owned by the feature that introduced them, so two
20//! features can choose their own roles without colliding. A **document
21//! role** ([`DocRole`]) is a different thing: one of a small fixed set of
22//! structural roles (a list of notes, a link to a cited work, a table of
23//! contents) that a backend
24//! with such a notion renders (the HTML backend writes it as the `role`
25//! attribute) and every other backend ignores. See [decorations, roles and
26//! kinds](crate::guide::concepts_overview#decorations-roles-and-kinds).
27//!
28//! # Anchors
29//!
30//! A payload's anchor field is a plain `String`: the anchor of the node, that
31//! is, the identifier a link points at when the node is a link target. A
32//! stage computed it before lowering (for reference points, the refs
33//! feature's anchors stage writes it into the table
34//! [`ANCHORS`](crate::stdlib::features::refs::ANCHORS)); the payload holds
35//! the final identifier, not a reference to be resolved later.
36//!
37//! # Projections and readers
38//!
39//! Every payload type implements [`PresPayload`]. Its
40//! [`project`](PresPayload::project) method returns the payload's
41//! **projection**: the serialized form in which a lowered tree's payloads are
42//! printed ([`crate::dump::project`]) and stored ([`crate::dump::session`]).
43//! The reader registered for the element ([`payload_readers`]) rebuilds the
44//! typed value from exactly that projection, through the `from_projection`
45//! function of each type below. A projection is owned data made of names, numbers and strings, never a span
46//! or a node identifier, so a lowered tree can be written out and read back
47//! without a tree to resolve identifiers against.
48//!
49//! A projection is one map per payload, its keys in a fixed order. An
50//! optional field is a key present only when it has a value, and a list
51//! field a key present only when the list is not empty, which keeps stored
52//! projections short. The keys per element:
53//!
54//! - `par`: `{anchor?}`; `block`: `{role?, kinds?, anchor?, doc_role?}`;
55//! `block-heading` and `runin-heading`: `{name, level, in_toc, anchor?}`;
56//! `span`: `{style?, role?, kinds?, anchor?, doc_role?}`; `list`: `{kinds?,
57//! anchor?, entry_anchors?, entry_levels?}`;
58//! - `cells`: `{rows, cols, cells}`, the cells a list of maps `{row, col,
59//! row_span?, col_span?, align?, header?, rules?, styles?}` (a span present
60//! only when it is not one);
61//! - `lines`: `{}`; `line`: `{indent_left, indent_right, align}`, the two
62//! indentations each a [`Length`]'s text (`2tab`);
63//! - `verbatim`: `{kind, display, lang?}`; `math-passthrough`: `{display, env?,
64//! role?}`; `math-text`: `{command?, anchor?, at_tag?}` (`at_tag` present only
65//! when true);
66//! - `link`: `{href, kind, doc_role?, label?, shows_target?}`
67//! (`shows_target` present only when true); `image`: `{src, display, alt?,
68//! width?, height?, srcset?, anchor?}`;
69//! - `unsupported`: `{element, message}`; `dropped`: `{condition, detail}`;
70//! `unknown`: `{kind, name, spelling}`;
71//! - the three decorations: `{}`; `deco-mark`: `{slot}`; `subtree`: `{tree}`
72//! (the tree identifier's display form, `tree#3`).
73
74use std::fmt;
75use std::sync::Arc;
76
77use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};
78
79use crate::model::addr::TreeId;
80use crate::model::names::{ElementName, Name};
81use crate::dump::session::PayloadReaders;
82use crate::lang::{Flm, PresPayload};
83
84use super::length::Length;
85use super::names;
86
87// --- projection helpers -----------------------------------------------------------------
88//
89// The six that carry no knowledge of these payloads — `text`, `map`, `bad`,
90// `entries`, `field` and `string` — are `pub(crate)` because the construct
91// elements of the backend families (`crate::stdlib::backends::latex::construct`,
92// `crate::stdlib::backends::html::construct`) project and read their payloads
93// the same way and share them.
94
95/// A string as serial data.
96pub(crate) fn text(value: impl Into<String>) -> SerialValue {
97 SerialValue::Str(value.into())
98}
99
100/// A projection's map, its keys in the order given.
101pub(crate) fn map(entries: Vec<(&str, SerialValue)>) -> SerialValue {
102 SerialValue::Map(entries.into_iter().map(|(key, value)| (String::from(key), value)).collect())
103}
104
105/// A list of names as a list of strings.
106fn names(list: &[Name]) -> SerialValue {
107 SerialValue::List(list.iter().map(|name| text(name.as_str())).collect())
108}
109
110/// Pushes `key: value` when the option holds a value.
111fn push_opt(
112 entries: &mut Vec<(&'static str, SerialValue)>,
113 key: &'static str,
114 value: Option<SerialValue>,
115) {
116 if let Some(value) = value {
117 entries.push((key, value));
118 }
119}
120
121/// The reading side's failure for a payload of `element`.
122pub(crate) fn bad(element: &str, detail: impl fmt::Display) -> DeserializeError {
123 DeserializeError::failed(format!("the payload of `{element}`: {detail}"))
124}
125
126/// The entries of a projected payload: a map, or the failure mentioning the
127/// element.
128pub(crate) fn entries<'v>(
129 element: &str,
130 value: &'v SerialValue,
131) -> Result<&'v [(String, SerialValue)], DeserializeError> {
132 match value {
133 SerialValue::Map(entries) => Ok(entries),
134 other => Err(bad(element, format!("expected a map, found {other:?}"))),
135 }
136}
137
138/// The value stored under `key`, if the projection has that key.
139pub(crate) fn field<'v>(
140 entries: &'v [(String, SerialValue)],
141 key: &str,
142) -> Option<&'v SerialValue> {
143 entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)
144}
145
146/// An optional string field: absent and null read alike as `None`.
147fn opt_string(
148 element: &str,
149 entries: &[(String, SerialValue)],
150 key: &str,
151) -> Result<Option<String>, DeserializeError> {
152 match field(entries, key) {
153 None | Some(SerialValue::Null) => Ok(None),
154 Some(SerialValue::Str(s)) => Ok(Some(s.clone())),
155 Some(other) => Err(bad(element, format!("`{key}` must be a string, found {other:?}"))),
156 }
157}
158
159/// A required string field.
160pub(crate) fn string(
161 element: &str,
162 entries: &[(String, SerialValue)],
163 key: &str,
164) -> Result<String, DeserializeError> {
165 opt_string(element, entries, key)?.ok_or_else(|| bad(element, format!("`{key}` is missing")))
166}
167
168/// An optional integer field: absent and null read alike as `None`.
169fn opt_int(
170 element: &str,
171 entries: &[(String, SerialValue)],
172 key: &str,
173) -> Result<Option<i64>, DeserializeError> {
174 match field(entries, key) {
175 None | Some(SerialValue::Null) => Ok(None),
176 Some(SerialValue::Int(n)) => Ok(Some(*n)),
177 Some(other) => Err(bad(element, format!("`{key}` must be an integer, found {other:?}"))),
178 }
179}
180
181/// A required integer field.
182fn int(
183 element: &str,
184 entries: &[(String, SerialValue)],
185 key: &str,
186) -> Result<i64, DeserializeError> {
187 opt_int(element, entries, key)?.ok_or_else(|| bad(element, format!("`{key}` is missing")))
188}
189
190/// A list-of-names field; an absent or null key reads as the empty list.
191fn name_list(
192 element: &str,
193 entries: &[(String, SerialValue)],
194 key: &str,
195) -> Result<Vec<Name>, DeserializeError> {
196 match field(entries, key) {
197 None | Some(SerialValue::Null) => Ok(Vec::new()),
198 Some(SerialValue::List(items)) => items
199 .iter()
200 .map(|item| match item {
201 SerialValue::Str(s) => Ok(Name::from(s.as_str())),
202 other => Err(bad(element, format!("`{key}` holds a non-string {other:?}"))),
203 })
204 .collect(),
205 Some(other) => Err(bad(element, format!("`{key}` must be a list, found {other:?}"))),
206 }
207}
208
209/// An optional name field.
210fn name_opt(
211 element: &str,
212 entries: &[(String, SerialValue)],
213 key: &str,
214) -> Result<Option<Name>, DeserializeError> {
215 Ok(opt_string(element, entries, key)?.map(Name::from))
216}
217
218/// An optional document-role field, read by its stable name
219/// ([`DocRole::parse`]).
220fn doc_role_opt(
221 element: &str,
222 entries: &[(String, SerialValue)],
223) -> Result<Option<DocRole>, DeserializeError> {
224 match opt_string(element, entries, "doc_role")? {
225 None => Ok(None),
226 Some(name) => DocRole::parse(&name)
227 .map(Some)
228 .ok_or_else(|| bad(element, format!("unknown document role `{name}`"))),
229 }
230}
231
232/// An integer field narrowed to `0..=max`, refused outside that range.
233fn small(element: &str, key: &str, value: i64, max: i64) -> Result<u16, DeserializeError> {
234 if (0..=max).contains(&value) {
235 Ok(value as u16)
236 } else {
237 Err(bad(element, format!("`{key}` = {value} is outside 0..={max}")))
238 }
239}
240
241// --- the enumerations -------------------------------------------------------------------
242
243/// The display style of a `flm.pres.span` node: how the span is set, not what
244/// it means. A span with no style still groups its content and may carry a
245/// role and kinds; the style only designates a visual form.
246///
247/// The set is fixed and small. It covers the base formatting a text-like
248/// markup language needs, plus [semantic emphasis](SpanStyle::Emphasis), which
249/// is kept apart from plain italics because output formats that distinguish
250/// the two (HTML's `<em>` beside `<i>`) need both. An emitter that cannot
251/// express a style ignores it and writes the content.
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
253pub enum SpanStyle {
254 /// Semantic emphasis (`\emph`; HTML `<em>`).
255 Emphasis,
256 /// Bold weight (`\textbf`).
257 Bold,
258 /// Italic shape (`\textit`).
259 Italic,
260 /// A monospaced face (`\texttt`).
261 Monospace,
262 /// Underlined.
263 Underline,
264 /// Small capitals.
265 SmallCaps,
266 /// Raised, smaller.
267 Superscript,
268 /// Lowered, smaller.
269 Subscript,
270 /// The display of a reference whose target could not be resolved.
271 UnresolvedReference,
272}
273
274impl SpanStyle {
275 /// Every style, in declaration order.
276 pub const ALL: [SpanStyle; 9] = [
277 SpanStyle::Emphasis,
278 SpanStyle::Bold,
279 SpanStyle::Italic,
280 SpanStyle::Monospace,
281 SpanStyle::Underline,
282 SpanStyle::SmallCaps,
283 SpanStyle::Superscript,
284 SpanStyle::Subscript,
285 SpanStyle::UnresolvedReference,
286 ];
287
288 /// The style's stable name: its text in the projection, and the value of
289 /// the `data-flm-style` attribute of the HTML contract.
290 pub fn as_str(self) -> &'static str {
291 match self {
292 SpanStyle::Emphasis => "emph",
293 SpanStyle::Bold => "bold",
294 SpanStyle::Italic => "italic",
295 SpanStyle::Monospace => "monospace",
296 SpanStyle::Underline => "underline",
297 SpanStyle::SmallCaps => "small-caps",
298 SpanStyle::Superscript => "superscript",
299 SpanStyle::Subscript => "subscript",
300 SpanStyle::UnresolvedReference => "unresolved-reference",
301 }
302 }
303
304 /// The style of a stable name, if any.
305 pub fn parse(name: &str) -> Option<SpanStyle> {
306 SpanStyle::ALL.into_iter().find(|style| style.as_str() == name)
307 }
308}
309
310impl fmt::Display for SpanStyle {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 f.write_str(self.as_str())
313 }
314}
315
316/// The verbatim kind of a `flm.pres.verbatim` node: plain characters,
317/// computer code, or an identifier. A backend chooses from it how to render
318/// the content: an HTML backend can give each kind its own class, while the
319/// text backend writes the content alone, since plain text cannot show the
320/// distinction.
321#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
322pub enum VerbatimKind {
323 /// Characters typeset as they are, with no formatting of their own
324 /// (`\verbtext`, `{verbatimtext}`); also the kind of a bare verbatim
325 /// group that no element of a feature owns.
326 #[default]
327 Text,
328 /// Computer code (`\verbcode`, `{verbatimcode}`), possibly in the
329 /// language the payload's `lang` field gives.
330 Code,
331 /// An identifier: a keyword or a name, typically set in italics rather
332 /// than highlighted as code (`\verba`). Its stable name is `a`, after the
333 /// macro that writes it.
334 Identifier,
335}
336
337impl VerbatimKind {
338 /// Every kind, in the order the feature declares its callables.
339 pub const ALL: [VerbatimKind; 3] =
340 [VerbatimKind::Text, VerbatimKind::Code, VerbatimKind::Identifier];
341
342 /// The stable name.
343 pub fn as_str(self) -> &'static str {
344 match self {
345 VerbatimKind::Text => "text",
346 VerbatimKind::Code => "code",
347 VerbatimKind::Identifier => "a",
348 }
349 }
350
351 /// The kind of a stable name, if any.
352 pub fn parse(name: &str) -> Option<VerbatimKind> {
353 VerbatimKind::ALL.into_iter().find(|kind| kind.as_str() == name)
354 }
355}
356
357impl fmt::Display for VerbatimKind {
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 f.write_str(self.as_str())
360 }
361}
362
363/// Whether verbatim content is a block of its own or is part of a
364/// paragraph's flow.
365#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
366pub enum VerbatimDisplay {
367 /// Inside a paragraph's flow.
368 Inline,
369 /// A block of its own.
370 Block,
371}
372
373impl VerbatimDisplay {
374 /// The stable name.
375 pub fn as_str(self) -> &'static str {
376 match self {
377 VerbatimDisplay::Inline => "inline",
378 VerbatimDisplay::Block => "block",
379 }
380 }
381
382 /// The display of a stable name, if any.
383 pub fn parse(name: &str) -> Option<VerbatimDisplay> {
384 match name {
385 "inline" => Some(VerbatimDisplay::Inline),
386 "block" => Some(VerbatimDisplay::Block),
387 _ => None,
388 }
389 }
390}
391
392/// Whether an image is a block of its own or is inline, like a word of the
393/// text around it.
394///
395/// An image is a block where it is a direct child of a float's body, and
396/// inline content anywhere else
397/// ([`GraphicsImage`](crate::stdlib::features::graphics::GraphicsImage)).
398/// The default is [`Inline`](ImageDisplay::Inline).
399#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
400pub enum ImageDisplay {
401 /// Inside a paragraph's flow.
402 #[default]
403 Inline,
404 /// A block of its own.
405 Block,
406}
407
408impl ImageDisplay {
409 /// The stable name: `inline` or `block`.
410 pub fn as_str(self) -> &'static str {
411 match self {
412 ImageDisplay::Inline => "inline",
413 ImageDisplay::Block => "block",
414 }
415 }
416
417 /// The display of a stable name, if any.
418 pub fn parse(name: &str) -> Option<ImageDisplay> {
419 match name {
420 "inline" => Some(ImageDisplay::Inline),
421 "block" => Some(ImageDisplay::Block),
422 _ => None,
423 }
424 }
425}
426
427/// Whether math is inline or displayed (`\(…\)` versus `\[…\]` and the math
428/// environments).
429#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
430pub enum MathDisplay {
431 /// Inline math.
432 Inline,
433 /// Display math.
434 Display,
435}
436
437impl MathDisplay {
438 /// The stable name.
439 pub fn as_str(self) -> &'static str {
440 match self {
441 MathDisplay::Inline => "inline",
442 MathDisplay::Display => "display",
443 }
444 }
445
446 /// The display of a stable name, if any.
447 pub fn parse(name: &str) -> Option<MathDisplay> {
448 match name {
449 "inline" => Some(MathDisplay::Inline),
450 "display" => Some(MathDisplay::Display),
451 _ => None,
452 }
453 }
454}
455
456/// The horizontal alignment of a line of a `lines` node.
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
458pub enum LineAlign {
459 /// Flush left (the default).
460 #[default]
461 Left,
462 /// Centered.
463 Center,
464 /// Flush right.
465 Right,
466}
467
468impl LineAlign {
469 /// The stable name.
470 pub fn as_str(self) -> &'static str {
471 match self {
472 LineAlign::Left => "left",
473 LineAlign::Center => "center",
474 LineAlign::Right => "right",
475 }
476 }
477
478 /// The alignment of a stable name, if any.
479 pub fn parse(name: &str) -> Option<LineAlign> {
480 match name {
481 "left" => Some(LineAlign::Left),
482 "center" => Some(LineAlign::Center),
483 "right" => Some(LineAlign::Right),
484 _ => None,
485 }
486 }
487}
488
489/// A document role: a role in the structure of a document, taken from the
490/// digital-publishing accessibility roles (`doc-endnotes`, `doc-footnote`,
491/// …). It says what a block, a span or a link *is* among the notes, the
492/// cited works and the table of contents of a document, beyond what it looks
493/// like.
494///
495/// A payload carries it in its `doc_role` field ([`BlockPayload::doc_role`],
496/// [`SpanPayload::doc_role`], [`LinkPayload::doc_role`]). A backend that has
497/// such a notion renders it — the HTML backend writes the `role` attribute,
498/// `doc-` followed by the role's [stable name](DocRole::as_str), so that
499/// assistive technology such as a screen reader can announce what the element
500/// is; a backend that has none, the text backend among them, ignores it. It is
501/// distinct from the feature-owned role of [`BlockPayload::role`], which says
502/// what kind of container a node is and becomes a CSS class on HTML.
503#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
504pub enum DocRole {
505 /// A container holding the list of a document's notes, shown apart from
506 /// the running text (`doc-endnotes`).
507 Endnotes,
508 /// A note shown where it is written, or one entry of a list of notes
509 /// (`doc-footnote`).
510 Footnote,
511 /// A link from the running text to a note (`doc-noteref`).
512 NoteRef,
513 /// A link from a note back to where it is referenced (`doc-backlink`).
514 BackLink,
515 /// A container holding the list of the works a document cites
516 /// (`doc-bibliography`). The entries of the list carry no document role:
517 /// the role once defined for one, `doc-biblioentry`, is deprecated by
518 /// version 1.1 of the digital-publishing accessibility roles, because a
519 /// list item inside the bibliography already says what it is.
520 Bibliography,
521 /// A link from the running text to a cited work's entry in the
522 /// bibliography (`doc-biblioref`).
523 BiblioRef,
524 /// A container holding a document's table of contents (`doc-toc`).
525 Toc,
526}
527
528impl DocRole {
529 /// Every document role, in declaration order.
530 pub const ALL: [DocRole; 7] = [
531 DocRole::Endnotes,
532 DocRole::Footnote,
533 DocRole::NoteRef,
534 DocRole::BackLink,
535 DocRole::Bibliography,
536 DocRole::BiblioRef,
537 DocRole::Toc,
538 ];
539
540 /// The role's stable name: its text in the projection, and what the HTML
541 /// backend writes after `doc-`: `endnotes`, `footnote`, `noteref`,
542 /// `backlink`, `bibliography`, `biblioref`, `toc`.
543 pub fn as_str(self) -> &'static str {
544 match self {
545 DocRole::Endnotes => "endnotes",
546 DocRole::Footnote => "footnote",
547 DocRole::NoteRef => "noteref",
548 DocRole::BackLink => "backlink",
549 DocRole::Bibliography => "bibliography",
550 DocRole::BiblioRef => "biblioref",
551 DocRole::Toc => "toc",
552 }
553 }
554
555 /// The role of a stable name, if any.
556 pub fn parse(name: &str) -> Option<DocRole> {
557 DocRole::ALL.into_iter().find(|role| role.as_str() == name)
558 }
559}
560
561impl fmt::Display for DocRole {
562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563 f.write_str(self.as_str())
564 }
565}
566
567// --- the payloads -----------------------------------------------------------------------
568
569/// The payload of `flm.pres.par`, a laid-out paragraph: its anchor when it
570/// is a link target.
571#[derive(Debug, Clone, PartialEq, Eq, Default)]
572pub struct ParPayload {
573 /// The anchor (see the [module documentation](self#anchors)), when the
574 /// paragraph is a link target.
575 pub anchor: Option<String>,
576}
577
578impl PresPayload for ParPayload {
579 fn project(&self) -> SerialValue {
580 let mut entries = Vec::new();
581 push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
582 map(entries)
583 }
584}
585
586impl ParPayload {
587 /// The payload rebuilt from its projection, the value
588 /// [`project`](PresPayload::project) produced.
589 ///
590 /// # Errors
591 ///
592 /// Returns a [`DeserializeError`] mentioning `flm.pres.par` when the
593 /// projection is not a map, or when `anchor` is present and is not a string.
594 pub fn from_projection(value: &SerialValue) -> Result<ParPayload, DeserializeError> {
595 let entries = entries(names::PAR, value)?;
596 Ok(ParPayload { anchor: opt_string(names::PAR, entries, "anchor")? })
597 }
598}
599
600/// The payload of `flm.pres.block`, a block container: its role and kinds
601/// (what container it is), its anchor when it is a link target, and its
602/// document role. See the [module documentation](self#roles-kinds-and-document-roles).
603#[derive(Debug, Clone, PartialEq, Eq, Default)]
604pub struct BlockPayload {
605 /// The role: what the container is, as a dotted, feature-owned name. By
606 /// convention it is the source element's name for the block that holds
607 /// the element as a whole, and `<element>.<part>` for a block inside it
608 /// that the element's rule builds.
609 pub role: Option<Name>,
610 /// The kind tokens that classify the role further (`theoremlike`,
611 /// `lemma`). A backend or a stylesheet uses them to choose among
612 /// renderings of the same role.
613 pub kinds: Vec<Name>,
614 /// The anchor, when the block is a link target.
615 pub anchor: Option<String>,
616 /// The block's document role, when it has one: [`DocRole::Endnotes`] for
617 /// the container of a list of notes, [`DocRole::Footnote`] for a note
618 /// shown where it is written, [`DocRole::Bibliography`] for the container
619 /// of the list of cited works, [`DocRole::Toc`] for the container of a
620 /// table of contents. A backend without the notion ignores it.
621 pub doc_role: Option<DocRole>,
622}
623
624impl PresPayload for BlockPayload {
625 fn project(&self) -> SerialValue {
626 let mut entries = Vec::new();
627 push_opt(&mut entries, "role", self.role.as_ref().map(|r| text(r.as_str())));
628 if !self.kinds.is_empty() {
629 entries.push(("kinds", names(&self.kinds)));
630 }
631 push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
632 push_opt(&mut entries, "doc_role", self.doc_role.map(|r| text(r.as_str())));
633 map(entries)
634 }
635}
636
637impl BlockPayload {
638 /// The payload rebuilt from its projection, the value
639 /// [`project`](PresPayload::project) produced.
640 ///
641 /// # Errors
642 ///
643 /// Returns a [`DeserializeError`] mentioning `flm.pres.block` when the
644 /// projection is not a map, when `role` or `anchor` is present and is not a
645 /// string, when `kinds` is present and is not a list of strings, or when
646 /// `doc_role` is present and matches no document role ([`DocRole::parse`]).
647 pub fn from_projection(value: &SerialValue) -> Result<BlockPayload, DeserializeError> {
648 let e = entries(names::BLOCK, value)?;
649 Ok(BlockPayload {
650 role: name_opt(names::BLOCK, e, "role")?,
651 kinds: name_list(names::BLOCK, e, "kinds")?,
652 anchor: opt_string(names::BLOCK, e, "anchor")?,
653 doc_role: doc_role_opt(names::BLOCK, e)?,
654 })
655 }
656}
657
658/// The payload of `flm.pres.block-heading` and of `flm.pres.runin-heading`:
659/// the heading kind's name and level, whether the heading is listed in a
660/// table of contents, its anchor, and its number as plain text.
661///
662/// A heading carries the same facts whether it is placed on its own between
663/// blocks or set run in, at the start of the paragraph it introduces, so the
664/// two elements share this payload.
665#[derive(Debug, Clone, PartialEq, Eq)]
666pub struct HeadingPayload {
667 /// The name of the heading kind, such as `section`
668 /// ([`HeadingDecl::name`](crate::stdlib::features::headings::HeadingDecl::name)).
669 pub name: Name,
670 /// The heading level: a number counted from zero, the smaller the outer,
671 /// every value valid ([`Sectioning::level`](crate::model::aspects::Sectioning::level)).
672 pub level: u8,
673 /// Whether the heading is listed in a table of contents
674 /// ([`Sectioning::in_toc`](crate::model::aspects::Sectioning::in_toc)).
675 pub in_toc: bool,
676 /// The anchor, when the heading is a link target.
677 pub anchor: Option<String>,
678 /// The heading's number as plain text (`2.1`), where the document numbered
679 /// the heading; `None` otherwise. The number also stands in the heading's
680 /// content, in a span of role `flm.heading.number`; this field gives it to
681 /// a backend that writes it apart from the title (the `latex-rendered`
682 /// backend's key `number`). The HTML and text backends do not read it.
683 pub number: Option<String>,
684}
685
686impl PresPayload for HeadingPayload {
687 fn project(&self) -> SerialValue {
688 let mut entries = vec![
689 ("name", text(self.name.as_str())),
690 ("level", SerialValue::Int(i64::from(self.level))),
691 ("in_toc", SerialValue::Bool(self.in_toc)),
692 ];
693 push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
694 push_opt(&mut entries, "number", self.number.as_deref().map(text));
695 map(entries)
696 }
697}
698
699impl HeadingPayload {
700 /// The payload rebuilt from its projection, the value
701 /// [`project`](PresPayload::project) produced, for the heading element
702 /// `element` — `flm.pres.block-heading` or `flm.pres.runin-heading`, which
703 /// share this payload type. `element` is used only to name the element in
704 /// a failure.
705 ///
706 /// # Errors
707 ///
708 /// Returns a [`DeserializeError`] mentioning `element` when the projection is
709 /// not a map, when `name` is missing or is not a string, when `level` is
710 /// missing, is not an integer or lies outside `0..=255`, when `in_toc` is
711 /// missing or is not a boolean, or when `anchor` or `number` is present and
712 /// is not a string.
713 pub fn from_projection(
714 element: &str,
715 value: &SerialValue,
716 ) -> Result<HeadingPayload, DeserializeError> {
717 let e = entries(element, value)?;
718 let name = Name::from(string(element, e, "name")?.as_str());
719 let level = int(element, e, "level")?;
720 let level = small(element, "level", level, i64::from(u8::MAX))? as u8;
721 let in_toc = match field(e, "in_toc") {
722 Some(SerialValue::Bool(value)) => *value,
723 None | Some(SerialValue::Null) => {
724 return Err(bad(element, "`in_toc` is missing"));
725 }
726 Some(other) => {
727 return Err(bad(element, format!("`in_toc` must be a boolean, found {other:?}")));
728 }
729 };
730 Ok(HeadingPayload {
731 name,
732 level,
733 in_toc,
734 anchor: opt_string(element, e, "anchor")?,
735 number: opt_string(element, e, "number")?,
736 })
737 }
738}
739
740/// The payload of `flm.pres.span`, inline content: its display style, its
741/// role and kinds (what it is), its anchor when it is a link target, and its
742/// document role.
743#[derive(Debug, Clone, PartialEq, Eq, Default)]
744pub struct SpanPayload {
745 /// The display style, if the span designates one.
746 pub style: Option<SpanStyle>,
747 /// The role (see [`BlockPayload::role`]).
748 pub role: Option<Name>,
749 /// The kind tokens (see [`BlockPayload::kinds`]).
750 pub kinds: Vec<Name>,
751 /// The anchor, when the span is a link target.
752 pub anchor: Option<String>,
753 /// The span's document role, when it has one: [`DocRole::Footnote`] for
754 /// a note shown where it is written. A backend without the notion ignores
755 /// it.
756 pub doc_role: Option<DocRole>,
757}
758
759impl PresPayload for SpanPayload {
760 fn project(&self) -> SerialValue {
761 let mut entries = Vec::new();
762 push_opt(&mut entries, "style", self.style.map(|s| text(s.as_str())));
763 push_opt(&mut entries, "role", self.role.as_ref().map(|r| text(r.as_str())));
764 if !self.kinds.is_empty() {
765 entries.push(("kinds", names(&self.kinds)));
766 }
767 push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
768 push_opt(&mut entries, "doc_role", self.doc_role.map(|r| text(r.as_str())));
769 map(entries)
770 }
771}
772
773impl SpanPayload {
774 /// The payload rebuilt from its projection, the value
775 /// [`project`](PresPayload::project) produced.
776 ///
777 /// # Errors
778 ///
779 /// Returns a [`DeserializeError`] mentioning `flm.pres.span` when the
780 /// projection is not a map, when `style` is present and matches no style
781 /// ([`SpanStyle::parse`]), when `role` or `anchor` is present and is not a
782 /// string, when `kinds` is present and is not a list of strings, or when
783 /// `doc_role` is present and matches no document role ([`DocRole::parse`]).
784 pub fn from_projection(value: &SerialValue) -> Result<SpanPayload, DeserializeError> {
785 let e = entries(names::SPAN, value)?;
786 let style = match opt_string(names::SPAN, e, "style")? {
787 None => None,
788 Some(name) => Some(
789 SpanStyle::parse(&name)
790 .ok_or_else(|| bad(names::SPAN, format!("unknown style `{name}`")))?,
791 ),
792 };
793 Ok(SpanPayload {
794 style,
795 role: name_opt(names::SPAN, e, "role")?,
796 kinds: name_list(names::SPAN, e, "kinds")?,
797 anchor: opt_string(names::SPAN, e, "anchor")?,
798 doc_role: doc_role_opt(names::SPAN, e)?,
799 })
800 }
801}
802
803/// The payload of `flm.pres.list`: the list's kind tokens, its anchor, and
804/// the anchor and the level of each of its entries.
805#[derive(Debug, Clone, PartialEq, Eq, Default)]
806pub struct ListPayload {
807 /// The kind tokens: first at most one structural token,
808 /// [`LIST_NUMBERED`](super::LIST_NUMBERED),
809 /// [`LIST_UNNUMBERED`](super::LIST_UNNUMBERED) or
810 /// [`LIST_TERMS`](super::LIST_TERMS) (by which an HTML emitter chooses
811 /// `<ol>`, `<ul>` or `<dl>`), then any others, such as the name of the
812 /// environment that produced the list and
813 /// [`LIST_LABELED`](super::LIST_LABELED).
814 pub kinds: Vec<Name>,
815 /// The anchor, when the list as a whole is a link target.
816 pub anchor: Option<String>,
817 /// The anchor of each entry, in the order of the entries
818 /// ([`list_entries`](super::list_entries)): the identifier a link to that
819 /// entry points at, `None` for an entry that is not a link target. An
820 /// entry past the end of this list has no anchor, and anchors beyond the
821 /// last entry are ignored.
822 pub entry_anchors: Vec<Option<String>>,
823 /// The level of each entry, in the order of the entries, for a list whose
824 /// entries have levels (the entries of a table of contents, each at the
825 /// level of its heading): `None` for an entry without a level. An entry
826 /// past the end of this list has no level, and levels beyond the last
827 /// entry are ignored.
828 pub entry_levels: Vec<Option<u32>>,
829}
830
831impl PresPayload for ListPayload {
832 fn project(&self) -> SerialValue {
833 let mut entries = Vec::new();
834 if !self.kinds.is_empty() {
835 entries.push(("kinds", names(&self.kinds)));
836 }
837 push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
838 if !self.entry_anchors.is_empty() {
839 let anchors = self
840 .entry_anchors
841 .iter()
842 .map(|anchor| anchor.as_deref().map_or(SerialValue::Null, text))
843 .collect();
844 entries.push(("entry_anchors", SerialValue::List(anchors)));
845 }
846 if !self.entry_levels.is_empty() {
847 let levels = self
848 .entry_levels
849 .iter()
850 .map(|level| level.map_or(SerialValue::Null, |level| SerialValue::Int(i64::from(level))))
851 .collect();
852 entries.push(("entry_levels", SerialValue::List(levels)));
853 }
854 map(entries)
855 }
856}
857
858impl ListPayload {
859 /// The payload rebuilt from its projection, the value
860 /// [`project`](PresPayload::project) produced.
861 ///
862 /// # Errors
863 ///
864 /// Returns a [`DeserializeError`] mentioning `flm.pres.list` when the
865 /// projection is not a map, when `kinds` is present and is not a list of
866 /// strings, when `anchor` is present and is not a string, or when
867 /// `entry_anchors` is present and is not a list of strings and nulls, or
868 /// when `entry_levels` is present and is not a list of nulls and numbers
869 /// in the range of a `u32`.
870 pub fn from_projection(value: &SerialValue) -> Result<ListPayload, DeserializeError> {
871 let e = entries(names::LIST, value)?;
872 let entry_anchors = match field(e, "entry_anchors") {
873 None | Some(SerialValue::Null) => Vec::new(),
874 Some(SerialValue::List(items)) => items
875 .iter()
876 .map(|item| match item {
877 SerialValue::Null => Ok(None),
878 SerialValue::Str(s) => Ok(Some(s.clone())),
879 other => Err(bad(
880 names::LIST,
881 format!("`entry_anchors` holds a non-string {other:?}"),
882 )),
883 })
884 .collect::<Result<Vec<_>, _>>()?,
885 Some(other) => {
886 return Err(bad(names::LIST, format!("`entry_anchors` must be a list, found {other:?}")));
887 }
888 };
889 let bad_level = |found: &dyn std::fmt::Debug| {
890 bad(
891 names::LIST,
892 format!(
893 "‘entry_levels’ must be a list of nulls and integers in 0..={} (found {found:?})",
894 u32::MAX
895 ),
896 )
897 };
898 let entry_levels = match field(e, "entry_levels") {
899 None | Some(SerialValue::Null) => Vec::new(),
900 Some(SerialValue::List(items)) => items
901 .iter()
902 .map(|item| match item {
903 SerialValue::Null => Ok(None),
904 SerialValue::Int(n) => u32::try_from(*n).map(Some).map_err(|_| bad_level(n)),
905 other => Err(bad_level(other)),
906 })
907 .collect::<Result<Vec<_>, _>>()?,
908 Some(other) => return Err(bad_level(other)),
909 };
910 Ok(ListPayload {
911 kinds: name_list(names::LIST, e, "kinds")?,
912 anchor: opt_string(names::LIST, e, "anchor")?,
913 entry_anchors,
914 entry_levels,
915 })
916 }
917}
918
919// --- a table of cells ---------------------------------------------------------------------
920
921/// The largest number of grid positions — rows times columns — a
922/// [`CellsPayload`] may describe: one million.
923///
924/// A table's size is written by its author (`\merge{1-1000000}` spans a
925/// million columns), and every emitter visits every position of the grid
926/// ([`CellsPayload::grid`]), so the size is bounded wherever a table is read:
927/// the `cells` feature refuses a cell that would make its table larger, and
928/// [`CellsPayload::from_projection`] refuses a projection that describes a
929/// larger one.
930pub const MAX_CELLS_POSITIONS: u64 = 1_000_000;
931
932/// The horizontal alignment of one cell of a table of cells.
933#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
934pub enum CellAlign {
935 /// Flush left.
936 Left,
937 /// Centered.
938 Center,
939 /// Flush right.
940 Right,
941}
942
943impl CellAlign {
944 /// The stable name: `left`, `center` or `right`.
945 pub fn as_str(self) -> &'static str {
946 match self {
947 CellAlign::Left => "left",
948 CellAlign::Center => "center",
949 CellAlign::Right => "right",
950 }
951 }
952
953 /// The alignment of a stable name, if any.
954 pub fn parse(name: &str) -> Option<CellAlign> {
955 match name {
956 "left" => Some(CellAlign::Left),
957 "center" => Some(CellAlign::Center),
958 "right" => Some(CellAlign::Right),
959 _ => None,
960 }
961 }
962}
963
964/// What kind of header a cell of a table of cells is.
965#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
966pub enum CellHeader {
967 /// The cell heads its column (the HTML `<th scope="col">`).
968 Column,
969 /// The cell heads its row (the HTML `<th scope="row">`).
970 Row,
971}
972
973impl CellHeader {
974 /// The stable name: `column` or `row`.
975 pub fn as_str(self) -> &'static str {
976 match self {
977 CellHeader::Column => "column",
978 CellHeader::Row => "row",
979 }
980 }
981
982 /// The header kind of a stable name, if any.
983 pub fn parse(name: &str) -> Option<CellHeader> {
984 match name {
985 "column" => Some(CellHeader::Column),
986 "row" => Some(CellHeader::Row),
987 _ => None,
988 }
989 }
990}
991
992/// One edge of a cell of a table of cells, at which a rule is drawn.
993#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
994pub enum CellEdge {
995 /// The top edge.
996 Above,
997 /// The bottom edge.
998 Below,
999 /// The left edge.
1000 Left,
1001 /// The right edge.
1002 Right,
1003}
1004
1005impl CellEdge {
1006 /// The stable name: `above`, `below`, `left` or `right`.
1007 pub fn as_str(self) -> &'static str {
1008 match self {
1009 CellEdge::Above => "above",
1010 CellEdge::Below => "below",
1011 CellEdge::Left => "left",
1012 CellEdge::Right => "right",
1013 }
1014 }
1015
1016 /// The edge of a stable name, if any.
1017 pub fn parse(name: &str) -> Option<CellEdge> {
1018 match name {
1019 "above" => Some(CellEdge::Above),
1020 "below" => Some(CellEdge::Below),
1021 "left" => Some(CellEdge::Left),
1022 "right" => Some(CellEdge::Right),
1023 _ => None,
1024 }
1025 }
1026}
1027
1028/// One cell of a [`CellsPayload`]: its position in the grid, how many rows
1029/// and columns it spans, and the facts its style tokens state about it.
1030///
1031/// Rows and columns are counted from zero here (the syntax counts from one).
1032/// A cell occupies the rectangle of grid positions from (`row`, `col`) to
1033/// (`row + row_span - 1`, `col + col_span - 1`); its **top-left position** is
1034/// (`row`, `col`). Every fact is backend-neutral: a backend renders what it can
1035/// express and ignores the rest (the plain-text backend shows the alignment and
1036/// a column header only).
1037#[derive(Debug, Clone, PartialEq, Eq)]
1038pub struct CellSpec {
1039 /// The row of the cell's top-left position, from zero.
1040 pub row: u32,
1041 /// The column of the cell's top-left position, from zero.
1042 pub col: u32,
1043 /// How many rows the cell spans; at least one.
1044 pub row_span: u32,
1045 /// How many columns the cell spans; at least one.
1046 pub col_span: u32,
1047 /// The cell's alignment, when its style tokens give one.
1048 pub align: Option<CellAlign>,
1049 /// Whether the cell is a header, and of what.
1050 pub header: Option<CellHeader>,
1051 /// The edges at which a rule is drawn, each once, in the order the style
1052 /// tokens list them.
1053 pub rules: Vec<CellEdge>,
1054 /// The cell styles the cell carries, by name, in the order the style
1055 /// tokens list them. A backend renders each by a convention of its own (an
1056 /// attribute on HTML, a table command on the recomposed LaTeX), and the
1057 /// host's definitions for that backend give the name its meaning.
1058 pub styles: Vec<Name>,
1059}
1060
1061impl CellSpec {
1062 /// A cell spanning one row and one column at (`row`, `col`), with no
1063 /// style fact.
1064 pub fn at(row: u32, col: u32) -> CellSpec {
1065 CellSpec {
1066 row,
1067 col,
1068 row_span: 1,
1069 col_span: 1,
1070 align: None,
1071 header: None,
1072 rules: Vec::new(),
1073 styles: Vec::new(),
1074 }
1075 }
1076
1077 /// The row one past the cell's last.
1078 pub fn row_end(&self) -> u64 {
1079 u64::from(self.row) + u64::from(self.row_span)
1080 }
1081
1082 /// The column one past the cell's last.
1083 pub fn col_end(&self) -> u64 {
1084 u64::from(self.col) + u64::from(self.col_span)
1085 }
1086
1087 fn project(&self) -> SerialValue {
1088 let mut e: Vec<(&'static str, SerialValue)> = vec![
1089 ("row", SerialValue::Int(i64::from(self.row))),
1090 ("col", SerialValue::Int(i64::from(self.col))),
1091 ];
1092 if self.row_span != 1 {
1093 e.push(("row_span", SerialValue::Int(i64::from(self.row_span))));
1094 }
1095 if self.col_span != 1 {
1096 e.push(("col_span", SerialValue::Int(i64::from(self.col_span))));
1097 }
1098 push_opt(&mut e, "align", self.align.map(|align| text(align.as_str())));
1099 push_opt(&mut e, "header", self.header.map(|header| text(header.as_str())));
1100 if !self.rules.is_empty() {
1101 let rules = self.rules.iter().map(|edge| text(edge.as_str())).collect();
1102 e.push(("rules", SerialValue::List(rules)));
1103 }
1104 if !self.styles.is_empty() {
1105 e.push(("styles", names(&self.styles)));
1106 }
1107 map(e)
1108 }
1109
1110 fn from_projection(value: &SerialValue) -> Result<CellSpec, DeserializeError> {
1111 const E: &str = names::CELLS;
1112 let e = entries(E, value)?;
1113 let count = |key: &str, value: i64, min: i64| -> Result<u32, DeserializeError> {
1114 if (min..=i64::from(u32::MAX)).contains(&value) {
1115 Ok(value as u32)
1116 } else {
1117 Err(bad(E, format!("a cell's `{key}` = {value} is outside {min}..={}", u32::MAX)))
1118 }
1119 };
1120 let align = match opt_string(E, e, "align")? {
1121 None => None,
1122 Some(name) => Some(
1123 CellAlign::parse(&name)
1124 .ok_or_else(|| bad(E, format!("unknown cell alignment `{name}`")))?,
1125 ),
1126 };
1127 let header = match opt_string(E, e, "header")? {
1128 None => None,
1129 Some(name) => Some(
1130 CellHeader::parse(&name)
1131 .ok_or_else(|| bad(E, format!("unknown cell header kind `{name}`")))?,
1132 ),
1133 };
1134 let rules = name_list(E, e, "rules")?
1135 .iter()
1136 .map(|name| {
1137 CellEdge::parse(name.as_str())
1138 .ok_or_else(|| bad(E, format!("unknown cell edge `{name}`")))
1139 })
1140 .collect::<Result<Vec<_>, _>>()?;
1141 Ok(CellSpec {
1142 row: count("row", int(E, e, "row")?, 0)?,
1143 col: count("col", int(E, e, "col")?, 0)?,
1144 row_span: count("row_span", opt_int(E, e, "row_span")?.unwrap_or(1), 1)?,
1145 col_span: count("col_span", opt_int(E, e, "col_span")?.unwrap_or(1), 1)?,
1146 align,
1147 header,
1148 rules,
1149 styles: name_list(E, e, "styles")?,
1150 })
1151 }
1152}
1153
1154/// What occupies one position of a table's grid ([`CellsPayload::grid`]).
1155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1156pub enum GridPosition {
1157 /// No cell covers the position.
1158 Empty,
1159 /// The top-left position of the cell at this index of
1160 /// [`CellsPayload::cells`]: the position at which an emitter writes the
1161 /// cell.
1162 TopLeft(usize),
1163 /// A position the cell at this index covers by its span, other than its
1164 /// top-left one: a position at which an emitter writes nothing.
1165 Covered(usize),
1166}
1167
1168/// The payload of `flm.pres.cells`, a whole table of cells: its size and one
1169/// entry per cell. The cells' content is held in the node's content slots.
1170///
1171/// The node carries one content slot named `cell`
1172/// ([`CELL_SLOT`](super::CELL_SLOT)) per entry of [`cells`](Self::cells), in the
1173/// same order, so the slot at index *i* holds the content of entry *i*, a run
1174/// of blocks ([`cells_of`](super::cells_of) reads the two together). A grid
1175/// position no cell covers has no entry and no slot. The node has no anchor and
1176/// no role: a table of cells becomes a link target only through the node that
1177/// holds it, such as a float of the `table` float type.
1178///
1179/// An emitter visits the grid through [`grid`](Self::grid) and never
1180/// computes the occupancy from the entries itself.
1181#[derive(Debug, Clone, PartialEq, Eq, Default)]
1182pub struct CellsPayload {
1183 /// The number of rows of the grid.
1184 pub rows: u32,
1185 /// The number of columns of the grid.
1186 pub cols: u32,
1187 /// The cells, in row-major order of their top-left positions: by row, and
1188 /// within a row by column.
1189 pub cells: Vec<CellSpec>,
1190}
1191
1192impl PresPayload for CellsPayload {
1193 fn project(&self) -> SerialValue {
1194 map(vec![
1195 ("rows", SerialValue::Int(i64::from(self.rows))),
1196 ("cols", SerialValue::Int(i64::from(self.cols))),
1197 ("cells", SerialValue::List(self.cells.iter().map(CellSpec::project).collect())),
1198 ])
1199 }
1200}
1201
1202impl CellsPayload {
1203 /// What occupies every position of the grid: `grid()[row][col]`, the
1204 /// rows from zero, each row holding [`cols`](Self::cols) positions.
1205 ///
1206 /// Every emitter of a table of cells uses this, and none computes the
1207 /// occupancy itself. It is built from the entries in their order: an entry
1208 /// marks its top-left position and covers the rest of its rectangle. A
1209 /// payload the `cells` feature stages has no two entries overlapping and
1210 /// none outside the grid, and a payload read back from a projection has
1211 /// none either ([`from_projection`](Self::from_projection) refuses any
1212 /// other). For a payload built by hand otherwise, a position already held
1213 /// keeps its first holder and a position outside the grid is ignored.
1214 ///
1215 /// The result holds [`rows`](Self::rows) times [`cols`](Self::cols)
1216 /// positions, at most [`MAX_CELLS_POSITIONS`] for a payload the feature or
1217 /// the projection reader produced.
1218 pub fn grid(&self) -> Vec<Vec<GridPosition>> {
1219 let rows = self.rows as usize;
1220 let cols = self.cols as usize;
1221 let mut grid = vec![vec![GridPosition::Empty; cols]; rows];
1222 for (index, cell) in self.cells.iter().enumerate() {
1223 let row_end = cell.row_end().min(rows as u64) as usize;
1224 let col_end = cell.col_end().min(cols as u64) as usize;
1225 for (r, row) in grid.iter_mut().enumerate().take(row_end).skip(cell.row as usize) {
1226 for (c, position) in row.iter_mut().enumerate().take(col_end).skip(cell.col as usize) {
1227 if *position != GridPosition::Empty {
1228 continue;
1229 }
1230 *position = if r == cell.row as usize && c == cell.col as usize {
1231 GridPosition::TopLeft(index)
1232 } else {
1233 GridPosition::Covered(index)
1234 };
1235 }
1236 }
1237 }
1238 grid
1239 }
1240
1241 /// The payload rebuilt from its projection, the value
1242 /// [`project`](PresPayload::project) produced.
1243 ///
1244 /// # Errors
1245 ///
1246 /// Returns a [`DeserializeError`] mentioning `flm.pres.cells` when the
1247 /// projection is not a map; when `rows`, `cols` or `cells` is missing or of
1248 /// the wrong type; when an entry is not a map, lacks `row` or `col`, gives
1249 /// a span below one or a number outside the unsigned 32-bit range, or gives
1250 /// an alignment, a header kind or an edge that does not exist; and when the
1251 /// payload is not one the `cells` feature could stage: a grid of more than
1252 /// [`MAX_CELLS_POSITIONS`] positions, an entry reaching outside the grid,
1253 /// two entries overlapping, or the entries out of row-major order.
1254 pub fn from_projection(value: &SerialValue) -> Result<CellsPayload, DeserializeError> {
1255 const E: &str = names::CELLS;
1256 let e = entries(E, value)?;
1257 let size = |key: &str| -> Result<u32, DeserializeError> {
1258 let value = int(E, e, key)?;
1259 u32::try_from(value).map_err(|_| bad(E, format!("`{key}` = {value} is out of range")))
1260 };
1261 let rows = size("rows")?;
1262 let cols = size("cols")?;
1263 if u64::from(rows) * u64::from(cols) > MAX_CELLS_POSITIONS {
1264 return Err(bad(
1265 E,
1266 format!("a grid of {rows} by {cols} exceeds {MAX_CELLS_POSITIONS} positions"),
1267 ));
1268 }
1269 let cells = match field(e, "cells") {
1270 Some(SerialValue::List(items)) => {
1271 items.iter().map(CellSpec::from_projection).collect::<Result<Vec<_>, _>>()?
1272 }
1273 Some(other) => return Err(bad(E, format!("`cells` must be a list, found {other:?}"))),
1274 None => return Err(bad(E, "`cells` is missing")),
1275 };
1276 let payload = CellsPayload { rows, cols, cells };
1277 payload.check().map_err(|detail| bad(E, detail))?;
1278 Ok(payload)
1279 }
1280
1281 /// The consistency [`from_projection`](Self::from_projection) requires:
1282 /// every entry inside the grid, in row-major order, none overlapping.
1283 fn check(&self) -> Result<(), String> {
1284 for (index, cell) in self.cells.iter().enumerate() {
1285 if cell.row_end() > u64::from(self.rows) || cell.col_end() > u64::from(self.cols) {
1286 return Err(format!("the cell at index {index} reaches outside the grid"));
1287 }
1288 }
1289 if self.cells.windows(2).any(|pair| (pair[0].row, pair[0].col) >= (pair[1].row, pair[1].col)) {
1290 return Err("the cells are not in row-major order of their top-left positions".into());
1291 }
1292 let held = self.grid();
1293 for (index, cell) in self.cells.iter().enumerate() {
1294 for (r, row) in held.iter().enumerate().take(cell.row_end() as usize).skip(cell.row as usize) {
1295 for position in row.iter().take(cell.col_end() as usize).skip(cell.col as usize) {
1296 let holder = match *position {
1297 GridPosition::TopLeft(i) | GridPosition::Covered(i) => i,
1298 GridPosition::Empty => index,
1299 };
1300 if holder != index {
1301 return Err(format!(
1302 "the cell at index {index} overlaps the cell at index {holder} in row {r}"
1303 ));
1304 }
1305 }
1306 }
1307 }
1308 Ok(())
1309 }
1310}
1311
1312/// The payload of `flm.pres.dropped`, the mark a lowering rule stages where it
1313/// left out something it could not place: the condition of the diagnostic the
1314/// rule reported, and a short statement of it.
1315///
1316/// The node is always childless. What was left out does not reach the output;
1317/// the mark shows a reader of the output that something is missing, and
1318/// where, while the run's diagnostics say why. Each backend writes it as
1319/// prominently as it writes [`flm.pres.unsupported`](super::UNSUPPORTED).
1320#[derive(Debug, Clone, PartialEq, Eq)]
1321pub struct DroppedPayload {
1322 /// The condition of the diagnostic reported for what was dropped, such as
1323 /// `flm.cells.overlap`.
1324 pub condition: Name,
1325 /// A short statement of what was dropped, in the diagnostic's plain words,
1326 /// such as `cell overlapping another`.
1327 pub detail: String,
1328}
1329
1330impl PresPayload for DroppedPayload {
1331 fn project(&self) -> SerialValue {
1332 map(vec![("condition", text(self.condition.as_str())), ("detail", text(&self.detail))])
1333 }
1334}
1335
1336impl DroppedPayload {
1337 /// The payload rebuilt from its projection, the value
1338 /// [`project`](PresPayload::project) produced.
1339 ///
1340 /// # Errors
1341 ///
1342 /// Returns a [`DeserializeError`] mentioning `flm.pres.dropped` when the
1343 /// projection is not a map, or when `condition` or `detail` is missing or
1344 /// is not a string.
1345 pub fn from_projection(value: &SerialValue) -> Result<DroppedPayload, DeserializeError> {
1346 let e = entries(names::DROPPED, value)?;
1347 Ok(DroppedPayload {
1348 condition: Name::from(string(names::DROPPED, e, "condition")?),
1349 detail: string(names::DROPPED, e, "detail")?,
1350 })
1351 }
1352}
1353
1354/// The payload of `flm.pres.lines`, a sequence of lines: it holds no data.
1355#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1356pub struct LinesPayload;
1357
1358impl PresPayload for LinesPayload {
1359 fn project(&self) -> SerialValue {
1360 map(Vec::new())
1361 }
1362}
1363
1364impl LinesPayload {
1365 /// The payload rebuilt from its projection, the value
1366 /// [`project`](PresPayload::project) produced.
1367 ///
1368 /// # Errors
1369 ///
1370 /// Returns a [`DeserializeError`] mentioning `flm.pres.lines` when the
1371 /// projection is not a map.
1372 pub fn from_projection(value: &SerialValue) -> Result<LinesPayload, DeserializeError> {
1373 entries(names::LINES, value)?;
1374 Ok(LinesPayload)
1375 }
1376}
1377
1378/// The payload of `flm.pres.line`, one line of a `flm.pres.lines` node: the
1379/// line's indentation from the left and from the right, each a [`Length`],
1380/// and its alignment.
1381///
1382/// An indentation is a length, never a bare number: its unit is part of the
1383/// value, so that each backend applies it the same way, a
1384/// [tab](super::LengthUnit::Tabs) at the width that backend sets for it, any
1385/// other unit at its own size (see [`Length`]). Both default to the zero
1386/// length.
1387#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1388pub struct LinePayload {
1389 /// Indentation from the left.
1390 pub indent_left: Length,
1391 /// Indentation from the right.
1392 pub indent_right: Length,
1393 /// The alignment.
1394 pub align: LineAlign,
1395}
1396
1397impl PresPayload for LinePayload {
1398 fn project(&self) -> SerialValue {
1399 map(vec![
1400 ("indent_left", text(self.indent_left.to_string())),
1401 ("indent_right", text(self.indent_right.to_string())),
1402 ("align", text(self.align.as_str())),
1403 ])
1404 }
1405}
1406
1407impl LinePayload {
1408 /// The payload rebuilt from its projection, the value
1409 /// [`project`](PresPayload::project) produced.
1410 ///
1411 /// # Errors
1412 ///
1413 /// Returns a [`DeserializeError`] mentioning `flm.pres.line` when the
1414 /// projection is not a map, when `indent_left` or `indent_right` is
1415 /// present and is not the text of a length ([`Length::parse`]), or when
1416 /// `align` is present and matches no alignment ([`LineAlign::parse`]).
1417 pub fn from_projection(value: &SerialValue) -> Result<LinePayload, DeserializeError> {
1418 let e = entries(names::LINE, value)?;
1419 let length = |key: &str| -> Result<Length, DeserializeError> {
1420 match opt_string(names::LINE, e, key)? {
1421 None => Ok(Length::default()),
1422 Some(written) => Length::parse(&written)
1423 .map_err(|error| bad(names::LINE, format!("`{key}`: {error}"))),
1424 }
1425 };
1426 let align = match opt_string(names::LINE, e, "align")? {
1427 None => LineAlign::Left,
1428 Some(name) => LineAlign::parse(&name)
1429 .ok_or_else(|| bad(names::LINE, format!("unknown alignment `{name}`")))?,
1430 };
1431 Ok(LinePayload {
1432 indent_left: length("indent_left")?,
1433 indent_right: length("indent_right")?,
1434 align,
1435 })
1436 }
1437}
1438
1439/// The payload of `flm.pres.verbatim`: the verbatim kind, whether the content
1440/// is a block, and the language the content is written in when one was given.
1441#[derive(Debug, Clone, PartialEq, Eq)]
1442pub struct VerbatimPayload {
1443 /// The verbatim kind.
1444 pub kind: VerbatimKind,
1445 /// Block or inline.
1446 pub display: VerbatimDisplay,
1447 /// A language tag, when one was given (`python`).
1448 pub lang: Option<String>,
1449}
1450
1451impl PresPayload for VerbatimPayload {
1452 fn project(&self) -> SerialValue {
1453 let mut entries =
1454 vec![("kind", text(self.kind.as_str())), ("display", text(self.display.as_str()))];
1455 push_opt(&mut entries, "lang", self.lang.as_deref().map(text));
1456 map(entries)
1457 }
1458}
1459
1460impl VerbatimPayload {
1461 /// The payload rebuilt from its projection, the value
1462 /// [`project`](PresPayload::project) produced.
1463 ///
1464 /// # Errors
1465 ///
1466 /// Returns a [`DeserializeError`] mentioning `flm.pres.verbatim` when the
1467 /// projection is not a map, when `kind` or `display` is missing or matches
1468 /// no kind ([`VerbatimKind::parse`]) or display ([`VerbatimDisplay::parse`]),
1469 /// or when `lang` is present and is not a string.
1470 pub fn from_projection(value: &SerialValue) -> Result<VerbatimPayload, DeserializeError> {
1471 let e = entries(names::VERBATIM, value)?;
1472 let kind = string(names::VERBATIM, e, "kind")?;
1473 let kind = VerbatimKind::parse(&kind)
1474 .ok_or_else(|| bad(names::VERBATIM, format!("unknown kind `{kind}`")))?;
1475 let display = string(names::VERBATIM, e, "display")?;
1476 let display = VerbatimDisplay::parse(&display)
1477 .ok_or_else(|| bad(names::VERBATIM, format!("unknown display `{display}`")))?;
1478 Ok(VerbatimPayload { kind, display, lang: opt_string(names::VERBATIM, e, "lang")? })
1479 }
1480}
1481
1482/// The payload of `flm.pres.math-passthrough`, mathematics given to the backend as
1483/// source text: the display form, the environment name when the
1484/// mathematics is written as an environment, and the role.
1485///
1486/// The mathematics itself is not in the payload: it is the node's content,
1487/// copied as source text, which a backend gives to a formula renderer or
1488/// writes out again. The only part of that content that is not source text
1489/// is a [`flm.pres.math-text`](names::MATH_TEXT) node ([`MathTextPayload`]).
1490#[derive(Debug, Clone, PartialEq, Eq)]
1491pub struct MathPassthroughPayload {
1492 /// Inline or display.
1493 pub display: MathDisplay,
1494 /// The math environment's name (`align`), when the mathematics is written
1495 /// as an environment.
1496 pub env: Option<String>,
1497 /// The role (see [`BlockPayload::role`]): the `math-passthrough` feature's
1498 /// rules give the role of a formula's outermost element,
1499 /// [`flm.math.formula`](crate::stdlib::features::math::html::FORMULA_ROLE),
1500 /// whose class marks the formula in an HTML page.
1501 pub role: Option<Name>,
1502}
1503
1504impl PresPayload for MathPassthroughPayload {
1505 fn project(&self) -> SerialValue {
1506 let mut entries = vec![("display", text(self.display.as_str()))];
1507 push_opt(&mut entries, "env", self.env.as_deref().map(text));
1508 push_opt(&mut entries, "role", self.role.as_ref().map(|r| text(r.as_str())));
1509 map(entries)
1510 }
1511}
1512
1513impl MathPassthroughPayload {
1514 /// The payload rebuilt from its projection, the value
1515 /// [`project`](PresPayload::project) produced.
1516 ///
1517 /// # Errors
1518 ///
1519 /// Returns a [`DeserializeError`] mentioning `flm.pres.math-passthrough` when the
1520 /// projection is not a map, when `display` is missing or matches no display
1521 /// form ([`MathDisplay::parse`]), or when `env` or `role` is present and is
1522 /// not a string.
1523 pub fn from_projection(value: &SerialValue) -> Result<MathPassthroughPayload, DeserializeError> {
1524 let e = entries(names::MATH_PASSTHROUGH, value)?;
1525 let display = string(names::MATH_PASSTHROUGH, e, "display")?;
1526 let display = MathDisplay::parse(&display)
1527 .ok_or_else(|| bad(names::MATH_PASSTHROUGH, format!("unknown display `{display}`")))?;
1528 Ok(MathPassthroughPayload {
1529 display,
1530 env: opt_string(names::MATH_PASSTHROUGH, e, "env")?,
1531 role: name_opt(names::MATH_PASSTHROUGH, e, "role")?,
1532 })
1533 }
1534}
1535
1536/// The payload of `flm.pres.math-text`: the text command the content was
1537/// written in, and the anchor when the node is a link target.
1538///
1539/// The node's body is the content itself (ordinary inline content, lowered
1540/// like content anywhere else), and the node is inside a
1541/// [`flm.pres.math-passthrough`](names::MATH_PASSTHROUGH) node, among that node's source
1542/// text, at the content's position in the formula.
1543///
1544/// A node with no content at all and an anchor is a link target placed at a
1545/// point of the formula and showing nothing: such a node marks the start of
1546/// a numbered equation line.
1547///
1548/// A node marked [`at_tag`](MathTextPayload::at_tag) is at the position of a
1549/// line's tag, inside the argument of the `\tag*` the tag is written as. The
1550/// mark is needed because the HTML and text backends write such a position
1551/// differently: the HTML backend wraps the content in a pair of dollar signs,
1552/// and the text backend writes the content unchanged, as an author would have
1553/// typed it.
1554#[derive(Debug, Clone, Default, PartialEq, Eq)]
1555pub struct MathTextPayload {
1556 /// The text command the content was written in, without the leading
1557 /// backslash (`text`, `textbf`, `mbox`); `None` when no command was
1558 /// written, which is the case for a node that only carries an anchor.
1559 pub command: Option<String>,
1560 /// The anchor, when the node is a link target.
1561 pub anchor: Option<String>,
1562 /// Whether this content is at the position of an equation line's tag: the
1563 /// argument of the `\tag*` that writes a line's tag, whether the tag is
1564 /// the one its author wrote or the number the document gave the line.
1565 ///
1566 /// The HTML backend writes a pair of dollar signs around the content of
1567 /// such a node and nothing around any other; every other backend writes
1568 /// the content the same way wherever it is.
1569 pub at_tag: bool,
1570}
1571
1572impl PresPayload for MathTextPayload {
1573 fn project(&self) -> SerialValue {
1574 let mut entries = Vec::new();
1575 push_opt(&mut entries, "command", self.command.as_deref().map(text));
1576 push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
1577 if self.at_tag {
1578 entries.push(("at_tag", SerialValue::Bool(true)));
1579 }
1580 map(entries)
1581 }
1582}
1583
1584impl MathTextPayload {
1585 /// The payload rebuilt from its projection, the value
1586 /// [`project`](PresPayload::project) produced.
1587 ///
1588 /// # Errors
1589 ///
1590 /// Returns a [`DeserializeError`] mentioning `flm.pres.math-text` when the
1591 /// projection is not a map, when `command` or `anchor` is present and is
1592 /// not a string, or when `at_tag` is present and is not a boolean.
1593 pub fn from_projection(value: &SerialValue) -> Result<MathTextPayload, DeserializeError> {
1594 let e = entries(names::MATH_TEXT, value)?;
1595 let at_tag = match field(e, "at_tag") {
1596 None | Some(SerialValue::Null) => false,
1597 Some(SerialValue::Bool(value)) => *value,
1598 Some(_) => return Err(bad(names::MATH_TEXT, "`at_tag` is not a boolean")),
1599 };
1600 Ok(MathTextPayload {
1601 command: opt_string(names::MATH_TEXT, e, "command")?,
1602 anchor: opt_string(names::MATH_TEXT, e, "anchor")?,
1603 at_tag,
1604 })
1605 }
1606}
1607
1608/// The payload of `flm.pres.link`: its target and kind, its role in the
1609/// document's structure, and its accessible name.
1610///
1611/// The link's content (the children of the node) is always what a reader
1612/// sees. [`label`](LinkPayload::label) is an alternative a reader does not
1613/// see: the name assistive technology speaks in place of the content, for a
1614/// link whose content alone says little (a note's number, an arrow back to
1615/// where the note was referenced).
1616#[derive(Debug, Clone, PartialEq, Eq)]
1617pub struct LinkPayload {
1618 /// The target: `#` followed by the anchor for a target in the document, a
1619 /// URL otherwise.
1620 pub href: String,
1621 /// The link kind (`ref`, `cite`, `url`, `term`), which cannot be derived
1622 /// from the target.
1623 pub kind: Name,
1624 /// The link's document role, when it has one: [`DocRole::NoteRef`] for a
1625 /// link to a note, [`DocRole::BackLink`] for a link back from one,
1626 /// [`DocRole::BiblioRef`] for a link to a cited work. A backend without
1627 /// the notion ignores it.
1628 pub doc_role: Option<DocRole>,
1629 /// The link's accessible name (`Footnote 1`), spoken in place of its
1630 /// content by assistive technology, when it has one; the HTML backend
1631 /// writes it as `aria-label`. A backend without the notion ignores it,
1632 /// and the content stays what a reader sees either way.
1633 pub label: Option<String>,
1634 /// Whether the content is the target's own display: text derived from the
1635 /// target by the feature that staged the link, rather than words an
1636 /// author wrote for it. `\url{https://example.com/}` shows `example.com`,
1637 /// derived from its address, whereas
1638 /// `\href{https://example.com}{example.com}` shows the words its author
1639 /// wrote, which happen to match.
1640 ///
1641 /// The feature that staged the link states this fact; it is never the
1642 /// result of comparing the content with the target. Any backend may read it: the text backend
1643 /// prints the target after a link's content, and not after a link whose
1644 /// content already is the target's display unless asked to
1645 /// ([`TextRenderOptions`](crate::stdlib::backends::text::TextRenderOptions)).
1646 /// `false` for every link whose content was written by an author or is a
1647 /// reference's text, which is every link but a `\url` or an `\email`.
1648 pub shows_target: bool,
1649}
1650
1651impl PresPayload for LinkPayload {
1652 fn project(&self) -> SerialValue {
1653 let mut entries = vec![("href", text(&self.href)), ("kind", text(self.kind.as_str()))];
1654 push_opt(&mut entries, "doc_role", self.doc_role.map(|r| text(r.as_str())));
1655 push_opt(&mut entries, "label", self.label.as_deref().map(text));
1656 if self.shows_target {
1657 entries.push(("shows_target", SerialValue::Bool(true)));
1658 }
1659 map(entries)
1660 }
1661}
1662
1663impl LinkPayload {
1664 /// The payload rebuilt from its projection, the value
1665 /// [`project`](PresPayload::project) produced.
1666 ///
1667 /// # Errors
1668 ///
1669 /// Returns a [`DeserializeError`] mentioning `flm.pres.link` when the
1670 /// projection is not a map, when `href` or `kind` is missing or is not a
1671 /// string, when `doc_role` is present and matches no document role
1672 /// ([`DocRole::parse`]), when `label` is present and is not a string, or
1673 /// when `shows_target` is present and is not a boolean. An absent
1674 /// `shows_target` is `false`, the value the projection leaves out.
1675 pub fn from_projection(value: &SerialValue) -> Result<LinkPayload, DeserializeError> {
1676 let e = entries(names::LINK, value)?;
1677 let shows_target = match field(e, "shows_target") {
1678 None | Some(SerialValue::Null) => false,
1679 Some(SerialValue::Bool(value)) => *value,
1680 Some(_) => return Err(bad(names::LINK, "`shows_target` is not a boolean")),
1681 };
1682 Ok(LinkPayload {
1683 href: string(names::LINK, e, "href")?,
1684 kind: Name::from(string(names::LINK, e, "kind")?),
1685 doc_role: doc_role_opt(names::LINK, e)?,
1686 label: opt_string(names::LINK, e, "label")?,
1687 shows_target,
1688 })
1689 }
1690}
1691
1692/// One candidate of an image's `srcset`: a source and its descriptor
1693/// (`2x`, `640w`).
1694#[derive(Debug, Clone, PartialEq, Eq)]
1695pub struct SrcsetCandidate {
1696 /// The image source.
1697 pub src: String,
1698 /// The candidate's descriptor.
1699 pub descriptor: String,
1700}
1701
1702/// The payload of `flm.pres.image`: where the image is, and how it is to be
1703/// presented. The node has no content.
1704///
1705/// The display says whether the image is a block of its own (as the content
1706/// of a float) or inline in the text around it ([`ImageDisplay`]).
1707///
1708/// The two dimensions are the size the image is shown at, each a [`Length`]
1709/// kept in the unit it was given in; each backend writes them its own way (the
1710/// page as two custom properties its stylesheet reads, LaTeX through its
1711/// length writer) and none converts them. A dimension left out is the image's
1712/// natural size in that direction, the image keeping its proportions; where
1713/// both are set, the image is shown at exactly that size.
1714#[derive(Debug, Clone, PartialEq, Eq, Default)]
1715pub struct ImagePayload {
1716 /// The image source, as the backend's published graphics table resolved it.
1717 pub src: String,
1718 /// Block or inline.
1719 pub display: ImageDisplay,
1720 /// The alternative text, when given.
1721 pub alt: Option<String>,
1722 /// The width the image is shown at, when set.
1723 pub width: Option<Length>,
1724 /// The height the image is shown at, when set.
1725 pub height: Option<Length>,
1726 /// Alternative sources.
1727 pub srcset: Vec<SrcsetCandidate>,
1728 /// The anchor, when the image is a link target.
1729 pub anchor: Option<String>,
1730}
1731
1732impl PresPayload for ImagePayload {
1733 fn project(&self) -> SerialValue {
1734 let mut entries =
1735 vec![("src", text(&self.src)), ("display", text(self.display.as_str()))];
1736 push_opt(&mut entries, "alt", self.alt.as_deref().map(text));
1737 push_opt(&mut entries, "width", self.width.map(|length| text(length.to_string())));
1738 push_opt(&mut entries, "height", self.height.map(|length| text(length.to_string())));
1739 if !self.srcset.is_empty() {
1740 entries.push((
1741 "srcset",
1742 SerialValue::List(
1743 self.srcset
1744 .iter()
1745 .map(|c| {
1746 map(vec![("src", text(&c.src)), ("descriptor", text(&c.descriptor))])
1747 })
1748 .collect(),
1749 ),
1750 ));
1751 }
1752 push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
1753 map(entries)
1754 }
1755}
1756
1757impl ImagePayload {
1758 /// The payload rebuilt from its projection, the value
1759 /// [`project`](PresPayload::project) produced.
1760 ///
1761 /// # Errors
1762 ///
1763 /// Returns a [`DeserializeError`] mentioning `flm.pres.image` when the
1764 /// projection is not a map, when `src` is missing, when `display` is
1765 /// missing or matches no display ([`ImageDisplay::parse`]), when `alt` or `anchor`
1766 /// is present and is not a string, when `width` or `height` is present
1767 /// and is not the text of a length ([`Length::parse`]), or when `srcset`
1768 /// is present and is not a list of maps each holding a `src` and a
1769 /// `descriptor` string.
1770 pub fn from_projection(value: &SerialValue) -> Result<ImagePayload, DeserializeError> {
1771 let e = entries(names::IMAGE, value)?;
1772 let length = |key: &str| -> Result<Option<Length>, DeserializeError> {
1773 opt_string(names::IMAGE, e, key)?
1774 .map(|written| {
1775 Length::parse(&written)
1776 .map_err(|error| bad(names::IMAGE, format!("`{key}`: {error}")))
1777 })
1778 .transpose()
1779 };
1780 let srcset = match field(e, "srcset") {
1781 None | Some(SerialValue::Null) => Vec::new(),
1782 Some(SerialValue::List(items)) => items
1783 .iter()
1784 .map(|item| {
1785 let c = entries(names::IMAGE, item)?;
1786 Ok(SrcsetCandidate {
1787 src: string(names::IMAGE, c, "src")?,
1788 descriptor: string(names::IMAGE, c, "descriptor")?,
1789 })
1790 })
1791 .collect::<Result<Vec<_>, DeserializeError>>()?,
1792 Some(other) => {
1793 return Err(bad(names::IMAGE, format!("`srcset` must be a list, found {other:?}")));
1794 }
1795 };
1796 let display = string(names::IMAGE, e, "display")?;
1797 let display = ImageDisplay::parse(&display)
1798 .ok_or_else(|| bad(names::IMAGE, format!("unknown display `{display}`")))?;
1799 Ok(ImagePayload {
1800 src: string(names::IMAGE, e, "src")?,
1801 display,
1802 alt: opt_string(names::IMAGE, e, "alt")?,
1803 width: length("width")?,
1804 height: length("height")?,
1805 srcset,
1806 anchor: opt_string(names::IMAGE, e, "anchor")?,
1807 })
1808 }
1809}
1810
1811/// The payload of `flm.pres.unsupported`: the element the backend could not
1812/// render and a message saying why.
1813///
1814/// The node is always childless. What could not be rendered is described in
1815/// the run's diagnostics and does not reach the output; a backend writes a
1816/// mark in its place (the text backend writes `[unsupported: <element>]`).
1817/// The lowering driver stages the node for a
1818/// node of an accepted unrenderable element, for a node whose rule failed,
1819/// and for a node no rule lowers.
1820#[derive(Debug, Clone, PartialEq, Eq)]
1821pub struct UnsupportedPayload {
1822 /// The element that could not be rendered.
1823 pub element: ElementName,
1824 /// Why the element could not be rendered, as a short statement.
1825 pub message: String,
1826}
1827
1828impl PresPayload for UnsupportedPayload {
1829 fn project(&self) -> SerialValue {
1830 map(vec![("element", text(self.element.as_str())), ("message", text(&self.message))])
1831 }
1832}
1833
1834impl UnsupportedPayload {
1835 /// The payload rebuilt from its projection, the value
1836 /// [`project`](PresPayload::project) produced.
1837 ///
1838 /// # Errors
1839 ///
1840 /// Returns a [`DeserializeError`] mentioning `flm.pres.unsupported` when the
1841 /// projection is not a map, or when `element` or `message` is missing or
1842 /// is not a string.
1843 pub fn from_projection(value: &SerialValue) -> Result<UnsupportedPayload, DeserializeError> {
1844 let e = entries(names::UNSUPPORTED, value)?;
1845 Ok(UnsupportedPayload {
1846 element: ElementName::from(string(names::UNSUPPORTED, e, "element")?),
1847 message: string(names::UNSUPPORTED, e, "message")?,
1848 })
1849 }
1850}
1851
1852/// The invocation form an [`UnknownPayload`] records.
1853#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1854pub enum UnknownKind {
1855 /// A macro: `\foo`.
1856 Macro,
1857 /// An environment: `\begin{foo}…\end{foo}`.
1858 Environment,
1859}
1860
1861impl UnknownKind {
1862 /// The stable name.
1863 pub fn as_str(self) -> &'static str {
1864 match self {
1865 UnknownKind::Macro => "macro",
1866 UnknownKind::Environment => "environment",
1867 }
1868 }
1869
1870 /// The kind of a stable name, if any.
1871 pub fn parse(name: &str) -> Option<UnknownKind> {
1872 match name {
1873 "macro" => Some(UnknownKind::Macro),
1874 "environment" => Some(UnknownKind::Environment),
1875 _ => None,
1876 }
1877 }
1878}
1879
1880/// The payload of `flm.pres.unknown`, a macro or an environment the parse
1881/// could not attribute to any feature, carried into the output as the
1882/// document content it is. An environment's node holds its lowered body as
1883/// children; a macro's node is childless.
1884#[derive(Debug, Clone, PartialEq, Eq)]
1885pub struct UnknownPayload {
1886 /// Which invocation form was written.
1887 pub kind: UnknownKind,
1888 /// The callable's name as written, without any delimiter (`foo`).
1889 pub name: String,
1890 /// The source spelling of the invocation: `\foo` for a macro, the bare name
1891 /// for an environment (a backend writes its own `\begin`/`\end` around it).
1892 pub spelling: String,
1893}
1894
1895impl PresPayload for UnknownPayload {
1896 fn project(&self) -> SerialValue {
1897 map(vec![
1898 ("kind", text(self.kind.as_str())),
1899 ("name", text(&self.name)),
1900 ("spelling", text(&self.spelling)),
1901 ])
1902 }
1903}
1904
1905impl UnknownPayload {
1906 /// The payload rebuilt from its projection, the value
1907 /// [`project`](PresPayload::project) produced.
1908 ///
1909 /// # Errors
1910 ///
1911 /// Returns a [`DeserializeError`] mentioning `flm.pres.unknown` when the
1912 /// projection is not a map, when `kind` is missing or matches no invocation
1913 /// form ([`UnknownKind::parse`]), or when `name` or `spelling` is missing or
1914 /// is not a string.
1915 pub fn from_projection(value: &SerialValue) -> Result<UnknownPayload, DeserializeError> {
1916 let e = entries(names::UNKNOWN, value)?;
1917 let kind = string(names::UNKNOWN, e, "kind")?;
1918 let kind = UnknownKind::parse(&kind)
1919 .ok_or_else(|| bad(names::UNKNOWN, format!("unknown kind `{kind}`")))?;
1920 Ok(UnknownPayload {
1921 kind,
1922 name: string(names::UNKNOWN, e, "name")?,
1923 spelling: string(names::UNKNOWN, e, "spelling")?,
1924 })
1925 }
1926}
1927
1928/// The payload of the three decoration elements (`flm.pres.deco.runin`,
1929/// `flm.pres.deco.final`, `flm.pres.deco.margin`): it holds no data, since
1930/// the element states which decoration it is.
1931#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1932pub struct DecorationPayload;
1933
1934impl PresPayload for DecorationPayload {
1935 fn project(&self) -> SerialValue {
1936 map(Vec::new())
1937 }
1938}
1939
1940impl DecorationPayload {
1941 /// The payload rebuilt from its projection, for the decoration element
1942 /// `element` — any of `flm.pres.deco.runin`, `flm.pres.deco.final` and
1943 /// `flm.pres.deco.margin`, which share this payload type. `element` is used
1944 /// only to name the element in a failure.
1945 ///
1946 /// # Errors
1947 ///
1948 /// Returns a [`DeserializeError`] mentioning `element` when the projection is
1949 /// not a map.
1950 pub fn from_projection(
1951 element: &str,
1952 value: &SerialValue,
1953 ) -> Result<DecorationPayload, DeserializeError> {
1954 entries(element, value)?;
1955 Ok(DecorationPayload)
1956 }
1957}
1958
1959/// The payload of `flm.pres.deco-mark`, the decoration mark: the index, in
1960/// the slot list of the presentation node that holds the mark, of the
1961/// attached slot holding the decoration the lowering driver moved out of this
1962/// position ([`decoration_at`](super::decoration_at)).
1963#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1964pub struct DecoMarkPayload {
1965 /// The attached slot's index.
1966 pub slot: u32,
1967}
1968
1969impl PresPayload for DecoMarkPayload {
1970 fn project(&self) -> SerialValue {
1971 map(vec![("slot", SerialValue::Int(i64::from(self.slot)))])
1972 }
1973}
1974
1975impl DecoMarkPayload {
1976 /// The payload rebuilt from its projection, the value
1977 /// [`project`](PresPayload::project) produced.
1978 ///
1979 /// # Errors
1980 ///
1981 /// Returns a [`DeserializeError`] mentioning `flm.pres.deco-mark` when the
1982 /// projection is not a map, or when `slot` is missing, is not an integer, or
1983 /// is not a slot index (negative, or beyond `u32`).
1984 pub fn from_projection(value: &SerialValue) -> Result<DecoMarkPayload, DeserializeError> {
1985 let e = entries(names::DECO_MARK, value)?;
1986 let slot = int(names::DECO_MARK, e, "slot")?;
1987 let slot = u32::try_from(slot)
1988 .map_err(|_| bad(names::DECO_MARK, format!("`slot` = {slot} is not a slot index")))?;
1989 Ok(DecoMarkPayload { slot })
1990 }
1991}
1992
1993/// The payload of `flm.pres.subtree`: the document tree placed at this node.
1994/// An emitter that writes one output document inserts that tree's own
1995/// lowered form at this node.
1996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1997pub struct SubtreePayload {
1998 /// The tree placed here.
1999 pub tree: TreeId,
2000}
2001
2002impl PresPayload for SubtreePayload {
2003 fn project(&self) -> SerialValue {
2004 map(vec![("tree", text(self.tree.to_string()))])
2005 }
2006}
2007
2008impl SubtreePayload {
2009 /// The payload rebuilt from its projection, the value
2010 /// [`project`](PresPayload::project) produced.
2011 ///
2012 /// # Errors
2013 ///
2014 /// Returns a [`DeserializeError`] mentioning `flm.pres.subtree` when the
2015 /// projection is not a map, when `tree` is missing or is not a string, or
2016 /// when that string is not a document tree identifier — `tree#3`; a value
2017 /// identifier such as `value#1` is refused, since a value is never placed.
2018 pub fn from_projection(value: &SerialValue) -> Result<SubtreePayload, DeserializeError> {
2019 let e = entries(names::SUBTREE, value)?;
2020 let spelled = string(names::SUBTREE, e, "tree")?;
2021 let index = spelled
2022 .strip_prefix("tree#")
2023 .and_then(|n| n.parse::<u32>().ok())
2024 .filter(|n| n & (1 << 31) == 0)
2025 .ok_or_else(|| bad(names::SUBTREE, format!("`{spelled}` is not a document tree id")))?;
2026 Ok(SubtreePayload { tree: TreeId::tree(index) })
2027 }
2028}
2029
2030// --- the readers -----------------------------------------------------------------------
2031
2032/// Registers `parse` as the payload reader of `element`.
2033fn reader<P: PresPayload>(
2034 readers: &mut PayloadReaders,
2035 element: &'static str,
2036 parse: fn(&SerialValue) -> Result<P, DeserializeError>,
2037) {
2038 readers.register(element, move |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
2039 parse(value).map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
2040 });
2041}
2042
2043/// The payload readers of the whole vocabulary, one per element: what a
2044/// reading session ([`reader_with`](crate::dump::session::reader_with)) needs
2045/// to read a stored lowered tree back into typed payloads. Each reader
2046/// rebuilds a payload from its projection through the type's
2047/// `from_projection` function.
2048///
2049/// # Examples
2050///
2051/// ```
2052/// use flm_core::stdlib::backends::pres::{ALL, payload_readers};
2053///
2054/// assert_eq!(payload_readers().len(), ALL.len());
2055/// ```
2056pub fn payload_readers() -> PayloadReaders {
2057 let mut readers = PayloadReaders::new();
2058 reader(&mut readers, names::PAR, ParPayload::from_projection);
2059 reader(&mut readers, names::BLOCK, BlockPayload::from_projection);
2060 for element in [names::BLOCK_HEADING, names::RUNIN_HEADING] {
2061 readers.register(
2062 element,
2063 move |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
2064 HeadingPayload::from_projection(element, value)
2065 .map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
2066 },
2067 );
2068 }
2069 reader(&mut readers, names::SPAN, SpanPayload::from_projection);
2070 reader(&mut readers, names::LIST, ListPayload::from_projection);
2071 reader(&mut readers, names::CELLS, CellsPayload::from_projection);
2072 reader(&mut readers, names::LINES, LinesPayload::from_projection);
2073 reader(&mut readers, names::LINE, LinePayload::from_projection);
2074 reader(&mut readers, names::VERBATIM, VerbatimPayload::from_projection);
2075 reader(&mut readers, names::MATH_PASSTHROUGH, MathPassthroughPayload::from_projection);
2076 reader(&mut readers, names::MATH_TEXT, MathTextPayload::from_projection);
2077 reader(&mut readers, names::LINK, LinkPayload::from_projection);
2078 reader(&mut readers, names::IMAGE, ImagePayload::from_projection);
2079 reader(&mut readers, names::UNSUPPORTED, UnsupportedPayload::from_projection);
2080 reader(&mut readers, names::DROPPED, DroppedPayload::from_projection);
2081 reader(&mut readers, names::UNKNOWN, UnknownPayload::from_projection);
2082 for element in names::DECORATIONS {
2083 readers.register(
2084 element,
2085 move |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
2086 DecorationPayload::from_projection(element, value)
2087 .map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
2088 },
2089 );
2090 }
2091 reader(&mut readers, names::DECO_MARK, DecoMarkPayload::from_projection);
2092 reader(&mut readers, names::SUBTREE, SubtreePayload::from_projection);
2093 readers
2094}
2095
2096#[cfg(test)]
2097mod tests {
2098 use super::*;
2099
2100 /// A 2×3 table: a header spanning two columns, a cell spanning two rows,
2101 /// one empty position.
2102 fn table() -> CellsPayload {
2103 CellsPayload {
2104 rows: 2,
2105 cols: 3,
2106 cells: vec![
2107 CellSpec {
2108 col_span: 2,
2109 header: Some(CellHeader::Column),
2110 align: Some(CellAlign::Center),
2111 ..CellSpec::at(0, 0)
2112 },
2113 CellSpec {
2114 row_span: 2,
2115 rules: vec![CellEdge::Left, CellEdge::Below],
2116 styles: vec![Name::from("green"), Name::from("red")],
2117 ..CellSpec::at(0, 2)
2118 },
2119 CellSpec { header: Some(CellHeader::Row), ..CellSpec::at(1, 0) },
2120 ],
2121 }
2122 }
2123
2124 #[test]
2125 fn a_table_of_cells_projects_its_entries_and_reads_back() {
2126 let payload = table();
2127 let projected = payload.project();
2128 let cell = |entries: Vec<(&str, SerialValue)>| map(entries);
2129 assert_eq!(
2130 projected,
2131 map(vec![
2132 ("rows", SerialValue::Int(2)),
2133 ("cols", SerialValue::Int(3)),
2134 (
2135 "cells",
2136 SerialValue::List(vec![
2137 cell(vec![
2138 ("row", SerialValue::Int(0)),
2139 ("col", SerialValue::Int(0)),
2140 ("col_span", SerialValue::Int(2)),
2141 ("align", text("center")),
2142 ("header", text("column")),
2143 ]),
2144 cell(vec![
2145 ("row", SerialValue::Int(0)),
2146 ("col", SerialValue::Int(2)),
2147 ("row_span", SerialValue::Int(2)),
2148 ("rules", SerialValue::List(vec![text("left"), text("below")])),
2149 ("styles", SerialValue::List(vec![text("green"), text("red")])),
2150 ]),
2151 cell(vec![
2152 ("row", SerialValue::Int(1)),
2153 ("col", SerialValue::Int(0)),
2154 ("header", text("row")),
2155 ]),
2156 ]),
2157 ),
2158 ])
2159 );
2160 assert_eq!(CellsPayload::from_projection(&projected).unwrap(), payload);
2161 }
2162
2163 #[test]
2164 fn the_grid_answers_every_position() {
2165 use GridPosition::{Covered, Empty, TopLeft};
2166 assert_eq!(
2167 table().grid(),
2168 vec![vec![TopLeft(0), Covered(0), TopLeft(1)], vec![TopLeft(2), Empty, Covered(1)]]
2169 );
2170 assert_eq!(CellsPayload::default().grid(), Vec::<Vec<GridPosition>>::new());
2171 // A hand-built payload that overlaps or reaches outside: the first
2172 // holder keeps a position, and what lies outside is ignored.
2173 let odd = CellsPayload {
2174 rows: 1,
2175 cols: 2,
2176 cells: vec![CellSpec { col_span: 5, ..CellSpec::at(0, 0) }, CellSpec::at(0, 1)],
2177 };
2178 assert_eq!(odd.grid(), vec![vec![TopLeft(0), Covered(0)]]);
2179 }
2180
2181 #[test]
2182 fn a_projection_the_feature_could_not_stage_is_refused() {
2183 let refused = |payload: CellsPayload| {
2184 CellsPayload::from_projection(&payload.project()).expect_err("refused")
2185 };
2186 let mut outside = table();
2187 outside.cells[1].row_span = 3;
2188 refused(outside);
2189 let mut overlapping = table();
2190 overlapping.cells[2] = CellSpec { col_span: 3, ..CellSpec::at(1, 0) };
2191 refused(overlapping);
2192 let mut unordered = table();
2193 unordered.cells.swap(0, 1);
2194 refused(unordered);
2195 refused(CellsPayload { rows: 1001, cols: 1000, cells: Vec::new() });
2196 let zero_span = map(vec![
2197 ("rows", SerialValue::Int(1)),
2198 ("cols", SerialValue::Int(1)),
2199 (
2200 "cells",
2201 SerialValue::List(vec![map(vec![
2202 ("row", SerialValue::Int(0)),
2203 ("col", SerialValue::Int(0)),
2204 ("row_span", SerialValue::Int(0)),
2205 ])]),
2206 ),
2207 ]);
2208 assert!(CellsPayload::from_projection(&zero_span).is_err());
2209 }
2210
2211 #[test]
2212 fn the_dropped_mark_projects_and_reads_back() {
2213 let mark = DroppedPayload {
2214 condition: Name::from("flm.cells.overlap"),
2215 detail: String::from("cell overlapping another"),
2216 };
2217 assert_eq!(
2218 mark.project(),
2219 map(vec![
2220 ("condition", text("flm.cells.overlap")),
2221 ("detail", text("cell overlapping another")),
2222 ])
2223 );
2224 assert_eq!(DroppedPayload::from_projection(&mark.project()).unwrap(), mark);
2225 }
2226
2227 #[test]
2228 fn a_projection_omits_absent_optionals_and_empty_lists() {
2229 let block = BlockPayload::default();
2230 assert_eq!(block.project(), map(Vec::new()));
2231 let block = BlockPayload {
2232 role: Some(Name::from("t.thm")),
2233 kinds: vec![Name::from("lemma")],
2234 anchor: Some(String::from("lem-1")),
2235 doc_role: Some(DocRole::Endnotes),
2236 };
2237 assert_eq!(
2238 block.project(),
2239 map(vec![
2240 ("role", text("t.thm")),
2241 ("kinds", SerialValue::List(vec![text("lemma")])),
2242 ("anchor", text("lem-1")),
2243 ("doc_role", text("endnotes")),
2244 ])
2245 );
2246 }
2247
2248 #[test]
2249 fn every_payload_reads_back_from_its_projection() {
2250 let readers = payload_readers();
2251 assert_eq!(readers.len(), names::ALL.len());
2252 let heading = HeadingPayload {
2253 name: Name::from("subsection"),
2254 level: 2,
2255 in_toc: false,
2256 anchor: Some(String::from("sec")),
2257 number: Some(String::from("1.2")),
2258 };
2259 for element in [names::BLOCK_HEADING, names::RUNIN_HEADING] {
2260 assert_eq!(HeadingPayload::from_projection(element, &heading.project()).unwrap(), heading);
2261 }
2262 let span = SpanPayload { style: Some(SpanStyle::SmallCaps), ..SpanPayload::default() };
2263 assert_eq!(SpanPayload::from_projection(&span.project()).unwrap(), span);
2264 let span = SpanPayload { doc_role: Some(DocRole::Footnote), ..SpanPayload::default() };
2265 assert_eq!(SpanPayload::from_projection(&span.project()).unwrap(), span);
2266 let block = BlockPayload { doc_role: Some(DocRole::Endnotes), ..BlockPayload::default() };
2267 assert_eq!(BlockPayload::from_projection(&block.project()).unwrap(), block);
2268 // A link's document role, accessible name and `shows_target` project
2269 // only when set, and read back as they were written.
2270 let link = LinkPayload {
2271 href: String::from("#fn-1"),
2272 kind: Name::from("xnote"),
2273 doc_role: None,
2274 label: None,
2275 shows_target: false,
2276 };
2277 assert_eq!(link.project(), map(vec![("href", text("#fn-1")), ("kind", text("xnote"))]));
2278 assert_eq!(LinkPayload::from_projection(&link.project()).unwrap(), link);
2279 let link = LinkPayload {
2280 doc_role: Some(DocRole::NoteRef),
2281 label: Some(String::from("Footnote \"1\" <a>")),
2282 ..link
2283 };
2284 assert_eq!(LinkPayload::from_projection(&link.project()).unwrap(), link);
2285 let link = LinkPayload {
2286 href: String::from("https://example.com/"),
2287 kind: Name::from("url"),
2288 doc_role: None,
2289 label: None,
2290 shows_target: true,
2291 };
2292 assert_eq!(
2293 link.project(),
2294 map(vec![
2295 ("href", text("https://example.com/")),
2296 ("kind", text("url")),
2297 ("shows_target", SerialValue::Bool(true)),
2298 ])
2299 );
2300 assert_eq!(LinkPayload::from_projection(&link.project()).unwrap(), link);
2301 let math = MathPassthroughPayload {
2302 display: MathDisplay::Display,
2303 env: Some(String::from("align")),
2304 role: Some(Name::from("flm.math.formula")),
2305 };
2306 assert_eq!(MathPassthroughPayload::from_projection(&math.project()).unwrap(), math);
2307 let math_text = MathTextPayload {
2308 command: Some(String::from("textbf")),
2309 anchor: Some(String::from("eq-1")),
2310 at_tag: false,
2311 };
2312 assert_eq!(MathTextPayload::from_projection(&math_text.project()).unwrap(), math_text);
2313 assert_eq!(MathTextPayload::default().project(), map(Vec::new()));
2314 // The mark of a tag's position projects only when it is set, and reads
2315 // back as it was written.
2316 let at_tag = MathTextPayload { at_tag: true, ..MathTextPayload::default() };
2317 assert_eq!(MathTextPayload::from_projection(&at_tag.project()).unwrap(), at_tag);
2318 let subtree = SubtreePayload { tree: TreeId::tree(3) };
2319 assert_eq!(SubtreePayload::from_projection(&subtree.project()).unwrap(), subtree);
2320 let image = ImagePayload {
2321 src: String::from("a.png"),
2322 srcset: vec![SrcsetCandidate {
2323 src: String::from("a@2x.png"),
2324 descriptor: String::from("2x"),
2325 }],
2326 width: Some(Length::parse("5cm").unwrap()),
2327 height: Some(Length::parse("2.5in").unwrap()),
2328 display: ImageDisplay::Block,
2329 ..ImagePayload::default()
2330 };
2331 assert_eq!(ImagePayload::from_projection(&image.project()).unwrap(), image);
2332 let one_dimension =
2333 ImagePayload { height: Some(Length::parse("10pt").unwrap()), ..image.clone() };
2334 assert_eq!(
2335 ImagePayload::from_projection(&one_dimension.project()).unwrap(),
2336 one_dimension
2337 );
2338 let line = LinePayload {
2339 indent_left: Length::tabs(4),
2340 indent_right: Length::parse("1.5em").unwrap(),
2341 align: LineAlign::Right,
2342 };
2343 assert_eq!(LinePayload::from_projection(&line.project()).unwrap(), line);
2344 let unknown = UnknownPayload {
2345 kind: UnknownKind::Environment,
2346 name: String::from("nope"),
2347 spelling: String::from("nope"),
2348 };
2349 assert_eq!(UnknownPayload::from_projection(&unknown.project()).unwrap(), unknown);
2350 let verbatim = VerbatimPayload {
2351 kind: VerbatimKind::Identifier,
2352 display: VerbatimDisplay::Block,
2353 lang: Some(String::from("rust")),
2354 };
2355 assert_eq!(VerbatimPayload::from_projection(&verbatim.project()).unwrap(), verbatim);
2356 // A list's entry anchors and entry levels keep their order and their gaps.
2357 let list = ListPayload {
2358 kinds: vec![Name::from(names::LIST_NUMBERED), Name::from("enumerate")],
2359 anchor: None,
2360 entry_anchors: vec![None, Some(String::from("item-a")), None],
2361 entry_levels: vec![Some(2), None, Some(3)],
2362 };
2363 assert_eq!(ListPayload::from_projection(&list.project()).unwrap(), list);
2364 assert_eq!(ListPayload::default().project(), map(Vec::new()));
2365 }
2366
2367 #[test]
2368 fn every_verbatim_kind_round_trips_through_its_stable_name() {
2369 for kind in VerbatimKind::ALL {
2370 assert_eq!(VerbatimKind::parse(kind.as_str()), Some(kind));
2371 }
2372 assert_eq!(VerbatimKind::Identifier.as_str(), "a");
2373 assert_eq!(VerbatimKind::parse("identifier"), None);
2374 }
2375
2376 #[test]
2377 fn a_malformed_projection_is_a_typed_read_error() {
2378 assert!(LinkPayload::from_projection(&map(vec![("href", text("x"))])).is_err());
2379 assert!(SubtreePayload::from_projection(&map(vec![("tree", text("value#1"))])).is_err());
2380 }
2381
2382 #[test]
2383 fn document_role_names_round_trip_and_an_unknown_one_is_refused() {
2384 for role in DocRole::ALL {
2385 assert_eq!(DocRole::parse(role.as_str()), Some(role));
2386 }
2387 assert_eq!(DocRole::NoteRef.as_str(), "noteref");
2388 assert!(SpanPayload::from_projection(&map(vec![("doc_role", text("doc-noteref"))])).is_err());
2389 assert!(
2390 LinkPayload::from_projection(&map(vec![
2391 ("href", text("#a")),
2392 ("kind", text("ref")),
2393 ("label", SerialValue::Int(1)),
2394 ]))
2395 .is_err()
2396 );
2397 }
2398
2399 #[test]
2400 fn style_names_round_trip() {
2401 for style in SpanStyle::ALL {
2402 assert_eq!(SpanStyle::parse(style.as_str()), Some(style));
2403 }
2404 assert_eq!(SpanStyle::parse("blink"), None);
2405 }
2406}