Skip to main content

citum_engine/api/
warnings.rs

1/*
2SPDX-License-Identifier: MIT OR Apache-2.0
3SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
4*/
5
6//! Input-compatibility warning scanners.
7//!
8//! Each function inspects already-loaded inputs (style, bibliography) for
9//! constructs the engine tolerated but cannot act on — unknown reference
10//! classes, fields captured by the forward-compat `unknown_fields`
11//! catch-all, and unknown enum variants — and reports them as structured
12//! [`Warning`]s. Adapters (CLI, WASM, FFI) present these; they must never
13//! re-derive their own checks.
14
15use crate::processor::Processor;
16use crate::reference::Bibliography;
17use citum_schema::locale::{GeneralTerm, TermForm};
18use citum_schema::reference::{
19    ClassExtension, CollectionType, ContributorRole as ReferenceRole, MonographComponentType,
20    MonographType, ReferenceClass, SerialComponentType,
21};
22use citum_schema::template::ContributorRole as TemplateRole;
23
24use super::{Warning, WarningLevel};
25
26/// Scan the bibliography for unknown reference classes and return compatibility warnings.
27pub fn unknown_reference_class_warnings(bibliography: &Bibliography) -> Vec<Warning> {
28    bibliography
29        .iter()
30        .filter_map(|(ref_id, reference)| {
31            let ReferenceClass::Unknown(class) = reference.class() else {
32                return None;
33            };
34            Some(Warning {
35                level: WarningLevel::Warning,
36                code: "unknown_reference_class".to_string(),
37                citation_id: None,
38                ref_id: Some(ref_id.clone()),
39                message: format!(
40                    "Reference '{ref_id}' uses unknown class '{class}'; rendering will use only fields this engine understands."
41                ),
42            })
43        })
44        .collect()
45}
46
47/// Scan the bibliography for fields captured by the forward-compat
48/// `unknown_fields` catch-all and return per-reference warnings.
49///
50/// Unknown-class references are skipped here; they are already reported by
51/// [`unknown_reference_class_warnings`].
52pub fn unknown_reference_field_warnings(bibliography: &Bibliography) -> Vec<Warning> {
53    bibliography
54        .iter()
55        .filter_map(|(ref_id, reference)| {
56            let unknown = reference.unknown_fields()?;
57            if unknown.is_empty() {
58                return None;
59            }
60            let keys: Vec<&str> = unknown.keys().map(String::as_str).collect();
61            Some(Warning {
62                level: WarningLevel::Warning,
63                code: "unknown_reference_field".to_string(),
64                citation_id: None,
65                ref_id: Some(ref_id.clone()),
66                message: format!(
67                    "Reference '{ref_id}' has unknown field(s): {}; these fields are ignored during rendering.",
68                    keys.join(", ")
69                ),
70            })
71        })
72        .collect()
73}
74
75/// Scan the style and bibliography for unknown enum variants and term keys.
76///
77/// Returns a list of structured compatibility warnings for encounter of
78/// unknown variants that were captured via the tolerant-enum mechanism.
79pub fn unknown_enum_warnings(processor: &Processor) -> Vec<Warning> {
80    let mut warnings = Vec::new();
81
82    // 1. Scan bibliography
83    for (ref_id, reference) in &processor.bibliography {
84        match reference.extension() {
85            ClassExtension::Monograph(r) => {
86                if let MonographType::Unknown(s) = &r.r#type {
87                    warnings.push(Warning {
88                        level: WarningLevel::Warning,
89                        code: "unknown_enum_variant".to_string(),
90                        citation_id: None,
91                        ref_id: Some(ref_id.clone()),
92                        message: format!("Reference '{ref_id}' uses unknown monograph type '{s}'; rendering will use default monograph formatting."),
93                    });
94                }
95            }
96            ClassExtension::Collection(r) => {
97                if let CollectionType::Unknown(s) = &r.r#type {
98                    warnings.push(Warning {
99                        level: WarningLevel::Warning,
100                        code: "unknown_enum_variant".to_string(),
101                        citation_id: None,
102                        ref_id: Some(ref_id.clone()),
103                        message: format!("Reference '{ref_id}' uses unknown collection type '{s}'; rendering will use default collection formatting."),
104                    });
105                }
106            }
107            ClassExtension::CollectionComponent(r) => {
108                if let MonographComponentType::Unknown(s) = &r.r#type {
109                    warnings.push(Warning {
110                        level: WarningLevel::Warning,
111                        code: "unknown_enum_variant".to_string(),
112                        citation_id: None,
113                        ref_id: Some(ref_id.clone()),
114                        message: format!("Reference '{ref_id}' uses unknown monograph component type '{s}'; rendering will use default chapter formatting."),
115                    });
116                }
117            }
118            ClassExtension::SerialComponent(r) => {
119                if let SerialComponentType::Unknown(s) = &r.r#type {
120                    warnings.push(Warning {
121                        level: WarningLevel::Warning,
122                        code: "unknown_enum_variant".to_string(),
123                        citation_id: None,
124                        ref_id: Some(ref_id.clone()),
125                        message: format!("Reference '{ref_id}' uses unknown serial component type '{s}'; rendering will use default article formatting."),
126                    });
127                }
128            }
129            _ => {}
130        }
131
132        for contributor in reference.all_contributor_entries() {
133            if let ReferenceRole::Unknown(s) = &contributor.role {
134                warnings.push(Warning {
135                    level: WarningLevel::Warning,
136                    code: "unknown_enum_variant".to_string(),
137                    citation_id: None,
138                    ref_id: Some(ref_id.clone()),
139                    message: format!("Reference '{ref_id}' uses unknown contributor role '{s}'; this role may be ignored during rendering."),
140                });
141            }
142        }
143    }
144
145    // 2. Scan Style
146    if let Some(templates) = &processor.style.templates {
147        for (name, template) in templates {
148            scan_template_for_unknowns(template, &format!("template '{name}'"), &mut warnings);
149        }
150    }
151    if let Some(citation) = &processor.style.citation {
152        scan_citation_spec_for_unknowns(citation, "citation layout", &mut warnings);
153    }
154    if let Some(bib) = &processor.style.bibliography {
155        if let Some(template) = &bib.template {
156            scan_template_for_unknowns(template, "bibliography layout", &mut warnings);
157        }
158        if let Some(type_variants) = &bib.type_variants {
159            for variant in type_variants.values() {
160                if let Some(template) = variant.as_template() {
161                    scan_template_for_unknowns(template, "bibliography layout", &mut warnings);
162                }
163            }
164        }
165        if let Some(locales) = &bib.locales {
166            for locale_spec in locales {
167                scan_template_for_unknowns(
168                    &locale_spec.template,
169                    "bibliography layout",
170                    &mut warnings,
171                );
172            }
173        }
174    }
175    scan_bibliography_config_sort_for_citation_number(processor, &mut warnings);
176
177    warnings
178}
179
180/// Warn when the bibliography's explicit config-level sort lists
181/// `citation-number` as a key. `Sort::group_sort` drops the key rather than
182/// mapping it, so it contributes nothing to bibliography ordering — a silent
183/// no-op the style author almost certainly did not intend. The
184/// `citation-number` *preset* (`SortEntry::Preset`) is exempt: it is the
185/// documented way to say "no bibliography sort" for numeric styles.
186fn scan_bibliography_config_sort_for_citation_number(
187    processor: &Processor,
188    warnings: &mut Vec<Warning>,
189) {
190    let Some(citum_schema::options::SortEntry::Explicit(sort)) = processor
191        .get_bibliography_config()
192        .processing
193        .as_ref()
194        .map(citum_schema::options::Processing::config)
195        .and_then(|config| config.sort)
196    else {
197        return;
198    };
199
200    let uses_citation_number = sort
201        .template
202        .iter()
203        .any(|spec| matches!(spec.key, citum_schema::options::SortKey::CitationNumber));
204
205    if uses_citation_number {
206        warnings.push(Warning {
207            level: WarningLevel::Warning,
208            code: "citation_number_sort_not_supported".to_string(),
209            citation_id: None,
210            ref_id: None,
211            message: "Style bibliography configuration lists 'citation-number' as an explicit \
212                      sort key; it is not supported and is ignored for bibliography ordering."
213                .to_string(),
214        });
215    }
216}
217
218/// Recursively scan a [`citum_schema::CitationSpec`] and its mode/position
219/// sub-specs (`integral`, `non-integral`, `subsequent`, `ibid`), plus its
220/// `type-variants` and per-locale templates, for unknown enum variants.
221///
222/// The top-level `unknown_enum_warnings` scan previously inspected only the
223/// main citation template, missing unknown terms/roles/date-forms nested in
224/// sub-specs, type-variants, and localized templates.
225fn scan_citation_spec_for_unknowns(
226    spec: &citum_schema::CitationSpec,
227    location: &str,
228    warnings: &mut Vec<Warning>,
229) {
230    if let Some(template) = &spec.template {
231        scan_template_for_unknowns(template, location, warnings);
232    }
233    if let Some(type_variants) = &spec.type_variants {
234        for variant in type_variants.values() {
235            if let Some(template) = variant.as_template() {
236                scan_template_for_unknowns(template, location, warnings);
237            }
238        }
239    }
240    if let Some(locales) = &spec.locales {
241        for locale_spec in locales {
242            scan_template_for_unknowns(&locale_spec.template, location, warnings);
243        }
244    }
245
246    if let Some(child) = &spec.integral {
247        scan_citation_spec_for_unknowns(child, &format!("{location} (integral)"), warnings);
248    }
249    if let Some(child) = &spec.non_integral {
250        scan_citation_spec_for_unknowns(child, &format!("{location} (non-integral)"), warnings);
251    }
252    if let Some(child) = &spec.subsequent {
253        scan_citation_spec_for_unknowns(child, &format!("{location} (subsequent)"), warnings);
254    }
255    if let Some(child) = &spec.ibid {
256        scan_citation_spec_for_unknowns(child, &format!("{location} (ibid)"), warnings);
257    }
258}
259
260fn scan_template_for_unknowns(
261    components: &[citum_schema::template::TemplateComponent],
262    location: &str,
263    warnings: &mut Vec<Warning>,
264) {
265    use citum_schema::template::TemplateComponent;
266    for component in components {
267        match component {
268            TemplateComponent::Term(t) => {
269                if let GeneralTerm::Unknown(s) = &t.term {
270                    warnings.push(Warning {
271                        level: WarningLevel::Warning,
272                        code: "unknown_enum_variant".to_string(),
273                        citation_id: None,
274                        ref_id: None,
275                        message: format!("Style {location} uses unknown locale term key '{s}'; this term may render as empty."),
276                    });
277                }
278                if let Some(TermForm::Unknown(s)) = &t.form {
279                    warnings.push(Warning {
280                        level: WarningLevel::Warning,
281                        code: "unknown_enum_variant".to_string(),
282                        citation_id: None,
283                        ref_id: None,
284                        message: format!("Style {location} uses unknown term form '{s}'; falling back to long form."),
285                    });
286                }
287            }
288            TemplateComponent::Contributor(c) => {
289                if let TemplateRole::Unknown(s) = &c.contributor {
290                    warnings.push(Warning {
291                        level: WarningLevel::Warning,
292                        code: "unknown_enum_variant".to_string(),
293                        citation_id: None,
294                        ref_id: None,
295                        message: format!("Style {location} uses unknown contributor role '{s}'; this role may be ignored."),
296                    });
297                }
298                if let Some(label) = &c.label {
299                    let term = label.term.as_str();
300                    if !crate::values::contributor::labels::RECOGNIZED_LABEL_TERMS.contains(&term) {
301                        warnings.push(Warning {
302                            level: WarningLevel::Warning,
303                            code: "unknown_role_label_term".to_string(),
304                            citation_id: None,
305                            ref_id: None,
306                            message: format!("Style {location} uses unrecognized role-label term '{term}'; falling back to the contributor's own role term instead of the requested one."),
307                        });
308                    }
309                }
310            }
311            TemplateComponent::Date(d) => {
312                if let citum_schema::template::DateForm::Unknown(s) = &d.form {
313                    warnings.push(Warning {
314                        level: WarningLevel::Warning,
315                        code: "unknown_enum_variant".to_string(),
316                        citation_id: None,
317                        ref_id: None,
318                        message: format!("Style {location} uses unknown date form '{s}'; falling back to year only."),
319                    });
320                }
321            }
322            TemplateComponent::Group(g) => {
323                scan_template_for_unknowns(&g.group, location, warnings);
324            }
325            _ => {}
326        }
327    }
328}
329
330#[cfg(test)]
331#[allow(clippy::unwrap_used, reason = "tests")]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn unknown_enum_warnings_reports_unknown_term_in_integral_sub_spec() {
337        let yaml = "info:\n  title: Test\ncitation:\n  integral:\n    template:\n      - term: not-a-real-term\n";
338        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
339        let processor = Processor::new(style, Bibliography::new());
340
341        let warnings = unknown_enum_warnings(&processor);
342        assert!(
343            warnings
344                .iter()
345                .any(|w| w.message.contains("not-a-real-term") && w.message.contains("(integral)")),
346            "expected a warning for the unknown term in citation.integral.template, got: {warnings:?}"
347        );
348    }
349
350    #[test]
351    fn unknown_enum_warnings_reports_unknown_role_label_term() {
352        let yaml = "info:\n  title: Test\nbibliography:\n  template:\n    - contributor: editor\n      form: long\n      label: {term: not-a-real-role}\n";
353        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
354        let processor = Processor::new(style, Bibliography::new());
355
356        let warnings = unknown_enum_warnings(&processor);
357        assert!(
358            warnings
359                .iter()
360                .any(|w| w.code == "unknown_role_label_term"
361                    && w.message.contains("not-a-real-role")),
362            "expected a warning for the unrecognized role-label term, got: {warnings:?}"
363        );
364    }
365
366    #[test]
367    fn unknown_enum_warnings_does_not_flag_recognized_role_label_terms() {
368        let yaml = "info:\n  title: Test\nbibliography:\n  template:\n    - contributor: editor\n      form: long\n      label: {term: editor}\n";
369        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
370        let processor = Processor::new(style, Bibliography::new());
371
372        let warnings = unknown_enum_warnings(&processor);
373        assert!(
374            !warnings.iter().any(|w| w.code == "unknown_role_label_term"),
375            "did not expect a warning for a recognized role-label term, got: {warnings:?}"
376        );
377    }
378
379    #[test]
380    fn unknown_enum_warnings_reports_unknown_term_in_type_variants() {
381        let yaml = "info:\n  title: Test\ncitation:\n  type-variants:\n    book:\n      - term: not-a-real-term-2\n";
382        let style = citum_schema::Style::from_yaml_str(yaml).unwrap();
383        let processor = Processor::new(style, Bibliography::new());
384
385        let warnings = unknown_enum_warnings(&processor);
386        assert!(
387            warnings
388                .iter()
389                .any(|w| w.message.contains("not-a-real-term-2")),
390            "expected a warning for the unknown term in citation.type-variants, got: {warnings:?}"
391        );
392    }
393}