Skip to main content

flm_core/stdlib/features/citations/
entries.rs

1//! This module defines the table of the citation entries,
2//! `flm.citations.entries` ([`ENTRIES`]), and the retrieve stage
3//! ([`RETRIEVE`]), which writes this table.
4//!
5//! The retrieve stage reads the cited keys from the table
6//! [`KEYS`](super::KEYS) and calls the citation providers of the service slot
7//! [`PROVIDERS_SLOT`](super::PROVIDERS_SLOT) to obtain their citation entries.
8//! It checks each citation entry and writes the results to [`ENTRIES`]. Then
9//! it numbers the cited works and writes the numbers to the table
10//! [`CITATIONS`](super::CITATIONS).
11//!
12//! The table [`ENTRIES`] is read by the stage that builds the list of cited
13//! works, by the check stage, and by the lowering rules of `\cite` and `\R`
14//! under the in-place placement, where a citation mark contains the citation
15//! entries.
16
17use std::collections::BTreeMap;
18
19use techy::core::node::{NodeRef, NodeTree};
20use techy::error::Diagnostic;
21use techy::serialize::SerialValue;
22
23use crate::core::data::store::StageOut;
24use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
25use crate::core::plan::PlanCx;
26use crate::core::run::StageCx;
27use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
28use crate::lang::rewrites::blocks::run_holds_blocks;
29use crate::lang::text::plain_text;
30use crate::lang::{Flm, FlmDiagnostics};
31use crate::model::element::element_value;
32
33use super::diagnostics::{EntryCites, EntryNotInline, NoProvider, ProviderFailed, ProviderWarning};
34use super::elements::CitationElement;
35use super::numbers::{number_works, stage_failed, CITATIONS, KEYS};
36use super::providers::{
37    CitationAnswer, CitationEntry, CitationProvider, CitationProviderError, CitationRequest,
38    ProviderCx, PROVIDERS_SLOT,
39};
40
41/// The name of the table of the citation entries, `flm.citations.entries`.
42/// The table ([`CitationEntries`]) contains, for each cited key, its citation
43/// entry or the reason why it has none.
44pub const ENTRIES: TableName<CitationEntries> = TableName::new("flm.citations.entries");
45
46/// The name of the retrieve stage, `flm.citations.retrieve`. This stage
47/// obtains the citation entries from the citation providers, and writes the
48/// tables [`ENTRIES`] and [`CITATIONS`](super::CITATIONS).
49pub const RETRIEVE: &str = "flm.citations.retrieve";
50
51/// The reason why a cited key has no citation entry.
52///
53/// The table [`ENTRIES`] contains this reason for each cited key without a
54/// citation entry ([`Retrieval::Missing`]). The check stage reports each such
55/// citation key in the error [`NoEntry`](super::NoEntry), with the text that
56/// [`MissingEntry::reason`] returns.
57#[derive(Debug, Clone, PartialEq, Eq)]
58#[non_exhaustive]
59pub enum MissingEntry {
60    /// No citation provider has been contributed to the service slot
61    /// [`PROVIDERS_SLOT`].
62    NoProviderInstalled,
63    /// Every citation provider returned `Ok(None)` for the citation key, that
64    /// is, no citation provider handles this citation key.
65    UnknownProvider,
66    /// The [`CitationProviderError`] structure contains the details (including
67    /// the error message) that a citation provider reports when it fails to
68    /// retrieve a particular citation key. The retrieve stage also creates such
69    /// an error itself when [`CitationProvider::answer_all`] returns a
70    /// different number of results than it received requests.
71    Failed(CitationProviderError),
72    /// The citation entry contains a citation (`\cite` or `\R`), and the
73    /// retrieve stage refused it. The retrieve stage reports this case as the
74    /// error [`EntryCites`].
75    Cites,
76    /// The citation entry contains a paragraph break or a block, and the
77    /// retrieve stage refused it, because a citation entry must be inline
78    /// content. The retrieve stage reports this case as the error
79    /// [`EntryNotInline`].
80    NotInline,
81    /// The retrieve stage could not bring the citation entry up to date as the
82    /// document would show it ([value
83    /// catch-up](crate::guide::concepts_overview#value-catch-up)), and refused
84    /// it. For instance, a rewrite stage failed over the content of the
85    /// citation entry.
86    Unprocessable,
87}
88
89impl MissingEntry {
90    /// Returns the text that the error [`NoEntry`](super::NoEntry) contains
91    /// after the citation key to state this reason. For instance,
92    /// [`MissingEntry::UnknownProvider`] returns `no appropriate citation
93    /// provider found`.
94    pub fn reason(&self) -> String {
95        match self {
96            MissingEntry::NoProviderInstalled => "no bibliography source set up".to_string(),
97            MissingEntry::UnknownProvider => "no appropriate citation provider found".to_string(),
98            MissingEntry::Failed(error) => format!("failed to retrieve the bibliography entry ({error})"),
99            MissingEntry::Cites => "the bibliography entry may not use ‘\\cite’ recursively".to_string(),
100            MissingEntry::NotInline => {
101                "the bibliography entry must hold inline content only (no paragraph breaks or blocks)".to_string()
102            }
103            MissingEntry::Unprocessable => "failed to process the bibliography entry".to_string(),
104        }
105    }
106
107    /// Returns the token that represents this reason in the serialized form of
108    /// the table [`ENTRIES`], for instance `unknown` for
109    /// [`MissingEntry::UnknownProvider`].
110    fn token(&self) -> &'static str {
111        match self {
112            MissingEntry::NoProviderInstalled => "no-provider",
113            MissingEntry::UnknownProvider => "unknown",
114            MissingEntry::Failed(_) => "failed",
115            MissingEntry::Cites => "cites",
116            MissingEntry::NotInline => "not-inline",
117            MissingEntry::Unprocessable => "unprocessable",
118        }
119    }
120}
121
122/// The result of the retrieve stage for one cited key: the answer of a
123/// citation provider, or the reason why the citation key has no citation
124/// entry.
125#[derive(Debug, Clone)]
126pub enum Retrieval {
127    /// A citation provider returned this answer for the citation key, and the
128    /// retrieve stage accepted its citation entry.
129    Found(CitationAnswer),
130    /// The citation key has no citation entry, for the given reason.
131    Missing(MissingEntry),
132}
133
134/// The value of the table [`ENTRIES`]: the cited keys of the document, in
135/// order of first citation, each with the result of the retrieve stage
136/// ([`Retrieval`]).
137///
138/// The serialized form of the table ([`Table::project`]) is a list with one
139/// map for each cited key, in order of first citation. Each map contains the
140/// field `key`, with the citation key, and one of two other fields: `entry`,
141/// with the plain text of the citation entry, or `missing`, with a token that
142/// represents the reason why the citation key has no citation entry (for
143/// instance `failed`).
144#[derive(Debug, Clone, Default)]
145pub struct CitationEntries {
146    /// The citation keys, in order of first citation.
147    keys: Vec<String>,
148    /// The result of the retrieve stage for each citation key.
149    retrieved: BTreeMap<String, Retrieval>,
150}
151
152impl CitationEntries {
153    /// Returns the result of the retrieve stage for the citation key `key`, or
154    /// `None` if `key` is not among the cited keys of the document
155    /// ([`KEYS`]).
156    pub fn get(&self, key: &str) -> Option<&Retrieval> {
157        self.retrieved.get(key)
158    }
159
160    /// Returns the citation entry of the citation key `key`, or `None` if `key`
161    /// has no citation entry or is not among the cited keys of the document.
162    pub fn entry(&self, key: &str) -> Option<&CitationEntry> {
163        match self.retrieved.get(key)? {
164            Retrieval::Found(answer) => Some(&answer.entry),
165            Retrieval::Missing(_) => None,
166        }
167    }
168
169    /// Returns an iterator over the cited keys, in order of first citation,
170    /// each with the result of the retrieve stage for it.
171    pub fn iter(&self) -> impl Iterator<Item = (&str, &Retrieval)> {
172        self.keys.iter().filter_map(|key| self.retrieved.get(key).map(|found| (key.as_str(), found)))
173    }
174
175    /// Returns the number of cited keys in the table.
176    pub fn len(&self) -> usize {
177        self.keys.len()
178    }
179
180    /// Returns `true` if the table contains no cited key.
181    pub fn is_empty(&self) -> bool {
182        self.keys.is_empty()
183    }
184
185    /// Records `retrieval` for `key`, unless `key` already has one.
186    fn record(&mut self, key: &str, retrieval: Retrieval) {
187        if self.retrieved.contains_key(key) {
188            return;
189        }
190        self.keys.push(key.to_string());
191        self.retrieved.insert(key.to_string(), retrieval);
192    }
193}
194
195impl Table for CitationEntries {
196    /// Appends the citation keys of `piece` that this table does not contain
197    /// yet, with their results, in their order in `piece`. A citation key
198    /// that this table already contains keeps its result.
199    fn absorb(&mut self, piece: CitationEntries) {
200        let CitationEntries { keys, mut retrieved } = piece;
201        for key in keys {
202            if let Some(found) = retrieved.remove(&key) {
203                self.record(&key, found);
204            }
205        }
206    }
207
208    /// Returns the serialized form of the table, which the documentation of
209    /// [`CitationEntries`] describes.
210    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
211        SerialValue::List(
212            self.iter()
213                .map(|(key, found)| {
214                    let (field, value) = match found {
215                        Retrieval::Found(answer) => ("entry", plain_text(&answer.entry.content)),
216                        Retrieval::Missing(missing) => ("missing", missing.token().to_string()),
217                    };
218                    SerialValue::Map(vec![
219                        ("key".to_string(), SerialValue::Str(key.to_string())),
220                        (field.to_string(), SerialValue::Str(value)),
221                    ])
222                })
223                .collect(),
224        )
225    }
226
227    fn piece_class(&self) -> PieceClass {
228        if self.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
229    }
230}
231
232impl SingletonTable for CitationEntries {
233    const NAME: &'static str = "flm.citations.entries";
234}
235
236/// Returns `true` if `tree` contains a citation, that is, a node of `\cite` or
237/// of `\R`.
238fn cites(tree: &NodeTree<Flm>) -> bool {
239    tree.root().descendants().any(|node| element_value::<CitationElement>(&node).is_some())
240}
241
242/// Calls the citation providers `providers` for the citation keys `keys`, and
243/// returns one result for each citation key, in the order of `keys`.
244///
245/// The citation providers are called in the order of `providers`, which is
246/// the order of precedence of the service slot. Each citation provider
247/// receives, in one call of [`CitationProvider::answer_all`], the citation
248/// keys for which every citation provider before it returned `Ok(None)`. The
249/// first citation provider that returns an answer or an error for a citation
250/// key determines the result for this citation key.
251///
252/// If a citation provider returns a different number of results than it
253/// received citation keys, the result for each of these citation keys is
254/// [`MissingEntry::Failed`], and no later citation provider is called. A
255/// citation key for which every citation provider returned `Ok(None)` has the
256/// result [`MissingEntry::UnknownProvider`]. If `providers` is empty, every
257/// citation key has the result [`MissingEntry::NoProviderInstalled`].
258fn retrieve(keys: &[&str], providers: &[&dyn CitationProvider], cx: &ProviderCx<'_>) -> Vec<Retrieval> {
259    if providers.is_empty() {
260        return keys.iter().map(|_| Retrieval::Missing(MissingEntry::NoProviderInstalled)).collect();
261    }
262    let mut decided: Vec<Option<Retrieval>> = keys.iter().map(|_| None).collect();
263    let mut pending: Vec<usize> = (0..keys.len()).collect();
264    for provider in providers {
265        if pending.is_empty() {
266            break;
267        }
268        let requests: Vec<CitationRequest> = pending.iter().map(|&at| CitationRequest::new(keys[at])).collect();
269        let answers = provider.answer_all(&requests, cx);
270        if answers.len() != requests.len() {
271            let error = CitationProviderError::new(format!(
272                "the citation provider returned {} for {}; expected one result per key",
273                counted(answers.len(), "result", "results"),
274                counted(requests.len(), "key", "keys")
275            ));
276            for &at in &pending {
277                decided[at] = Some(Retrieval::Missing(MissingEntry::Failed(error.clone())));
278            }
279            pending.clear();
280            break;
281        }
282        let mut unclaimed = Vec::new();
283        for (&at, answer) in pending.iter().zip(answers) {
284            match answer {
285                Ok(None) => unclaimed.push(at),
286                Ok(Some(answer)) => decided[at] = Some(Retrieval::Found(answer)),
287                Err(error) => decided[at] = Some(Retrieval::Missing(MissingEntry::Failed(error))),
288            }
289        }
290        pending = unclaimed;
291    }
292    decided.into_iter().map(|found| found.unwrap_or(Retrieval::Missing(MissingEntry::UnknownProvider))).collect()
293}
294
295/// Returns `count` followed by the noun, `one` for a count of one and `many`
296/// otherwise: `1 answer`, `2 answers`.
297fn counted(count: usize, one: &str, many: &str) -> String {
298    format!("{count} {}", if count == 1 { one } else { many })
299}
300
301/// Checks the citation entry `entry`, and returns the reason for refusing it,
302/// or `None` if the citation entry is accepted.
303///
304/// The content of the citation entry is first brought up to date as the
305/// document would show it ([value
306/// catch-up](crate::guide::concepts_overview#value-catch-up)): the rewrite
307/// stages of the plan run over it, and expand the user definitions that it
308/// uses. The citation entry is refused if this fails
309/// ([`MissingEntry::Unprocessable`]), if its content then contains a citation
310/// ([`MissingEntry::Cites`]), or if its content contains a paragraph break or
311/// a block ([`MissingEntry::NotInline`]). The diagnostics reported while the
312/// content is brought up to date are added to `diags`.
313fn refusal(cx: &StageCx<'_>, entry: &CitationEntry, diags: &mut FlmDiagnostics) -> Option<MissingEntry> {
314    // The entry is tested as the document would show it, so that a citation or
315    // block content reached through a user definition is refused as it is when
316    // written directly.
317    let caught = match cx.resolve_value(&entry.content) {
318        Ok(caught) => caught,
319        Err(error) => {
320            if let Some(diagnostic) = error.diagnostic() {
321                diags.push(diagnostic.clone());
322            }
323            return Some(MissingEntry::Unprocessable);
324        }
325    };
326    for diagnostic in caught.diags {
327        diags.push(diagnostic);
328    }
329    if cites(&caught.tree) {
330        return Some(MissingEntry::Cites);
331    }
332    let content: Vec<NodeRef<'_, Flm>> = caught.tree.root().children().iter().collect();
333    if run_holds_blocks(&content) {
334        return Some(MissingEntry::NotInline);
335    }
336    None
337}
338
339/// The retrieve stage [`RETRIEVE`], a compute stage that runs once for the
340/// whole document.
341///
342/// The stage reads the cited keys from the table [`KEYS`], and calls the
343/// citation providers of the service slot [`PROVIDERS_SLOT`] for them
344/// ([`retrieve`]). It checks the citation entry of each answer ([`refusal`])
345/// and writes the results to the table [`ENTRIES`]. Then it numbers the cited
346/// works ([`number_works`]) and writes the numbers to the table [`CITATIONS`].
347///
348/// The cited works are numbered by the identities that the answers give
349/// ([`CitationAnswer::identity_for`]). The identity in an answer counts also
350/// when the stage refuses the citation entry of the answer. The identity of a
351/// citation key without an answer is the citation key itself.
352///
353/// The stage reports the following diagnostics at the first citation of the
354/// citation key concerned:
355///
356/// - [`ProviderFailed`] for an error of a citation provider;
357/// - [`ProviderWarning`] for each warning text of an answer;
358/// - [`EntryCites`] or [`EntryNotInline`] for a refused citation entry.
359///
360/// If the document cites works and the service slot contains no citation
361/// provider, the stage reports [`NoProvider`] once, at the first citation of
362/// the document. The diagnostics reported while a citation entry is brought up
363/// to date are reported at the content of the citation entry.
364#[derive(Debug, Default)]
365pub(super) struct Retrieve;
366
367impl Stage for Retrieve {
368    fn decl(&self) -> StageDecl {
369        StageDecl::new(RETRIEVE, Effect::Compute, Scope::Document).writes(ENTRIES).writes(CITATIONS).docs(
370            "Retrieves the citation entries of the cited keys from the citation providers in \
371             `flm.citations.providers` and writes them to `flm.citations.entries`, then numbers \
372             the cited works in order of first citation and writes the numbers to `flm.citations`.",
373        )
374    }
375
376    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
377        Needs::new().reads(KEYS)
378    }
379
380    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
381        let cited = match cx.get(KEYS) {
382            Ok(Some(cited)) => cited,
383            Ok(None) => return,
384            Err(error) => return stage_failed(out, RETRIEVE, error),
385        };
386        let providers: Vec<&dyn CitationProvider> =
387            cx.registry().services().services_by_precedence_named::<dyn CitationProvider>(PROVIDERS_SLOT).collect();
388        let provider_cx = ProviderCx::new(cx.registry().lang(), cx.progress());
389        if providers.is_empty() {
390            if let Some((key, span)) = cited.iter().next() {
391                out.diags.push(Diagnostic::error(NoProvider { key: key.to_string() }, span.clone()));
392            }
393        }
394        let keys: Vec<&str> = cited.iter().map(|(key, _)| key).collect();
395        let answers = retrieve(&keys, &providers, &provider_cx);
396        let mut entries = CitationEntries::default();
397        let mut identities: Vec<(&str, String)> = Vec::with_capacity(keys.len());
398        for ((key, span), mut found) in cited.iter().zip(answers) {
399            let identity = match &found {
400                Retrieval::Found(answer) => answer.identity_for(key).to_string(),
401                Retrieval::Missing(_) => key.to_string(),
402            };
403            identities.push((key, identity));
404            if let Retrieval::Found(answer) = &found {
405                for detail in &answer.warnings {
406                    let warning = ProviderWarning { key: key.to_string(), detail: detail.clone() };
407                    out.diags.push(Diagnostic::warning(warning, span.clone()));
408                }
409                if let Some(missing) = refusal(cx, &answer.entry, &mut out.diags) {
410                    found = Retrieval::Missing(missing);
411                }
412            }
413            let (owned, span) = (key.to_string(), span.clone());
414            match &found {
415                Retrieval::Missing(MissingEntry::Failed(error)) => out.diags.push(Diagnostic::error(
416                    ProviderFailed { key: owned, detail: error.detail.clone() },
417                    span,
418                )),
419                Retrieval::Missing(MissingEntry::Cites) => out.diags.push(Diagnostic::error(EntryCites { key: owned }, span)),
420                Retrieval::Missing(MissingEntry::NotInline) => {
421                    out.diags.push(Diagnostic::error(EntryNotInline { key: owned }, span))
422                }
423                _ => {}
424            }
425            entries.record(key, found);
426        }
427        let works = number_works(identities.iter().map(|(key, identity)| (*key, identity.as_str())));
428        match out.table(ENTRIES) {
429            Ok(table) => *table = entries,
430            Err(error) => stage_failed(out, RETRIEVE, error),
431        }
432        match out.table(CITATIONS) {
433            Ok(table) => *table = works,
434            Err(error) => stage_failed(out, RETRIEVE, error),
435        }
436    }
437}