flm_core/stdlib/backends/pres/read.rs
1//! Reading presentation nodes: the functions a backend's emitter reads a
2//! lowered tree with.
3//!
4//! A presentation node is a callable node of the presentation form
5//! ([`is_presentation`]); its typed payload is read with [`payload_of`]. Its
6//! children are divided, in order, among its slots:
7//!
8//! - **Content slots** come first: on most elements a single slot named `body`
9//! and marked as the body ([`body_of`]); on a list node, a `label` slot and
10//! an `item` slot per entry, read by position because the two names repeat
11//! ([`list_entries`]); on a table of cells, one `cell` slot per entry of its
12//! payload ([`cells_of`]).
13//! - **Attached slots** follow: one per decoration the lowering driver moved
14//! out of the node's content slots, named after the decoration's element
15//! ([`attached_slots`]). A decoration is a node whose element carries the
16//! [`Decoration`](super::Decoration) aspect; the decoration mark
17//! (`flm.pres.deco-mark`) left at its former position gives the index of
18//! its attached slot, and [`decoration_at`] returns the decoration a mark
19//! refers to. See [decorations, roles and
20//! kinds](crate::guide::concepts_overview#decorations-roles-and-kinds).
21//!
22//! Two functions read the text of a run of nodes, for different purposes:
23//! [`plain_text`] returns the characters of the run with every construct
24//! left out (what a heading is measured by and a list label is padded from),
25//! and [`recompose_source`] returns the run's source text, byte for byte
26//! (what an emitter writes for the opaque content of a math or verbatim
27//! node). [`spelling_identity`] builds on the second to decide whether two
28//! written runs are the same.
29//!
30//! [`holds_text`] and [`ends_in_sentence_punctuation`] are the two tests every
31//! backend makes before it adds a stop after a run-in heading: whether there
32//! is a title at all, and whether the title already ends in sentence
33//! punctuation. Every backend calls these two functions, so two outputs of
34//! the same document cannot disagree about which titles get a stop.
35//! [`heading_depth`] likewise computes, for every backend, how deep a heading
36//! is below the render's root heading level.
37
38use techy::core::node::{BodySlotExt, NodeRef, NodeSlice, SlotRole};
39use techy::error::DiagnosticInfo;
40use techy::latexlike::{EnvironmentSyntax, InvocationSyntaxData, LatexlikeCallableType};
41use techy::recompose::{
42 ComposePiece, ConcatPieces, Recompose, RecomposeContext, Recomposer, core_source_instruction,
43};
44
45use crate::lang::copy::{ValueContent, copy_run_into_value};
46use crate::lang::guard::{self, GuardPolicy};
47use crate::lang::text::collapse_whitespace;
48use crate::lang::{Flm, FlmCallableType, PresPayload};
49use crate::layout::is_breakable_space;
50
51use super::payload::{CellsPayload, DecoMarkPayload};
52
53/// Whether `node` is a presentation node: a callable node of the presentation
54/// form, which is the form every element of [the vocabulary](super) is
55/// registered with.
56pub fn is_presentation(node: &NodeRef<'_, Flm>) -> bool {
57 node.callable_type() == Some(FlmCallableType::Presentation)
58}
59
60/// The node's typed payload as a `P`: `None` when the node carries no payload
61/// — most nodes of a document — or carries one of another type.
62///
63/// Three kinds of node carry a payload
64/// ([`FlmNodeExt::payload`](crate::lang::FlmNodeExt::payload)): a presentation
65/// node, a synthesized node carrying data of its own, and a node a rewrite
66/// rebuilt with data of its own, such as one part of a [block-transparent
67/// element](crate::lang::rewrites::blocks::transparent) cut at a paragraph
68/// break, which carries its element's record. The type to ask for is the one
69/// the element uses: [`ParPayload`](super::ParPayload) for `flm.pres.par`,
70/// [`LinkPayload`](super::LinkPayload) for `flm.pres.link`, the element's own
71/// record type for the parts of a block-transparent element, and so on.
72pub fn payload_of<'t, P: PresPayload>(node: &NodeRef<'t, Flm>) -> Option<&'t P> {
73 node.ext().payload.as_deref().and_then(|payload| payload.downcast_ref::<P>())
74}
75
76/// The content of the node's body slot — the content slot marked as the body,
77/// named `body` on every element of the vocabulary that has one. `None` for a
78/// node without a body slot, such as `flm.pres.image` or a list node.
79pub fn body_of<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeSlice<'t, Flm>> {
80 node.body()
81}
82
83/// The content of the slot at `index` in the node's slot list, counting
84/// content slots and attached slots alike; `None` when the node has no slot
85/// there.
86pub fn slot_of<'t>(node: &NodeRef<'t, Flm>, index: usize) -> Option<NodeSlice<'t, Flm>> {
87 node.slot_content_nodes(index)
88}
89
90/// How many slots the node has, content slots and attached slots together.
91pub fn slot_count(node: &NodeRef<'_, Flm>) -> usize {
92 node.slots().map_or(0, |slots| slots.len())
93}
94
95/// One attached slot of a presentation node: the slot that holds a decoration
96/// the lowering driver moved out of the node's content, with the slot's
97/// position and name.
98#[derive(Debug, Clone)]
99pub struct AttachedSlot<'t> {
100 /// The slot's index in the node's slot list: the number the payload of
101 /// the corresponding `flm.pres.deco-mark` node carries.
102 pub index: usize,
103 /// The slot's name, which is the decoration element's name (for instance
104 /// `flm.pres.deco.runin`).
105 pub name: Option<&'t str>,
106 /// The slot's content: the decoration node it holds.
107 pub content: NodeSlice<'t, Flm>,
108}
109
110/// The attached slots of a presentation node, in slot order: one per
111/// decoration the lowering driver moved out of the node's content slots.
112/// Empty for a node that carries no decoration.
113pub fn attached_slots<'t>(node: &NodeRef<'t, Flm>) -> Vec<AttachedSlot<'t>> {
114 let Some(slots) = node.slots() else { return Vec::new() };
115 slots
116 .iter()
117 .enumerate()
118 .filter(|(_, slot)| slot.role == SlotRole::Attached)
119 .filter_map(|(index, slot)| {
120 Some(AttachedSlot {
121 index,
122 name: slot.name(),
123 content: node.slot_content_nodes(index)?,
124 })
125 })
126 .collect()
127}
128
129/// The decoration that the decoration mark `mark` (a `flm.pres.deco-mark`
130/// node) refers to: the first node of the attached slot of `carrier` whose
131/// index the mark's payload gives. `carrier` is the presentation node whose
132/// content slot holds the mark.
133///
134/// Returns `None` when `mark` carries no [`DecoMarkPayload`] or `carrier` has
135/// no slot at the index the payload gives. Only a tree built by hand can have
136/// that shape; in a tree the lowering driver produced, every mark has its
137/// decoration.
138pub fn decoration_at<'t>(
139 carrier: &NodeRef<'t, Flm>,
140 mark: &NodeRef<'t, Flm>,
141) -> Option<NodeRef<'t, Flm>> {
142 let payload = payload_of::<DecoMarkPayload>(mark)?;
143 carrier.slot_content_nodes(payload.slot as usize)?.first()
144}
145
146/// The `(label, item)` content pairs of a `flm.pres.list` node, in order.
147///
148/// The slots are read by position rather than by name, since `label` and
149/// `item` repeat once per entry. A last slot with no partner is ignored, so a
150/// malformed list still reads as the entries it does have.
151pub fn list_entries<'t>(node: &NodeRef<'t, Flm>) -> Vec<(NodeSlice<'t, Flm>, NodeSlice<'t, Flm>)> {
152 let count = slot_count(node);
153 let mut entries = Vec::with_capacity(count / 2);
154 let mut index = 0;
155 while index + 1 < count {
156 if let (Some(label), Some(item)) =
157 (node.slot_content_nodes(index), node.slot_content_nodes(index + 1))
158 {
159 entries.push((label, item));
160 }
161 index += 2;
162 }
163 entries
164}
165
166/// A `flm.pres.cells` node's payload and the content of each of its cells, in
167/// the order of the payload's entries: the slot at index *i* is entry *i*'s.
168///
169/// Returns `None` when the node carries no [`CellsPayload`]. A slot missing
170/// for an entry (a shape a tree built by hand can have, never one the `cells`
171/// feature stages) is returned as `None` in the list, so the list always has
172/// one item per entry.
173pub fn cells_of<'t>(
174 node: &NodeRef<'t, Flm>,
175) -> Option<(&'t CellsPayload, Vec<Option<NodeSlice<'t, Flm>>>)> {
176 let payload = payload_of::<CellsPayload>(node)?;
177 let contents = (0..payload.cells.len()).map(|index| node.slot_content_nodes(index)).collect();
178 Some((payload, contents))
179}
180
181/// The plain text of a run: the characters of every text node among the given
182/// nodes and their descendants, concatenated in document order.
183///
184/// Everything that is not text is left out, with nothing put in its place, so
185/// the result measures the run's characters; it is not a rendering of the
186/// run. An emitter uses it where it needs a width: a heading's underline, the
187/// column at which a list's items start.
188pub fn plain_text<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> String {
189 let mut out = String::new();
190 for node in nodes {
191 if let Some(text) = node.chars() {
192 out.push_str(text);
193 }
194 for child in node.descendants() {
195 if let Some(text) = child.chars() {
196 out.push_str(text);
197 }
198 }
199 }
200 out
201}
202
203/// The characters a run-in heading's title may already end in, in which case a
204/// backend adds no stop of its own: the period, the comma, the colon, the
205/// semicolon, the question mark and the exclamation mark.
206///
207/// The test a backend makes is [`ends_in_sentence_punctuation`], which reads
208/// a run of nodes; this constant is the character set that test uses, for a
209/// caller that already has the text.
210///
211/// # Examples
212///
213/// ```
214/// use flm_core::stdlib::backends::pres::RUN_IN_STOPS;
215///
216/// assert!("Why?".ends_with(RUN_IN_STOPS));
217/// assert!(!"Note".ends_with(RUN_IN_STOPS));
218/// ```
219pub const RUN_IN_STOPS: [char; 6] = ['.', ',', ':', ';', '?', '!'];
220
221/// The stop a backend writes after a run-in heading's title when the render
222/// request sets none: a period. It is the default of the `run_in_stop` render
223/// option of every backend that has this option.
224pub const DEFAULT_RUN_IN_STOP: &str = ".";
225
226/// The heading level a backend writes as its first-level heading when the
227/// render request sets none: 1, the level of a section. It is the default of
228/// the `root_heading_level` render option of every backend that writes a
229/// heading by its level
230/// ([`HtmlRenderOptions::root_heading_level`](crate::stdlib::backends::html::HtmlRenderOptions::root_heading_level),
231/// [`TextRenderOptions::root_heading_level`](crate::stdlib::backends::text::TextRenderOptions::root_heading_level)).
232///
233/// A heading's level is a number counted from zero, the smaller the outer, and
234/// every value is a level ([`HeadingPayload::level`](super::HeadingPayload::level));
235/// the root says which of them a render writes first.
236pub const DEFAULT_ROOT_HEADING_LEVEL: u8 = 1;
237
238/// How deep a heading of level `level` is below the root heading level
239/// `root`: 0 for a heading at the root's level (the first-level heading,
240/// `<h1>` on an HTML page), 1 for one level deeper, and so on. Every backend
241/// that writes a heading by its level computes the depth with this function,
242/// so two outputs of one document cannot disagree about a heading's depth.
243///
244/// # Errors
245///
246/// [`HeadingAboveRoot`] when `level` is less than `root`: such a heading has
247/// no depth below the root. A backend reports it as an Error and writes the
248/// heading at depth 0, the root's level.
249///
250/// # Examples
251///
252/// ```
253/// use flm_core::stdlib::backends::pres::heading_depth;
254///
255/// assert_eq!(heading_depth(1, 1), Ok(0));
256/// assert_eq!(heading_depth(3, 1), Ok(2));
257/// assert_eq!(heading_depth(0, 0), Ok(0));
258/// assert!(heading_depth(0, 1).is_err());
259/// ```
260pub fn heading_depth(level: u8, root: u8) -> Result<u8, HeadingAboveRoot> {
261 level.checked_sub(root).ok_or(HeadingAboveRoot { level, root })
262}
263
264/// Condition `flm.pres.heading-above-root`: a heading's level is less than
265/// the render's root heading level (the `root_heading_level` render option),
266/// so the heading is above the first-level heading the render writes and has
267/// no depth below it ([`heading_depth`]).
268///
269/// Both the HTML backend and the text backend report this one condition, for
270/// every block heading they write; on HTML it is reported regardless of the
271/// tag the render options map the heading's kind to
272/// ([`HtmlRenderOptions::heading_tags`](crate::stdlib::backends::html::HtmlRenderOptions::heading_tags)).
273///
274/// Recovery: the heading is written at the root's level, as a first-level
275/// heading — on the page, a heading whose kind is mapped keeps its mapped tag
276/// — and on the page its attribute `data-flm-level` still says its own level.
277#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
278#[diagnostic(
279 id = "flm.pres.heading-above-root",
280 message = "a heading's level must be at least the root heading level {root} (the render \
281 option `root_heading_level`); this heading's level is {level}"
282)]
283pub struct HeadingAboveRoot {
284 /// The heading's level.
285 pub level: u8,
286 /// The render's root heading level.
287 pub root: u8,
288}
289
290/// Whether the content of a run-in decoration already ends in sentence
291/// punctuation — one of [`RUN_IN_STOPS`] — so that a backend writing such a
292/// decoration should not add a stop of its own.
293///
294/// The test is the run's [`plain_text`], trimmed of trailing whitespace (which
295/// includes a non-breaking space). Every backend that adds a stop asks this one
296/// function, so that two outputs of the same document cannot disagree about
297/// which titles get one.
298///
299/// **This test is a heuristic.** It looks only at the characters the title
300/// ends in, not at what the title's last element is: a title ending in a
301/// formula, or in a box drawn by an author's own command, ends in no
302/// character of the list and gets the stop after it. An extension that needs
303/// headings treated another way registers a lowering rule or a stage of its
304/// own; [the extension guide](crate::guide::extending#lowering-rules)
305/// explains how.
306///
307/// See [`holds_text`], which tests whether there is a title for the stop to
308/// follow at all.
309pub fn ends_in_sentence_punctuation<'t>(
310 nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
311) -> bool {
312 plain_text(nodes).trim_end().ends_with(RUN_IN_STOPS)
313}
314
315/// Whether a run holds text beyond breakable whitespace: its [`plain_text`] has
316/// at least one character that is not a space a line may be broken at
317/// ([`is_breakable_space`]).
318///
319/// A run that fails this test is blank (`\paragraph{}` and `\paragraph{ }`
320/// both reach a backend that way), and a blank run-in title has nothing for a
321/// stop to follow, so no backend writes one after it. Both the text and the
322/// HTML backend call this function, as they call
323/// [`ends_in_sentence_punctuation`], so that they cannot disagree.
324///
325/// A non-breaking space is text the author asked for and not breakable
326/// whitespace, so a title holding one is not blank.
327pub fn holds_text<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> bool {
328 plain_text(nodes).chars().any(|c| !is_breakable_space(c))
329}
330
331/// The source text of a run of nodes, as techy's source recomposer writes it
332/// again from what the nodes recorded of their invocations: byte for byte
333/// for a run parsed from one source. An emitter writes this for an opaque
334/// body: the content of a math node, or a verbatim run holding a construct a
335/// template substituted into it.
336///
337/// The nodes may belong to any tree and come from several sources, and the
338/// result then **means what the nodes mean**: a control word written with
339/// nothing after it, such as `\alpha`, is followed by a space when the next
340/// node's text begins with a letter. For example, a user definition's
341/// template `\alpha#1` used with the argument `x` gives `\alpha x`, where the
342/// two texts put together would make the single command `\alphax`. A run
343/// parsed from one source never holds two such nodes, so its text is
344/// unchanged.
345///
346/// A run techy cannot write again (a tree built by hand whose invocation
347/// records are not coherent) is not an error here: the run's [`plain_text`]
348/// is returned instead.
349///
350/// Call this on a worker thread (see
351/// [`on_worker_thread`](crate::lang::guard::on_worker_thread)): copying the
352/// run and recomposing it are both recursive walks, guarded by the stack that
353/// remains on the thread it runs on, which a worker thread declares. Every
354/// stage of a run already executes on a worker thread, and the text emitter's
355/// entry point ([`emit`](crate::stdlib::backends::text::emit())) creates one
356/// for itself. On a thread that declares no stack, the guard applies techy's
357/// small default budget, and a deeply nested run gives its [`plain_text`].
358pub fn recompose_source(nodes: &[NodeRef<'_, Flm>]) -> String {
359 let Some(first) = nodes.first() else { return String::new() };
360 // The run copied verbatim into a value tree (the language's one copy
361 // helper), then recomposed from the copies' recorded payloads.
362 let copied = match copy_run_into_value(nodes, first, ValueContent::Own, GuardPolicy::StackBudget) {
363 Ok(tree) => tree,
364 Err(_) => return plain_text(nodes.iter().copied()),
365 };
366 match guard::recomposer(&mut Spelling, GuardPolicy::StackBudget).recompose(&copied, ()) {
367 Ok(text) => text.0,
368 Err(_) => plain_text(nodes.iter().copied()),
369 }
370}
371
372/// Source text being put together from the spellings of nodes, which keeps a
373/// control word at its end apart from a letter that follows (see
374/// [`recompose_source`]).
375#[derive(Debug, Clone, Default)]
376struct SourceText(String);
377
378impl From<&str> for SourceText {
379 fn from(text: &str) -> SourceText {
380 SourceText(String::from(text))
381 }
382}
383
384impl From<String> for SourceText {
385 fn from(text: String) -> SourceText {
386 SourceText(text)
387 }
388}
389
390impl ComposePiece for SourceText {
391 fn empty() -> SourceText {
392 SourceText::default()
393 }
394
395 fn append(&mut self, other: SourceText) {
396 if ends_with_control_word(&self.0) && other.0.starts_with(|c: char| c.is_ascii_alphabetic()) {
397 self.0.push(' ');
398 }
399 self.0.push_str(&other.0);
400 }
401}
402
403/// Whether `text` ends with a control word: letters after a backslash that is
404/// not itself escaped. The writer of a formula's TeX
405/// ([`tex`](crate::stdlib::features::math::tex)) keeps its pieces apart by
406/// the same test.
407pub(crate) fn ends_with_control_word(text: &str) -> bool {
408 let head = text.trim_end_matches(|c: char| c.is_ascii_alphabetic());
409 if head.len() == text.len() {
410 return false;
411 }
412 let backslashes = head.len() - head.trim_end_matches('\\').len();
413 backslashes % 2 == 1
414}
415
416/// The recomposer of [`recompose_source`]: each node's recorded spelling, as
417/// techy's own source recomposer writes it, put together as [`SourceText`].
418struct Spelling;
419
420/// The failure of [`Spelling`]: a callable whose invocation record does not
421/// match the form of its callable, which a parse never produces.
422#[derive(Debug)]
423struct IncoherentInvocation;
424
425impl<A> Recomposer<Flm, A> for Spelling {
426 type State = ();
427 type Piece = SourceText;
428 type Error = IncoherentInvocation;
429
430 fn recompose_node(
431 &mut self,
432 node: NodeRef<'_, Flm, A>,
433 _state: &(),
434 _cx: &mut RecomposeContext<'_, Flm, A>,
435 ) -> Result<Recompose<SourceText, ()>, IncoherentInvocation> {
436 if let Some(instruction) = core_source_instruction(node) {
437 return Ok(instruction);
438 }
439 let data = node.callable().ok_or(IncoherentInvocation)?;
440 let source = node.span().source();
441 let name: &str = &data.name;
442 // The invocation as it was written, then the argument regions as
443 // children, as techy's source recomposer writes it.
444 let (head, tail) = match &data.invocation_syntax {
445 InvocationSyntaxData::Macro { escape_char, post_space } if data.callable_type.is_macro() => {
446 (format!("{escape_char}{name}{}", post_space.resolve(source)), String::new())
447 }
448 InvocationSyntaxData::Environment(env) if data.callable_type.is_environment() => {
449 (env.write_begin(name, source), env.write_end(name, source))
450 }
451 InvocationSyntaxData::Specials if data.callable_type.is_specials() => {
452 (String::from(name), String::new())
453 }
454 _ => return Err(IncoherentInvocation),
455 };
456 Ok(Recompose::Concat(
457 ConcatPieces::children().wrap(SourceText(head), SourceText(tail)),
458 ))
459 }
460}
461
462/// The identity of the run written as `nodes` (the top-level nodes of an
463/// argument), computed from its source text: each node's own source text, in
464/// order, with comments left out, every run of whitespace ([the whitespace of
465/// FLM text](crate::lang::text#whitespace)) made one space and the ends
466/// trimmed. The result is the empty text when the run is empty or holds only
467/// whitespace. Two runs written alike (the same text and the same
468/// markup, however the whitespace is laid out) have the same identity; case
469/// and markup count.
470///
471/// This is the only function that decides whether two written runs are the
472/// same. It computes a term's identity, which a term definition, its aliases
473/// and a term link use ([the identity of a
474/// term](crate::stdlib::features::defterm::elements#the-identity-of-a-term));
475/// whether two citation notes are one note
476/// ([`stage_mark`](crate::stdlib::features::citations::stage_mark)); and a
477/// citation key, each part of a `\cite`'s keys between two commas
478/// ([`read_chunk`](crate::stdlib::features::citations::read_chunk)).
479///
480/// Call this on a worker thread, as every stage and every lowering rule runs:
481/// writing the nodes' source text again is a recursive walk guarded by a
482/// budget sized for such a thread ([`recompose_source`]).
483///
484/// # Examples
485///
486/// ```
487/// use std::sync::Arc;
488/// use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
489/// use flm_core::lang::{parse_fragment, FlmOrigin, FlmSource, ParseOptions};
490/// use flm_core::model::doc::FragmentLayout;
491/// use flm_core::stdlib::{self, StdlibConfig};
492/// use flm_core::stdlib::backends::pres::spelling_identity;
493///
494/// let mut builder = RegistryBuilder::new();
495/// builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
496/// builder.use_package(flm_core::math_passthrough::package());
497/// let registry = builder.build(&RegistryInputs::new())?;
498/// let source = FlmSource::new("See \\term{\\emph{Markov}\n chain}.");
499/// let fragment = parse_fragment(
500/// registry.lang(),
501/// Arc::new(source.with_origin(FlmOrigin::none())),
502/// FragmentLayout::default(),
503/// &ParseOptions::default(),
504/// )?;
505/// let link = fragment.tree().root().descendants()
506/// .find(|node| node.name() == Some("term"))
507/// .expect("the term link");
508/// let shown = link.argument_content_nodes_named("shown")?.expect("written");
509/// assert_eq!(spelling_identity(shown.iter()), "\\emph{Markov} chain");
510/// # Ok::<(), Box<dyn std::error::Error>>(())
511/// ```
512pub fn spelling_identity<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> String {
513 let nodes: Vec<NodeRef<'t, Flm>> = nodes.into_iter().filter(|node| !node.is_comment()).collect();
514 // Each node re-emitted from what it records of its own spelling, never its
515 // span or a slice of a source: a node's span is not its spelling once two
516 // text nodes are merged, and a term from a template spans two sources.
517 collapse_whitespace(&recompose_source(&nodes))
518}
519
520/// Whether the slot at `index` is the node's body slot: the content slot an
521/// emitter treats as the node's content ([`BODY_SLOT`](super::BODY_SLOT) on
522/// every element of the vocabulary that has one).
523pub fn is_body_slot(node: &NodeRef<'_, Flm>, index: usize) -> bool {
524 node.slots().and_then(|slots| slots.get(index)).is_some_and(|slot| slot.ext.is_body())
525}