Skip to main content

flm_core/stdlib/backends/lowering/
pointer.rs

1//! Content pointers: synthesized nodes that show content written elsewhere in
2//! the tree, without copying it.
3//!
4//! A **content pointer** ([`ContentPointer`]) is the payload of a synthesized
5//! node that shows, where the node is placed, content written elsewhere in
6//! the tree (an xnote's content in the list of xnotes, a term in its
7//! definition's lead-in, a theorem's title) without copying it: the address of
8//! the node the content belongs to, and the node region of that node that
9//! holds it (one of its arguments or slots; [`NodeRegion`]). See [content
10//! pointers](crate::guide::concepts_overview#content-pointers).
11//!
12//! A feature that needs one builds a node of an element of its own carrying a
13//! `ContentPointer`, and that element's lowering rule calls
14//! [`lower_content_pointer`]. The function lowers the pointed region where the
15//! pointer is placed, through [`Lowerer::lower_region`], as content of the
16//! tree that holds it: a numbered list inside it is numbered as the document
17//! numbered it, a labeled equation is an ordinary labeled reference point.
18//! The content is lowered once, where the pointer is placed, provided the
19//! feature lowers that region nowhere else.
20//!
21//! The feature that owns the pointer's element supplies a check
22//! ([`PointerCheck`]) that the node a pointer refers to is one whose region
23//! that element may show, because content shown both through a pointer and in
24//! its own place would appear twice. Where the check fails, it reports a
25//! condition of the feature's own.
26
27use techy::core::node::{BuildId, NodeRef};
28use techy::serialize::SerialValue;
29
30use crate::core::lowering::{LowerCx, LowerError, Lowerer, NodeRegion, RegionShape};
31use crate::lang::{Flm, PresPayload};
32use crate::model::addr::NodeAddr;
33
34use super::error::RegionNotFound;
35
36/// The payload of a content pointer: the node some content belongs to, and
37/// the node region of that node that holds the content, which the pointer
38/// shows where it is placed. A feature's own synthesized element carries it
39/// (see the [module documentation](self)).
40///
41/// The node is identified by its address, which is valid only within the
42/// run that built the pointer: the address of a node of a document tree, or
43/// of a node of a synthesized value the lowering holds (see
44/// [`Lowerer::lower_region`]). A pointer stored in a table must refer to a
45/// node of a document tree: a synthesized value's identifier is valid only
46/// inside the stage call that brought the value up to date, and the runner
47/// adds a table to the run's store after that call has ended.
48///
49/// Its projection is `{target: "<tree>/<node index>", region: "argument
50/// <i>"}` (or `"slot <i>"`). No payload reader is registered for it, so a
51/// tree holding a pointer can be printed but not read back.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct ContentPointer {
54    /// The address of the node the content belongs to.
55    pub target: NodeAddr,
56    /// The node region of that node that holds the content.
57    pub region: NodeRegion,
58}
59
60impl PresPayload for ContentPointer {
61    fn project(&self) -> SerialValue {
62        SerialValue::Map(vec![
63            (
64                String::from("target"),
65                SerialValue::Str(format!("{}/{}", self.target.tree, self.target.node.index())),
66            ),
67            (String::from("region"), SerialValue::Str(self.region.to_string())),
68        ])
69    }
70}
71
72impl ContentPointer {
73    /// The payload of the content pointer `node`, or `None` for a node that
74    /// carries none.
75    pub fn of<'n>(node: &'n NodeRef<'_, Flm>) -> Option<&'n ContentPointer> {
76        node.ext().payload.as_deref()?.downcast_ref::<ContentPointer>()
77    }
78}
79
80/// The check a feature supplies to [`lower_content_pointer`]. It receives the
81/// [`Lowerer`], the node a pointer refers to and the node region the pointer
82/// gives, and returns whether the pointer's element may show that region of
83/// that node. When it returns `false`, it must already have reported the
84/// refusal (a condition of the feature's own, at the pointer); the pointer
85/// then writes nothing.
86///
87/// # Errors
88///
89/// A [`LowerError`] the check returns ends the pointer's lowering with that
90/// error, for example a table read the calling rule did not declare.
91pub type PointerCheck<'f> =
92    dyn FnMut(&mut dyn Lowerer, &NodeRef<'_, Flm>, NodeRegion) -> Result<bool, LowerError> + 'f;
93
94/// Lowers the content that the node `pointer` refers to through its
95/// [`ContentPointer`] payload, where `pointer` is placed. Every lowering rule
96/// of an element whose nodes carry a content pointer calls this function.
97///
98/// The function looks up, through [`Lowerer::lower_region`], the node and
99/// the region the pointer refers to, and calls `check` with them; if `check`
100/// refuses them, the pointer writes nothing. Otherwise the region's content
101/// is lowered and arranged by `shape` ([`RegionShape`]; the plain shape is
102/// [`lower_region_content`](super::lower_region_content)), and the staged
103/// nodes are returned.
104///
105/// A pointer to a node the lowering cannot reach, or to a region that node
106/// does not have, is reported at the pointer as
107/// `flm.lowering.region-not-found` ([`RegionNotFound`], with the pointer's
108/// element) and writes nothing either; the content around the pointer is
109/// still written.
110///
111/// # Errors
112///
113/// [`LowerError`] when `pointer` carries no [`ContentPointer`], and any error
114/// `check` or `shape` returns.
115pub fn lower_content_pointer(
116    cx: &mut LowerCx<'_>,
117    lw: &mut dyn Lowerer,
118    pointer: &NodeRef<'_, Flm>,
119    check: &mut PointerCheck<'_>,
120    shape: &mut RegionShape<'_>,
121) -> Result<Vec<BuildId>, LowerError> {
122    let named = ContentPointer::of(pointer)
123        .cloned()
124        .ok_or_else(|| {
125            LowerError::structure("missing ‘ContentPointer’ payload on the node")
126        })?;
127    let lowered = lw.lower_region(cx, named.target, named.region, &mut |cx, lw, node, content| {
128        if !check(lw, node, named.region)? {
129            return Ok(Vec::new());
130        }
131        shape(cx, lw, node, content)
132    });
133    match lowered {
134        Err(LowerError::RegionNotFound { detail }) => {
135            let condition = RegionNotFound {
136                backend: lw.backend().to_string(),
137                rule: lw.rule().to_string(),
138                element: pointer.ext().element.name.to_string(),
139                detail,
140            };
141            lw.error(condition, pointer.span().clone());
142            Ok(Vec::new())
143        }
144        other => other,
145    }
146}