use crate::stdlib::backends::pres;
pub const CORE_CHUNK: &str = "flm.latex.def.flmx.core";
pub const HEADINGS_CHUNK: &str = "flm.latex.def.flmx.headings";
pub const LINKS_CHUNK: &str = "flm.latex.def.flmx.links";
pub const LISTS_CHUNK: &str = "flm.latex.def.flmx.lists";
pub const LINES_CHUNK: &str = "flm.latex.def.flmx.lines";
pub const VERBATIM_CHUNK: &str = "flm.latex.def.flmx.verbatim";
pub const CELLS_CHUNK: &str = "flm.latex.def.flmx.cells";
pub const IMAGES_CHUNK: &str = "flm.latex.def.flmx.images";
pub const MARKS_CHUNK: &str = "flm.latex.def.flmx.marks";
pub const CHUNKS: [&str; 9] = [
CORE_CHUNK,
HEADINGS_CHUNK,
LINKS_CHUNK,
LISTS_CHUNK,
LINES_CHUNK,
VERBATIM_CHUNK,
CELLS_CHUNK,
IMAGES_CHUNK,
MARKS_CHUNK,
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Form {
Paragraph,
Environment(&'static str),
Command(&'static str),
CommandOrEnvironment {
command: &'static str,
environment: &'static str,
},
Formula,
FormulaText,
AtMark,
Placed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Origin {
Field(&'static str),
EntryField(&'static str),
Slot(&'static str),
EntrySlot(&'static str),
Computed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Value {
Name,
Words,
Content,
Text,
Address,
Length,
Number,
Bool,
Specs,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Key {
pub key: &'static str,
pub origin: Origin,
pub value: Value,
}
impl Key {
pub fn field(&self) -> Option<&'static str> {
match self.origin {
Origin::Field(field) | Origin::EntryField(field) => Some(field),
_ => None,
}
}
pub fn is_entry(&self) -> bool {
matches!(self.origin, Origin::EntryField(_) | Origin::EntrySlot(_))
}
pub fn is_renamed(&self) -> bool {
self.field().is_some_and(|field| field.replace('_', "-") != self.key)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Row {
pub element: &'static str,
pub form: Form,
pub keys: &'static [Key],
pub args: &'static [&'static str],
pub not_written: &'static [(&'static str, &'static str)],
pub chunk: Option<&'static str>,
}
impl Row {
pub fn key(&self, key: &str) -> Option<&Key> {
self.keys.iter().find(|entry| entry.key == key)
}
}
const fn field(key: &'static str, field: &'static str, value: Value) -> Key {
Key { key, origin: Origin::Field(field), value }
}
const fn computed(key: &'static str, value: Value) -> Key {
Key { key, origin: Origin::Computed, value }
}
const HEADING_KEYS: [Key; 7] = [
field("kind", "name", Value::Name),
field("level", "level", Value::Number),
field("toc", "in_toc", Value::Bool),
field("anchor", "anchor", Value::Name),
field("number", "number", Value::Text),
computed("plain", Value::Text),
Key { key: "alt", origin: Origin::Slot(pres::ALT_SLOT), value: Value::Content },
];
const RUNIN_HEADING_KEYS: [Key; 8] = [
HEADING_KEYS[0],
HEADING_KEYS[1],
HEADING_KEYS[2],
HEADING_KEYS[3],
HEADING_KEYS[4],
HEADING_KEYS[5],
HEADING_KEYS[6],
computed("stop", Value::Text),
];
pub static ROWS: &[Row] = &[
Row {
element: pres::PAR,
form: Form::Paragraph,
keys: &[],
args: &[],
not_written: &[("anchor", "written as `\\flmxTarget{<anchor>}` at the paragraph's start")],
chunk: Some(CORE_CHUNK),
},
Row {
element: pres::BLOCK,
form: Form::Environment("flmxBlock"),
keys: &[
field("role", "role", Value::Name),
field("kinds", "kinds", Value::Words),
field("anchor", "anchor", Value::Name),
field("doc-role", "doc_role", Value::Name),
],
args: &[],
not_written: &[],
chunk: Some(CORE_CHUNK),
},
Row {
element: pres::BLOCK_HEADING,
form: Form::Command("flmxHeading"),
keys: &HEADING_KEYS,
args: &[],
not_written: &[],
chunk: Some(HEADINGS_CHUNK),
},
Row {
element: pres::RUNIN_HEADING,
form: Form::Command("flmxRuninHeading"),
keys: &RUNIN_HEADING_KEYS,
args: &[],
not_written: &[],
chunk: Some(HEADINGS_CHUNK),
},
Row {
element: pres::SPAN,
form: Form::Command("flmxSpan"),
keys: &[
field("style", "style", Value::Name),
field("role", "role", Value::Name),
field("kinds", "kinds", Value::Words),
field("anchor", "anchor", Value::Name),
field("doc-role", "doc_role", Value::Name),
],
args: &[],
not_written: &[],
chunk: Some(CORE_CHUNK),
},
Row {
element: pres::LIST,
form: Form::Environment("flmxList"),
keys: &[
field("kinds", "kinds", Value::Words),
field("anchor", "anchor", Value::Name),
computed("depth", Value::Number),
Key { key: "label", origin: Origin::EntrySlot(pres::LABEL_SLOT), value: Value::Content },
Key {
key: "anchor",
origin: Origin::EntryField("entry_anchors"),
value: Value::Name,
},
],
args: &[],
not_written: &[(
"entry_levels",
"an entry's level selects its looks in a page's stylesheet; the document's LaTeX sets \
the entries of a list alike, a nested list by its `depth`",
)],
chunk: Some(LISTS_CHUNK),
},
Row {
element: pres::CELLS,
form: Form::Environment("flmxCells"),
keys: &[
field("rows", "rows", Value::Number),
field("cols", "cols", Value::Number),
field("cells", "cells", Value::Specs),
],
args: &[],
not_written: &[],
chunk: Some(CELLS_CHUNK),
},
Row {
element: pres::LINES,
form: Form::Environment("flmxLines"),
keys: &[],
args: &[],
not_written: &[],
chunk: Some(LINES_CHUNK),
},
Row {
element: pres::LINE,
form: Form::Command("flmxLine"),
keys: &[
field("indent-left", "indent_left", Value::Length),
field("indent-right", "indent_right", Value::Length),
field("align", "align", Value::Name),
],
args: &[],
not_written: &[],
chunk: Some(LINES_CHUNK),
},
Row {
element: pres::VERBATIM,
form: Form::CommandOrEnvironment {
command: "flmxVerbatim",
environment: "flmxVerbatimBlock",
},
keys: &[field("kind", "kind", Value::Name), field("lang", "lang", Value::Name)],
args: &[],
not_written: &[(
"display",
"chooses the form: the command `\\flmxVerbatim` inline, the environment \
`flmxVerbatimBlock` for a block",
)],
chunk: Some(VERBATIM_CHUNK),
},
Row {
element: pres::MATH_PASSTHROUGH,
form: Form::Formula,
keys: &[],
args: &[],
not_written: &[
("display", "chooses the delimiters: `\\(…\\)` inline, `\\[…\\]` or an environment displayed"),
("env", "the environment written, starred, around a displayed formula's source"),
],
chunk: None,
},
Row {
element: pres::MATH_TEXT,
form: Form::FormulaText,
keys: &[],
args: &[],
not_written: &[
("command", "the command written around the content inside the formula, `\\text` by default"),
("anchor", "written as `\\flmxTarget{<anchor>}` inside the formula"),
("at_tag", "at a tag the content is written alone, since the source holds `\\tag*{` around it"),
],
chunk: None,
},
Row {
element: pres::LINK,
form: Form::Command("flmxLink"),
keys: &[
field("kind", "kind", Value::Name),
field("href", "href", Value::Address),
computed("target", Value::Name),
field("doc-role", "doc_role", Value::Name),
field("label", "label", Value::Text),
field("shows-target", "shows_target", Value::Bool),
],
args: &[],
not_written: &[],
chunk: Some(LINKS_CHUNK),
},
Row {
element: pres::IMAGE,
form: Form::Command("flmxImage"),
keys: &[
field("width", "width", Value::Length),
field("height", "height", Value::Length),
field("alt", "alt", Value::Text),
field("display", "display", Value::Name),
field("anchor", "anchor", Value::Name),
],
args: &[],
not_written: &[
("src", "the path is the command's mandatory argument"),
("srcset", "the candidates a browser chooses among; LaTeX includes the one file"),
],
chunk: Some(IMAGES_CHUNK),
},
Row {
element: pres::UNSUPPORTED,
form: Form::Command("flmxUnsupported"),
keys: &[],
args: &["element", "message"],
not_written: &[],
chunk: Some(MARKS_CHUNK),
},
Row {
element: pres::DROPPED,
form: Form::Command("flmxDropped"),
keys: &[],
args: &["condition", "detail"],
not_written: &[],
chunk: Some(MARKS_CHUNK),
},
Row {
element: pres::UNKNOWN,
form: Form::Command("flmxUnknown"),
keys: &[field("kind", "kind", Value::Name)],
args: &["name", "spelling"],
not_written: &[],
chunk: Some(MARKS_CHUNK),
},
Row {
element: pres::DECO_RUNIN,
form: Form::Command("flmxDecoRunin"),
keys: &[computed("stop", Value::Text)],
args: &[],
not_written: &[],
chunk: Some(CORE_CHUNK),
},
Row {
element: pres::DECO_FINAL,
form: Form::Command("flmxDecoFinal"),
keys: &[],
args: &[],
not_written: &[],
chunk: Some(CORE_CHUNK),
},
Row {
element: pres::DECO_MARGIN,
form: Form::Command("flmxDecoMargin"),
keys: &[],
args: &[],
not_written: &[],
chunk: Some(CORE_CHUNK),
},
Row {
element: pres::DECO_MARK,
form: Form::AtMark,
keys: &[],
args: &[],
not_written: &[("slot", "identifies the decoration written in the mark's place")],
chunk: None,
},
Row {
element: pres::SUBTREE,
form: Form::Placed,
keys: &[],
args: &[],
not_written: &[("tree", "identifies the document tree written in the node's place")],
chunk: None,
},
];
pub fn row(element: &str) -> Option<&'static Row> {
ROWS.iter().find(|row| row.element == element)
}
pub fn print_rows() -> String {
let mut out = String::new();
for row in ROWS {
let keys: Vec<String> = row
.keys
.iter()
.map(|key| match key.origin {
Origin::Field(field) if key.is_renamed() => format!("{} ({field})", key.key),
Origin::EntryField(field) => format!("item {} ({field})", key.key),
Origin::EntrySlot(slot) => format!("item {} (slot {slot})", key.key),
Origin::Slot(slot) => format!("{} (slot {slot})", key.key),
_ => String::from(key.key),
})
.collect();
let keys = if keys.is_empty() { String::new() } else { format!("[{}]", keys.join(", ")) };
let args: String = row.args.iter().map(|arg| format!("{{{arg}}}")).collect();
let form = match row.form {
Form::Paragraph => String::from("a paragraph"),
Form::Environment(name) => format!("\\begin{{{name}}}{keys}{args} … \\end{{{name}}}"),
Form::Command(name) => format!("\\{name}{keys}{args}"),
Form::CommandOrEnvironment { command, environment } => {
format!("\\{command}{keys} or \\begin{{{environment}}}{keys} … \\end{{{environment}}}")
}
Form::Formula => String::from("the formula's delimiters around its source"),
Form::FormulaText => String::from("content inside the formula's source"),
Form::AtMark => String::from("the decoration at the mark's place"),
Form::Placed => String::from("the placed tree in place"),
};
let chunk = row.chunk.map(|chunk| format!(" ({chunk})")).unwrap_or_default();
out.push_str(&format!("{}: {form}{chunk}\n", row.element));
}
out
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use techy::serialize::SerialValue;
use super::*;
use crate::lang::PresPayload;
use crate::model::addr::TreeId;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::pres::{
BlockPayload, CellSpec, CellsPayload, DecoMarkPayload, DecorationPayload, DocRole,
DroppedPayload, HeadingPayload, ImageDisplay, ImagePayload, Length, LineAlign,
LinePayload, LinesPayload, LinkPayload, ListPayload, MathDisplay, MathPassthroughPayload,
MathTextPayload, ParPayload, SpanPayload, SpanStyle, SrcsetCandidate, SubtreePayload,
UnknownKind, UnknownPayload, UnsupportedPayload, VerbatimDisplay, VerbatimKind,
VerbatimPayload,
};
fn name(text: &str) -> Name {
Name::from(text)
}
fn populated_payloads() -> Vec<(&'static str, Arc<dyn PresPayload>)> {
let anchor = || Some(String::from("a-1"));
let heading = || HeadingPayload { name: name("section"), level: 1, in_toc: true, anchor: anchor(), number: Some(String::from("1")) };
let mut cell = CellSpec::at(1, 1);
cell.styles = vec![name("green")];
vec![
(pres::PAR, Arc::new(ParPayload { anchor: anchor() }) as Arc<dyn PresPayload>),
(
pres::BLOCK,
Arc::new(BlockPayload {
role: Some(name("flm.theorems.theorem")),
kinds: vec![name("theorem")],
anchor: anchor(),
doc_role: Some(DocRole::Endnotes),
}),
),
(pres::BLOCK_HEADING, Arc::new(heading())),
(pres::RUNIN_HEADING, Arc::new(heading())),
(
pres::SPAN,
Arc::new(SpanPayload {
style: Some(SpanStyle::Bold),
role: Some(name("flm.defterm.term")),
kinds: vec![name("primary")],
anchor: anchor(),
doc_role: Some(DocRole::Footnote),
}),
),
(
pres::LIST,
Arc::new(ListPayload {
kinds: vec![name("numbered")],
anchor: anchor(),
entry_anchors: vec![Some(String::from("item-a"))],
entry_levels: vec![Some(1)],
}),
),
(pres::CELLS, Arc::new(CellsPayload { rows: 1, cols: 1, cells: vec![cell] })),
(pres::LINES, Arc::new(LinesPayload)),
(
pres::LINE,
Arc::new(LinePayload {
indent_left: Length::tabs(1),
indent_right: Length::tabs(2),
align: LineAlign::Center,
}),
),
(
pres::VERBATIM,
Arc::new(VerbatimPayload {
kind: VerbatimKind::Code,
display: VerbatimDisplay::Block,
lang: Some(String::from("rust")),
}),
),
(
pres::MATH_PASSTHROUGH,
Arc::new(MathPassthroughPayload {
display: MathDisplay::Display,
env: Some(String::from("align")),
role: None,
}),
),
(
pres::MATH_TEXT,
Arc::new(MathTextPayload { command: Some(String::from("text")), anchor: anchor(), at_tag: true }),
),
(
pres::LINK,
Arc::new(LinkPayload {
href: String::from("#a-1"),
kind: name("ref"),
doc_role: Some(DocRole::NoteRef),
label: Some(String::from("Footnote 1")),
shows_target: true,
}),
),
(
pres::IMAGE,
Arc::new(ImagePayload {
src: String::from("a.png"),
display: ImageDisplay::Block,
alt: Some(String::from("a")),
width: Some(Length::tabs(1)),
height: Some(Length::tabs(1)),
srcset: vec![SrcsetCandidate { src: String::from("b.png"), descriptor: String::from("2x") }],
anchor: anchor(),
}),
),
(
pres::UNSUPPORTED,
Arc::new(UnsupportedPayload { element: ElementName::from("x.box"), message: String::from("why") }),
),
(
pres::DROPPED,
Arc::new(DroppedPayload { condition: name("x.left-out"), detail: String::from("what") }),
),
(
pres::UNKNOWN,
Arc::new(UnknownPayload {
kind: UnknownKind::Macro,
name: String::from("foo"),
spelling: String::from("\\foo"),
}),
),
(pres::DECO_RUNIN, Arc::new(DecorationPayload)),
(pres::DECO_FINAL, Arc::new(DecorationPayload)),
(pres::DECO_MARGIN, Arc::new(DecorationPayload)),
(pres::DECO_MARK, Arc::new(DecoMarkPayload { slot: 1 })),
(pres::SUBTREE, Arc::new(SubtreePayload { tree: TreeId::tree(1) })),
]
}
#[test]
fn every_element_of_the_vocabulary_has_exactly_one_row() {
let mut elements: Vec<&str> = ROWS.iter().map(|row| row.element).collect();
elements.sort_unstable();
let mut all = pres::ALL.to_vec();
all.sort_unstable();
assert_eq!(elements, all);
assert_eq!(populated_payloads().len(), ROWS.len());
}
#[test]
fn every_payload_field_is_a_key_an_argument_or_not_written_with_a_reason() {
for (element, payload) in populated_payloads() {
let row = row(element).expect("a row for every element");
let SerialValue::Map(entries) = payload.project() else {
panic!("`{element}` projects as something other than a map");
};
let projected: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
for key in &projected {
let known = row.keys.iter().any(|entry| entry.field() == Some(key))
|| row.args.contains(key)
|| row.not_written.iter().any(|(field, _)| field == key);
assert!(known, "`{element}`'s field `{key}` is not in its row");
}
let named = row
.keys
.iter()
.filter_map(Key::field)
.chain(row.args.iter().copied())
.chain(row.not_written.iter().map(|(field, _)| *field));
for field in named {
assert!(projected.contains(&field), "`{element}`'s row names `{field}`, not projected");
}
}
}
#[test]
fn the_keys_of_a_row_are_the_field_names_with_hyphens_but_the_two_heading_renames() {
let renamed: Vec<(&str, &str)> = ROWS
.iter()
.flat_map(|row| row.keys.iter())
.filter(|key| key.is_renamed())
.map(|key| (key.key, key.field().unwrap_or_default()))
.collect();
assert_eq!(
renamed,
[("kind", "name"), ("toc", "in_toc"), ("kind", "name"), ("toc", "in_toc"), ("anchor", "entry_anchors")]
);
}
#[test]
fn the_printed_table_holds_one_line_per_element() {
let table = print_rows();
assert_eq!(table.lines().count(), ROWS.len());
assert!(table.contains(
"flm.pres.block-heading: \\flmxHeading[kind (name), level, toc (in_toc), anchor, number, plain, alt (slot alt)] (flm.latex.def.flmx.headings)"
), "{table}");
assert!(table.contains("flm.pres.dropped: \\flmxDropped{condition}{detail} (flm.latex.def.flmx.marks)"), "{table}");
}
}