flm_core/stdlib/features/citations/numbers.rs
1//! This module defines the table of cited keys [`KEYS`], the table of cited
2//! works [`CITATIONS`], the collect stage that writes the table of cited keys,
3//! and the function [`number_works`] that numbers the cited works, along with
4//! the error [`StageFailed`] that the stages of the `citations` feature report.
5//!
6//! The collect stage [`COLLECT`] records every citation key that the document
7//! cites. The retrieve stage [`RETRIEVE`](super::RETRIEVE) then obtains the
8//! citation entries of these citation keys from the citation providers. The
9//! answer of a citation provider can give the *identity* of the cited work
10//! ([`CitationAnswer`](super::CitationAnswer)), and citation keys with the same
11//! identity refer to the same work. The retrieve stage numbers the cited works
12//! with [`number_works`] and writes the result to the table of cited works.
13
14use std::collections::BTreeMap;
15
16use techy::error::{Diagnostic, DiagnosticInfo};
17use techy::serialize::SerialValue;
18
19use crate::core::data::store::StageOut;
20use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
21use crate::core::plan::PlanCx;
22use crate::core::run::StageCx;
23use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
24use crate::lang::{FlmOrigin, FlmSpan, nowhere};
25use crate::stdlib::features::index::{ElementIndex, ELEMENT_INDEX, walk_values_of};
26
27use super::elements::{read_chunk, CitationElement, Chunk, Reading};
28
29/// The name of the table of cited keys, `flm.citations.keys`, whose value is a
30/// [`CitedKeys`]. The collect stage [`COLLECT`] writes this table. The retrieve
31/// stage [`RETRIEVE`](super::RETRIEVE) and the check stage
32/// [`CHECK`](super::CHECK) read it.
33pub const KEYS: TableName<CitedKeys> = TableName::new("flm.citations.keys");
34
35/// The name of the table of cited works, `flm.citations`, whose value is a
36/// [`CitedWorks`]. The retrieve stage [`RETRIEVE`](super::RETRIEVE) writes this
37/// table. The lowering rules of `\cite` and `\R` read the number and the
38/// identifier of each cited work from this table, and the stage
39/// [`BUILD_BIBLIOGRAPHY`](super::BUILD_BIBLIOGRAPHY) reads it to build the list
40/// of cited works.
41pub const CITATIONS: TableName<CitedWorks> = TableName::new("flm.citations");
42
43/// The name of the collect stage, `flm.citations.collect`. This stage records
44/// every citation key that the document cites in the table [`KEYS`].
45pub const COLLECT: &str = "flm.citations.collect";
46
47/// The prefix of the identifier of a cited work, `citation-`. The identifier
48/// of the work numbered 3 is `citation-3`.
49///
50/// In the output, the entry of a work in the list of cited works has the
51/// identifier of the work as its anchor, and the numbers in the citation marks
52/// link to this anchor. For instance, in HTML output, the entry of the work
53/// numbered 3 has the attribute `id="citation-3"`, and the number 3 in a
54/// citation mark is a link to `#citation-3`.
55pub const IDENTIFIER_PREFIX: &str = "citation-";
56
57/// The value of the table of cited keys ([`KEYS`]). It contains every citation
58/// key that the document cites, once, in order of first citation, that is, in
59/// the order in which the citation keys first appear in the document.
60///
61/// Each citation key is stored with the span of its first citation: the span
62/// of the `\cite` or `\R` node whose citation chunk ([`Chunk`]) first contains
63/// the citation key. The stages of the `citations` feature report the
64/// diagnostics about a citation key at this span, for instance
65/// [`NoEntry`](super::NoEntry) for a citation key without a citation entry.
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
67pub struct CitedKeys {
68 /// The citation keys, in order of first citation, each with the span of
69 /// its first citation.
70 keys: Vec<(String, FlmSpan)>,
71}
72
73impl CitedKeys {
74 /// Returns the cited keys of the citation chunks `chunks`. Each item of
75 /// `chunks` is a citation chunk with the span of the `\cite` or `\R` node
76 /// from which it was read, and the items must be in document order. The
77 /// result contains each citation key once, with the span of the first
78 /// citation chunk that contains it.
79 pub fn of<'c, 't: 'c>(chunks: impl IntoIterator<Item = (&'c FlmSpan, &'c Chunk<'t>)>) -> CitedKeys {
80 let mut keys = CitedKeys::default();
81 for (span, chunk) in chunks {
82 for item in &chunk.items {
83 keys.cite(&item.key, span);
84 }
85 }
86 keys
87 }
88
89 /// Returns every citation key with the span of its first citation, in
90 /// order of first citation.
91 pub fn iter(&self) -> impl Iterator<Item = (&str, &FlmSpan)> {
92 self.keys.iter().map(|(key, span)| (key.as_str(), span))
93 }
94
95 /// Returns the span of the first citation of `key`, or `None` if the table
96 /// does not contain `key`.
97 pub fn first_citation(&self, key: &str) -> Option<&FlmSpan> {
98 self.keys.iter().find(|(cited, _)| cited == key).map(|(_, span)| span)
99 }
100
101 /// Returns how many distinct citation keys are cited.
102 pub fn len(&self) -> usize {
103 self.keys.len()
104 }
105
106 /// Returns whether no citation key is cited.
107 pub fn is_empty(&self) -> bool {
108 self.keys.is_empty()
109 }
110
111 /// Records `key`, first cited at `span`, unless it is already recorded.
112 fn cite(&mut self, key: &str, span: &FlmSpan) {
113 if !self.keys.iter().any(|(cited, _)| cited == key) {
114 self.keys.push((key.to_string(), span.clone()));
115 }
116 }
117}
118
119impl Table for CitedKeys {
120 /// Appends the citation keys of `piece` that this table does not contain
121 /// yet, in their order and with their spans.
122 fn absorb(&mut self, piece: CitedKeys) {
123 for (key, span) in &piece.keys {
124 self.cite(key, span);
125 }
126 }
127
128 /// Serializes the table as the list of the citation keys, in order of
129 /// first citation.
130 fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
131 SerialValue::List(self.iter().map(|(key, _)| SerialValue::Str(key.to_string())).collect())
132 }
133
134 fn piece_class(&self) -> PieceClass {
135 if self.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
136 }
137}
138
139impl SingletonTable for CitedKeys {
140 const NAME: &'static str = "flm.citations.keys";
141}
142
143/// A `CitedWork` contains the number, the identifier and the identity of a
144/// cited work. The table of cited works ([`CitedWorks`]) stores a `CitedWork`
145/// for each citation key, and the citation keys that refer to the same work
146/// have equal `CitedWork` values.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct CitedWork {
149 /// The number of the work. The cited works are numbered from 1, in the
150 /// order of the first citation of any of their citation keys.
151 pub number: usize,
152 /// The identifier of the work, as in `citation-1`: the prefix
153 /// [`IDENTIFIER_PREFIX`] followed by the number. In the output, it is the
154 /// anchor of the entry of the work in the list of cited works.
155 pub identifier: String,
156 /// The identity of the work. Citation keys with the same identity refer to
157 /// the same work. The identity is the one that the citation provider gives
158 /// in its answer for the citation key
159 /// ([`CitationAnswer::identity`](super::CitationAnswer::identity)). If the
160 /// citation key has no answer, or its answer gives no identity, the
161 /// identity is the citation key itself.
162 pub identity: String,
163}
164
165/// The value of the table of cited works ([`CITATIONS`]). It contains every
166/// citation key that the document cites, in order of first citation, each
167/// with the cited work ([`CitedWork`]) that it refers to. Citation keys with
168/// the same identity refer to the same work (see [`CitedWork::identity`]). The
169/// function [`number_works`] creates this value.
170///
171/// The table is keyed by the text of the citation keys
172/// ([`work`](CitedWorks::work)), not by nodes. Therefore a citation that is
173/// copied, for instance with the title of a heading that a reference displays,
174/// expands to the same numbers as the original citation.
175#[derive(Debug, Clone, Default, PartialEq, Eq)]
176pub struct CitedWorks {
177 /// Every citation key, in order of first citation.
178 keys: Vec<String>,
179 /// Each citation key's work.
180 works: BTreeMap<String, CitedWork>,
181 /// The citation key of the first citation of each work, in the order of
182 /// the numbers. The work numbered `n` is at index `n - 1`.
183 firsts: Vec<String>,
184 /// Each identity's number.
185 numbers: BTreeMap<String, usize>,
186}
187
188impl CitedWorks {
189 /// Returns the work that the citation key `key` refers to, or `None` if the
190 /// table does not contain `key`. This is the case for a citation key that
191 /// is cited only outside the trees of the document (see
192 /// [`Uncollected`](super::Uncollected)).
193 pub fn work(&self, key: &str) -> Option<&CitedWork> {
194 self.works.get(key)
195 }
196
197 /// Returns every cited work once, in the order of the numbers, with the
198 /// citation key under which it was first cited.
199 pub fn works(&self) -> impl Iterator<Item = (&str, &CitedWork)> {
200 self.firsts.iter().filter_map(|key| self.works.get(key).map(|work| (key.as_str(), work)))
201 }
202
203 /// Returns every cited key with its work, in order of first citation.
204 pub fn keys(&self) -> impl Iterator<Item = (&str, &CitedWork)> {
205 self.keys.iter().filter_map(|key| self.works.get(key).map(|work| (key.as_str(), work)))
206 }
207
208 /// Returns the number of cited works. Citation keys that refer to the same
209 /// work count as one work.
210 pub fn len(&self) -> usize {
211 self.firsts.len()
212 }
213
214 /// Returns whether no work is cited.
215 pub fn is_empty(&self) -> bool {
216 self.firsts.is_empty()
217 }
218
219 /// Records `key` as a citation key of the work with the identity
220 /// `identity`, unless the table already contains `key`. If a work with
221 /// this identity is already numbered, `key` refers to this work.
222 /// Otherwise, `key` refers to a new work with the next number.
223 fn cite(&mut self, key: &str, identity: &str) {
224 if self.works.contains_key(key) {
225 return;
226 }
227 let number = match self.numbers.get(identity) {
228 Some(number) => *number,
229 None => {
230 self.firsts.push(key.to_string());
231 let number = self.firsts.len();
232 self.numbers.insert(identity.to_string(), number);
233 number
234 }
235 };
236 let identifier = format!("{IDENTIFIER_PREFIX}{number}");
237 self.keys.push(key.to_string());
238 self.works.insert(key.to_string(), CitedWork { number, identifier, identity: identity.to_string() });
239 }
240}
241
242impl Table for CitedWorks {
243 /// Records the citation keys of `piece` that this table does not contain
244 /// yet, in their order, each with the identity of its work. The works are
245 /// numbered in the same way as by [`number_works`].
246 fn absorb(&mut self, piece: CitedWorks) {
247 for (key, work) in piece.keys() {
248 self.cite(key, &work.identity);
249 }
250 }
251
252 /// Serializes the table as a list with one map for each citation key, in
253 /// order of first citation. Each map has the keys `key`, `number`, `id`
254 /// (the identifier of the work) and `identity`.
255 fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
256 SerialValue::List(
257 self.keys()
258 .map(|(key, work)| {
259 SerialValue::Map(vec![
260 ("key".to_string(), SerialValue::Str(key.to_string())),
261 ("number".to_string(), SerialValue::Int(work.number as i64)),
262 ("id".to_string(), SerialValue::Str(work.identifier.clone())),
263 ("identity".to_string(), SerialValue::Str(work.identity.clone())),
264 ])
265 })
266 .collect(),
267 )
268 }
269
270 fn piece_class(&self) -> PieceClass {
271 if self.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
272 }
273}
274
275impl SingletonTable for CitedWorks {
276 const NAME: &'static str = "flm.citations";
277}
278
279/// Numbers the cited works of the citation keys `keys`, and returns the result
280/// as the value of the table of cited works ([`CITATIONS`]).
281///
282/// Each item of `keys` is a pair of a citation key and the identity of the
283/// work that the citation key refers to (see [`CitedWork::identity`]).
284/// Citation keys with the same identity refer to the same work. The identities
285/// are compared as exact strings. The works are numbered from 1, in the order
286/// in which their identities first appear in `keys`. If `keys` contains a
287/// citation key more than once, only its first pair counts.
288///
289/// The retrieve stage [`RETRIEVE`](super::RETRIEVE) calls this function once,
290/// after it has obtained the answers of the citation providers. It passes
291/// every cited key of the document, in order of first citation, so that the
292/// works are numbered in the order of their first citation.
293pub fn number_works<'k>(keys: impl IntoIterator<Item = (&'k str, &'k str)>) -> CitedWorks {
294 let mut works = CitedWorks::default();
295 for (key, identity) in keys {
296 works.cite(key, identity);
297 }
298 works
299}
300
301/// Returns every citation chunk in the trees of the document, in document
302/// order, each with the span of the `\cite` or `\R` node from which it was
303/// read. The citation chunks are read with [`Reading::InStage`]: a `\cite`
304/// call whose citation keys contain a placeholder of a user definition
305/// contributes no citation key.
306fn document_chunks<'t>(
307 cx: &StageCx<'t>,
308 index: &'t ElementIndex,
309) -> Vec<(FlmSpan, Chunk<'t>)> {
310 let mut chunks = Vec::new();
311 for (_, node, _) in walk_values_of::<CitationElement>(cx, index) {
312 // Read in a stage, a chunk is never refused.
313 if let Ok(chunk) = read_chunk(&node, Reading::InStage) {
314 chunks.push((node.span().clone(), chunk));
315 }
316 }
317 chunks
318}
319
320/// Reports the error [`StageFailed`] for the stage named `stage`, with the
321/// description `detail` of the failure.
322pub(super) fn stage_failed(out: &mut StageOut<'_>, stage: &str, detail: impl ToString) {
323 out.diags.push(Diagnostic::error(
324 StageFailed { stage: stage.to_string(), detail: detail.to_string() },
325 nowhere(FlmOrigin::none()),
326 ));
327}
328
329/// The error that is reported when a stage of the `citations` feature fails
330/// (id `flm.citations.stage-failed`).
331///
332/// A stage fails when it cannot read or write one of its tables. This happens
333/// only when the code of a feature is faulty: a stage accesses a table that it
334/// did not declare, or accesses a table with a value type that differs from
335/// the declared one (see
336/// [`AccessError`](crate::core::data::store::AccessError)). The stage
337/// [`BUILD_BIBLIOGRAPHY`](super::BUILD_BIBLIOGRAPHY) also fails when it cannot
338/// build the list of cited works (see [`build_list`](super::build_list)).
339///
340/// Reported at no position in the document. A stage that cannot read a table
341/// stops, and each table that a failed stage did not write is empty. The
342/// consequences for the document depend on the stage:
343///
344/// - If the collect stage [`COLLECT`] fails, no citation key is numbered.
345/// Each `\cite` and `\R` then reports [`Uncollected`](super::Uncollected)
346/// for each of its citation keys, and expands to a dropped mark
347/// (`flm.pres.dropped`).
348/// - If the retrieve stage [`RETRIEVE`](super::RETRIEVE) fails, the table of
349/// cited works ([`CITATIONS`]) or the table of citation entries
350/// ([`ENTRIES`](super::ENTRIES)) is empty. Without the table of cited works,
351/// the citations expand to dropped marks, as after a failure of the collect
352/// stage. Without the table of citation entries, the check stage reports
353/// [`NoEntry`](super::NoEntry) for each citation key.
354/// - If the check stage [`CHECK`](super::CHECK) fails, no citation key is
355/// reported for a missing citation entry.
356/// - If the stage [`BUILD_BIBLIOGRAPHY`](super::BUILD_BIBLIOGRAPHY) fails, the
357/// list of cited works has no content and does not appear in the output.
358#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
359#[diagnostic(id = "flm.citations.stage-failed", message = "Stage ‘{stage}’ failed: {detail}")]
360pub struct StageFailed {
361 /// The name of the stage: `flm.citations.collect`,
362 /// `flm.citations.retrieve`, `flm.citations.check` or
363 /// `flm.citations.build-bibliography`.
364 pub stage: String,
365 /// The description of the failure.
366 pub detail: String,
367}
368
369/// The collect stage `flm.citations.collect` ([`COLLECT`]) records every
370/// citation key that the document cites in the table of cited keys
371/// ([`KEYS`]). The stage runs once for the whole document. It finds the
372/// `\cite` and `\R` nodes in the element index ([`ELEMENT_INDEX`]), reads the
373/// citation chunk of each node, and records each citation key at its first
374/// citation.
375///
376/// The stage does not number the cited works, because the numbers depend on
377/// the identities of the works, which the retrieve stage obtains later from
378/// the citation providers. The stage does not report mistakes in the
379/// citations; the lowering rules of `\cite` and `\R` report them.
380///
381/// The stage reports [`StageFailed`] when it cannot read the element index or
382/// write the table of cited keys.
383#[derive(Debug, Default)]
384pub(super) struct Collect;
385
386impl Stage for Collect {
387 fn decl(&self) -> StageDecl {
388 StageDecl::new(COLLECT, Effect::Compute, Scope::Document).writes(KEYS).docs(
389 "Writes every citation key that the document cites to the table \
390 `flm.citations.keys`, in order of first citation, with the position of its first \
391 citation in the source.",
392 )
393 }
394
395 fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
396 Needs::new().reads(ELEMENT_INDEX)
397 }
398
399 fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
400 let failed = |out: &mut StageOut<'_>, detail: String| stage_failed(out, COLLECT, detail);
401 let index = match cx.get(ELEMENT_INDEX) {
402 Ok(Some(index)) => index,
403 Ok(None) => return,
404 Err(error) => return failed(out, error.to_string()),
405 };
406 let chunks = document_chunks(cx, index);
407 let keys = CitedKeys::of(chunks.iter().map(|(span, chunk)| (span, chunk)));
408 match out.table(KEYS) {
409 Ok(table) => *table = keys,
410 Err(error) => failed(out, error.to_string()),
411 }
412 }
413}