Skip to main content

flm_core/stdlib/features/metadata/
rules.rs

1//! The synthesized elements of the metadata's pieces, and their default lowering
2//! rules. Every backend uses these rules, except that the `latex-recomposed` backend
3//! has rules of its own for each of them ([`latex`](super::latex)), and the `text`
4//! backend has rules of its own for the title and for one author
5//! ([`text`](super::text)).
6//!
7//! The elements are [`TITLE`], [`AUTHOR`], [`AUTHOR_ENTRY`], [`AUTHOR_NAME`],
8//! [`AUTHOR_AFFILIATION`], [`AUTHOR_EMAIL`], [`AUTHOR_NOTE`] and [`DATE`]. They are
9//! synthesized: no document can write them, and the stage
10//! [`BuildMetadata`](super::BuildMetadata) builds them from the metadata. The rules
11//! of the three pieces stage a [`flm.pres.block`](crate::stdlib::backends::pres::BLOCK)
12//! per piece, whose role is the element's name and whose kind token is
13//! [`KIND_METADATA`], so that a stylesheet or a program's lowering rule can select
14//! on them:
15//!
16//! - the title and the date ([`MetaTextRule`]): the block holds the text as one
17//!   paragraph;
18//! - the authors ([`AuthorRule`]): the block holds each author, one after the other,
19//!   each a unit of lines ([`EntryRule`]): the name, each affiliation, the email
20//!   address and each note on a line of its own, each in a
21//!   [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) whose role is the
22//!   element's name ([`PartRule`], [`EmailRule`]). The email address is a link to
23//!   `mailto:` followed by the address.
24//!
25//! ```text
26//! flm.pres.block { role: flm.metadata.author, kinds: [metadata] }
27//!   ├ flm.pres.lines                                      the first author
28//!   │   ├ flm.pres.line
29//!   │   │   └ flm.pres.span { role: flm.metadata.author.name }  the name
30//!   │   ├ flm.pres.line
31//!   │   │   └ flm.pres.span { role: flm.metadata.author.affiliation }  an affiliation
32//!   │   ├ flm.pres.line
33//!   │   │   └ flm.pres.span { role: flm.metadata.author.email }
34//!   │   │       └ flm.pres.link { href: mailto:<address>, kind: url }  the address
35//!   │   └ flm.pres.line
36//!   │       └ flm.pres.span { role: flm.metadata.author.note }  a note
37//!   └ flm.pres.lines                                      the next author, …
38//! ```
39//!
40//! The rules write no affiliation's number ([`AffiliationPayload`](super::AffiliationPayload)).
41//! How the authors are laid out beyond this (the size of each part, the authors
42//! side by side) is the business of the feature's stylesheet ([`stylesheet`](super::stylesheet))
43//! and LaTeX definitions ([`latex_rendered`](super::latex_rendered)), or of a
44//! compose template's.
45//!
46//! The rules of the three pieces require the feature's style identifier [`STYLE`]
47//! at every piece they stage: the `html` backend resolves it to the feature's
48//! stylesheet, the `latex-rendered` backend to the feature's definition piece
49//! ([`latex_rendered`](super::latex_rendered)).
50
51use std::sync::Arc;
52
53use techy::core::node::{BuildId, NodeRef, NodeSlice};
54
55use crate::core::lowering::{
56    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
57};
58use crate::core::registry::{BuildError, FeatureBuilder};
59use crate::lang::mint::{ElementDef, SyntaxDef};
60use crate::lang::Flm;
61use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
62use crate::model::element::ElementSpec;
63use crate::model::names::{ElementName, Name};
64use crate::stdlib::backends::lowering::lower_blocks_with_edges;
65use crate::stdlib::backends::pres::{self, BlockPayload, Length, LinePayload, LinesPayload, LinkPayload, SpanPayload};
66use crate::stdlib::features::href::LINK_KIND;
67
68use super::{
69    EmailPayload, AUTHOR, AUTHOR_AFFILIATION, AUTHOR_EMAIL, AUTHOR_ENTRY, AUTHOR_NAME, AUTHOR_NOTE, DATE,
70    KIND_METADATA, STYLE, TITLE,
71};
72
73/// The scheme written before an author's email address in the address of its
74/// link, `mailto:`.
75const MAILTO: &str = "mailto:";
76
77/// Returns the name of the default lowering rule of the element `element`,
78/// `<element>.lower.default`.
79pub fn rule_name(element: &str) -> String {
80    format!("{element}.lower.default")
81}
82
83/// Returns the payload of the block the rules of the three pieces stage: the
84/// element's name as its role, and the kind token [`KIND_METADATA`].
85pub(super) fn block(role: &str) -> BlockPayload {
86    BlockPayload { role: Some(Name::from(role)), kinds: vec![Name::from(KIND_METADATA)], anchor: None, doc_role: None }
87}
88
89/// Returns the payload of the span that holds a part of an author: the part's
90/// element name as its role.
91fn span(role: &str) -> SpanPayload {
92    SpanPayload { role: Some(Name::from(role)), ..SpanPayload::default() }
93}
94
95/// Returns each child of `node` as a slice of one node, in order, as
96/// [`Lowerer::lower_nodes`] takes them.
97pub(super) fn each_child<'t>(node: &NodeRef<'t, Flm>) -> Result<Vec<NodeSlice<'t, Flm>>, LowerError> {
98    let children = node.children();
99    let start = children.range().start;
100    (0u32..)
101        .zip(children.iter())
102        .map(|(index, _)| {
103            node.tree()
104                .slice(start + index..start + index + 1)
105                .ok_or_else(|| LowerError::structure("a child outside its parent's children"))
106        })
107        .collect()
108}
109
110/// Lowers the content of `node`, one run of inline text, writing each paragraph
111/// the block-structure pass placed the content in as its content alone.
112pub(super) fn inline_content(
113    node: &NodeRef<'_, Flm>,
114    cx: &mut LowerCx<'_>,
115    lw: &mut dyn Lowerer,
116) -> Result<Vec<BuildId>, LowerError> {
117    let paragraph = Arc::clone(&lw.lang().structural().paragraph);
118    let mut content = Vec::new();
119    for (one, child) in each_child(node)?.into_iter().zip(node.children().iter()) {
120        if child.ext().element.name == paragraph.name {
121            content.extend(lw.lower_children(cx, &child)?);
122        } else {
123            content.extend(lw.lower_nodes(cx, one)?);
124        }
125    }
126    Ok(content)
127}
128
129/// The default lowering rule of the title and of the date, the elements
130/// [`TITLE`] and [`DATE`], on every backend except `latex-recomposed` (and, for
131/// the title, `text`, [`TitleTextRule`](super::TitleTextRule)). It stages
132///
133/// ```text
134/// flm.pres.block { role: <the element's name>, kinds: [metadata] }
135///   └ flm.pres.par
136///       └ the text, lowered through the rules
137/// ```
138#[derive(Debug)]
139pub struct MetaTextRule {
140    role: &'static str,
141}
142
143impl Lower for MetaTextRule {
144    fn lower(
145        &self,
146        node: NodeRef<'_, Flm>,
147        cx: &mut LowerCx<'_>,
148        lw: &mut dyn Lowerer,
149    ) -> Result<Lowering, LowerError> {
150        lw.require(&Name::from(STYLE));
151        let content: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
152        let body = lower_blocks_with_edges(cx, lw, &content, Vec::new(), Vec::new())?;
153        Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block(self.role), body)?]))
154    }
155}
156
157/// The default lowering rule of the authors, the element [`AUTHOR`], on every
158/// backend except `latex-recomposed`. It stages a `flm.pres.block` of role
159/// `flm.metadata.author` and kind token `metadata` holding each author, lowered
160/// through its rule ([`EntryRule`]), in order.
161#[derive(Debug, Default)]
162pub struct AuthorRule;
163
164impl Lower for AuthorRule {
165    fn lower(
166        &self,
167        node: NodeRef<'_, Flm>,
168        cx: &mut LowerCx<'_>,
169        lw: &mut dyn Lowerer,
170    ) -> Result<Lowering, LowerError> {
171        lw.require(&Name::from(STYLE));
172        let body = lw.lower_children(cx, &node)?;
173        Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block(AUTHOR), body)?]))
174    }
175}
176
177/// The default lowering rule of one author, the element [`AUTHOR_ENTRY`], on every
178/// backend except `latex-recomposed` and `text`
179/// ([`EntryTextRule`](super::EntryTextRule)). It stages one `flm.pres.lines`
180/// holding one `flm.pres.line` per part of the author (the name, each
181/// affiliation, the email address, each note, in this order), each line holding
182/// its part lowered through the part's rule ([`PartRule`], [`EmailRule`]). The
183/// lines carry no indentation and the default alignment.
184#[derive(Debug, Default)]
185pub struct EntryRule;
186
187impl Lower for EntryRule {
188    fn lower(
189        &self,
190        node: NodeRef<'_, Flm>,
191        cx: &mut LowerCx<'_>,
192        lw: &mut dyn Lowerer,
193    ) -> Result<Lowering, LowerError> {
194        Ok(Lowering::Emit(vec![entry_lines(&node, cx, lw, |_| Length::default())?]))
195    }
196}
197
198/// Stages the `flm.pres.lines` of the author `node`: one `flm.pres.line` per part,
199/// in order, each holding the part lowered through its rule and indented by
200/// `indent` of the part's element name.
201pub(super) fn entry_lines(
202    node: &NodeRef<'_, Flm>,
203    cx: &mut LowerCx<'_>,
204    lw: &mut dyn Lowerer,
205    indent: impl Fn(&str) -> Length,
206) -> Result<BuildId, LowerError> {
207    let mut lines = Vec::new();
208    for (one, child) in each_child(node)?.into_iter().zip(node.children().iter()) {
209        let part = lw.lower_nodes(cx, one)?;
210        let line = LinePayload { indent_left: indent(child.ext().element.name.as_str()), ..LinePayload::default() };
211        lines.push(lw.pres_with(cx, &ElementName::from(pres::LINE), line, part)?);
212    }
213    lw.pres_with(cx, &ElementName::from(pres::LINES), LinesPayload, lines)
214}
215
216/// The default lowering rule of an author's name, of an affiliation and of a note,
217/// the elements [`AUTHOR_NAME`], [`AUTHOR_AFFILIATION`] and [`AUTHOR_NOTE`], on every
218/// backend except `latex-recomposed`. It stages a `flm.pres.span` whose role is the
219/// element's name, holding the text lowered through the rules.
220#[derive(Debug)]
221pub struct PartRule {
222    role: &'static str,
223}
224
225impl Lower for PartRule {
226    fn lower(
227        &self,
228        node: NodeRef<'_, Flm>,
229        cx: &mut LowerCx<'_>,
230        lw: &mut dyn Lowerer,
231    ) -> Result<Lowering, LowerError> {
232        let content = inline_content(&node, cx, lw)?;
233        Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::SPAN), span(self.role), content)?]))
234    }
235}
236
237/// The default lowering rule of an author's email address, the element
238/// [`AUTHOR_EMAIL`], on every backend except `latex-recomposed`. It stages
239///
240/// ```text
241/// flm.pres.span { role: flm.metadata.author.email }
242///   └ flm.pres.link { href: mailto:<address>, kind: url, shows_target }
243///       └ the address
244/// ```
245///
246/// The link is of kind `url`, the kind of a link to an address outside the
247/// document, and shows its target: its content is the address.
248#[derive(Debug, Default)]
249pub struct EmailRule;
250
251impl Lower for EmailRule {
252    fn lower(
253        &self,
254        node: NodeRef<'_, Flm>,
255        cx: &mut LowerCx<'_>,
256        lw: &mut dyn Lowerer,
257    ) -> Result<Lowering, LowerError> {
258        let address = email_of(&node)?;
259        let payload = LinkPayload {
260            href: format!("{MAILTO}{address}"),
261            kind: Name::from(LINK_KIND),
262            doc_role: None,
263            label: None,
264            shows_target: true,
265        };
266        let text = lw.text(cx, address)?;
267        let link = lw.pres_with(cx, &ElementName::from(pres::LINK), payload, vec![text])?;
268        Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::SPAN), span(AUTHOR_EMAIL), vec![link])?]))
269    }
270}
271
272/// Returns the address that the email node `node` carries.
273///
274/// # Errors
275///
276/// [`LowerError::Structure`] for a node that carries no [`EmailPayload`].
277pub(super) fn email_of<'n>(node: &'n NodeRef<'_, Flm>) -> Result<&'n str, LowerError> {
278    EmailPayload::of(node)
279        .map(|payload| payload.address.as_str())
280        .ok_or_else(|| LowerError::structure("missing ‘EmailPayload’ on an author’s email node"))
281}
282
283/// Declares, for the feature `b` registers, the synthesized elements and their
284/// default lowering rules.
285pub(super) fn declare(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
286    let owner = b.feature().clone();
287    let elements = [
288        (TITLE, "The document's title.", "The title of the document, built from its metadata."),
289        (
290            AUTHOR,
291            "The document's authors, one author per child.",
292            "The list of the document's authors, built from its metadata.",
293        ),
294        (
295            AUTHOR_ENTRY,
296            "One author of the document: the name, then each affiliation, the email address and each note.",
297            "One author of the document, in the list of its authors.",
298        ),
299        (AUTHOR_NAME, "An author's name.", "The name of one author of the document."),
300        (
301            AUTHOR_AFFILIATION,
302            "One affiliation of an author, with its number among the document's affiliations.",
303            "One affiliation of one author of the document.",
304        ),
305        (
306            AUTHOR_EMAIL,
307            "An author's email address, a plain text.",
308            "The email address of one author of the document.",
309        ),
310        (AUTHOR_NOTE, "One note about an author.", "One note about one author of the document."),
311        (DATE, "The document's date.", "The date of the document, built from its metadata."),
312    ];
313    for (name, docs, type_docs) in elements {
314        b.element_type_text(name, type_docs)?;
315        let role = Arc::new(FixedBlockRole(BlockRole::Block)) as Arc<dyn BlockRoleAspect>;
316        b.element(
317            ElementDef::new(
318                owner.clone(),
319                Vec::<&str>::new(),
320                SyntaxDef::Synthesized,
321                Arc::new(ElementSpec::new(name).docs(docs).with(role)),
322            )
323            .docs(format!("{docs} No document can write it: a stage builds it from the metadata.")),
324        )?;
325    }
326    for element in [TITLE, DATE] {
327        b.lowering_rule(
328            LoweringRule::new(
329                rule_name(element),
330                element,
331                LoweringDecl::new().produces(pres::BLOCK).produces(pres::PAR),
332                Arc::new(MetaTextRule { role: element }),
333                DefaultMark::Everywhere,
334            )
335            .docs(format!("`{element}` lowers to a `flm.pres.block` holding the text as one paragraph")),
336        )?;
337    }
338    b.lowering_rule(
339        LoweringRule::new(
340            rule_name(AUTHOR),
341            AUTHOR,
342            LoweringDecl::new().produces(pres::BLOCK),
343            Arc::new(AuthorRule),
344            DefaultMark::Everywhere,
345        )
346        .docs("the authors lower to a `flm.pres.block` holding each author in order"),
347    )?;
348    b.lowering_rule(
349        LoweringRule::new(
350            rule_name(AUTHOR_ENTRY),
351            AUTHOR_ENTRY,
352            LoweringDecl::new().produces(pres::LINES).produces(pres::LINE),
353            Arc::new(EntryRule),
354            DefaultMark::Everywhere,
355        )
356        .docs("an author lowers to a `flm.pres.lines`, each part of the author on a `flm.pres.line` of its own"),
357    )?;
358    for element in [AUTHOR_NAME, AUTHOR_AFFILIATION, AUTHOR_NOTE] {
359        b.lowering_rule(
360            LoweringRule::new(
361                rule_name(element),
362                element,
363                LoweringDecl::new().produces(pres::SPAN),
364                Arc::new(PartRule { role: element }),
365                DefaultMark::Everywhere,
366            )
367            .docs(format!("`{element}` lowers to a `flm.pres.span` of role `{element}` holding the text")),
368        )?;
369    }
370    b.lowering_rule(
371        LoweringRule::new(
372            rule_name(AUTHOR_EMAIL),
373            AUTHOR_EMAIL,
374            LoweringDecl::new().produces(pres::SPAN).produces(pres::LINK),
375            Arc::new(EmailRule),
376            DefaultMark::Everywhere,
377        )
378        .docs(
379            "an email address lowers to a `flm.pres.span` of role `flm.metadata.author.email` holding a \
380             `flm.pres.link` of kind `url` to `mailto:` followed by the address, showing the address",
381        ),
382    )?;
383    Ok(())
384}