Skip to main content

flm_core/stdlib/features/citations/
providers.rs

1//! The citation providers: the services through which a host gives the
2//! library the citation entries of the cited works.
3//!
4//! A citation provider ([`CitationProvider`]) is a service (a value one
5//! feature, or the embedding program, supplies for another feature to use;
6//! see [services](crate::core::services)) that the host contributes to the
7//! service slot [`PROVIDERS_SLOT`]. The retrieve stage
8//! ([`RETRIEVE`](super::RETRIEVE)) hands it the cited keys
9//! ([`CitationRequest`]) with a context ([`ProviderCx`]), and it returns for
10//! each citation key a [`CitationResult`]: an answer ([`CitationAnswer`],
11//! holding the [`CitationEntry`] and the work's identity), "not mine", or a
12//! [`CitationProviderError`]. A citation provider builds the citation entry
13//! from FLM source ([`ProviderCx::parse_entry`]) or from parts
14//! ([`EntryPiece`], [`ProviderCx::build_entry`]).
15
16use std::fmt;
17use std::sync::Arc;
18
19use techy::core::node::{NodeRef, NodeTree};
20use techy::error::Severity;
21
22use crate::lang::copy::{copy_pieces_into_value, CommandPiece, ValueContent, ValuePiece};
23use crate::lang::{parse_fragment, BuiltLang, Flm, FlmOrigin, FlmSource, ParseOptions};
24use crate::model::doc::{Fragment, FragmentLayout};
25use crate::progress::Scope;
26use crate::stdlib::features::href::HrefCommand;
27use crate::stdlib::features::textstyles::TextStyle;
28
29/// The name of the service slot of the citation providers,
30/// `flm.citations.providers` (declared with
31/// [`service_slot`](crate::core::registry::FeatureBuilder::service_slot)). It
32/// takes any number of [`CitationProvider`] values, asked in the order of
33/// precedence
34/// ([`Services::services_by_precedence_named`](crate::core::services::Services::services_by_precedence_named)):
35/// the providers of the feature placed last in the feature order first, each
36/// feature's in the order it contributed them, and the host's last. The
37/// feature declares it and never requires a
38/// contribution: a registry with no citation provider builds, every cited key
39/// of its documents then has no citation entry, and the retrieve stage
40/// reports [`NoProvider`](super::NoProvider) once per document that cites a
41/// work.
42///
43/// A host contributes a citation provider with
44/// [`RegistryBuilder::contribute_to`](crate::core::registry::RegistryBuilder::contribute_to)
45/// (see the example on [`CitationProvider`]), which places it after every
46/// feature's contribution, or from a feature with
47/// [`FeatureBuilder::contribute_to`](crate::core::registry::FeatureBuilder::contribute_to)
48/// or, where the `citations` feature may be absent from the registry,
49/// [`FeatureBuilder::peer_slot`](crate::core::registry::FeatureBuilder::peer_slot).
50pub const PROVIDERS_SLOT: &str = "flm.citations.providers";
51
52/// What the retrieve stage asks a citation provider about one cited key.
53///
54/// New fields may be added: a citation provider reads the fields it needs,
55/// and only the retrieve stage creates a request.
56#[derive(Debug, Clone, PartialEq, Eq)]
57#[non_exhaustive]
58pub struct CitationRequest {
59    /// The citation key, as the author wrote it between the braces of
60    /// `\cite`, recomposed from the parsed nodes, with every run of whitespace
61    /// made one space and the ends trimmed: `knuth84`, `arxiv:1234.5678`. The
62    /// library reads no meaning into it; the citation provider decides what a
63    /// prefix such as `arxiv:` means.
64    pub key: String,
65}
66
67impl CitationRequest {
68    /// Creates the request for the citation key `key`.
69    pub(super) fn new(key: impl Into<String>) -> CitationRequest {
70        CitationRequest { key: key.into() }
71    }
72}
73
74/// The citation entry of one cited work: what the list of cited works shows
75/// for it, and what a citation mark shows for it under the in-place placement
76/// ([`CitationPlacement::InPlace`](super::CitationPlacement::InPlace)).
77///
78/// Its content is a [synthesized
79/// value](crate::guide::concepts_overview#synthesized-values) (a small tree
80/// held outside the document's trees) of inline content in the document's own
81/// vocabulary: text, `\emph`, a link, a formula. It must state no fact about
82/// the document: a citation entry that declares a label is refused where it
83/// is shown, as any synthesized value stating such a fact is (see [value
84/// catch-up](crate::guide::concepts_overview#value-catch-up)). The retrieve
85/// stage reads each citation entry as the document would show it, with user
86/// definitions expanded, and refuses one that holds a citation (`\cite`,
87/// `\R`) or block content (a paragraph break, a list, a heading); the citation
88/// key then has no citation entry.
89///
90/// New fields may be added; build one with [`ProviderCx::parse_entry`],
91/// [`ProviderCx::build_entry`] or [`CitationEntry::new`].
92#[derive(Debug, Clone)]
93#[non_exhaustive]
94pub struct CitationEntry {
95    /// The citation entry's content: a synthesized value's tree, as
96    /// [`copy_run_into_value`](crate::lang::copy::copy_run_into_value) makes
97    /// one, whose root's children are the content.
98    pub content: Arc<NodeTree<Flm>>,
99}
100
101impl CitationEntry {
102    /// Creates the citation entry that shows `content`, a synthesized value's
103    /// tree whose root's children are inline content. A citation provider
104    /// usually calls [`ProviderCx::parse_entry`] or [`ProviderCx::build_entry`]
105    /// instead, which make such a tree.
106    pub fn new(content: Arc<NodeTree<Flm>>) -> CitationEntry {
107        CitationEntry { content }
108    }
109}
110
111/// A citation provider's answer for a citation key it knows: the work's
112/// citation entry, the work's identity, and warnings for the author.
113///
114/// The **identity** of a cited work is one spelling of its citation key that
115/// every citation key referring to the same work shares: `arxiv:1211.1037`
116/// for both `arXiv:1211.1037` and `arxiv:1211.1037`. Citation keys answered
117/// with the same identity are one cited work: one number, one identifier, one
118/// entry in the list of cited works. Identities are compared as characters,
119/// across the answers of every citation provider, so a citation provider
120/// writes a work's identity in the spelling that any citation provider
121/// answering for the same work would use. Only a citation provider knows which
122/// citation keys refer to one work: the library reads no meaning into a
123/// citation key.
124///
125/// An answer that gives no identity has the citation key as written as its
126/// identity: the work is then a work of its own, unless another citation
127/// key's answer gives that citation key as its identity.
128///
129/// An answer may also carry **warnings**: what the citation provider has to
130/// tell the author about the citation key, for example that two citation keys
131/// cited as two works refer to the same work. Each warning is reported as a
132/// Warning ([`ProviderWarning`](super::ProviderWarning),
133/// `flm.citations.provider-warning`) at the citation key's first citation,
134/// with the citation provider's text as its message; the citation entry is
135/// shown and the numbering is unchanged.
136///
137/// New fields may be added; build one with [`CitationAnswer::new`] and the
138/// builders [`with_identity`](CitationAnswer::with_identity) and
139/// [`with_warning`](CitationAnswer::with_warning).
140#[derive(Debug, Clone)]
141#[non_exhaustive]
142pub struct CitationAnswer {
143    /// The work's citation entry.
144    pub entry: CitationEntry,
145    /// The work's identity, or `None` to use the citation key as written.
146    pub identity: Option<String>,
147    /// What the citation provider tells the author about the citation key,
148    /// each a sentence in the citation provider's own words, reported as a
149    /// Warning at the citation key's first citation.
150    pub warnings: Vec<String>,
151}
152
153impl CitationAnswer {
154    /// Creates the answer that shows `entry`, with no identity (the citation
155    /// key as written is the work's identity) and no warning.
156    pub fn new(entry: CitationEntry) -> CitationAnswer {
157        CitationAnswer { entry, identity: None, warnings: Vec::new() }
158    }
159
160    /// Builder: sets the work's identity to `identity`. Every citation key
161    /// answered with the same identity refers to the same work.
162    pub fn with_identity(mut self, identity: impl Into<String>) -> CitationAnswer {
163        self.identity = Some(identity.into());
164        self
165    }
166
167    /// Builder: adds the warning `text`, a sentence stating what the author
168    /// should know about the citation key, reported as a Warning at the
169    /// citation key's first citation. Warnings are reported in the order they
170    /// were added.
171    pub fn with_warning(mut self, text: impl Into<String>) -> CitationAnswer {
172        self.warnings.push(text.into());
173        self
174    }
175
176    /// Returns the identity of the work this answer gives for `key`: its
177    /// identity where it has one, else `key` itself.
178    pub fn identity_for<'a>(&'a self, key: &'a str) -> &'a str {
179        self.identity.as_deref().unwrap_or(key)
180    }
181}
182
183/// What a citation provider returns for one citation key: `Ok(Some(answer))`
184/// for a citation key it serves, `Ok(None)` ("not mine") for a citation key it
185/// does not serve, so that the next citation provider is asked, or an error for
186/// a citation key it claims and could not answer.
187pub type CitationResult = Result<Option<CitationAnswer>, CitationProviderError>;
188
189/// One part of the content of a citation entry that a citation provider
190/// builds with [`ProviderCx::build_entry`]: characters, FLM source, or a
191/// group of parts with a meaning (emphasis, strong importance, a link).
192///
193/// Each group is written as the command of the feature that owns its
194/// meaning: `\emph` and `\textbf` (the `textstyles` feature), `\href` (the
195/// `href` feature). A citation entry built from parts is therefore shown on
196/// every output exactly as the same content written in FLM. A group whose
197/// command the registry's language does not define shows its content alone.
198///
199/// New kinds of parts may be added.
200#[derive(Debug, Clone)]
201#[non_exhaustive]
202pub enum EntryPiece {
203    /// Characters, shown exactly as they are, `%` and `\` included.
204    Text(String),
205    /// FLM source, parsed as inline content under the registry's language, as
206    /// [`ProviderCx::parse_entry`] parses it: a formula in a title.
207    Source(Arc<FlmSource>),
208    /// Emphasized content (`\emph`).
209    Emphasized(Vec<EntryPiece>),
210    /// Content of strong importance, set in bold (`\textbf`).
211    Strong(Vec<EntryPiece>),
212    /// A link to `address` around content (`\href`). The address is passed on
213    /// unchanged; the feature that owns links decides what each output does
214    /// with it.
215    Link {
216        /// The address the link goes to: `https://doi.org/10.1103/…`.
217        address: String,
218        /// What the link shows.
219        content: Vec<EntryPiece>,
220    },
221}
222
223impl EntryPiece {
224    /// Creates a part of characters: `EntryPiece::Text(text.into())`.
225    pub fn text(text: impl Into<String>) -> EntryPiece {
226        EntryPiece::Text(text.into())
227    }
228}
229
230/// Why a citation provider could not answer for a citation key it claims, in
231/// the citation provider's own words. The retrieve stage reports it in the
232/// Error [`ProviderFailed`](super::ProviderFailed), and no later citation
233/// provider is asked about that citation key.
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub struct CitationProviderError {
236    /// What went wrong, in the citation provider's words: `the server did not
237    /// answer`.
238    pub detail: String,
239}
240
241impl CitationProviderError {
242    /// Creates the error that says `detail`.
243    pub fn new(detail: impl Into<String>) -> CitationProviderError {
244        CitationProviderError { detail: detail.into() }
245    }
246}
247
248impl fmt::Display for CitationProviderError {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.write_str(&self.detail)
251    }
252}
253
254impl std::error::Error for CitationProviderError {}
255
256/// The context the retrieve stage gives a citation provider together with the
257/// requests: the built language of the registry, through which the citation
258/// provider makes its citation entries into content of the document's
259/// vocabulary ([`parse_entry`](ProviderCx::parse_entry),
260/// [`build_entry`](ProviderCx::build_entry)), and the scope under which it
261/// reports its slow work on the progress sheet of the build
262/// ([`progress`](ProviderCx::progress)).
263#[derive(Debug, Clone, Copy)]
264pub struct ProviderCx<'a> {
265    lang: &'a BuiltLang,
266    progress: &'a Scope,
267}
268
269impl<'a> ProviderCx<'a> {
270    /// Creates the context of a request under the built language `lang`,
271    /// reporting under `progress`.
272    pub(super) fn new(lang: &'a BuiltLang, progress: &'a Scope) -> ProviderCx<'a> {
273        ProviderCx { lang, progress }
274    }
275
276    /// Returns the scope of the retrieve stage's row on the progress sheet of
277    /// the build ([`StageCx::progress`](crate::core::run::StageCx::progress)).
278    ///
279    /// The stage declares no row of its own: a citation provider that does
280    /// slow work, such as fetching citation entries over the network, declares
281    /// its rows under this scope ([`Scope::child`]), counting the citation
282    /// keys that are slow to answer and not those it answers from a cache. It
283    /// asks [`cancelled`](Scope::cancelled) between two such keys, and returns
284    /// as soon as it can when the build was cancelled: what a cancelled step
285    /// produced is discarded whole, so what it returns need not be
286    /// meaningful. In a build that reports nowhere, the scope is
287    /// [`Scope::none`], whose methods do nothing; the provider calls them all
288    /// the same.
289    pub fn progress(&self) -> &'a Scope {
290        self.progress
291    }
292
293    /// Returns the built language of the registry the document is processed
294    /// under.
295    pub fn lang(&self) -> &'a BuiltLang {
296        self.lang
297    }
298
299    /// Returns the citation entry whose content is `source`, FLM parsed as
300    /// inline content under the registry's language: `Knuth, \emph{The Art of
301    /// Computer Programming}`. The source's origin says where the text came
302    /// from, so a diagnostic about the citation entry's content points there.
303    ///
304    /// The source must be inline content: a citation entry holding a paragraph
305    /// break or a block (a list, a heading) is returned, and the retrieve stage
306    /// then refuses it.
307    ///
308    /// The retrieve stage calls the citation providers on a worker thread (a
309    /// thread with a large enough stack; see
310    /// [`on_worker_thread`](crate::lang::guard::on_worker_thread)); a citation
311    /// provider that calls this method on another thread of its own runs it on
312    /// a worker thread too, as the copy into a synthesized value requires.
313    ///
314    /// # Errors
315    ///
316    /// A [`CitationProviderError`] holding the message of the first Error the
317    /// parse reports (an unknown command, a brace left open), or the failure
318    /// of the parse or of the copy into a synthesized value (content nesting
319    /// too deeply).
320    pub fn parse_entry(&self, source: Arc<FlmSource>) -> Result<CitationEntry, CitationProviderError> {
321        let fragment = self.parse_inline(source)?;
322        let root = fragment.tree().root();
323        let nodes: Vec<ValuePiece<'_, '_>> = root.children().iter().map(ValuePiece::Node).collect();
324        self.copy(&nodes, &root).map(CitationEntry::new)
325    }
326
327    /// Returns the citation entry made of `pieces`, in order: characters shown
328    /// as they are, FLM source parsed as [`parse_entry`](ProviderCx::parse_entry)
329    /// parses it, and groups written as the commands of the features that own
330    /// their meaning ([`EntryPiece`]). A citation provider that holds a work's
331    /// citation entry as structured parts (a formatter's italic and bold runs,
332    /// a link) uses it to make content with no text to escape and nothing to
333    /// parse back.
334    ///
335    /// The characters of a text part, and the groups, come from no source
336    /// text: a diagnostic about them has no position.
337    ///
338    /// The retrieve stage calls the citation providers on a worker thread (a
339    /// thread with a large enough stack; see
340    /// [`on_worker_thread`](crate::lang::guard::on_worker_thread)); a citation
341    /// provider that calls this method on another thread of its own runs it on
342    /// a worker thread too, as the copy into a synthesized value requires.
343    ///
344    /// # Errors
345    ///
346    /// A [`CitationProviderError`] holding the message of the first Error a
347    /// source part's parse reports, or the failure of a copy (content nesting
348    /// too deeply, or a group's command that could not be looked up in the
349    /// language).
350    pub fn build_entry(&self, pieces: &[EntryPiece]) -> Result<CitationEntry, CitationProviderError> {
351        let anchor = self.parse_inline(Arc::new(FlmSource::new("").with_origin(FlmOrigin::none())))?;
352        self.build(pieces, &anchor.tree().root()).map(CitationEntry::new)
353    }
354
355    /// Parses `source` as inline content; refuses it with the first Error the
356    /// parse reports.
357    fn parse_inline(&self, source: Arc<FlmSource>) -> Result<Fragment, CitationProviderError> {
358        let fragment =
359            parse_fragment(self.lang, source, FragmentLayout::Inline, &ParseOptions::default())
360                .map_err(|error| CitationProviderError::new(error.to_string()))?;
361        if let Some(error) = fragment.diags().iter().find(|d| d.severity() == Severity::Error) {
362            return Err(CitationProviderError::new(error.message()));
363        }
364        Ok(fragment)
365    }
366
367    /// Copies `pieces` into a synthesized value's tree at `anchor`, as the
368    /// citation entry's own content.
369    fn copy(&self, pieces: &[ValuePiece<'_, '_>], anchor: &NodeRef<'_, Flm>) -> Result<Arc<NodeTree<Flm>>, CitationProviderError> {
370        copy_pieces_into_value(pieces, anchor, ValueContent::Own, self.lang.guard())
371            .map_err(|error| CitationProviderError::new(error.to_string()))
372    }
373
374    /// Builds the synthesized value's tree of `pieces`: each group is built
375    /// first into a tree of its own, whose nodes the whole then copies.
376    fn build(&self, pieces: &[EntryPiece], anchor: &NodeRef<'_, Flm>) -> Result<Arc<NodeTree<Flm>>, CitationProviderError> {
377        enum Part<'p> {
378            Text(&'p str),
379            Tree(Arc<NodeTree<Flm>>),
380        }
381        let mut parts = Vec::with_capacity(pieces.len());
382        for piece in pieces {
383            let part = match piece {
384                EntryPiece::Text(text) => Part::Text(text),
385                EntryPiece::Source(source) => Part::Tree(Arc::clone(self.parse_inline(Arc::clone(source))?.tree())),
386                EntryPiece::Emphasized(content) => {
387                    Part::Tree(self.group(TextStyle::Emphasis.command(), None, content, anchor)?)
388                }
389                EntryPiece::Strong(content) => Part::Tree(self.group(TextStyle::Bold.command(), None, content, anchor)?),
390                EntryPiece::Link { address, content } => {
391                    Part::Tree(self.group(HrefCommand::Href.name(), Some(address), content, anchor)?)
392                }
393            };
394            parts.push(part);
395        }
396        let values: Vec<ValuePiece<'_, '_>> = parts
397            .iter()
398            .flat_map(|part| match part {
399                Part::Text(text) => vec![ValuePiece::Text(text)],
400                Part::Tree(tree) => tree.root().children().iter().map(ValuePiece::Node).collect(),
401            })
402            .collect();
403        self.copy(&values, anchor)
404    }
405
406    /// Builds the tree of the command `\name` around `content`, with the
407    /// characters of `first` as its first argument where there is one; builds
408    /// the tree of `content` alone where the language defines no such
409    /// command.
410    fn group(
411        &self,
412        name: &str,
413        first: Option<&str>,
414        content: &[EntryPiece],
415        anchor: &NodeRef<'_, Flm>,
416    ) -> Result<Arc<NodeTree<Flm>>, CitationProviderError> {
417        let inner = self.build(content, anchor)?;
418        let command = CommandPiece::new(name, anchor.span().clone(), Arc::clone(anchor.parsing_state()))
419            .map_err(|error| CitationProviderError::new(error.to_string()))?;
420        let Some(mut command) = command else {
421            return Ok(inner);
422        };
423        let root = inner.root();
424        let nodes: Vec<ValuePiece<'_, '_>> = root.children().iter().map(ValuePiece::Node).collect();
425        if let Some(first) = first {
426            command.arguments.push(Some(vec![ValuePiece::Text(first)]));
427        }
428        command.arguments.push(Some(nodes));
429        self.copy(&[ValuePiece::Command(&command)], anchor)
430    }
431}
432
433/// A citation provider: a service that answers cited keys with their works'
434/// citation entries and identities. A host contributes citation providers to
435/// the service slot [`PROVIDERS_SLOT`].
436///
437/// The library performs no input or output: a citation provider that reads a
438/// file or asks a server does so as a service of the host. The retrieve stage
439/// hands the citation providers, in the order of the service slot, the
440/// distinct citation keys of a document in order of first citation, each
441/// citation provider in one call ([`answer_all`](CitationProvider::answer_all)).
442/// The first citation provider receives every citation key, and each later
443/// one receives the citation keys that every citation provider before it
444/// answered "not mine". The citation provider that answers a citation key,
445/// with an answer or with an error, decides it. A citation provider that
446/// answers one citation key at a time implements
447/// [`answer`](CitationProvider::answer) alone, and the default
448/// [`answer_all`](CitationProvider::answer_all) calls it for each citation
449/// key; a citation provider that fetches in batches implements both.
450///
451/// A citation provider is asked again in every run, under every workflow, the
452/// `check` workflow included. A citation provider whose answers are costly to
453/// obtain should therefore keep the answers it has given and return them
454/// again, unchanged.
455///
456/// # Examples
457///
458/// A provider answering from a map of FLM texts:
459///
460/// ```
461/// use std::collections::BTreeMap;
462/// use std::sync::Arc;
463///
464/// use flm_core::core::registry::RegistryBuilder;
465/// use flm_core::lang::{FlmOrigin, FlmSource};
466/// use flm_core::stdlib::features::citations::{
467///     CitationAnswer, CitationProvider, CitationRequest, CitationResult, ProviderCx,
468///     PROVIDERS_SLOT,
469/// };
470///
471/// struct FromMap(BTreeMap<String, String>);
472///
473/// impl CitationProvider for FromMap {
474///     fn answer(&self, request: &CitationRequest, cx: &ProviderCx<'_>) -> CitationResult {
475///         let Some(text) = self.0.get(&request.key) else { return Ok(None) };
476///         let source = FlmSource::new(text.as_str()).with_origin(FlmOrigin::new("refs.flm"));
477///         cx.parse_entry(Arc::new(source)).map(|entry| Some(CitationAnswer::new(entry)))
478///     }
479/// }
480///
481/// let entries = BTreeMap::from([("knuth84".to_string(), "Knuth, 1984".to_string())]);
482/// let mut builder = RegistryBuilder::new();
483/// builder.contribute_to(PROVIDERS_SLOT, Arc::new(FromMap(entries)) as Arc<dyn CitationProvider>);
484/// ```
485pub trait CitationProvider: Send + Sync {
486    /// Returns the answer for the work cited as `request.key`:
487    /// `Ok(Some(answer))`, with the citation entry and what this citation
488    /// provider knows of the work ([`CitationAnswer`]); `Ok(None)` for a
489    /// citation key this citation provider does not serve, so that the next
490    /// citation provider is asked; or an error, for a citation key this
491    /// citation provider claims and could not answer, which ends the lookup of
492    /// that citation key.
493    ///
494    /// # Errors
495    ///
496    /// A [`CitationProviderError`] in the citation provider's own words; the
497    /// citation key then has no citation entry, and no later citation provider
498    /// is asked about it.
499    fn answer(&self, request: &CitationRequest, cx: &ProviderCx<'_>) -> CitationResult;
500
501    /// Returns the answers for `requests`, one per request and in the same
502    /// order, each as [`answer`](CitationProvider::answer) describes. The
503    /// default calls [`answer`](CitationProvider::answer) for each request in
504    /// turn; a citation provider that fetches many citation keys at once
505    /// overrides it.
506    ///
507    /// A citation provider must return exactly one result per request. When
508    /// the number differs, every citation key of the call gets an error saying
509    /// so, reported as [`ProviderFailed`](super::ProviderFailed), and no later
510    /// citation provider is asked about these citation keys.
511    fn answer_all(&self, requests: &[CitationRequest], cx: &ProviderCx<'_>) -> Vec<CitationResult> {
512        requests.iter().map(|request| self.answer(request, cx)).collect()
513    }
514}