Skip to main content

flm_core/stdlib/features/quote/
lower.rs

1//! The general lowering rules of the `quote` feature, the defaults on every
2//! backend: [`QuoteRule`] lowers a quotation to one `flm.pres.block` of role
3//! [`QUOTE_ROLE`] holding one block per quotation section, and
4//! [`SectionRule`] lowers a quotation-section command outside section
5//! position to its argument's content, reporting it unless it is part of a
6//! quotation body's bare content.
7//!
8//! The rules read the body each time they lower a quotation and store
9//! nothing: the quotation sections are the body's direct children in section
10//! position, and a lines section is split into lines while the rule stages
11//! it. The reading of one line ([`read_line`]) and the tests of the two
12//! commands of a lines section are shared with the recomposition rule of the
13//! `latex-recomposed` backend ([`latex`](super::latex)).
14
15use techy::core::node::{BuildId, NodeRef};
16use techy::error::Diagnostic;
17
18use crate::core::lowering::{Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl};
19use crate::lang::Flm;
20use crate::lang::mint::is_field_named;
21use crate::lang::rewrites::blocks::argument_holds_blocks;
22use crate::model::element::element_value;
23use crate::model::names::{ElementName, Name};
24use crate::stdlib::backends::lowering::{
25    is_blank, lower_paragraph, lower_run, stage_trimmed, stage_trimmed_runs,
26};
27use crate::stdlib::backends::pres::{self, BlockPayload, Length, LinePayload, LinesPayload};
28
29use super::config::{QuoteSection, english_list};
30use super::diagnostics::{BareContent, IndentMidLine, NestedSection};
31use super::html::STYLE;
32use super::elements::{QuoteElement, SectionElement, is_in_quote_body, section_position};
33use super::{INDENT_COMMAND, LINEBREAK_COMMAND, QUOTE_ROLE};
34
35/// The implementation of the lowering rule [`QUOTE_RULE`](super::QUOTE_RULE),
36/// the default on every backend: a quotation lowers to one `flm.pres.block`
37/// of role [`QUOTE_ROLE`] whose one kind token is the environment's name,
38/// holding one `flm.pres.block` per quotation section in the order written,
39/// of the role of the section's kind ([`QuoteSection::role`]):
40///
41/// - a text or an attribution section holds one paragraph over its content,
42///   the whitespace at both ends of it trimmed;
43/// - a block section holds its content's paragraphs and blocks, or one
44///   paragraph where its content is written as inline content;
45/// - a lines section holds one `flm.pres.lines` with one `flm.pres.line` per
46///   line: the content is split at every `\\`, each line's leading `\indent`s
47///   are counted into its left indentation as that many tabs, and the
48///   whitespace at both ends of each line is trimmed.
49///
50/// The rule reads the body's direct children as a sequence of
51/// quotation-section commands and **bare runs**. A quotation-section command
52/// in *section position*, written directly in the body of an environment that
53/// accepts it, opens a quotation section; each maximal run of other content
54/// between two of them is one bare run. Whitespace and source comments at a
55/// run's edges stage nothing, and a run that holds nothing else stages
56/// nothing. A bare run is staged exactly as a quotation section of the
57/// environment's bare-content kind would be staged over the same content. In
58/// an environment that reads no bare content, a bare run is reported once
59/// ([`BareContent`]) and lowered in place inside the quotation's block,
60/// outside any quotation section. A quotation section that holds nothing,
61/// such as `\attributed{}`, is an empty block of its role. An `\indent`
62/// after the first content of its line is reported ([`IndentMidLine`]) and
63/// left out.
64///
65/// A quotation-section command that the environment does not accept, written
66/// in its body, can only be a command of an enclosing quotation, available
67/// there because the body is inside one of that quotation's quotation
68/// sections. It is part of a bare run like any other content, and its own
69/// rule ([`SectionRule`]) lowers it to its content without reporting it a
70/// second time.
71///
72/// At every quotation the rule requires the feature's style identifier
73/// [`STYLE`] (`flm.quote.style`), which each backend resolves as it resolves
74/// requirements: the stylesheet on the `html` backend, the definition pieces
75/// delivering it on the `latex-rendered` backend, nothing on the `text`
76/// backend.
77///
78/// # Errors
79///
80/// [`LowerError`] when the node carries no [`QuoteElement`], and any error
81/// from lowering the content.
82#[derive(Debug, Default, Clone, Copy)]
83pub struct QuoteRule;
84
85impl Lower for QuoteRule {
86    fn lower(
87        &self,
88        node: NodeRef<'_, Flm>,
89        cx: &mut LowerCx<'_>,
90        lw: &mut dyn Lowerer,
91    ) -> Result<Lowering, LowerError> {
92        lw.require(&Name::from(STYLE));
93        let value = element_value::<QuoteElement>(&node)
94            .ok_or_else(|| LowerError::structure("a quotation without its element's data"))?;
95        let body: Vec<NodeRef<'_, Flm>> =
96            node.body().map(|body| body.iter().collect()).unwrap_or_default();
97        let mut children = Vec::new();
98        let mut start = 0;
99        for (at, child) in body.iter().enumerate() {
100            if let Some(position) = section_position(child) {
101                bare_run(cx, lw, value, &body[start..at], &mut children)?;
102                children.push(stage_section_node(cx, lw, position.section, child)?);
103                start = at + 1;
104            }
105        }
106        bare_run(cx, lw, value, &body[start..], &mut children)?;
107        let payload = BlockPayload {
108            role: Some(Name::from(QUOTE_ROLE)),
109            kinds: vec![Name::from(value.name.as_str())],
110            anchor: None,
111            doc_role: None,
112        };
113        let block = lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, children)?;
114        Ok(Lowering::Emit(vec![block]))
115    }
116}
117
118/// Returns the declaration shared by the rules that lower a quotation into
119/// the presentation vocabulary ([`QuoteRule`], and the `html` backend's rule
120/// that calls it): they produce blocks, paragraphs, and a lines section's
121/// `flm.pres.lines` and `flm.pres.line`.
122pub(super) fn quote_decl() -> LoweringDecl {
123    LoweringDecl::new()
124        .produces(pres::BLOCK)
125        .produces(pres::PAR)
126        .produces(pres::LINES)
127        .produces(pres::LINE)
128}
129
130/// Stages `run`, a maximal run of bare content between two quotation
131/// sections of the quotation `value`, without the whitespace and source
132/// comments at its edges: as one quotation section of the environment's
133/// bare-content kind, or, where the environment reads no bare content,
134/// reported once and lowered in place. A run that holds nothing but
135/// whitespace and source comments stages nothing.
136fn bare_run(
137    cx: &mut LowerCx<'_>,
138    lw: &mut dyn Lowerer,
139    value: &QuoteElement,
140    run: &[NodeRef<'_, Flm>],
141    out: &mut Vec<BuildId>,
142) -> Result<(), LowerError> {
143    let is_edge = |node: &NodeRef<'_, Flm>| node.is_comment() || is_blank(node);
144    let Some(first) = run.iter().position(|node| !is_edge(node)) else { return Ok(()) };
145    let last = run.iter().rposition(|node| !is_edge(node)).unwrap_or(first);
146    let run = &run[first..=last];
147    let holds_blocks = value.environment.holds_blocks();
148    match value.environment.bare {
149        Some(kind) => out.push(stage_section(cx, lw, kind, run, holds_blocks)?),
150        None => {
151            lw.diagnose(Diagnostic::error(bare_content(value), run[0].span().clone()));
152            // An environment reading no bare content has a body of blocks.
153            out.extend(lower_blocks(cx, lw, run)?);
154        }
155    }
156    Ok(())
157}
158
159/// Returns the condition reporting bare content in the quote environment
160/// `value`, listing the quotation-section commands it accepts.
161pub(super) fn bare_content(value: &QuoteElement) -> BareContent {
162    let sections =
163        value.environment.sections.iter().map(|section| format!("‘\\{}’", section.as_str()));
164    BareContent { environment: value.name.clone(), sections: english_list(sections, "or") }
165}
166
167/// Stages the quotation section that the quotation-section command `node`
168/// writes, over the command's argument.
169fn stage_section_node(
170    cx: &mut LowerCx<'_>,
171    lw: &mut dyn Lowerer,
172    section: QuoteSection,
173    node: &NodeRef<'_, Flm>,
174) -> Result<BuildId, LowerError> {
175    let content: Vec<NodeRef<'_, Flm>> =
176        node.argument_content_nodes(0).map(|nodes| nodes.iter().collect()).unwrap_or_default();
177    stage_section(cx, lw, section, &content, argument_holds_blocks(node, 0))
178}
179
180/// Stages one quotation section of the kind `section` over `content`, which
181/// holds paragraphs and blocks when `holds_blocks` is true and inline content
182/// otherwise.
183fn stage_section(
184    cx: &mut LowerCx<'_>,
185    lw: &mut dyn Lowerer,
186    section: QuoteSection,
187    content: &[NodeRef<'_, Flm>],
188    holds_blocks: bool,
189) -> Result<BuildId, LowerError> {
190    let staged = match section {
191        QuoteSection::Lines => vec![stage_lines(cx, lw, content)?],
192        QuoteSection::Block if holds_blocks => lower_blocks(cx, lw, content)?,
193        QuoteSection::Text | QuoteSection::Attributed | QuoteSection::Block => {
194            let run = stage_trimmed(cx, lw, content, is_line_command)?;
195            if run.is_empty() {
196                Vec::new()
197            } else {
198                vec![lower_paragraph(cx, lw, None, run, Vec::new())?]
199            }
200        }
201    };
202    sub_block(cx, lw, section, staged)
203}
204
205/// Stages a `flm.pres.block` of the role of the kind `section`, holding
206/// `content`.
207fn sub_block(
208    cx: &mut LowerCx<'_>,
209    lw: &mut dyn Lowerer,
210    section: QuoteSection,
211    content: Vec<BuildId>,
212) -> Result<BuildId, LowerError> {
213    let payload = BlockPayload {
214        role: Some(Name::from(section.role())),
215        kinds: Vec::new(),
216        anchor: None,
217        doc_role: None,
218    };
219    lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, content)
220}
221
222/// Lowers `content`, paragraphs and blocks, one block at a time, leaving out
223/// the source comments and whitespace among them.
224fn lower_blocks(
225    cx: &mut LowerCx<'_>,
226    lw: &mut dyn Lowerer,
227    content: &[NodeRef<'_, Flm>],
228) -> Result<Vec<BuildId>, LowerError> {
229    let mut out = Vec::new();
230    for node in content {
231        if !(node.is_comment() || is_blank(node)) {
232            out.extend(lower_run(cx, lw, std::slice::from_ref(node))?);
233        }
234    }
235    Ok(out)
236}
237
238/// Stages a lines section over `content`: one `flm.pres.lines` holding one
239/// `flm.pres.line` per line, the content split at every `\\`. A lines
240/// section that holds neither content nor a `\\` has no line at all.
241fn stage_lines(
242    cx: &mut LowerCx<'_>,
243    lw: &mut dyn Lowerer,
244    content: &[NodeRef<'_, Flm>],
245) -> Result<BuildId, LowerError> {
246    let mut lines = Vec::new();
247    if content.iter().any(|node| is_content(node) || is_linebreak(node)) {
248        for line in content.split(is_linebreak) {
249            lines.push(stage_line(cx, lw, line)?);
250        }
251    }
252    lw.pres_with(cx, &ElementName::from(pres::LINES), LinesPayload, lines)
253}
254
255/// Stages one line: its leading `\indent` commands (whitespace and source
256/// comments before and between them are skipped) set its left indentation
257/// to as many tabs, a later `\indent` is reported and left out, and the rest
258/// of the line is staged with the whitespace at both of its ends trimmed.
259fn stage_line(
260    cx: &mut LowerCx<'_>,
261    lw: &mut dyn Lowerer,
262    line: &[NodeRef<'_, Flm>],
263) -> Result<BuildId, LowerError> {
264    let (indent_left, runs) = read_line(lw, line);
265    let staged = stage_trimmed_runs(cx, lw, &runs, is_line_command)?;
266    let payload = LinePayload { indent_left, ..LinePayload::default() };
267    lw.pres_with(cx, &ElementName::from(pres::LINE), payload, staged)
268}
269
270/// Reads one line of a lines section, the nodes between two `\\`, and
271/// returns its left indentation, as many tabs as its leading `\indent`
272/// commands (whitespace and source comments before and between them are
273/// skipped), and the rest of its nodes as runs of siblings, every `\indent`
274/// left out. An `\indent` after the first content of the line is reported
275/// ([`IndentMidLine`]).
276///
277/// Every rule that lowers a lines section reads its lines with this
278/// function, so that the indentation and the report are the same on every
279/// backend.
280pub(super) fn read_line<'l, 't>(
281    lw: &mut dyn Lowerer,
282    line: &'l [NodeRef<'t, Flm>],
283) -> (Length, Vec<&'l [NodeRef<'t, Flm>]>) {
284    let mut indents: i32 = 0;
285    let mut started = false;
286    let mut runs: Vec<&[NodeRef<'_, Flm>]> = Vec::new();
287    let mut run_start = 0;
288    for (at, node) in line.iter().enumerate() {
289        if is_field_named(node, INDENT_COMMAND) {
290            if started {
291                lw.diagnose(Diagnostic::error(IndentMidLine, node.span().clone()));
292            } else {
293                indents = indents.saturating_add(1);
294            }
295            runs.push(&line[run_start..at]);
296            run_start = at + 1;
297        } else if is_content(node) {
298            started = true;
299        }
300    }
301    runs.push(&line[run_start..]);
302    (Length::tabs(indents), runs)
303}
304
305/// Returns whether `node` is content of a quotation section: neither a
306/// source comment, nor whitespace, nor one of the two commands of a lines
307/// section.
308pub(super) fn is_content(node: &NodeRef<'_, Flm>) -> bool {
309    !(node.is_comment() || is_blank(node) || is_line_command(node))
310}
311
312/// Returns whether `node` is one of the two commands of a lines section,
313/// `\\` or `\indent`, which write nothing in place.
314pub(super) fn is_line_command(node: &NodeRef<'_, Flm>) -> bool {
315    is_linebreak(node) || is_field_named(node, INDENT_COMMAND)
316}
317
318/// Returns whether `node` is the `\\` that ends a line of a lines section.
319pub(super) fn is_linebreak(node: &NodeRef<'_, Flm>) -> bool {
320    is_field_named(node, LINEBREAK_COMMAND)
321}
322
323/// The implementation of the lowering rule
324/// [`SECTION_RULE`](super::SECTION_RULE), the default on every backend: a
325/// quotation-section command outside section position is lowered as its
326/// argument's content, with a lines section's `\\` and `\indent` left out.
327/// (A command in section position never reaches this rule: the lowering rule
328/// of its quotation stages its quotation section and does not lower the
329/// command node itself.)
330///
331/// A command written inside another quotation section's argument
332/// (`\lines{\text{x}}`), or anywhere else outside a quotation's body, is
333/// reported ([`NestedSection`]). A command written directly in the body of a
334/// quote environment that does not accept it (a command of an enclosing
335/// quotation, available in a nested quotation's body) is part of that body's
336/// bare content, which the quotation's rule reports once per bare run where
337/// the environment reads none; this rule does not report it a second time.
338///
339/// # Errors
340///
341/// [`LowerError`] when the node carries no [`SectionElement`], and any error
342/// from lowering the content.
343#[derive(Debug, Default, Clone, Copy)]
344pub struct SectionRule;
345
346impl Lower for SectionRule {
347    fn lower(
348        &self,
349        node: NodeRef<'_, Flm>,
350        cx: &mut LowerCx<'_>,
351        lw: &mut dyn Lowerer,
352    ) -> Result<Lowering, LowerError> {
353        let section = element_value::<SectionElement>(&node)
354            .ok_or_else(|| LowerError::structure(
355                "a quotation-section command without its element's data"
356            ))?
357            .section;
358        if !is_in_quote_body(&node) {
359            lw.diagnose(Diagnostic::error(
360                NestedSection { section: section.as_str().to_string() },
361                node.span().clone(),
362            ));
363        }
364        let content: Vec<NodeRef<'_, Flm>> =
365            node.argument_content_nodes(0).map(|nodes| nodes.iter().collect()).unwrap_or_default();
366        let mut out = Vec::new();
367        for run in content.split(|node| is_linebreak(node) || is_field_named(node, INDENT_COMMAND)) {
368            out.extend(lower_run(cx, lw, run)?);
369        }
370        Ok(Lowering::Emit(out))
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::stdlib::features::quote::QuoteEnvironment;
378
379    #[test]
380    fn the_bare_content_report_lists_the_accepted_sections_as_english_does() {
381        let listed = |sections: Vec<QuoteSection>| {
382            let environment = QuoteEnvironment::new(sections);
383            bare_content(&QuoteElement { name: "quote".into(), environment }).sections
384        };
385        assert_eq!(listed(vec![QuoteSection::Block]), "‘\\block’");
386        assert_eq!(listed(vec![QuoteSection::Block, QuoteSection::Text]), "‘\\text’ or ‘\\block’");
387        assert_eq!(
388            listed(QuoteSection::ALL.to_vec()),
389            "‘\\text’, ‘\\lines’, ‘\\attributed’ or ‘\\block’"
390        );
391    }
392}