Skip to main content

flm_core/stdlib/features/citations/
mark.rs

1//! The citation mark of a citation chunk: [`stage_mark`], the only function
2//! that stages one, the feature's settings as the lowering rules read them
3//! ([`MarkSettings`]), and the general lowering rules of `\cite` and `\R`
4//! ([`CiteRule`], [`RefCiteRule`]).
5//!
6//! To stage a node is to build it into the lowered tree through the
7//! [`Lowerer`] a lowering rule is handed. The general rules are the default
8//! rules of `\cite` and `\R` on every backend but the recomposed LaTeX,
9//! which has rules of its own ([`latex`](super::latex)). The general rules
10//! require the feature's style identifier [`STYLE`] (`flm.citations.style`) at every
11//! citation chunk, which each backend resolves as it resolves requirements:
12//! the stylesheet on the `html` backend ([`html`](super::html)), the
13//! definition pieces delivering it on the `latex-rendered` backend, nothing
14//! on the `text` backend.
15//!
16//! The citation mark is a span whose role and kind tokens say what it is (a
17//! role is a feature-owned name that says what a presentation node is, and
18//! kind tokens classify it further; see
19//! [roles and kinds](crate::stdlib::backends::pres::payload)): role
20//! [`MARK_ROLE`], kind token [`ATTACHED`] or [`STANDALONE`], and [`IN_PLACE`]
21//! under the in-place placement. The space before a `\cite`'s citation mark
22//! has the role [`SPACE_ROLE`], and the word before an `\R`'s citation mark
23//! the role [`WORD_ROLE`].
24
25use std::sync::{Arc, OnceLock};
26
27use techy::core::node::{BuildId, NodeRef, NodeTree};
28
29use crate::core::lowering::{
30    chars_at_lowering, DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl,
31    LoweringRule,
32};
33use crate::core::registry::{LateInit, LateInitError};
34use crate::lang::rewrites::userdefs::template::{PlaceholderVocabulary, TemplateLanguage};
35use crate::lang::text::is_space;
36use crate::lang::{BuiltLang, Flm, FlmDiagnostics, FlmSpan};
37use crate::model::names::{ElementName, Name};
38use crate::stdlib::backends::lowering::stage_trimmed;
39use crate::stdlib::backends::pres::{
40    self, DocRole, DroppedPayload, LinkPayload, SpanPayload, SpanStyle, spelling_identity,
41};
42use crate::stdlib::features::numbering::{
43    compile_text, format_many, instantiate_fixed, CounterStyle, CounterValue, FormatOptions,
44    JoinText, NumberedValue,
45};
46
47use super::config::{CitationPlacement, CitationsConfig, MarkForm, CAPITAL_VARIANT};
48use super::diagnostics::{NoCitation, NoKey, Uncollected, UnknownFlag};
49use super::html::STYLE;
50use super::elements::{
51    leading_call, read_chunk, Chunk, ChunkMistake, Reading, CITE, FLAGS_ARG,
52    REFCITE,
53};
54use super::entries::{CitationEntries, ENTRIES};
55use super::numbers::{CitedWorks, CITATIONS};
56
57/// The role of a citation mark's span, `flm.citations.mark`.
58pub const MARK_ROLE: &str = "flm.citations.mark";
59
60/// The role of the span that holds the word `\R` writes before its citation
61/// mark, `flm.citations.word`.
62pub const WORD_ROLE: &str = "flm.citations.word";
63
64/// The role of the span that holds the space written before the citation
65/// mark of a `\cite` ([`space_before`]), `flm.citations.space`.
66///
67/// The space is a character of the text, in a span of its own, so that a
68/// stylesheet can select it (to hide it or change its width) while the text a
69/// reader copies keeps it.
70pub const SPACE_ROLE: &str = "flm.citations.space";
71
72/// The kind token of the citation mark of a `\cite`, `attached`: the citation
73/// mark belongs to the content before it, and the space that its form calls
74/// for is written before it.
75pub const ATTACHED: &str = "attached";
76
77/// The kind token of the citation mark of an `\R`, `standalone`: the citation
78/// mark is a part of its sentence, shown inline, with nothing written before
79/// it.
80pub const STANDALONE: &str = "standalone";
81
82/// The kind token of a citation mark under the in-place placement,
83/// `in-place`, which the span carries after [`ATTACHED`] or [`STANDALONE`]:
84/// the citation mark shows the citation entries.
85pub const IN_PLACE: &str = "in-place";
86
87/// The kind of every link from a citation mark to a cited work, `cite`.
88pub const LINK_KIND: &str = "cite";
89
90/// The name of the general lowering rule of `\cite`,
91/// `flm.citations.cite.lower.default` ([`CiteRule`]), the default on every
92/// backend.
93pub const CITE_RULE: &str = "flm.citations.cite.lower.default";
94
95/// The name of the general lowering rule of `\R`,
96/// `flm.citations.refcite.lower.default` ([`RefCiteRule`]), the default on
97/// every backend.
98pub const REFCITE_RULE: &str = "flm.citations.refcite.lower.default";
99
100/// The flag of `\R` that selects the capitalized word (the citation counter style's
101/// variant [`CAPITAL_VARIANT`]), `S`.
102pub const CAPITAL_FLAG: char = 'S';
103
104/// The flag of `\R` that writes no word, only the citation mark, `I`.
105pub const INLINE_FLAG: char = 'I';
106
107/// The no-break space (U+00A0) written before an attached citation mark,
108/// under the bracketed form and under the in-place placement.
109pub const NO_BREAK_SPACE: &str = "\u{a0}";
110
111/// How a citation mark is placed in its sentence: attached to the content
112/// before it (`\cite`) or standing alone (`\R`).
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum Standing {
115    /// The citation mark of a `\cite`: attached to the content before it,
116    /// with the space of its form written before it ([`space_before`]).
117    Attached,
118    /// The citation mark of an `\R`: a part of its sentence, shown inline and
119    /// never raised, with nothing written before it.
120    Standalone,
121}
122
123impl Standing {
124    /// Returns the kind token that the citation mark's span carries:
125    /// [`ATTACHED`] or [`STANDALONE`].
126    pub fn kind_token(self) -> &'static str {
127        match self {
128            Standing::Attached => ATTACHED,
129            Standing::Standalone => STANDALONE,
130        }
131    }
132}
133
134/// The feature's settings as the lowering rules read them: the
135/// configuration, and its texts (the citation counter style, the note
136/// separator and the title of the list of cited works) compiled when the
137/// registry is built.
138///
139/// The feature creates one value per registration and shares it between its
140/// rules; a build hook ([`LateInit`]) compiles the texts once the language is
141/// built. Before that, the accessors that need the compiled texts return a
142/// structure error, which a built registry never returns.
143#[derive(Debug)]
144pub struct MarkSettings {
145    config: CitationsConfig,
146    compiled: OnceLock<Compiled>,
147}
148
149/// The compiled texts of the configuration.
150struct Compiled {
151    style: CounterStyle,
152    separator: Arc<NodeTree<Flm>>,
153    title: Option<Arc<NodeTree<Flm>>>,
154}
155
156impl std::fmt::Debug for Compiled {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        f.debug_struct("Compiled").field("style", &self.style).finish_non_exhaustive()
159    }
160}
161
162impl MarkSettings {
163    /// Creates the settings of `config`, its texts not yet compiled; the
164    /// feature registers [`CompileSettings`] to compile them.
165    pub(super) fn new(config: CitationsConfig) -> MarkSettings {
166        MarkSettings { config, compiled: OnceLock::new() }
167    }
168
169    /// Returns the configuration.
170    pub fn config(&self) -> &CitationsConfig {
171        &self.config
172    }
173
174    /// Returns the compiled texts, or a structure error before the registry
175    /// build compiled them, which never happens with a built registry.
176    fn compiled(&self) -> Result<&Compiled, LowerError> {
177        self.compiled
178            .get()
179            .ok_or_else(|| LowerError::structure("the citation settings were not compiled"))
180    }
181
182    /// Returns the compiled citation counter style.
183    ///
184    /// # Errors
185    ///
186    /// A structure error ([`LowerError::structure`]) before the registry build
187    /// compiled the citation counter style.
188    pub fn style(&self) -> Result<&CounterStyle, LowerError> {
189        Ok(&self.compiled()?.style)
190    }
191
192    /// Returns the compiled title of the heading above the list of cited works
193    /// ([`heading_title`](CitationsConfig::heading_title)), or `None` for a
194    /// list with no heading.
195    ///
196    /// # Errors
197    ///
198    /// A structure error ([`LowerError::structure`]) before the registry build
199    /// compiled the title.
200    pub fn heading_title(&self) -> Result<Option<&Arc<NodeTree<Flm>>>, LowerError> {
201        Ok(self.compiled()?.title.as_ref())
202    }
203}
204
205/// The build hook ([`LateInit`]) that compiles the citation counter style,
206/// the note separator and the title of the list of cited works. A text
207/// that is not valid FLM fails the registry build, with a message that
208/// identifies the citation counter style or the text.
209pub(super) struct CompileSettings {
210    pub(super) settings: Arc<MarkSettings>,
211}
212
213/// Compiles `text`, the configuration's text described by `what`, as FLM
214/// text with no placeholder, in the template language that counter styles
215/// use.
216fn compile_fixed(lang: &BuiltLang, text: &str, what: &str) -> Result<Arc<NodeTree<Flm>>, LateInitError> {
217    let failed = |error: &dyn std::fmt::Display| LateInitError::new(format!("{what} is set to `{text}`, which is not valid FLM text: {error}"));
218    let language = TemplateLanguage::new(lang).map_err(|errors| {
219        failed(&errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))
220    })?;
221    let template = compile_text(text, what, &PlaceholderVocabulary::new(0), lang, &language)
222        .map_err(|error| failed(&error))?;
223    instantiate_fixed(&template).map_err(|error| failed(&error))
224}
225
226impl LateInit for CompileSettings {
227    fn late_init(&self, lang: &BuiltLang, _diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
228        let config = &self.settings.config;
229        let style = config.style.compile(lang).map_err(|error| {
230            LateInitError::new(format!("the option `style` of the feature `citations` is not a valid counter style: {error}"))
231        })?;
232        let separator = compile_fixed(lang, &config.note_separator, "the option `note_separator` of the feature `citations`")?;
233        let title = config
234            .heading_title
235            .as_deref()
236            .map(|title| compile_fixed(lang, title, "the option `heading_title` of the feature `citations`"))
237            .transpose()?;
238        // One hook per registration of the feature, run once.
239        let _ = self.settings.compiled.set(Compiled { style, separator, title });
240        Ok(())
241    }
242}
243
244/// Returns the text written before the citation mark of a `\cite` under
245/// `config`: a no-break space ([`NO_BREAK_SPACE`]) under the bracketed form,
246/// and under the in-place placement regardless of the form; `None` under the
247/// superscript form of the listed placement. Nothing is ever written before
248/// the citation mark of an `\R`.
249///
250/// The general rule of `\cite` ([`CiteRule`]) stages it, on every backend
251/// that runs that rule, as a span of role [`SPACE_ROLE`] holding the
252/// character, directly before the citation mark's span. The HTML page writes
253/// the character inside an element that a stylesheet can select, and the
254/// character is part of the text a reader copies.
255pub fn space_before(config: &CitationsConfig) -> Option<&'static str> {
256    match (config.placement, config.mark) {
257        (CitationPlacement::InPlace, _) | (CitationPlacement::Listed, MarkForm::Bracketed) => {
258            Some(NO_BREAK_SPACE)
259        }
260        (CitationPlacement::Listed, MarkForm::Superscript) => None,
261    }
262}
263
264/// What [`stage_mark`] staged, and how many numbers the citation mark
265/// holds.
266#[derive(Debug, Clone)]
267pub struct StagedMark {
268    /// The citation mark's span, or, for a citation chunk with nothing to
269    /// show, a dropped mark (`flm.pres.dropped`).
270    pub node: BuildId,
271    /// How many numbers the citation mark holds, counting each cited work once
272    /// per group; 0 for a dropped mark. Under the in-place placement the count
273    /// is computed the same way, although the citation mark shows citation
274    /// entries. The rule of `\R` chooses the singular or the plural word by
275    /// it.
276    pub shown: usize,
277}
278
279/// One group of a citation mark: the numbers of the items without a note, or
280/// of the items of one note.
281struct Group<'t> {
282    /// The note's spelling with whitespace collapsed, `None` for the group of
283    /// the items without a note.
284    identity: Option<String>,
285    /// The note as written at its first appearance.
286    note: Option<Vec<NodeRef<'t, Flm>>>,
287    /// The group's numbers with their identifiers, in item order.
288    works: Vec<(usize, String)>,
289}
290
291/// Reports each mistake that [`read_chunk`] found in `chunk` as an Error at
292/// the span of its call ([`ChunkMistake::NoKey`] as [`NoKey`]).
293pub fn report_mistakes(lw: &mut dyn Lowerer, chunk: &Chunk<'_>) {
294    for mistake in &chunk.mistakes {
295        match mistake {
296            ChunkMistake::NoKey { span } => lw.error(NoKey, span.clone()),
297        }
298    }
299}
300
301/// Stages the citation mark of `chunk` (what is shown in the text for the
302/// citation chunk) and returns it with the count of numbers it holds. This is
303/// the only function that stages a citation mark; the rules of `\cite` and
304/// of `\R` call it.
305///
306/// Each item's number and identifier are looked up by its citation key in the
307/// table [`CITATIONS`], never by the node, so a citation mark shows the same
308/// numbers wherever its citation chunk is lowered, a copy shown again
309/// included. A citation key that the table does not hold is reported
310/// ([`Uncollected`]) at `span` and left out.
311///
312/// The citation mark is one span of role [`MARK_ROLE`] whose kind token is
313/// the [`Standing`]'s, holding, in order: one group of every item without a
314/// note, then one group per distinct note in order of the note's first
315/// appearance in the citation chunk. Two notes are the same note when their
316/// content has the same spelling with whitespace collapsed
317/// ([`spelling_identity`]). A group holds the citation counter style's opening
318/// delimiter, its numbers sorted and compressed through [`format_many`], then,
319/// for a note, the note separator and the note's content lowered with its
320/// edges trimmed, then the closing delimiter. With `a`, `b`, `c`, `d`, `e`
321/// cited in that order earlier, `\cite{c,b}\cite[Thm 4]{a}\cite{d}\cite[Thm
322/// 4]{e}` reads `[2–4][1,5; Thm 4]`. Each work appears once in a group: two
323/// citation keys of one work, or a citation key written twice, show one
324/// number, and [`StagedMark::shown`] counts the numbers shown. Every number is
325/// a link of kind [`LINK_KIND`] to its work's identifier, with the document
326/// role [`DocRole::BiblioRef`] (written `role="doc-biblioref"` on the HTML
327/// page); the delimiters and the join texts are outside the links.
328///
329/// The configuration's form decides the delimiters. Under
330/// [`MarkForm::Superscript`] a group has none, two groups are joined by the
331/// citation counter style's `list_mid` join text, and an
332/// attached citation mark's span carries the superscript style; a standalone
333/// citation mark is never raised.
334///
335/// A citation chunk with no item to show (every call has a mistake, every
336/// citation key is reported as [`Uncollected`], or an `\R` has no citation
337/// after it) is staged as a dropped mark ([`pres::DROPPED`]; see
338/// [recovery](crate::stdlib::backends::lowering::error)) instead.
339///
340/// Under the in-place placement ([`CitationPlacement::InPlace`]) the citation
341/// mark shows the citation entries instead: for each item whose citation key
342/// has a number, in item order, one group between the citation counter style's
343/// delimiters holding the item's citation entry (read by its citation key from
344/// the table [`ENTRIES`] and spliced with [`Lowerer::splice`]), then the note
345/// separator and the note where the item has one:
346/// `[Knuth, 1984][Lamport, 1994; Thm 4]`. The form, the sorting, the ranges
347/// and the join texts do not apply, nothing is linked, the span carries the
348/// kind token [`IN_PLACE`] after the [`Standing`]'s, and an item whose
349/// citation key has no citation entry shows a dropped mark inside its
350/// delimiters.
351///
352/// A caller's rule must declare that it reads [`CITATIONS`] and [`ENTRIES`]
353/// and produces [`pres::SPAN`], [`pres::LINK`] and [`pres::DROPPED`].
354///
355/// # Errors
356///
357/// [`LowerError`] from staging, and a structure error before the registry
358/// build compiled the settings.
359pub fn stage_mark(
360    cx: &mut LowerCx<'_>,
361    lw: &mut dyn Lowerer,
362    chunk: &Chunk<'_>,
363    settings: &MarkSettings,
364    standing: Standing,
365    span: &FlmSpan,
366) -> Result<StagedMark, LowerError> {
367    let compiled = settings.compiled()?;
368    let form = settings.config.mark;
369    let found: Vec<Option<(usize, String)>> = {
370        let citations: Option<&CitedWorks> = lw.get(CITATIONS)?;
371        chunk
372            .items
373            .iter()
374            .map(|item| {
375                let work = citations?.work(&item.key)?;
376                Some((work.number, work.identifier.clone()))
377            })
378            .collect()
379    };
380    let mut groups: Vec<Group<'_>> = vec![Group { identity: None, note: None, works: Vec::new() }];
381    let mut uncollected = false;
382    for (item, work) in chunk.items.iter().zip(found) {
383        let Some(work) = work else {
384            lw.error(Uncollected { key: item.key.clone() }, span.clone());
385            uncollected = true;
386            continue;
387        };
388        let identity = item.note.as_ref().map(|note| spelling_identity(note.iter().copied()));
389        let at = match groups.iter().position(|group| group.identity == identity) {
390            Some(at) => at,
391            None => {
392                groups.push(Group { identity, note: item.note.clone(), works: Vec::new() });
393                groups.len() - 1
394            }
395        };
396        // The numbers of a group are a set: two keys of one work, or one key
397        // written twice, show one number.
398        if !groups[at].works.iter().any(|(number, _)| *number == work.0) {
399            groups[at].works.push(work);
400        }
401    }
402    groups.retain(|group| !group.works.is_empty());
403    let shown: usize = groups.iter().map(|group| group.works.len()).sum();
404    if shown == 0 {
405        let node = stage_dropped(cx, lw, chunk, uncollected)?;
406        return Ok(StagedMark { node, shown: 0 });
407    }
408    let style = &compiled.style;
409    if settings.config.placement == CitationPlacement::InPlace {
410        return stage_in_place(cx, lw, chunk, compiled, standing, shown);
411    }
412    let delimited = form == MarkForm::Bracketed;
413    let mut children = Vec::new();
414    for (index, group) in groups.iter().enumerate() {
415        // The superscript form writes no delimiters, so two groups are separated
416        // by the style's join text between two items of a list.
417        if index > 0 && !delimited {
418            children.extend(lw.splice(cx, style.join().text(JoinText::ListMid))?);
419        }
420        if delimited {
421            children.extend(lw.splice(cx, style.open())?);
422        }
423        children.extend(stage_numbers(cx, lw, style, &group.works)?);
424        if let Some(note) = &group.note {
425            children.extend(lw.splice(cx, &compiled.separator)?);
426            children.extend(stage_trimmed(cx, lw, note, |_| false)?);
427        }
428        if delimited {
429            children.extend(lw.splice(cx, style.close())?);
430        }
431    }
432    let raised = form == MarkForm::Superscript && standing == Standing::Attached;
433    let payload = SpanPayload {
434        style: raised.then_some(SpanStyle::Superscript),
435        role: Some(Name::from(MARK_ROLE)),
436        kinds: vec![Name::from(standing.kind_token())],
437        ..SpanPayload::default()
438    };
439    let node = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, children)?;
440    Ok(StagedMark { node, shown })
441}
442
443/// Stages the dropped mark ([`pres::DROPPED`]) shown in place of a citation
444/// chunk with no item to show. Its condition gives the reason: every citation
445/// key uncollected (`uncollected`), else the citation chunk's first mistake,
446/// else no citation at all.
447pub(super) fn stage_dropped(
448    cx: &mut LowerCx<'_>,
449    lw: &mut dyn Lowerer,
450    chunk: &Chunk<'_>,
451    uncollected: bool,
452) -> Result<BuildId, LowerError> {
453    let condition = if uncollected {
454        "flm.citations.uncollected"
455    } else {
456        match chunk.mistakes.first() {
457            Some(ChunkMistake::NoKey { .. }) => "flm.citations.no-key",
458            None => "flm.citations.no-citation",
459        }
460    };
461    let mark = DroppedPayload { condition: Name::from(condition), detail: "citation".to_string() };
462    lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())
463}
464
465/// The note of an item, as [`read_chunk`] returns it.
466type Note<'t> = Option<Vec<NodeRef<'t, Flm>>>;
467
468/// Stages the citation mark of `chunk` under the in-place placement, as
469/// [`stage_mark`] describes: one group per item whose citation key has a
470/// number, holding its citation entry or a dropped mark.
471fn stage_in_place(
472    cx: &mut LowerCx<'_>,
473    lw: &mut dyn Lowerer,
474    chunk: &Chunk<'_>,
475    compiled: &Compiled,
476    standing: Standing,
477    shown: usize,
478) -> Result<StagedMark, LowerError> {
479    // Each shown item's entry, looked up by its key before anything is staged.
480    let items: Vec<(Option<Arc<NodeTree<Flm>>>, &Note<'_>)> = {
481        let citations: Option<&CitedWorks> = lw.get(CITATIONS)?;
482        let entries: Option<&CitationEntries> = lw.get(ENTRIES)?;
483        chunk
484            .items
485            .iter()
486            .filter(|item| citations.is_some_and(|citations| citations.work(&item.key).is_some()))
487            .map(|item| {
488                let entry = entries.and_then(|entries| entries.entry(&item.key));
489                (entry.map(|entry| Arc::clone(&entry.content)), &item.note)
490            })
491            .collect()
492    };
493    let style = &compiled.style;
494    let mut children = Vec::new();
495    for (entry, note) in items {
496        children.extend(lw.splice(cx, style.open())?);
497        match entry {
498            Some(content) => children.extend(lw.splice(cx, &content)?),
499            None => {
500                let mark = DroppedPayload {
501                    condition: Name::from("flm.citations.no-entry"),
502                    detail: "bibliography entry".to_string(),
503                };
504                children.push(lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?);
505            }
506        }
507        if let Some(note) = note {
508            children.extend(lw.splice(cx, &compiled.separator)?);
509            children.extend(stage_trimmed(cx, lw, note, |_| false)?);
510        }
511        children.extend(lw.splice(cx, style.close())?);
512    }
513    let payload = SpanPayload {
514        role: Some(Name::from(MARK_ROLE)),
515        kinds: vec![Name::from(standing.kind_token()), Name::from(IN_PLACE)],
516        ..SpanPayload::default()
517    };
518    let node = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, children)?;
519    Ok(StagedMark { node, shown })
520}
521
522/// Stages the numbers of one group, sorted and compressed by the citation
523/// counter style, each number a link to its work.
524fn stage_numbers(
525    cx: &mut LowerCx<'_>,
526    lw: &mut dyn Lowerer,
527    style: &CounterStyle,
528    works: &[(usize, String)],
529) -> Result<Vec<BuildId>, LowerError> {
530    let values: Vec<CounterValue> =
531        works.iter().map(|(number, _)| CounterValue::new(*number as i64)).collect();
532    let numbered: Vec<NumberedValue<'_>> = values.iter().map(NumberedValue::new).collect();
533    let options = FormatOptions::new().without_word().without_delimiters();
534    let segments = format_many(style, &numbered, &options)
535        .map_err(|error| LowerError::structure(error.to_string()))?;
536    let mut staged = Vec::new();
537    for segment in &segments {
538        let body = lw.splice(cx, segment.content())?;
539        match segment.link().and_then(|position| works.get(position)) {
540            Some((_, identifier)) => {
541                let payload = LinkPayload {
542                    href: format!("#{identifier}"),
543                    kind: Name::from(LINK_KIND),
544                    doc_role: Some(DocRole::BiblioRef),
545                    label: None,
546                    shows_target: false,
547                };
548                staged.push(lw.pres_with(cx, &ElementName::from(pres::LINK), payload, body)?);
549            }
550            None => staged.extend(body),
551        }
552    }
553    Ok(staged)
554}
555
556/// The flags of an `\R` node as read: whether the capitalized word is
557/// chosen, and whether a word is written.
558pub(super) struct Flags {
559    pub(super) capital: bool,
560    pub(super) word: bool,
561}
562
563/// Reads the flags of the `\R` node `node`: each character of its flags
564/// argument is a flag, and whitespace is skipped. An unknown flag is reported
565/// ([`UnknownFlag`]) and ignored; a flags argument that is not plain
566/// characters is reported once ([`UnknownFlag`] with its plain text) and
567/// ignored as a whole.
568///
569/// # Errors
570///
571/// [`LowerError::PlaceholderCharacters`] for a flags argument that holds a
572/// placeholder of a user definition's template being lowered without
573/// expansion ([`chars_at_lowering`]).
574pub(super) fn read_flags(node: &NodeRef<'_, Flm>, lw: &mut dyn Lowerer) -> Result<Flags, LowerError> {
575    let mut flags = Flags { capital: false, word: true };
576    let Ok(Some(content)) = node.argument_content_nodes_named(FLAGS_ARG) else {
577        return Ok(flags);
578    };
579    let text = match chars_at_lowering(content.iter())? {
580        Ok(text) => text,
581        Err(_) => {
582            let flag = crate::lang::text::plain_text_of(content.iter());
583            lw.error(UnknownFlag { flag }, node.span().clone());
584            return Ok(flags);
585        }
586    };
587    for flag in text.chars().filter(|flag| !is_space(*flag)) {
588        match flag {
589            CAPITAL_FLAG => flags.capital = true,
590            INLINE_FLAG => flags.word = false,
591            other => lw.error(UnknownFlag { flag: other.to_string() }, node.span().clone()),
592        }
593    }
594    Ok(flags)
595}
596
597/// The body of the general rule of `\cite`, [`CITE_RULE`]: it stages the
598/// space that the form calls for ([`space_before`]) in a span of role
599/// [`SPACE_ROLE`], then the citation chunk's attached citation mark
600/// ([`stage_mark`]). It reports the citation chunk's writing mistakes
601/// ([`report_mistakes`]), and requires the feature's style identifier
602/// [`STYLE`].
603///
604/// # Errors
605///
606/// As [`read_chunk`](super::read_chunk) and [`stage_mark`].
607#[derive(Debug)]
608pub struct CiteRule {
609    settings: Arc<MarkSettings>,
610}
611
612impl CiteRule {
613    /// Creates the rule under the feature's settings.
614    pub(super) fn new(settings: &Arc<MarkSettings>) -> CiteRule {
615        CiteRule { settings: Arc::clone(settings) }
616    }
617}
618
619impl Lower for CiteRule {
620    fn lower(
621        &self,
622        node: NodeRef<'_, Flm>,
623        cx: &mut LowerCx<'_>,
624        lw: &mut dyn Lowerer,
625    ) -> Result<Lowering, LowerError> {
626        lw.require(&Name::from(STYLE));
627        let chunk = read_chunk(&node, Reading::AtLowering)?;
628        report_mistakes(lw, &chunk);
629        let mut out = Vec::with_capacity(2);
630        if let Some(space) = space_before(&self.settings.config) {
631            let body = vec![lw.text(cx, space)?];
632            let payload = SpanPayload { role: Some(Name::from(SPACE_ROLE)), ..SpanPayload::default() };
633            out.push(lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?);
634        }
635        let mark = stage_mark(cx, lw, &chunk, &self.settings, Standing::Attached, node.span())?;
636        out.push(mark.node);
637        Ok(Lowering::Emit(out))
638    }
639}
640
641/// The body of the general rule of `\R`, [`REFCITE_RULE`]: it stages the
642/// citation counter style's word in the variant the flags select, singular or
643/// plural by [`StagedMark::shown`], in a span of role [`WORD_ROLE`], then the
644/// citation chunk's standalone citation mark ([`stage_mark`]). It writes no
645/// word under the flag `I` or for a dropped mark, and nothing before the word.
646/// It reports an `\R` with no `\cite` directly after it ([`NoCitation`]), the
647/// flags it does not define ([`UnknownFlag`]) and the citation chunk's writing
648/// mistakes ([`report_mistakes`]). It requires the feature's style
649/// identifier [`STYLE`].
650///
651/// # Errors
652///
653/// As [`read_chunk`](super::read_chunk) and [`stage_mark`].
654#[derive(Debug)]
655pub struct RefCiteRule {
656    settings: Arc<MarkSettings>,
657}
658
659impl RefCiteRule {
660    /// Creates the rule under the feature's settings.
661    pub(super) fn new(settings: &Arc<MarkSettings>) -> RefCiteRule {
662        RefCiteRule { settings: Arc::clone(settings) }
663    }
664}
665
666impl Lower for RefCiteRule {
667    fn lower(
668        &self,
669        node: NodeRef<'_, Flm>,
670        cx: &mut LowerCx<'_>,
671        lw: &mut dyn Lowerer,
672    ) -> Result<Lowering, LowerError> {
673        lw.require(&Name::from(STYLE));
674        let flags = read_flags(&node, lw)?;
675        if leading_call(&node).is_none() {
676            lw.error(NoCitation, node.span().clone());
677        }
678        let chunk = read_chunk(&node, Reading::AtLowering)?;
679        report_mistakes(lw, &chunk);
680        let mark = stage_mark(cx, lw, &chunk, &self.settings, Standing::Standalone, node.span())?;
681        let mut out = Vec::with_capacity(2);
682        if flags.word && mark.shown > 0 {
683            let variant = flags.capital.then_some(CAPITAL_VARIANT);
684            let style = self.settings.style()?;
685            if let Some(word) = style.word_text(mark.shown, variant) {
686                let body = lw.splice(cx, word)?;
687                let payload = SpanPayload { role: Some(Name::from(WORD_ROLE)), ..SpanPayload::default() };
688                out.push(lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?);
689            }
690        }
691        out.push(mark.node);
692        Ok(Lowering::Emit(out))
693    }
694}
695
696/// The declaration of what the general rules of `\cite` and `\R` read and
697/// produce.
698pub(super) fn decl() -> LoweringDecl {
699    LoweringDecl::new()
700        .reads(CITATIONS)
701        .reads(ENTRIES)
702        .produces(pres::SPAN)
703        .produces(pres::LINK)
704        .produces(pres::DROPPED)
705}
706
707/// The general rules of `\cite` and `\R`, marked as the defaults on every
708/// backend. The `latex-recomposed` backend has rules of its own, marked as
709/// the defaults there.
710pub(super) fn rules(settings: &Arc<MarkSettings>) -> Vec<LoweringRule> {
711    vec![
712        LoweringRule::new(
713            CITE_RULE,
714            CITE,
715            decl(),
716            Arc::new(CiteRule::new(settings)),
717            DefaultMark::Everywhere,
718        )
719        .docs(
720            "a citation chunk lowers to the space its form calls for and a `flm.pres.span` of \
721             role `flm.citations.mark`, kind token `attached`, holding its numbers as links of kind \
722             `cite`",
723        ),
724        LoweringRule::new(
725            REFCITE_RULE,
726            REFCITE,
727            decl(),
728            Arc::new(RefCiteRule::new(settings)),
729            DefaultMark::Everywhere,
730        )
731        .docs(
732            "a citation chunk written with `\\R` lowers to the citation counter style's word in a \
733             `flm.pres.span` of role `flm.citations.word`, then the citation mark, kind token \
734             `standalone`, shown inline",
735        ),
736    ]
737}