Skip to main content

flm_core/stdlib/features/defterm/
lead_in.rs

1//! The lead-in of a term definition: the configured lead-in template
2//! ([`DeftermConfig::lead_in`](super::DeftermConfig::lead_in)), compiled once
3//! when the registry is built and written at every term definition as a
4//! run-in decoration of its first paragraph; and the term pointer, the
5//! synthesized node that shows the term inside the lead-in.
6//!
7//! # The template and the term pointer
8//!
9//! A build hook ([`LateInit`]) compiles the template once the language is
10//! built. The registry build fails, with a message that quotes the template,
11//! on a template that does not parse, that uses a placeholder other than
12//! `#{term}`, that writes it with keys in brackets (`#[…]{term}`), that uses
13//! it more than once, or that is blank.
14//!
15//! At a term definition, the term definition's rule instantiates the
16//! template. Its `#{term}` is replaced by one node of the element
17//! [`TERM_POINTER`], whose payload is a [`ContentPointer`] to the term
18//! definition's node and the region of its term argument; the rest of
19//! the template is ordinary content. The instance is lowered where the
20//! lead-in is placed, and the pointer's rule ([`PointerRule`]) lowers the
21//! term there, through [`lower_content_pointer`]: the term is shown where it
22//! was written, as the document's own content, and never copied. The term is
23//! lowered there and nowhere else, because the term definition's rule lowers
24//! its term argument through the lead-in alone; a template therefore may use
25//! `#{term}` at most once.
26//!
27//! The pointer is checked where it is lowered: a pointer to anything but a
28//! term definition's term argument is reported as [`PointerRefused`].
29//!
30//! The element is synthesized: no source text produces it, so an author
31//! cannot write it.
32
33use std::fmt;
34use std::sync::{Arc, OnceLock};
35
36use techy::core::node::{BuildId, NodeRef, NodeTree};
37
38use crate::core::lowering::{
39    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
40    NodeRegion,
41};
42use crate::core::registry::{LateInit, LateInitError};
43use crate::lang::copy::{SynthesizedPiece, ValueContent, ValuePiece, copy_pieces_into_value};
44use crate::lang::guard::GuardPolicy;
45use crate::lang::mint::FlmSynthesizedSpec;
46use crate::lang::rewrites::userdefs::template::{
47    CompiledTemplate, PlaceholderVocabulary, TemplateLanguage,
48};
49use crate::lang::{BuiltLang, Flm, FlmDiagnostics};
50use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
51use crate::model::element::{ElementSpec, element_value};
52use crate::model::names::{ElementName, Name};
53use crate::stdlib::backends::lowering::{
54    ContentPointer, lower_content_pointer, lower_region_content,
55};
56use crate::stdlib::backends::pres::{self, DecorationPayload, SpanPayload};
57use crate::stdlib::features::numbering::{
58    Binding, Bindings, StyleError, compile_text, instantiate_template, occurrences_of,
59};
60
61use super::diagnostics::PointerRefused;
62use super::elements::{DeftermElement, TERM_ARG};
63
64/// The only placeholder name of the lead-in template, `term`: `#{term}` is
65/// the term being defined, as the term definition writes it.
66pub const TERM_PLACEHOLDER: &str = "term";
67
68/// The element of the node that replaces `#{term}` in an instantiated
69/// lead-in, `flm.defterm.term-pointer`: synthesized, never written in a
70/// document; its payload is a [`ContentPointer`] to the term ([`PointerRule`]).
71pub const TERM_POINTER: &str = "flm.defterm.term-pointer";
72
73/// The name of the general lowering rule of [`TERM_POINTER`],
74/// `flm.defterm.term-pointer.lower.default` ([`PointerRule`]), the default on
75/// every backend.
76pub const POINTER_RULE: &str = "flm.defterm.term-pointer.lower.default";
77
78/// The role of the span that holds a term definition's lead-in inside its
79/// run-in decoration, `flm.defterm.leadin`.
80pub const LEAD_IN_ROLE: &str = "flm.defterm.leadin";
81
82/// The name of the body slot of a pointer node, which holds nothing.
83const BODY_SLOT: &str = "body";
84
85/// The element value of [`TERM_POINTER`]: inline content, with no aspect but
86/// its block role.
87pub(super) fn pointer_element() -> Arc<ElementSpec> {
88    Arc::new(
89        ElementSpec::new(TERM_POINTER)
90            .docs(
91                "The term of a term definition, shown where a lead-in template places \
92                 `#{term}`; synthesized, never written in a document.",
93            )
94            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT))),
95    )
96}
97
98// --- the template ----------------------------------------------------------------------------
99
100/// What the feature shares between its registration, its build hook and the
101/// term definition's rules: the lead-in as configured, the element of the
102/// pointer node, and the compiled template once the hook has run.
103pub(super) struct LeadIn {
104    declared: Option<String>,
105    spec: Arc<FlmSynthesizedSpec>,
106    compiled: OnceLock<CompiledTemplate>,
107}
108
109impl fmt::Debug for LeadIn {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        f.debug_struct("LeadIn").field("declared", &self.declared).finish_non_exhaustive()
112    }
113}
114
115impl LeadIn {
116    /// The lead-in `declared` — the template, or `None` for no lead-in —
117    /// with the pointer node carrying `element`.
118    pub(super) fn new(declared: Option<String>, element: Arc<ElementSpec>) -> LeadIn {
119        LeadIn {
120            declared,
121            spec: Arc::new(FlmSynthesizedSpec::new(element)),
122            compiled: OnceLock::new(),
123        }
124    }
125
126    /// Whether a lead-in is configured at all.
127    pub(super) fn is_set(&self) -> bool {
128        self.declared.is_some()
129    }
130}
131
132/// Compiles `text`, the configured lead-in.
133///
134/// # Errors
135///
136/// A sentence that quotes the template and says what is wrong with it.
137fn compile_lead_in(
138    text: &str,
139    lang: &BuiltLang,
140    language: &TemplateLanguage,
141) -> Result<CompiledTemplate, String> {
142    let refused = |detail: String| {
143        format!("the option `lead_in` of the feature `defterm` is set to `{text}`, which {detail}")
144    };
145    if text.trim().is_empty() {
146        return Err(refused(String::from(
147            "is blank; leave `lead_in` unset to give term definitions no lead-in",
148        )));
149    }
150    let vocabulary = PlaceholderVocabulary::new(0).extra(TERM_PLACEHOLDER, false);
151    let template = compile_text(text, "the defterm feature's lead-in", &vocabulary, lang, language)
152        .map_err(|error| refused(format!("is not valid FLM text: {}", describe(&error))))?;
153    if occurrences_of(&template).len() > 1 {
154        return Err(refused(format!(
155            "uses `#{{{TERM_PLACEHOLDER}}}` more than once, and it may use it at most once"
156        )));
157    }
158    Ok(template)
159}
160
161/// What `error` reports, as one sentence: the diagnostics of a template that
162/// did not compile, one after the other.
163fn describe(error: &StyleError) -> String {
164    match error {
165        StyleError::Template { diagnostics, .. } | StyleError::Parse { diagnostics, .. } => {
166            diagnostics.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
167        }
168        other => other.to_string(),
169    }
170}
171
172/// The feature's build hook ([`LateInit`]): it compiles the configured
173/// lead-in once the language is built. A template that does not compile
174/// fails the registry build: it is configuration, and a mistake in it is
175/// reported once rather than at every term definition. Nothing is compiled
176/// where no lead-in is configured.
177pub(super) struct CompileLeadIn {
178    pub(super) lead_in: Arc<LeadIn>,
179}
180
181impl LateInit for CompileLeadIn {
182    fn late_init(&self, lang: &BuiltLang, _diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
183        let Some(text) = &self.lead_in.declared else { return Ok(()) };
184        let language = TemplateLanguage::new(lang).map_err(|errors| {
185            LateInitError::new(format!(
186                "the template language of the defterm feature: {}",
187                errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
188            ))
189        })?;
190        let template = compile_lead_in(text, lang, &language).map_err(LateInitError::new)?;
191        // The hook runs once per registration of the feature, and a registry
192        // holds the feature once, so the cell is empty here.
193        let _ = self.lead_in.compiled.set(template);
194        Ok(())
195    }
196}
197
198// --- writing ---------------------------------------------------------------------------------
199
200/// The lead-in's instance at the term definition `node`, the node being
201/// lowered: the compiled template with its `#{term}` replaced by a term
202/// pointer to the term definition's term argument, as a synthesized value
203/// ready to be spliced ([`Lowerer::splice`]); `None` where no lead-in is
204/// configured.
205///
206/// Every backend instantiates the lead-in through this function:
207/// [`stage_lead_in`] lowers the instance where a term definition's first
208/// paragraph opens, and the recomposed LaTeX lowers it as the begin code of
209/// the environment's LaTeX definition, where the pointer's rule on that
210/// backend writes the environment's parameter ([`latex`](super::latex)).
211///
212/// # Errors
213///
214/// [`LowerError`] when the template was not compiled — the hook did not run —
215/// or when the instance could not be built.
216pub(super) fn lead_in_instance(
217    lead_in: &LeadIn,
218    node: &NodeRef<'_, Flm>,
219    lw: &dyn Lowerer,
220) -> Result<Option<Arc<NodeTree<Flm>>>, LowerError> {
221    if !lead_in.is_set() {
222        return Ok(None);
223    }
224    let template = lead_in
225        .compiled
226        .get()
227        .ok_or_else(|| LowerError::other("the lead-in of the defterm feature was not compiled"))?;
228    let region = NodeRegion::argument_named(node, TERM_ARG)
229        .ok_or_else(|| LowerError::structure("a definition without its term argument"))?;
230    let pointer = SynthesizedPiece {
231        spec: Arc::clone(&lead_in.spec),
232        slot: BODY_SLOT,
233        span: node.span().clone(),
234        state: Arc::clone(node.parsing_state()),
235        body: Vec::new(),
236        payload: Some(Arc::new(ContentPointer { target: lw.addr(), region })),
237    };
238    let term = copy_pieces_into_value(&[ValuePiece::Synthesized(&pointer)], node, ValueContent::Own, GuardPolicy::StackBudget)
239        .map_err(|error| LowerError::other(error.to_string()))?;
240    let bindings = Bindings::new(vec![Binding {
241        name: TERM_PLACEHOLDER.to_string(),
242        keys: String::new(),
243        content: term,
244    }]);
245    instantiate_template(node.span(), template, &bindings)
246        .map(Some)
247        .map_err(|error| LowerError::other(error.to_string()))
248}
249
250/// The lead-in of the term definition `node`, the node being lowered: its
251/// instance ([`lead_in_instance`]) lowered where the lead-in is placed, in a
252/// span of role [`LEAD_IN_ROLE`] inside a
253/// [`flm.pres.deco.runin`](crate::stdlib::backends::pres::DECO_RUNIN)
254/// decoration; nothing where no lead-in is configured.
255///
256/// The calling rule places the decoration at the start of the term
257/// definition's first paragraph, and must declare that it produces
258/// `flm.pres.span` and `flm.pres.deco.runin`.
259///
260/// # Errors
261///
262/// [`LowerError`] when the instance could not be built, and from its
263/// lowering.
264pub(super) fn stage_lead_in(
265    lead_in: &LeadIn,
266    node: &NodeRef<'_, Flm>,
267    cx: &mut LowerCx<'_>,
268    lw: &mut dyn Lowerer,
269) -> Result<Vec<BuildId>, LowerError> {
270    let Some(instance) = lead_in_instance(lead_in, node, lw)? else {
271        return Ok(Vec::new());
272    };
273    let content = lw.splice(cx, &instance)?;
274    let payload = SpanPayload { role: Some(Name::from(LEAD_IN_ROLE)), ..SpanPayload::default() };
275    let span = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, content)?;
276    let deco = lw.pres_with(cx, &ElementName::from(pres::DECO_RUNIN), DecorationPayload, vec![span])?;
277    Ok(vec![deco])
278}
279
280// --- the pointer's rule ----------------------------------------------------------------------
281
282/// The general rule of the element [`TERM_POINTER`], [`POINTER_RULE`]: the
283/// default on every backend.
284pub(super) fn pointer_rule() -> LoweringRule {
285    LoweringRule::new(
286        POINTER_RULE,
287        TERM_POINTER,
288        LoweringDecl::new(),
289        Arc::new(PointerRule),
290        DefaultMark::Everywhere,
291    )
292    .docs(
293        "a term pointer lowers to the term of the term definition it refers to, lowered where \
294         the pointer is placed",
295    )
296}
297
298/// The lowering rule [`POINTER_RULE`], the default on every backend: the
299/// term the pointer refers to ([`ContentPointer`]), lowered where the
300/// pointer is placed, as it is written in the term definition, through
301/// [`lower_content_pointer`].
302///
303/// A pointer to anything but a term definition's term argument is reported
304/// as [`PointerRefused`] and writes nothing. A pointer to a node the lowering
305/// cannot reach, or to a region the node does not have, is reported at the
306/// pointer as the lowering stage's `flm.lowering.region-not-found` and writes
307/// nothing; the lead-in around it and the term definition are still
308/// written.
309#[derive(Debug, Default, Clone, Copy)]
310pub struct PointerRule;
311
312impl Lower for PointerRule {
313    fn lower(
314        &self,
315        node: NodeRef<'_, Flm>,
316        cx: &mut LowerCx<'_>,
317        lw: &mut dyn Lowerer,
318    ) -> Result<Lowering, LowerError> {
319        let span = node.span().clone();
320        let mut check = |lw: &mut dyn Lowerer, named: &NodeRef<'_, Flm>, region: NodeRegion| {
321            if element_value::<DeftermElement>(named).is_some()
322                && NodeRegion::argument_named(named, TERM_ARG) == Some(region)
323            {
324                return Ok(true);
325            }
326            let element = named.ext().element.name.to_string();
327            lw.error(PointerRefused { element, region: region.to_string() }, span.clone());
328            Ok(false)
329        };
330        let staged = lower_content_pointer(cx, lw, &node, &mut check, &mut lower_region_content)?;
331        Ok(Lowering::Emit(staged))
332    }
333}