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