Skip to main content

flm_core/stdlib/backends/text/
construct.rs

1//! The text construct elements: content set at the right edge of its line,
2//! and a run of blocks set between rule lines, as nodes in the lowered tree.
3//!
4//! A construct element is a presentation element that mirrors one construct
5//! of an output format, so that format-specific output is structured data in
6//! the lowered tree rather than a string (see [backends, lowering, and
7//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)).
8//! Plain text has two constructs that the shared presentation vocabulary
9//! cannot express, since they depend on the width of the printed lines: a
10//! part of a line pushed to the right edge, such as an equation's number, and
11//! rule lines as wide as the content they enclose, such as the rules above
12//! and under a document's title. This module holds the two elements that
13//! mirror them, with their payloads:
14//!
15//! | element | payload | slots | printed as |
16//! |---|---|---|---|
17//! | [`FLUSH_RIGHT`] (`flm.pres.text.flush-right`) | [`FlushRightPayload`]: no data | one [`BODY_SLOT`](crate::stdlib::backends::pres::BODY_SLOT), inline content | its content on one line, ending at the last column of the line width where it fits there, otherwise [`FLUSH_RIGHT_GAP`] columns after what precedes it |
18//! | [`RULED`] (`flm.pres.text.ruled`) | [`RuledPayload`]: whether a rule line stands above the body, and whether one stands under it | one [`BODY_SLOT`](crate::stdlib::backends::pres::BODY_SLOT), a run of blocks | its body on lines of its own, between rule lines as wide as the widest printed line of the body |
19//!
20//! The [text emitter](mod@super::emit) prints them with the layout engine's
21//! constructors [`DocBuf::flush_right`](crate::layout::DocBuf::flush_right)
22//! and [`DocBuf::ruled`](crate::layout::DocBuf::ruled); its module
23//! documentation states what each prints in full.
24//!
25//! The `text` feature ([`super::TextBackend`]), which registers the text
26//! backend, registers both elements through [`register`], and the text
27//! backend writes them natively ([`native_elements`](super::native_elements)).
28//! They are **not** part of the shared presentation vocabulary
29//! ([`ALL`](crate::stdlib::backends::pres::ALL)): a backend that is not the
30//! text backend cannot write them, and a lowering rule that stages one (builds
31//! a node of it into the lowered tree; see
32//! [`Lowerer`](crate::core::lowering::Lowerer)) is a rule for the text
33//! backend. A feature that stages one without registering the `text` feature
34//! itself declares it through a peer declaration
35//! ([`PeerName`](crate::core::registry::PeerName),
36//! [`FeatureBuilder::peer_element`](crate::core::registry::FeatureBuilder::peer_element)).
37//!
38//! # Projections
39//!
40//! Each payload implements [`PresPayload`] with a self-contained projection
41//! (the value written when a lowered tree is serialized,
42//! [`crate::dump::session`]) and has a registered reader that rebuilds the
43//! payload from it ([`payload_readers`]). The projections are: `flush-right`:
44//! `{}`; `ruled`: `{above, below}`, two booleans, an absent or null key read
45//! as `false`.
46
47use std::sync::Arc;
48
49use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};
50
51use crate::core::registry::{BuildError, FeatureBuilder};
52use crate::dump::session::PayloadReaders;
53use crate::lang::{Flm, PresPayload};
54use crate::stdlib::backends::pres::payload::{bad, entries, field, map};
55
56/// `flm.pres.text.flush-right` — inline content set at the right edge of its
57/// line.
58pub const FLUSH_RIGHT: &str = "flm.pres.text.flush-right";
59
60/// `flm.pres.text.ruled` — a run of blocks set between rule lines as wide as
61/// its widest printed line.
62pub const RULED: &str = "flm.pres.text.ruled";
63
64/// The two construct elements of the text backend, in the order of the
65/// module documentation's table.
66pub const ALL: [&str; 2] = [FLUSH_RIGHT, RULED];
67
68/// The columns between the content of a [`FLUSH_RIGHT`] node and what
69/// precedes it on its line, where the content does not fit at the right edge
70/// of the line or the line has no width: four.
71pub const FLUSH_RIGHT_GAP: u16 = 4;
72
73/// The payload of `flm.pres.text.flush-right`: it holds no data. The node's
74/// content, in its body slot, is what is set at the right edge.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
76pub struct FlushRightPayload;
77
78impl FlushRightPayload {
79    /// Rebuilds the payload from its projection, the value
80    /// [`project`](PresPayload::project) produced.
81    ///
82    /// # Errors
83    ///
84    /// Returns a [`DeserializeError`] that identifies
85    /// `flm.pres.text.flush-right` when the projection is not a map.
86    pub fn from_projection(value: &SerialValue) -> Result<FlushRightPayload, DeserializeError> {
87        entries(FLUSH_RIGHT, value)?;
88        Ok(FlushRightPayload)
89    }
90}
91
92impl PresPayload for FlushRightPayload {
93    fn project(&self) -> SerialValue {
94        map(Vec::new())
95    }
96}
97
98/// The payload of `flm.pres.text.ruled`: where the rule lines stand around
99/// the node's body.
100///
101/// Each rule line is the character of a heading at the root level
102/// ([`TextRenderOptions::heading_rules`](super::TextRenderOptions::heading_rules))
103/// repeated to the width of the widest line the body prints; a node with
104/// neither rule prints its body alone.
105///
106/// # Examples
107///
108/// ```
109/// use flm_core::lang::PresPayload;
110/// use flm_core::stdlib::backends::text::construct::RuledPayload;
111///
112/// let both = RuledPayload { above: true, below: true };
113/// assert_eq!(RuledPayload::from_projection(&both.project()).unwrap(), both);
114/// ```
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
116pub struct RuledPayload {
117    /// Whether a rule line stands above the body.
118    pub above: bool,
119    /// Whether a rule line stands under the body.
120    pub below: bool,
121}
122
123impl RuledPayload {
124    /// Rebuilds the payload from its projection, the value
125    /// [`project`](PresPayload::project) produced.
126    ///
127    /// # Errors
128    ///
129    /// Returns a [`DeserializeError`] that identifies `flm.pres.text.ruled`
130    /// when the projection is not a map, or when `above` or `below` is
131    /// present and is neither a boolean nor null.
132    pub fn from_projection(value: &SerialValue) -> Result<RuledPayload, DeserializeError> {
133        let e = entries(RULED, value)?;
134        let flag = |key: &str| match field(e, key) {
135            None | Some(SerialValue::Null) => Ok(false),
136            Some(SerialValue::Bool(value)) => Ok(*value),
137            Some(other) => Err(bad(RULED, format!("`{key}` must be a boolean, found {other:?}"))),
138        };
139        Ok(RuledPayload { above: flag("above")?, below: flag("below")? })
140    }
141}
142
143impl PresPayload for RuledPayload {
144    fn project(&self) -> SerialValue {
145        map(vec![("above", SerialValue::Bool(self.above)), ("below", SerialValue::Bool(self.below))])
146    }
147}
148
149/// Returns the payload readers of the two construct elements: what a reading
150/// session ([`reader_with`](crate::dump::session::reader_with)) needs, beside
151/// the shared vocabulary's own
152/// ([`payload_readers`](crate::stdlib::backends::pres::payload_readers)), to
153/// read a stored lowered tree of the text backend back into typed payloads.
154///
155/// # Examples
156///
157/// ```
158/// use flm_core::stdlib::backends::text::construct::{ALL, payload_readers};
159///
160/// let readers = payload_readers();
161/// assert_eq!(readers.len(), ALL.len());
162/// assert!(ALL.iter().all(|name| readers.elements().any(|element| element.as_str() == *name)));
163/// ```
164pub fn payload_readers() -> PayloadReaders {
165    let mut readers = PayloadReaders::new();
166    readers.register(FLUSH_RIGHT, |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
167        FlushRightPayload::from_projection(value)
168            .map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
169    });
170    readers.register(RULED, |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
171        RuledPayload::from_projection(value).map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
172    });
173    readers
174}
175
176/// Registers the construct elements `flm.pres.text.flush-right` and
177/// `flm.pres.text.ruled` with their payload types. The `text` feature
178/// ([`super::TextBackend`]) calls this from its own registration; a second
179/// registration in one registry declares the elements twice and fails the
180/// build.
181///
182/// # Errors
183///
184/// Returns the [`BuildError`] the feature builder raises for a presentation
185/// element already declared in this registry.
186pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
187    b.presentation_element::<FlushRightPayload>(
188        FLUSH_RIGHT,
189        "inline content set at the right edge of its line on the text output",
190    )?;
191    b.presentation_element::<RuledPayload>(
192        RULED,
193        "a run of blocks between rule lines as wide as its widest line on the text output",
194    )?;
195    Ok(())
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn an_absent_rule_reads_as_none() {
204        let read = RuledPayload::from_projection(&map(vec![("below", SerialValue::Bool(true))]));
205        assert_eq!(read.expect("reads"), RuledPayload { above: false, below: true });
206    }
207
208    #[test]
209    fn a_projection_that_is_not_one_is_refused() {
210        assert!(FlushRightPayload::from_projection(&SerialValue::Null).is_err());
211        assert!(RuledPayload::from_projection(&SerialValue::Int(1)).is_err());
212        let wrong = map(vec![("above", SerialValue::Str(String::from("yes")))]);
213        assert!(RuledPayload::from_projection(&wrong).is_err());
214    }
215}