flm_core/stdlib/features/citations/elements.rs
1//! The two elements of the `citations` feature, `\cite` and `\R`, their
2//! argument declarations, and the reader of a citation chunk.
3//!
4//! A citation chunk is a `\cite` together with the `\cite` calls written
5//! directly after it, or the `\cite` calls written directly after an `\R`
6//! (see the [module documentation](super#citation-chunks)). The further calls
7//! are fields named `cite` ([`CITE_FIELD`]) of a tack-on argument (the
8//! trailing argument that absorbs field macros; see
9//! [fields](crate::guide::concepts_overview#fields-data-a-construct-reads)):
10//! [`MORE_ARG`] on `\cite`, [`CITATION_ARG`] on `\R`. [`read_chunk`] reads a
11//! citation chunk; the stages and the general lowering rules read through it,
12//! and the rules of the recomposed LaTeX read the same way, one call at a
13//! time, so every reader gets the same citation keys.
14
15use std::sync::{Arc, LazyLock};
16
17use techy::core::node::NodeRef;
18use techy::extract::split_at_chars_drop_annotations;
19
20use crate::core::lowering::{spelling_at_lowering, LowerError};
21use crate::lang::mint::{is_field_named, ArgDef, ArgStdKind, TackOnField};
22use crate::lang::{Flm, FlmSpan};
23use crate::model::aspects::{
24 ApartFromText, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole, InlineSpacing,
25};
26use crate::model::element::{element_value, ElementSpec};
27use crate::stdlib::backends::pres::spelling_identity;
28
29/// The name of the element of `\cite`, `flm.citations.cite`. One node of it
30/// carries one citation chunk: its own call and the calls written directly
31/// after it, held in its tack-on argument [`MORE_ARG`].
32pub const CITE: &str = "flm.citations.cite";
33
34/// The name of the element of `\R`, `flm.citations.refcite`. One node of it
35/// carries the citation chunk written directly after the `\R`, shown as a
36/// noun of its sentence with the citation counter style's word before its
37/// citation mark.
38pub const REFCITE: &str = "flm.citations.refcite";
39
40/// The name of a call's optional note argument, `note`.
41pub const NOTE_ARG: &str = "note";
42
43/// The name of a call's citation keys argument, `keys`.
44pub const KEYS_ARG: &str = "keys";
45
46/// The argument role of citation keys, `flm.citations.key`: the role of the
47/// keys argument ([`KEYS_ARG`]) of `\cite` and of the `cite` fields that
48/// `\cite` and `\R` take.
49pub const KEY_ARG_ROLE: &str = "flm.citations.key";
50
51/// The name of the tack-on argument of `\cite` that holds the further calls of
52/// its citation chunk, `more`.
53pub const MORE_ARG: &str = "more";
54
55/// The name of the field that each further call of a citation chunk is read
56/// as, `cite`: `\cite{a}\cite{b}` is one `\cite` node whose argument
57/// [`MORE_ARG`] holds one field named `cite`. The `\cite` written after an
58/// `\R` is also a field of this name, in the argument [`CITATION_ARG`].
59pub const CITE_FIELD: &str = "cite";
60
61/// The name of `\R`'s optional flags argument, `flags`.
62pub const FLAGS_ARG: &str = "flags";
63
64/// The name of `\R`'s tack-on argument, `citation`, which holds the `\cite`
65/// written directly after the `\R` as a field named [`CITE_FIELD`].
66pub const CITATION_ARG: &str = "citation";
67
68/// The per-value data of the two elements: whether a node is a `\cite` or an
69/// `\R`, the two kinds of node that carry a citation chunk.
70///
71/// [`read_chunk`] reads a citation chunk from either: from a `\cite` node's
72/// own arguments and its further calls, or from the field `cite` written
73/// after an `\R`. The stages find the nodes carrying a citation chunk by this
74/// type (`walk_values_of::<CitationElement>` over the element index).
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum CitationElement {
77 /// `\cite[note]{keys}`, attached to the content before it.
78 Cite,
79 /// `\R[flags]\cite[note]{keys}`, a noun of its sentence, its citation mark
80 /// standalone.
81 RefCite,
82}
83
84/// The citation keys of a citation chunk are not words of the text around
85/// it, and neither are the flags of an `\R`; the notes are. A heading without
86/// a label gets an identifier encoded from the text of its title
87/// ([`ApartFromText`]); when the title holds `\cite[Thm 4]{a}`, that text is
88/// the title's own words and `Thm 4`, without the citation key `a`.
89impl ApartFromText for CitationElement {
90 fn apart_from_text(&self, node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
91 let mut apart: Vec<ContentRef> = calls(node)
92 .iter()
93 .filter_map(|call| call.argument_content_nodes_named(KEYS_ARG).ok().flatten())
94 .flat_map(|keys| keys.iter().map(|key| ContentRef::Node(key.id())).collect::<Vec<_>>())
95 .collect();
96 if *self == CitationElement::RefCite {
97 apart.push(ContentRef::ArgumentNamed(FLAGS_ARG.to_string()));
98 }
99 apart
100 }
101}
102
103/// The note and the keys of one call, the two arguments `\cite` and its field
104/// share.
105fn call_args() -> Vec<ArgDef> {
106 vec![
107 ArgDef::named(NOTE_ARG, ArgStdKind::Optional)
108 .docs("A note shown after the numbers, `[1; Thm 4]`; it belongs to every citation key of the call."),
109 ArgDef::named(KEYS_ARG, ArgStdKind::Mandatory)
110 .docs(
111 "The citation keys of the cited works, separated by commas; a citation key is FLM code, kept as typed, and a comma inside braces belongs to it.",
112 )
113 .role(KEY_ARG_ROLE)
114 .with_opaque_wrapper(),
115 ]
116}
117
118/// The field `cite` that holds one further call of a citation chunk, and may
119/// be repeated: the note and the citation keys of that call.
120fn more_field() -> TackOnField {
121 TackOnField::new(CITE_FIELD, call_args())
122 .repeatable()
123 .docs("A further call of the citation chunk, `\\cite[note]{keys}`; may be repeated.")
124}
125
126/// The tack-on argument [`MORE_ARG`], which holds the further calls of a
127/// citation chunk.
128fn more_arg() -> ArgDef {
129 ArgDef::named(MORE_ARG, ArgStdKind::TackOn { fields: vec![more_field()] })
130 .docs("Further `\\cite` calls written directly after this one, read with it as one citation chunk.")
131}
132
133/// The argument declarations of `\cite`, in order: the note ([`NOTE_ARG`]),
134/// the citation keys ([`KEYS_ARG`]), and the further calls of the citation
135/// chunk ([`MORE_ARG`]).
136pub fn cite_args() -> Vec<ArgDef> {
137 let mut args = call_args();
138 args.push(more_arg());
139 args
140}
141
142/// The argument declarations of `\R`, in order: the flags ([`FLAGS_ARG`]),
143/// then the tack-on argument [`CITATION_ARG`], which takes the `\cite`
144/// written directly after the `\R` as a field named `cite` with `\cite`'s
145/// three arguments. `\R[S]\cite{a,b}\cite{c}` therefore reads as one citation
146/// chunk, and `\R[S]{\cite{a}}` holds no citation, because the `\cite` is
147/// inside a group.
148pub fn refcite_args() -> Vec<ArgDef> {
149 let mut field_args = call_args();
150 field_args.push(more_arg());
151 let field = TackOnField::new(CITE_FIELD, field_args)
152 .docs("The citation that `\\R` writes as a noun: `\\cite[note]{keys}`, with its further calls.");
153 vec![
154 ArgDef::named(FLAGS_ARG, ArgStdKind::Optional)
155 .docs("Flags: `S` writes the capitalized word before the citation mark (`Refs.~`), `I` writes no word.")
156 .with_opaque_wrapper(),
157 ArgDef::named(CITATION_ARG, ArgStdKind::TackOn { fields: vec![field] })
158 .docs("The citation written directly after `\\R`."),
159 ]
160}
161
162static CITE_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
163 // A mark is attached to the content before it: the whitespace the author
164 // wrote before `\cite` is removed, and the rule writes the space the form
165 // calls for.
166 let role = BlockRole::Inline(InlineSpacing { absorb_before: true, absorb_after: false });
167 Arc::new(
168 ElementSpec::new(CITE)
169 .docs("A citation chunk, `\\cite[note]{keys}`, attached to the content before it.")
170 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(role)))
171 .with::<dyn ApartFromText>(Arc::new(CitationElement::Cite))
172 .with_value(Arc::new(CitationElement::Cite)),
173 )
174});
175
176/// The element value of every `\cite` node (one value, shared by all of
177/// them), as the feature registers it.
178pub fn cite_element() -> Arc<ElementSpec> {
179 Arc::clone(&CITE_ELEMENT)
180}
181
182static REFCITE_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
183 Arc::new(
184 ElementSpec::new(REFCITE)
185 .docs("A citation chunk written as a noun, `\\R\\cite{keys}`, after a word, `ref.~` or `refs.~` by default.")
186 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
187 .with::<dyn ApartFromText>(Arc::new(CitationElement::RefCite))
188 .with_value(Arc::new(CitationElement::RefCite)),
189 )
190});
191
192/// The element value of every `\R` node (one value, shared by all of them),
193/// as the feature registers it.
194pub fn refcite_element() -> Arc<ElementSpec> {
195 Arc::clone(&REFCITE_ELEMENT)
196}
197
198// --- the chunk reader ------------------------------------------------------------------------
199
200/// The fields named [`CITE_FIELD`] among the content of the argument `arg`
201/// of `node`, in order.
202fn fields_in<'t>(node: &NodeRef<'t, Flm>, arg: &str) -> Vec<NodeRef<'t, Flm>> {
203 match node.argument_content_nodes_named(arg) {
204 Ok(Some(content)) => content.iter().filter(|field| is_field_named(field, CITE_FIELD)).collect(),
205 _ => Vec::new(),
206 }
207}
208
209/// Returns the first call of the citation chunk that `node` carries: the
210/// `\cite` node itself, or the field `cite` written after an `\R`. Returns
211/// `None` for an `\R` with no `\cite` directly after it, and for a node of
212/// neither element.
213pub fn leading_call<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeRef<'t, Flm>> {
214 match element_value::<CitationElement>(node)? {
215 CitationElement::Cite => Some(*node),
216 CitationElement::RefCite => fields_in(node, CITATION_ARG).into_iter().next(),
217 }
218}
219
220/// Returns every call of the citation chunk that `node` carries, in the order
221/// written: the first call ([`leading_call`]), then the further calls held in
222/// its argument [`MORE_ARG`]. Each call holds the arguments [`NOTE_ARG`] and
223/// [`KEYS_ARG`]. Returns an empty list where [`leading_call`] returns
224/// `None`.
225pub fn calls<'t>(node: &NodeRef<'t, Flm>) -> Vec<NodeRef<'t, Flm>> {
226 let Some(leader) = leading_call(node) else { return Vec::new() };
227 let mut out = vec![leader];
228 out.extend(fields_in(&leader, MORE_ARG));
229 out
230}
231
232/// One item of a citation chunk: a citation key, and the note of the call it
233/// was written in.
234#[derive(Debug, Clone)]
235pub struct CitationItem<'t> {
236 /// The citation key: the FLM code written for it, recomposed from the
237 /// parsed nodes, with every run of whitespace made one space and the ends
238 /// trimmed ([`spelling_identity`]).
239 pub key: String,
240 /// The content of the call's note, when the call has one: the same nodes
241 /// for every citation key of that call.
242 pub note: Option<Vec<NodeRef<'t, Flm>>>,
243}
244
245/// A mistake in the writing of one call of a citation chunk, found by
246/// [`read_chunk`]; the call contributes no item. [`report_mistakes`](super::report_mistakes)
247/// reports each one as a diagnostic.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum ChunkMistake {
250 /// The call holds no citation key: `\cite{}`, `\cite{ , }`. Reported as
251 /// [`NoKey`](super::NoKey).
252 NoKey {
253 /// The call's span.
254 span: FlmSpan,
255 },
256}
257
258/// A citation chunk as [`read_chunk`] returns it: its items in the order
259/// written, and the mistakes of its calls.
260#[derive(Debug, Clone, Default)]
261pub struct Chunk<'t> {
262 /// The items, one per key, in the order written: `\cite[Thm 4]{a,b}`
263 /// gives `(a, Thm 4)` and `(b, Thm 4)`.
264 pub items: Vec<CitationItem<'t>>,
265 /// The calls that contribute no item, and why.
266 pub mistakes: Vec<ChunkMistake>,
267}
268
269/// Where a citation chunk is read: in a lowering rule or in a stage. The two
270/// differ in how they treat citation keys that hold a placeholder of a user
271/// definition's template (`\cite{arxiv:#1}` inside a template). Such citation
272/// keys are not known until the template is expanded, because a placeholder
273/// has no spelling of its own.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub enum Reading {
276 /// In a lowering rule: the citation keys are checked with
277 /// [`spelling_at_lowering`], and a placeholder among them makes
278 /// [`read_chunk`] return [`LowerError::PlaceholderCharacters`]. The rule
279 /// returns that error unchanged, and the user definition's use sites are
280 /// then expanded rather than written as a definition.
281 AtLowering,
282 /// In a stage: a call whose citation keys hold a placeholder gives no item
283 /// and no mistake.
284 InStage,
285}
286
287/// Reads the citation chunk that `node` carries (a `\cite` node, or an `\R`
288/// node through the field written after it) as a list of items, each a
289/// citation key and its call's note, in the order written. It serves both
290/// elements, in a lowering rule and in a stage (`reading`).
291///
292/// Each call's citation keys are its keys argument, FLM content, split at the
293/// commas that are outside every group, command argument and formula
294/// (`\cite{a,{b,c},d}` gives `a`, `{b,c}`, `d`). Each part is recomposed to
295/// the FLM code it was written as, with every run of whitespace made one space
296/// and the ends trimmed ([`spelling_identity`]), so a citation key holding
297/// braces or a command keeps them. An empty part is skipped (`\cite{a,,b}`
298/// gives `a`, `b`). The reader reads no meaning into a citation key: the
299/// citation providers decide what it refers to. A call with no citation key
300/// gives no item and a [`ChunkMistake`]. An `\R` with no `\cite` directly
301/// after it gives an empty citation chunk.
302///
303/// # Errors
304///
305/// [`LowerError::PlaceholderCharacters`] under [`Reading::AtLowering`], for
306/// citation keys that hold a placeholder of a user definition's template that
307/// is being lowered without expansion.
308pub fn read_chunk<'t>(node: &NodeRef<'t, Flm>, reading: Reading) -> Result<Chunk<'t>, LowerError> {
309 let mut chunk = Chunk::default();
310 for call in calls(node) {
311 read_call(&call, reading, &mut chunk)?;
312 }
313 Ok(chunk)
314}
315
316/// Reads one call of a citation chunk (a call that [`calls`] returns) into
317/// `chunk`: its items are appended in the order written, or its
318/// [`ChunkMistake`] is recorded, exactly as [`read_chunk`] reads each call.
319/// The recomposed LaTeX's rules read a citation chunk call by call, because
320/// they write each call as the author wrote it.
321///
322/// # Errors
323///
324/// As [`read_chunk`].
325pub(super) fn read_call<'t>(call: &NodeRef<'t, Flm>, reading: Reading, chunk: &mut Chunk<'t>) -> Result<(), LowerError> {
326 let keys = match call.argument_content_nodes_named(KEYS_ARG) {
327 Ok(Some(content)) => Some(content),
328 _ => None,
329 };
330 if let Some(keys) = keys {
331 // The source recomposer re-emits nothing for a placeholder, so keys
332 // holding one are not known until the template is expanded.
333 let known = spelling_at_lowering(keys.iter());
334 match reading {
335 Reading::AtLowering => known?,
336 Reading::InStage => {
337 if known.is_err() {
338 return Ok(());
339 }
340 }
341 }
342 }
343 let note: Option<Vec<NodeRef<'t, Flm>>> = match call.argument_content_nodes_named(NOTE_ARG) {
344 Ok(Some(content)) => Some(content.iter().collect()),
345 _ => None,
346 };
347 let before = chunk.items.len();
348 // Splitting fails only on a broken tree (techy cannot build the
349 // segments' tree); such keys give no item.
350 if let Some(Ok(segments)) = keys.map(|keys| split_at_chars_drop_annotations(keys, ",")) {
351 for segment in segments.segments() {
352 let key = spelling_identity(segment.iter());
353 if !key.is_empty() {
354 chunk.items.push(CitationItem { key, note: note.clone() });
355 }
356 }
357 }
358 if chunk.items.len() == before {
359 chunk.mistakes.push(ChunkMistake::NoKey { span: call.span().clone() });
360 }
361 Ok(())
362}