citum-engine 0.80.0

Citum citation and bibliography processor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/*
SPDX-License-Identifier: MIT OR Apache-2.0
SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
*/

//! Input-compatibility warning scanners.
//!
//! Each function inspects already-loaded inputs (style, bibliography) for
//! constructs the engine tolerated but cannot act on — unknown reference
//! classes, fields captured by the forward-compat `unknown_fields`
//! catch-all, and unknown enum variants — and reports them as structured
//! [`Warning`]s. Adapters (CLI, WASM, FFI) present these; they must never
//! re-derive their own checks.

use crate::processor::Processor;
use crate::reference::Bibliography;
use citum_schema::locale::{GeneralTerm, TermForm};
use citum_schema::options::TermLocale;
use citum_schema::reference::{
    ClassExtension, CollectionType, ContributorRole as ReferenceRole, MonographComponentType,
    MonographType, ReferenceClass, SerialComponentType,
};
use citum_schema::template::ContributorRole as TemplateRole;

use super::{Warning, WarningLevel};

/// Scan the bibliography for tagged items whose effective language has no
/// loaded locale under `options.multilingual.term-locale: item`.
///
/// A no-op unless `term-locale: item` is active in the citation or
/// bibliography scope. Untagged items resolve to the style locale by design
/// (positive-evidence rule, `PER_ITEM_TERM_LOCALE.md` §3) and never warn;
/// only items that *do* carry a language with no matching loaded locale are
/// reported, so the silent style-locale fallback stays discoverable. Reuses
/// [`crate::processor::rendering::lookup_embedded_locale`] — the same
/// exact-tag → primary-language lookup the renderer itself uses — so this
/// scanner and the render-time fallback never diverge.
pub fn term_locale_fallback_warnings(processor: &Processor) -> Vec<Warning> {
    let term_locale_is_item = |config: &citum_schema::options::Config| {
        config
            .multilingual
            .as_ref()
            .is_some_and(|ml| ml.term_locale == TermLocale::Item)
    };
    let active = term_locale_is_item(&processor.get_citation_config())
        || term_locale_is_item(&processor.get_bibliography_config());
    if !active {
        return Vec::new();
    }

    processor
        .bibliography
        .iter()
        .filter_map(|(ref_id, reference)| {
            let language = crate::values::effective_item_language(reference)?;
            if crate::processor::rendering::lookup_embedded_locale(&language).is_some() {
                return None;
            }
            Some(Warning {
                level: WarningLevel::Warning,
                code: "term_locale_unavailable".to_string(),
                citation_id: None,
                ref_id: Some(ref_id.clone()),
                message: format!(
                    "Reference '{ref_id}' has language '{language}' but no loaded locale matches it; \
                     term-locale: item falls back to the style locale for this reference's terms."
                ),
            })
        })
        .collect()
}

/// Warn when the bibliography config declares a numeric or alphabetic
/// reference-marker mode with no `label-wrap` and no `label-separator`,
/// which renders the marker flush against the entry body (`1Smith`, not
/// `1. Smith` or `[1] Smith`).
///
/// `label-separator` defaults to empty by design, and several shipped
/// styles depend on a genuinely flush marker — `royal-society-of-chemistry`
/// documents `second-field-align="flush"` from its CSL source, and
/// `gb-t-7714-2025-base` documents a bracketed-but-flush marker — so this is
/// advisory, not an error: it surfaces a configuration shape that is easy to
/// author unintentionally without asserting it is wrong. `author-date` mode
/// is exempt: it never produces a bibliography marker (see `marker.rs`), so
/// wrap and separator are inert for it. See `docs/specs/REFERENCE_MARKERS.md`.
pub fn bibliography_label_missing_separator_warnings(processor: &Processor) -> Vec<Warning> {
    let config = processor.get_bibliography_options();
    let produces_marker = matches!(
        config.label_mode,
        Some(
            citum_schema::options::BibliographyLabelMode::Numeric
                | citum_schema::options::BibliographyLabelMode::Alphabetic
        )
    );
    if !produces_marker || config.label_wrap.is_some() || config.label_separator.is_some() {
        return Vec::new();
    }

    vec![Warning {
        level: WarningLevel::Warning,
        code: "bibliography_label_no_separator".to_string(),
        citation_id: None,
        ref_id: None,
        message: "Bibliography configuration declares a numeric or alphabetic label-mode with \
                  no label-wrap and no label-separator; the reference marker will render flush \
                  against the entry body (e.g. '1Smith' rather than '1. Smith'). If this is \
                  intentional (flush second-field-align), no action is needed."
            .to_string(),
    }]
}

/// Scan the bibliography for unknown reference classes and return compatibility warnings.
pub fn unknown_reference_class_warnings(bibliography: &Bibliography) -> Vec<Warning> {
    bibliography
        .iter()
        .filter_map(|(ref_id, reference)| {
            let ReferenceClass::Unknown(class) = reference.class() else {
                return None;
            };
            Some(Warning {
                level: WarningLevel::Warning,
                code: "unknown_reference_class".to_string(),
                citation_id: None,
                ref_id: Some(ref_id.clone()),
                message: format!(
                    "Reference '{ref_id}' uses unknown class '{class}'; rendering will use only fields this engine understands."
                ),
            })
        })
        .collect()
}

/// Scan the bibliography for fields captured by the forward-compat
/// `unknown_fields` catch-all and return per-reference warnings.
///
/// Unknown-class references are skipped here; they are already reported by
/// [`unknown_reference_class_warnings`].
pub fn unknown_reference_field_warnings(bibliography: &Bibliography) -> Vec<Warning> {
    bibliography
        .iter()
        .filter_map(|(ref_id, reference)| {
            let unknown = reference.unknown_fields()?;
            if unknown.is_empty() {
                return None;
            }
            let keys: Vec<&str> = unknown.keys().map(String::as_str).collect();
            Some(Warning {
                level: WarningLevel::Warning,
                code: "unknown_reference_field".to_string(),
                citation_id: None,
                ref_id: Some(ref_id.clone()),
                message: format!(
                    "Reference '{ref_id}' has unknown field(s): {}; these fields are ignored during rendering.",
                    keys.join(", ")
                ),
            })
        })
        .collect()
}

/// Scan the style and bibliography for unknown enum variants and term keys.
///
/// Returns a list of structured compatibility warnings for encounter of
/// unknown variants that were captured via the tolerant-enum mechanism.
pub fn unknown_enum_warnings(processor: &Processor) -> Vec<Warning> {
    let mut warnings = Vec::new();

    // 1. Scan bibliography
    for (ref_id, reference) in &processor.bibliography {
        match reference.extension() {
            ClassExtension::Monograph(r) => {
                if let MonographType::Unknown(s) = &r.r#type {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown monograph type '{s}'; rendering will use default monograph formatting."),
                    });
                }
            }
            ClassExtension::Collection(r) => {
                if let CollectionType::Unknown(s) = &r.r#type {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown collection type '{s}'; rendering will use default collection formatting."),
                    });
                }
            }
            ClassExtension::CollectionComponent(r) => {
                if let MonographComponentType::Unknown(s) = &r.r#type {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown monograph component type '{s}'; rendering will use default chapter formatting."),
                    });
                }
            }
            ClassExtension::SerialComponent(r) => {
                if let SerialComponentType::Unknown(s) = &r.r#type {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown serial component type '{s}'; rendering will use default article formatting."),
                    });
                }
            }
            _ => {}
        }

        for contributor in reference.all_contributor_entries() {
            for role in contributor.roles.as_slice() {
                if let ReferenceRole::Unknown(s) = role {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: Some(ref_id.clone()),
                        message: format!("Reference '{ref_id}' uses unknown contributor role '{s}'; this role may be ignored during rendering."),
                    });
                }
            }
        }
    }

    // 2. Scan Style
    if let Some(templates) = &processor.style.templates {
        for (name, template) in templates {
            scan_template_for_unknowns(template, &format!("template '{name}'"), &mut warnings);
        }
    }
    if let Some(citation) = &processor.style.citation {
        scan_citation_spec_for_unknowns(citation, "citation layout", &mut warnings);
    }
    if let Some(bib) = &processor.style.bibliography {
        if let Some(template) = &bib.template {
            scan_template_variant_for_unknowns(template, "bibliography layout", &mut warnings);
        }
        if let Some(type_variants) = &bib.type_variants {
            for variant in type_variants.values() {
                if let Some(template) = variant.as_template() {
                    scan_template_for_unknowns(template, "bibliography layout", &mut warnings);
                }
            }
        }
        if let Some(locales) = &bib.locales {
            for locale_spec in locales {
                scan_template_for_unknowns(
                    &locale_spec.template,
                    "bibliography layout",
                    &mut warnings,
                );
            }
        }
    }
    scan_bibliography_config_sort_for_citation_number(processor, &mut warnings);

    warnings
}

/// Warn when the bibliography's explicit config-level sort lists
/// `citation-number` as a key. `Sort::group_sort` drops the key rather than
/// mapping it, so it contributes nothing to bibliography ordering — a silent
/// no-op the style author almost certainly did not intend. The
/// `citation-number` *preset* (`SortEntry::Preset`) is exempt: it is the
/// documented way to say "no bibliography sort" for numeric styles.
fn scan_bibliography_config_sort_for_citation_number(
    processor: &Processor,
    warnings: &mut Vec<Warning>,
) {
    let Some(citum_schema::options::SortEntry::Explicit(sort)) = processor
        .get_bibliography_config()
        .processing
        .as_ref()
        .map(citum_schema::options::Processing::config)
        .and_then(|config| config.sort)
    else {
        return;
    };

    let uses_citation_number = sort
        .template
        .iter()
        .any(|spec| matches!(spec.key, citum_schema::options::SortKey::CitationNumber));

    if uses_citation_number {
        warnings.push(Warning {
            level: WarningLevel::Warning,
            code: "citation_number_sort_not_supported".to_string(),
            citation_id: None,
            ref_id: None,
            message: "Style bibliography configuration lists 'citation-number' as an explicit \
                      sort key; it is not supported and is ignored for bibliography ordering."
                .to_string(),
        });
    }
}

/// Recursively scan a [`citum_schema::CitationSpec`] and its mode/position
/// sub-specs (`integral`, `non-integral`, `subsequent`, `ibid`), plus its
/// `type-variants` and per-locale templates, for unknown enum variants.
///
/// The top-level `unknown_enum_warnings` scan previously inspected only the
/// main citation template, missing unknown terms/roles/date-forms nested in
/// sub-specs, type-variants, and localized templates.
fn scan_citation_spec_for_unknowns(
    spec: &citum_schema::CitationSpec,
    location: &str,
    warnings: &mut Vec<Warning>,
) {
    if let Some(template) = &spec.template {
        scan_template_variant_for_unknowns(template, location, warnings);
    }
    if let Some(type_variants) = &spec.type_variants {
        for variant in type_variants.values() {
            if let Some(template) = variant.as_template() {
                scan_template_for_unknowns(template, location, warnings);
            }
        }
    }
    if let Some(locales) = &spec.locales {
        for locale_spec in locales {
            scan_template_for_unknowns(&locale_spec.template, location, warnings);
        }
    }

    if let Some(child) = &spec.integral {
        scan_citation_spec_for_unknowns(child, &format!("{location} (integral)"), warnings);
    }
    if let Some(child) = &spec.non_integral {
        scan_citation_spec_for_unknowns(child, &format!("{location} (non-integral)"), warnings);
    }
    if let Some(child) = &spec.subsequent {
        scan_citation_spec_for_unknowns(child, &format!("{location} (subsequent)"), warnings);
    }
    if let Some(child) = &spec.ibid {
        scan_citation_spec_for_unknowns(child, &format!("{location} (ibid)"), warnings);
    }
}

fn scan_template_variant_for_unknowns(
    variant: &citum_schema::template::TemplateVariant,
    location: &str,
    warnings: &mut Vec<Warning>,
) {
    match variant {
        citum_schema::template::TemplateVariant::Full(template) => {
            scan_template_for_unknowns(template, location, warnings);
        }
        citum_schema::template::TemplateVariant::Diff(diff) => {
            for add in &diff.add {
                scan_template_for_unknowns(
                    std::slice::from_ref(&add.component),
                    location,
                    warnings,
                );
            }
        }
    }
}

fn scan_template_for_unknowns(
    components: &[citum_schema::template::TemplateComponent],
    location: &str,
    warnings: &mut Vec<Warning>,
) {
    use citum_schema::template::TemplateComponent;
    for component in components {
        match component {
            TemplateComponent::Term(t) => {
                if let GeneralTerm::Unknown(s) = &t.term {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: None,
                        message: format!("Style {location} uses unknown locale term key '{s}'; this term may render as empty."),
                    });
                }
                if let Some(TermForm::Unknown(s)) = &t.form {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: None,
                        message: format!("Style {location} uses unknown term form '{s}'; falling back to long form."),
                    });
                }
            }
            TemplateComponent::Contributor(c) => {
                for role in c.contributor.as_slice() {
                    if let TemplateRole::Unknown(s) = role {
                        warnings.push(Warning {
                            level: WarningLevel::Warning,
                            code: "unknown_enum_variant".to_string(),
                            citation_id: None,
                            ref_id: None,
                            message: format!("Style {location} uses unknown contributor role '{s}'; this role may be ignored."),
                        });
                    }
                }
                if let Some(label) = &c.label {
                    let term = label.term.as_str();
                    if !crate::values::contributor::labels::RECOGNIZED_LABEL_TERMS.contains(&term) {
                        warnings.push(Warning {
                            level: WarningLevel::Warning,
                            code: "unknown_role_label_term".to_string(),
                            citation_id: None,
                            ref_id: None,
                            message: format!("Style {location} uses unrecognized role-label term '{term}'; falling back to the contributor's own role term instead of the requested one."),
                        });
                    }
                }
            }
            TemplateComponent::Date(d) => {
                if let citum_schema::template::DateForm::Unknown(s) = &d.form {
                    warnings.push(Warning {
                        level: WarningLevel::Warning,
                        code: "unknown_enum_variant".to_string(),
                        citation_id: None,
                        ref_id: None,
                        message: format!("Style {location} uses unknown date form '{s}'; falling back to year only."),
                    });
                }
            }
            TemplateComponent::Group(g) => {
                scan_template_for_unknowns(&g.group, location, warnings);
            }
            _ => {}
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, reason = "tests")]
mod tests {
    use super::*;

    #[test]
    fn bibliography_label_missing_separator_warnings_reports_bare_numeric_label_mode() {
        let yaml = "info:\n  title: Test\nbibliography:\n  options:\n    label-mode: numeric\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = bibliography_label_missing_separator_warnings(&processor);
        assert!(
            warnings
                .iter()
                .any(|w| w.code == "bibliography_label_no_separator"),
            "expected a warning for label-mode with no wrap and no separator, got: {warnings:?}"
        );
    }

    #[test]
    fn bibliography_label_missing_separator_warnings_silent_with_label_wrap() {
        let yaml = "info:\n  title: Test\nbibliography:\n  options:\n    label-mode: numeric\n    label-wrap: period\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = bibliography_label_missing_separator_warnings(&processor);
        assert!(
            !warnings
                .iter()
                .any(|w| w.code == "bibliography_label_no_separator"),
            "did not expect a warning once label-wrap is declared, got: {warnings:?}"
        );
    }

    #[test]
    fn bibliography_label_missing_separator_warnings_silent_with_label_separator() {
        let yaml = "info:\n  title: Test\nbibliography:\n  options:\n    label-mode: numeric\n    label-separator: ' '\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = bibliography_label_missing_separator_warnings(&processor);
        assert!(
            !warnings
                .iter()
                .any(|w| w.code == "bibliography_label_no_separator"),
            "did not expect a warning once label-separator is declared, got: {warnings:?}"
        );
    }

    #[test]
    fn bibliography_label_missing_separator_warnings_silent_for_author_date_mode() {
        let yaml = "info:\n  title: Test\nbibliography:\n  options:\n    label-mode: author-date\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = bibliography_label_missing_separator_warnings(&processor);
        assert!(
            !warnings
                .iter()
                .any(|w| w.code == "bibliography_label_no_separator"),
            "author-date mode never produces a bibliography marker, so wrap/separator are \
             inert; did not expect a warning, got: {warnings:?}"
        );
    }

    #[test]
    fn bibliography_label_missing_separator_warnings_silent_with_no_label_mode() {
        let yaml = "info:\n  title: Test\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = bibliography_label_missing_separator_warnings(&processor);
        assert!(
            warnings.is_empty(),
            "did not expect a warning with no bibliography options at all, got: {warnings:?}"
        );
    }

    #[test]
    fn unknown_enum_warnings_reports_unknown_term_in_integral_sub_spec() {
        let yaml = "info:\n  title: Test\ncitation:\n  integral:\n    template:\n      - term: not-a-real-term\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = unknown_enum_warnings(&processor);
        assert!(
            warnings
                .iter()
                .any(|w| w.message.contains("not-a-real-term") && w.message.contains("(integral)")),
            "expected a warning for the unknown term in citation.integral.template, got: {warnings:?}"
        );
    }

    #[test]
    fn unknown_enum_warnings_reports_unknown_role_label_term() {
        let yaml = "info:\n  title: Test\nbibliography:\n  template:\n    - contributor: editor\n      form: long\n      label: {term: not-a-real-role}\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = unknown_enum_warnings(&processor);
        assert!(
            warnings
                .iter()
                .any(|w| w.code == "unknown_role_label_term"
                    && w.message.contains("not-a-real-role")),
            "expected a warning for the unrecognized role-label term, got: {warnings:?}"
        );
    }

    #[test]
    fn unknown_enum_warnings_does_not_flag_recognized_role_label_terms() {
        let yaml = "info:\n  title: Test\nbibliography:\n  template:\n    - contributor: editor\n      form: long\n      label: {term: editor}\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = unknown_enum_warnings(&processor);
        assert!(
            !warnings.iter().any(|w| w.code == "unknown_role_label_term"),
            "did not expect a warning for a recognized role-label term, got: {warnings:?}"
        );
    }

    #[test]
    fn unknown_enum_warnings_does_not_flag_director_role_label_term() {
        let yaml = "info:\n  title: Test\nbibliography:\n  template:\n    - contributor: director\n      form: long\n      label: {term: director, form: short}\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = unknown_enum_warnings(&processor);
        assert!(
            !warnings.iter().any(|w| w.code == "unknown_role_label_term"),
            "did not expect a warning for the director role-label term \
             (chicago-author-date-18th's song type-variant relies on this), \
             got: {warnings:?}"
        );
    }

    #[test]
    fn unknown_enum_warnings_reports_unknown_term_in_type_variants() {
        let yaml = "info:\n  title: Test\ncitation:\n  type-variants:\n    book:\n      - term: not-a-real-term-2\n";
        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
        let processor = Processor::new(style, Bibliography::new());

        let warnings = unknown_enum_warnings(&processor);
        assert!(
            warnings
                .iter()
                .any(|w| w.message.contains("not-a-real-term-2")),
            "expected a warning for the unknown term in citation.type-variants, got: {warnings:?}"
        );
    }
}