flm-core 0.7.0

FLM semantic markup framework — core library, built on techy
Documentation
//! The text construct elements: content set at the right edge of its line,
//! and a run of blocks set between rule lines, as nodes in the lowered tree.
//!
//! A construct element is a presentation element that mirrors one construct
//! of an output format, so that format-specific output is structured data in
//! the lowered tree rather than a string (see [backends, lowering, and
//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)).
//! Plain text has two constructs that the shared presentation vocabulary
//! cannot express, since they depend on the width of the printed lines: a
//! part of a line pushed to the right edge, such as an equation's number, and
//! rule lines as wide as the content they enclose, such as the rules above
//! and under a document's title. This module holds the two elements that
//! mirror them, with their payloads:
//!
//! | element | payload | slots | printed as |
//! |---|---|---|---|
//! | [`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 |
//! | [`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 |
//!
//! The [text emitter](mod@super::emit) prints them with the layout engine's
//! constructors [`DocBuf::flush_right`](crate::layout::DocBuf::flush_right)
//! and [`DocBuf::ruled`](crate::layout::DocBuf::ruled); its module
//! documentation states what each prints in full.
//!
//! The `text` feature ([`super::TextBackend`]), which registers the text
//! backend, registers both elements through [`register`], and the text
//! backend writes them natively ([`native_elements`](super::native_elements)).
//! They are **not** part of the shared presentation vocabulary
//! ([`ALL`](crate::stdlib::backends::pres::ALL)): a backend that is not the
//! text backend cannot write them, and a lowering rule that stages one (builds
//! a node of it into the lowered tree; see
//! [`Lowerer`](crate::core::lowering::Lowerer)) is a rule for the text
//! backend. A feature that stages one without registering the `text` feature
//! itself declares it through a peer declaration
//! ([`PeerName`](crate::core::registry::PeerName),
//! [`FeatureBuilder::peer_element`](crate::core::registry::FeatureBuilder::peer_element)).
//!
//! # Projections
//!
//! Each payload implements [`PresPayload`] with a self-contained projection
//! (the value written when a lowered tree is serialized,
//! [`crate::dump::session`]) and has a registered reader that rebuilds the
//! payload from it ([`payload_readers`]). The projections are: `flush-right`:
//! `{}`; `ruled`: `{above, below}`, two booleans, an absent or null key read
//! as `false`.

use std::sync::Arc;

use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};

use crate::core::registry::{BuildError, FeatureBuilder};
use crate::dump::session::PayloadReaders;
use crate::lang::{Flm, PresPayload};
use crate::stdlib::backends::pres::payload::{bad, entries, field, map};

/// `flm.pres.text.flush-right` — inline content set at the right edge of its
/// line.
pub const FLUSH_RIGHT: &str = "flm.pres.text.flush-right";

/// `flm.pres.text.ruled` — a run of blocks set between rule lines as wide as
/// its widest printed line.
pub const RULED: &str = "flm.pres.text.ruled";

/// The two construct elements of the text backend, in the order of the
/// module documentation's table.
pub const ALL: [&str; 2] = [FLUSH_RIGHT, RULED];

/// The columns between the content of a [`FLUSH_RIGHT`] node and what
/// precedes it on its line, where the content does not fit at the right edge
/// of the line or the line has no width: four.
pub const FLUSH_RIGHT_GAP: u16 = 4;

/// The payload of `flm.pres.text.flush-right`: it holds no data. The node's
/// content, in its body slot, is what is set at the right edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FlushRightPayload;

impl FlushRightPayload {
    /// Rebuilds the payload from its projection, the value
    /// [`project`](PresPayload::project) produced.
    ///
    /// # Errors
    ///
    /// Returns a [`DeserializeError`] that identifies
    /// `flm.pres.text.flush-right` when the projection is not a map.
    pub fn from_projection(value: &SerialValue) -> Result<FlushRightPayload, DeserializeError> {
        entries(FLUSH_RIGHT, value)?;
        Ok(FlushRightPayload)
    }
}

impl PresPayload for FlushRightPayload {
    fn project(&self) -> SerialValue {
        map(Vec::new())
    }
}

/// The payload of `flm.pres.text.ruled`: where the rule lines stand around
/// the node's body.
///
/// Each rule line is the character of a heading at the root level
/// ([`TextRenderOptions::heading_rules`](super::TextRenderOptions::heading_rules))
/// repeated to the width of the widest line the body prints; a node with
/// neither rule prints its body alone.
///
/// # Examples
///
/// ```
/// use flm_core::lang::PresPayload;
/// use flm_core::stdlib::backends::text::construct::RuledPayload;
///
/// let both = RuledPayload { above: true, below: true };
/// assert_eq!(RuledPayload::from_projection(&both.project()).unwrap(), both);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RuledPayload {
    /// Whether a rule line stands above the body.
    pub above: bool,
    /// Whether a rule line stands under the body.
    pub below: bool,
}

impl RuledPayload {
    /// Rebuilds the payload from its projection, the value
    /// [`project`](PresPayload::project) produced.
    ///
    /// # Errors
    ///
    /// Returns a [`DeserializeError`] that identifies `flm.pres.text.ruled`
    /// when the projection is not a map, or when `above` or `below` is
    /// present and is neither a boolean nor null.
    pub fn from_projection(value: &SerialValue) -> Result<RuledPayload, DeserializeError> {
        let e = entries(RULED, value)?;
        let flag = |key: &str| match field(e, key) {
            None | Some(SerialValue::Null) => Ok(false),
            Some(SerialValue::Bool(value)) => Ok(*value),
            Some(other) => Err(bad(RULED, format!("`{key}` must be a boolean, found {other:?}"))),
        };
        Ok(RuledPayload { above: flag("above")?, below: flag("below")? })
    }
}

impl PresPayload for RuledPayload {
    fn project(&self) -> SerialValue {
        map(vec![("above", SerialValue::Bool(self.above)), ("below", SerialValue::Bool(self.below))])
    }
}

/// Returns the payload readers of the two construct elements: what a reading
/// session ([`reader_with`](crate::dump::session::reader_with)) needs, beside
/// the shared vocabulary's own
/// ([`payload_readers`](crate::stdlib::backends::pres::payload_readers)), to
/// read a stored lowered tree of the text backend back into typed payloads.
///
/// # Examples
///
/// ```
/// use flm_core::stdlib::backends::text::construct::{ALL, payload_readers};
///
/// let readers = payload_readers();
/// assert_eq!(readers.len(), ALL.len());
/// assert!(ALL.iter().all(|name| readers.elements().any(|element| element.as_str() == *name)));
/// ```
pub fn payload_readers() -> PayloadReaders {
    let mut readers = PayloadReaders::new();
    readers.register(FLUSH_RIGHT, |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
        FlushRightPayload::from_projection(value)
            .map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
    });
    readers.register(RULED, |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
        RuledPayload::from_projection(value).map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
    });
    readers
}

/// Registers the construct elements `flm.pres.text.flush-right` and
/// `flm.pres.text.ruled` with their payload types. The `text` feature
/// ([`super::TextBackend`]) calls this from its own registration; a second
/// registration in one registry declares the elements twice and fails the
/// build.
///
/// # Errors
///
/// Returns the [`BuildError`] the feature builder raises for a presentation
/// element already declared in this registry.
pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
    b.presentation_element::<FlushRightPayload>(
        FLUSH_RIGHT,
        "inline content set at the right edge of its line on the text output",
    )?;
    b.presentation_element::<RuledPayload>(
        RULED,
        "a run of blocks between rule lines as wide as its widest line on the text output",
    )?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_absent_rule_reads_as_none() {
        let read = RuledPayload::from_projection(&map(vec![("below", SerialValue::Bool(true))]));
        assert_eq!(read.expect("reads"), RuledPayload { above: false, below: true });
    }

    #[test]
    fn a_projection_that_is_not_one_is_refused() {
        assert!(FlushRightPayload::from_projection(&SerialValue::Null).is_err());
        assert!(RuledPayload::from_projection(&SerialValue::Int(1)).is_err());
        let wrong = map(vec![("above", SerialValue::Str(String::from("yes")))]);
        assert!(RuledPayload::from_projection(&wrong).is_err());
    }
}