Skip to main content

flm_core/stdlib/features/metadata/
build.rs

1//! The stage [`BuildMetadata`] (`flm.metadata.build`), which parses the document's
2//! metadata and builds the three pieces of the [`metadata`](super) feature, and the
3//! diagnostic [`MetadataFailed`] it reports when a part of the metadata cannot be built.
4
5use std::sync::Arc;
6
7use techy::core::node::{NodeRef, NodeTree};
8use techy::error::{Diagnostic, DiagnosticInfo};
9use techy::source::SourceSpan;
10
11use crate::core::data::store::StageOut;
12use crate::core::data::table::TableHandle;
13use crate::core::piece::Piece;
14use crate::core::plan::PlanCx;
15use crate::core::registry::FlmRegistry;
16use crate::core::run::StageCx;
17use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
18use crate::lang::copy::{copy_pieces_into_value, SynthesizedPiece, ValueContent, ValuePiece};
19use crate::lang::mint::FlmSynthesizedSpec;
20use crate::lang::{nowhere, parse_fragment, Flm, FlmOrigin, FlmSource, FlmSpan, ParseOptions, PresPayload};
21use crate::model::doc::{Fragment, FragmentLayout};
22use crate::stdlib::backends::pres;
23
24use super::{
25    AffiliationPayload, DocMeta, EmailPayload, MetaAuthor, MetaText, AUTHOR, AUTHOR_AFFILIATION, AUTHOR_EMAIL,
26    AUTHOR_ENTRY, AUTHOR_NAME, AUTHOR_NOTE, BUILD, DATE, READ, TITLE,
27};
28
29/// The label of the origin under which a text of the metadata without a place
30/// is parsed, `metadata`.
31const NO_PLACE_LABEL: &str = "metadata";
32
33/// The stage [`BUILD`] (`flm.metadata.build`), which builds the metadata's pieces:
34/// a compute stage that runs once per document. It reads the option [`DocMeta`],
35/// writes the tables [`TITLE`], [`AUTHOR`] and [`DATE`], and provides the
36/// capability [`READ`].
37///
38/// Each text (the title, each author's name, affiliations and notes, the date) is
39/// parsed as inline FLM content with the registry's language, as a source named
40/// after the file the text was written in and counted from the text's line and
41/// column there, so that each problem the parse finds is reported at its place in
42/// that file. Every problem the parse finds is reported. An author's email address
43/// is not parsed.
44///
45/// The title's content is one [`TITLE`] node holding the parsed content, and the
46/// date's one [`DATE`] node. The authors' content is one [`AUTHOR`] node holding
47/// one [`AUTHOR_ENTRY`] node per author, in the order given; an author's node
48/// holds, in this order, an [`AUTHOR_NAME`] node, one [`AUTHOR_AFFILIATION`] node
49/// per affiliation, carrying the affiliation's number ([`AffiliationPayload`]), an
50/// [`AUTHOR_EMAIL`] node carrying the address ([`EmailPayload`]) when the author
51/// has one, and one [`AUTHOR_NOTE`] node per note. The stage numbers the distinct
52/// affiliations of the document from 1, in the order in which they first appear;
53/// two affiliations whose texts are the same once the whitespace at both ends is
54/// trimmed are the same affiliation. A piece without a text holds no content, and
55/// no backend places it.
56///
57/// A part that cannot be parsed or built is reported as [`MetadataFailed`]. The
58/// title or the date is then left out; in the authors, the affiliation or the
59/// note is left out, and an author whose name cannot be parsed is left out
60/// whole.
61#[derive(Debug, Default, Clone, Copy)]
62pub struct BuildMetadata;
63
64impl Stage for BuildMetadata {
65    fn decl(&self) -> StageDecl {
66        StageDecl::new(BUILD, Effect::Compute, Scope::Document)
67            .writes(TableHandle::<Piece>::new(TITLE))
68            .writes(TableHandle::<Piece>::new(AUTHOR))
69            .writes(TableHandle::<Piece>::new(DATE))
70            .provides(READ)
71            .docs(
72                "Parses the document's title, authors and date as inline content and builds the \
73                 pieces `flm.metadata.title`, `flm.metadata.author` and `flm.metadata.date`.",
74            )
75    }
76
77    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
78        Needs::new().option::<DocMeta>()
79    }
80
81    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
82        let meta = match cx.option::<DocMeta>() {
83            Ok(meta) => meta,
84            Err(error) => {
85                failed(out, "the metadata", error.to_string());
86                return;
87            }
88        };
89        let registry = cx.registry();
90        let title = meta.title.as_ref().and_then(|text| single(registry, TITLE, text, out));
91        let authors = authors(registry, &meta.authors, out);
92        let date = meta.date.as_ref().and_then(|text| single(registry, DATE, text, out));
93        for (name, content) in [(TITLE, title), (AUTHOR, authors), (DATE, date)] {
94            match out.table(&TableHandle::<Piece>::new(name)) {
95                Ok(table) => *table = Piece { content },
96                Err(error) => failed(out, name, error.to_string()),
97            }
98        }
99    }
100}
101
102/// Returns the source of `text`: named after the file the text was written in and
103/// counted from the text's line and column there, or under the label
104/// [`NO_PLACE_LABEL`] for a text without a place.
105fn source(text: &MetaText) -> Arc<FlmSource> {
106    let source = FlmSource::new(text.text.clone());
107    Arc::new(match &text.place {
108        Some(place) => source
109            .with_origin(FlmOrigin::new(place.file.clone()))
110            .with_line_column_number_offsets(place.line as usize, place.column as usize),
111        None => source.with_origin(FlmOrigin::synthetic(NO_PLACE_LABEL)),
112    })
113}
114
115/// Returns `text` parsed as inline content, with every problem of the parse
116/// reported into `out`; `None` when the parse fails altogether, which is reported
117/// too.
118fn parse(registry: &FlmRegistry, what: &str, text: &MetaText, out: &mut StageOut<'_>) -> Option<Fragment> {
119    match parse_fragment(registry.lang(), source(text), FragmentLayout::Inline, &ParseOptions::default()) {
120        Ok(fragment) => {
121            for diagnostic in fragment.diags().iter() {
122                out.diags.push(diagnostic.clone());
123            }
124            Some(fragment)
125        }
126        Err(error) => {
127            failed(out, what, error.to_string());
128            None
129        }
130    }
131}
132
133/// Returns the synthesized specification of the element `name`, which this
134/// feature registers.
135fn spec(registry: &FlmRegistry, name: &str) -> Result<Arc<FlmSynthesizedSpec>, String> {
136    match registry.element_value(name) {
137        Ok(Some(element)) => Ok(Arc::new(FlmSynthesizedSpec::new(Arc::clone(element)))),
138        Ok(None) => Err(format!("no element `{name}` is registered")),
139        Err(error) => Err(error.to_string()),
140    }
141}
142
143/// Returns the body of a node holding `nodes`, the content of a parsed text.
144fn body<'n, 't>(nodes: &'n [NodeRef<'t, Flm>]) -> Vec<ValuePiece<'n, 't>> {
145    nodes.iter().copied().map(ValuePiece::Node).collect()
146}
147
148/// Returns the content of the title piece or of the date piece: one node of the
149/// element `name` holding `text`, parsed.
150fn single(registry: &FlmRegistry, name: &str, text: &MetaText, out: &mut StageOut<'_>) -> Option<Arc<NodeTree<Flm>>> {
151    let fragment = parse(registry, name, text, out)?;
152    let root = fragment.tree().root();
153    let nodes: Vec<NodeRef<'_, Flm>> = root.children().iter().collect();
154    let built = spec(registry, name).and_then(|spec| {
155        let node = SynthesizedPiece {
156            spec,
157            slot: pres::BODY_SLOT,
158            span: root.span().clone(),
159            state: Arc::clone(root.parsing_state()),
160            body: body(&nodes),
161            payload: None,
162        };
163        copy_pieces_into_value(&[ValuePiece::Synthesized(&node)], &root, ValueContent::Own, registry.lang().guard())
164            .map_err(|error| error.to_string())
165    });
166    built.map_err(|detail| failed(out, name, detail)).ok()
167}
168
169/// One author, parsed: the name, each affiliation with its text, the email
170/// address with its span, and each note. An affiliation or a note that could not
171/// be parsed is left out.
172struct ParsedAuthor<'m> {
173    name: Fragment,
174    affiliations: Vec<(Fragment, &'m str)>,
175    email: Option<(&'m str, FlmSpan)>,
176    notes: Vec<Fragment>,
177}
178
179/// The specifications of the elements of the authors piece.
180struct AuthorSpecs {
181    root: Arc<FlmSynthesizedSpec>,
182    entry: Arc<FlmSynthesizedSpec>,
183    name: Arc<FlmSynthesizedSpec>,
184    affiliation: Arc<FlmSynthesizedSpec>,
185    email: Arc<FlmSynthesizedSpec>,
186    note: Arc<FlmSynthesizedSpec>,
187}
188
189impl AuthorSpecs {
190    fn of(registry: &FlmRegistry) -> Result<AuthorSpecs, String> {
191        Ok(AuthorSpecs {
192            root: spec(registry, AUTHOR)?,
193            entry: spec(registry, AUTHOR_ENTRY)?,
194            name: spec(registry, AUTHOR_NAME)?,
195            affiliation: spec(registry, AUTHOR_AFFILIATION)?,
196            email: spec(registry, AUTHOR_EMAIL)?,
197            note: spec(registry, AUTHOR_NOTE)?,
198        })
199    }
200}
201
202/// Returns the content nodes of a parsed text: the children of its root.
203fn content(fragment: &Fragment) -> Vec<NodeRef<'_, Flm>> {
204    fragment.tree().root().children().iter().collect()
205}
206
207/// Returns a node of the element of `spec` holding `nodes`, the content of the
208/// parsed text `fragment`, at the text's span and carrying `payload`.
209fn part<'n, 't>(
210    spec: &Arc<FlmSynthesizedSpec>,
211    fragment: &'t Fragment,
212    nodes: &'n [NodeRef<'t, Flm>],
213    payload: Option<Arc<dyn PresPayload>>,
214) -> SynthesizedPiece<'n, 't> {
215    let root = fragment.tree().root();
216    SynthesizedPiece {
217        spec: Arc::clone(spec),
218        slot: pres::BODY_SLOT,
219        span: root.span().clone(),
220        state: Arc::clone(root.parsing_state()),
221        body: body(nodes),
222        payload,
223    }
224}
225
226/// Returns the content of the authors piece: one [`AUTHOR`] node holding one
227/// [`AUTHOR_ENTRY`] node per author, in the order given; `None` when there is no
228/// author, or when no author's name could be parsed.
229///
230/// Each text but the email address is parsed as inline content. An author whose
231/// name cannot be parsed is left out, and so is an affiliation or a note that
232/// cannot be parsed. The distinct affiliations are numbered from 1 in the order
233/// in which they first appear, two affiliations being the same when their texts
234/// are the same once the whitespace at both ends is trimmed
235/// ([`AffiliationPayload`]).
236fn authors(registry: &FlmRegistry, authors: &[MetaAuthor], out: &mut StageOut<'_>) -> Option<Arc<NodeTree<Flm>>> {
237    let mut parsed: Vec<ParsedAuthor<'_>> = Vec::new();
238    for author in authors {
239        let name = parse(registry, AUTHOR, &author.name, out);
240        let affiliations = (author.affiliations.iter())
241            .filter_map(|text| Some((parse(registry, AUTHOR, text, out)?, text.text.as_str())))
242            .collect();
243        let notes = author.notes.iter().filter_map(|text| parse(registry, AUTHOR, text, out)).collect();
244        let email = author.email.as_ref().map(|text| {
245            (text.text.as_str(), SourceSpan::new(&source(text), 0..text.text.len()))
246        });
247        if let Some(name) = name {
248            parsed.push(ParsedAuthor { name, affiliations, email, notes });
249        }
250    }
251    let first = parsed.first()?.name.tree().root();
252    let mut distinct: Vec<&str> = Vec::new();
253    let mut numbers: Vec<Vec<usize>> = Vec::new();
254    for author in &parsed {
255        let mut these = Vec::new();
256        for (_, text) in &author.affiliations {
257            let text = text.trim();
258            let at = distinct.iter().position(|known| *known == text).unwrap_or_else(|| {
259                distinct.push(text);
260                distinct.len() - 1
261            });
262            these.push(at + 1);
263        }
264        numbers.push(these);
265    }
266    let built = AuthorSpecs::of(registry).and_then(|specs| {
267        // The content nodes of every text, which the parts' nodes borrow.
268        let names: Vec<Vec<NodeRef<'_, Flm>>> = parsed.iter().map(|author| content(&author.name)).collect();
269        let affiliations: Vec<Vec<Vec<NodeRef<'_, Flm>>>> = (parsed.iter())
270            .map(|author| author.affiliations.iter().map(|(fragment, _)| content(fragment)).collect())
271            .collect();
272        let notes: Vec<Vec<Vec<NodeRef<'_, Flm>>>> =
273            parsed.iter().map(|author| author.notes.iter().map(content).collect()).collect();
274        let parts: Vec<Vec<SynthesizedPiece<'_, '_>>> = (parsed.iter().enumerate())
275            .map(|(at, author)| {
276                let root = author.name.tree().root();
277                let mut parts = vec![part(&specs.name, &author.name, &names[at], None)];
278                for (((fragment, _), nodes), number) in
279                    author.affiliations.iter().zip(&affiliations[at]).zip(&numbers[at])
280                {
281                    let payload = AffiliationPayload { number: *number };
282                    parts.push(part(&specs.affiliation, fragment, nodes, Some(Arc::new(payload))));
283                }
284                if let Some((address, span)) = &author.email {
285                    parts.push(SynthesizedPiece {
286                        spec: Arc::clone(&specs.email),
287                        slot: pres::BODY_SLOT,
288                        span: span.clone(),
289                        state: Arc::clone(root.parsing_state()),
290                        body: Vec::new(),
291                        payload: Some(Arc::new(EmailPayload { address: address.to_string() })),
292                    });
293                }
294                for (fragment, nodes) in author.notes.iter().zip(&notes[at]) {
295                    parts.push(part(&specs.note, fragment, nodes, None));
296                }
297                parts
298            })
299            .collect();
300        let entries: Vec<SynthesizedPiece<'_, '_>> = (parsed.iter().zip(&parts))
301            .map(|(author, parts)| {
302                let root = author.name.tree().root();
303                SynthesizedPiece {
304                    spec: Arc::clone(&specs.entry),
305                    slot: pres::BODY_SLOT,
306                    span: root.span().clone(),
307                    state: Arc::clone(root.parsing_state()),
308                    body: parts.iter().map(ValuePiece::Synthesized).collect(),
309                    payload: None,
310                }
311            })
312            .collect();
313        let node = SynthesizedPiece {
314            spec: Arc::clone(&specs.root),
315            slot: pres::BODY_SLOT,
316            span: first.span().clone(),
317            state: Arc::clone(first.parsing_state()),
318            body: entries.iter().map(ValuePiece::Synthesized).collect(),
319            payload: None,
320        };
321        copy_pieces_into_value(&[ValuePiece::Synthesized(&node)], &first, ValueContent::Own, registry.lang().guard())
322            .map_err(|error| error.to_string())
323    });
324    built.map_err(|detail| failed(out, AUTHOR, detail)).ok()
325}
326
327/// Reports that `what` (one of the three pieces, or `the metadata`) could not be
328/// built, as the Error [`MetadataFailed`], with the part written as an author
329/// knows it.
330fn failed(out: &mut StageOut<'_>, what: &str, detail: String) {
331    let what = match what {
332        TITLE => "the title",
333        AUTHOR => "the authors",
334        DATE => "the date",
335        other => other,
336    };
337    out.diags.push(Diagnostic::error(
338        MetadataFailed { what: what.to_string(), detail },
339        nowhere(FlmOrigin::synthetic(NO_PLACE_LABEL)),
340    ));
341}
342
343/// Condition `flm.metadata.failed`, an Error: a part of the metadata could not be
344/// parsed or built, because its content nests too deeply or because of a fault
345/// in the program. Recovery: the title or the date is left out; in the authors,
346/// the affiliation or the note is left out, and an author whose name cannot be
347/// parsed is left out whole.
348#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
349#[diagnostic(id = "flm.metadata.failed", message = "{what} could not be read: {detail}")]
350pub struct MetadataFailed {
351    /// The part, as an author knows it: `the title`, `the authors`, `the date`, or
352    /// `the metadata`.
353    pub what: String,
354    /// Why the part could not be read.
355    pub detail: String,
356}