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