Skip to main content

jubarte_doc/
audit.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! `jubarte validate --rules a11y,style,structure`: accessibility, style and
6//! structure findings with the paragraph id an agent can act on.
7//!
8//! Every rule reads the admitted package through [`crate::inspect`]'s read
9//! model, so a finding's `location` is the same paragraph id (`p12`,
10//! `header1.p1`) that `jubarte read --json` prints and an edit plan targets.
11//! When a finding has no paragraph (a document-wide setting), the location
12//! is the part name.
13//!
14//! Two rules need a layout pass: `FONT_SUBSTITUTED` reads the renderer's font
15//! resolutions, and `STALE_FIELD_CACHE` compares a cached `NUMPAGES` result
16//! with the laid-out page count. The pass runs only when one of them is
17//! selected and has something to read, and it lays out in
18//! `jubarte_render::convert::RevisionStyle::Word` because the cached page count it is checked
19//! against is Word's. [`AuditReport::layout`](crate::audit::AuditReport::layout) says whether it ran.
20//! [`audit_report_with`](crate::audit::audit_report_with) takes the pass from the caller, or none, for builds
21//! that leave the renderer out.
22
23use std::collections::{BTreeMap, BTreeSet};
24use std::fmt;
25
26use serde::Serialize;
27
28use crate::inspect::{
29    InspectError, Opened, body_paragraph_nodes, parse_part, project_paragraph,
30    story_paragraph_nodes,
31};
32use crate::namespaces::{MC, W, WP};
33use crate::xmllinq::{Dom, NodeId, XName};
34#[cfg(feature = "render")]
35use jubarte_render::convert::{PdfOptions, RenderReport, RevisionStyle, docx_render_report};
36
37/// Every rule: `(code, rule set, severity)`, in report order.
38pub const RULES: &[(&str, &str, &str)] = &[
39    ("HEADING_SKIP", "a11y", "warning"),
40    ("IMAGE_NO_DESCR", "a11y", "error"),
41    ("TABLE_NO_HEADER_ROW", "a11y", "warning"),
42    ("MISSING_LANG", "a11y", "warning"),
43    ("LITERAL_BULLET", "style", "warning"),
44    ("EMPTY_SPACER_PARAGRAPH", "style", "info"),
45    ("DIRECT_FORMATTING_OVERRIDES_STYLE", "style", "info"),
46    ("STALE_FIELD_CACHE", "structure", "warning"),
47    ("FONT_SUBSTITUTED", "structure", "info"),
48];
49
50/// The rule sets [`RULES`] groups codes into: the last three of
51/// [`crate::validate::RULE_SETS`].
52#[doc(hidden)]
53pub const RULE_SETS: &[&str] = crate::validate::RULE_SETS.split_at(2).1;
54
55/// Characters typed as list markers instead of using Word numbering.
56const LITERAL_MARKERS: &[char] = &['•', '◦', '▪', '-', '*', '·'];
57
58/// One audit finding.
59#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
60pub struct AuditFinding {
61    /// Rule code.
62    pub code: String,
63    /// `a11y`, `style` or `structure`.
64    pub rule_set: String,
65    /// `error`, `warning` or `info`.
66    pub severity: String,
67    /// A paragraph id (`p12`, `header1.p1`) or a part name.
68    pub location: String,
69    /// What was found, in one sentence.
70    pub message: String,
71}
72
73/// Findings plus what ran to produce them.
74#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
75pub struct AuditReport {
76    /// Findings, rule by rule in [`RULES`] order, each in document order.
77    pub findings: Vec<AuditFinding>,
78    /// The codes that ran.
79    pub rules: Vec<String>,
80    /// Whether a layout pass ran (`FONT_SUBSTITUTED`, or a numeric
81    /// `NUMPAGES` cache for `STALE_FIELD_CACHE`).
82    pub layout: bool,
83}
84
85/// Why an audit could not run.
86#[derive(Debug)]
87pub enum AuditError {
88    /// The package could not be admitted or read.
89    Inspect(InspectError),
90    /// The layout pass failed.
91    Layout(String),
92    /// A requested rule is neither a rule code nor a rule set.
93    UnknownRule(String),
94}
95
96impl fmt::Display for AuditError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match self {
99            Self::Inspect(error) => write!(f, "{error}"),
100            Self::Layout(error) => write!(f, "layout pass failed: {error}"),
101            Self::UnknownRule(rule) => {
102                let codes: Vec<&str> = RULES.iter().map(|rule| rule.0).collect();
103                write!(
104                    f,
105                    "unknown audit rule {rule}; expected one of {} or {}",
106                    RULE_SETS.join(", "),
107                    codes.join(", ")
108                )
109            }
110        }
111    }
112}
113
114impl std::error::Error for AuditError {}
115
116impl From<InspectError> for AuditError {
117    fn from(error: InspectError) -> Self {
118        Self::Inspect(error)
119    }
120}
121
122/// Audit `docx` with `rules` (rule sets or codes; empty selects every rule).
123///
124/// # Errors
125///
126/// [`AuditError::UnknownRule`] when a rule is neither a known set nor a
127/// known code; [`AuditError::Layout`] when the layout pass fails;
128/// [`AuditError::Inspect`] when the package cannot be admitted or read.
129#[cfg(feature = "render")]
130pub fn audit(docx: &[u8], rules: &[&str]) -> Result<Vec<AuditFinding>, AuditError> {
131    Ok(audit_report(docx, rules)?.findings)
132}
133
134#[cfg(feature = "render")]
135/// [`audit`] plus the codes that ran and whether a layout pass ran.
136///
137/// # Errors
138///
139/// As [`audit`].
140#[cfg(feature = "render")]
141pub fn audit_report(docx: &[u8], rules: &[&str]) -> Result<AuditReport, AuditError> {
142    audit_report_with(docx, rules, Some(&mut word_layout))
143}
144
145#[cfg(feature = "render")]
146/// The native layout pass: the document laid out in
147/// [`RevisionStyle::Word`], whose page count the `NUMPAGES` cache is
148/// checked against.
149///
150/// # Errors
151///
152/// [`AuditError::Layout`] when the renderer fails.
153pub fn word_layout(docx: &[u8]) -> Result<RenderReport, AuditError> {
154    let options = PdfOptions {
155        revisions: RevisionStyle::Word,
156        ..PdfOptions::default()
157    };
158    docx_render_report(docx, options).map_err(|error| AuditError::Layout(error.to_string()))
159}
160
161/// True when `rule` is one of the audit's rule sets or codes.
162#[doc(hidden)]
163pub fn is_rule(rule: &str) -> bool {
164    RULE_SETS.contains(&rule) || RULES.iter().any(|known| known.0 == rule)
165}
166
167#[cfg(feature = "render")]
168/// A layout pass [`audit_report_with`] calls at most once.
169pub type LayoutPass<'a> = &'a mut dyn FnMut(&[u8]) -> Result<RenderReport, AuditError>;
170
171/// No value: without the `render` feature there is no layout pass, so the
172/// only [`LayoutPass`] option [`audit_report_with`] takes is `None`.
173#[cfg(not(feature = "render"))]
174#[derive(Debug)]
175pub enum NoLayout {}
176
177/// Without the `render` feature a layout pass cannot exist: pass `None`.
178#[cfg(not(feature = "render"))]
179pub type LayoutPass<'a> = &'a NoLayout;
180
181/// `audit_report` (with the `render` feature) with the layout pass supplied by the caller, so a build
182/// without the renderer (the slim WASM build) can audit without linking it.
183///
184/// Without a pass (`None`), `FONT_SUBSTITUTED` is left out of the default
185/// selection and asking for it is [`AuditError::Layout`];
186/// `STALE_FIELD_CACHE` still reports empty TOC and `NUMPAGES` caches but
187/// cannot compare a cached page count with a layout.
188///
189/// # Errors
190///
191/// [`AuditError::UnknownRule`] when a rule is neither a known set nor a
192/// known code; [`AuditError::Layout`] when the supplied layout pass fails
193/// or when `FONT_SUBSTITUTED` is requested without a layout pass;
194/// [`AuditError::Inspect`] when the package cannot be admitted or read.
195pub fn audit_report_with(
196    docx: &[u8],
197    rules: &[&str],
198    layout: Option<LayoutPass<'_>>,
199) -> Result<AuditReport, AuditError> {
200    let selected = select(rules, layout.is_some())?;
201    let opened = Opened::open(docx)?;
202    let package = Package::read(opened)?;
203    let mut findings = Vec::new();
204    #[cfg(feature = "render")]
205    let (mut layout, mut laid_out) = (layout, None);
206    for &(code, _, _) in &selected {
207        match code {
208            "HEADING_SKIP" => package.heading_skip(&mut findings),
209            "IMAGE_NO_DESCR" => package.image_no_descr(&mut findings),
210            "TABLE_NO_HEADER_ROW" => package.table_no_header_row(&mut findings),
211            "MISSING_LANG" => package.missing_lang(&mut findings),
212            "LITERAL_BULLET" => package.literal_bullet(&mut findings),
213            "EMPTY_SPACER_PARAGRAPH" => package.empty_spacers(&mut findings),
214            "DIRECT_FORMATTING_OVERRIDES_STYLE" => package.direct_formatting(&mut findings),
215            "STALE_FIELD_CACHE" => {
216                let fields = package.fields();
217                #[cfg(feature = "render")]
218                let pages = {
219                    let numeric = fields
220                        .iter()
221                        .any(|field| field.keyword == "NUMPAGES" && field.number().is_some());
222                    match layout.as_deref_mut() {
223                        Some(pass) if numeric => {
224                            Some(lay_out(docx, pass, &mut laid_out)?.page_count)
225                        }
226                        _ => None,
227                    }
228                };
229                #[cfg(not(feature = "render"))]
230                let pages = None;
231                stale_fields(&fields, pages, &mut findings);
232            }
233            #[cfg(not(feature = "render"))]
234            _ => unreachable!("select keeps FONT_SUBSTITUTED only with a layout pass"),
235            #[cfg(feature = "render")]
236            _ => {
237                let pass = layout
238                    .as_deref_mut()
239                    .expect("select keeps FONT_SUBSTITUTED only with a layout pass");
240                let fonts = &lay_out(docx, pass, &mut laid_out)?.fonts;
241                let mut seen = BTreeSet::new();
242                for font in fonts.iter().filter(|font| font.substituted()) {
243                    if seen.insert(font.requested.clone()) {
244                        findings.push(finding(
245                            code,
246                            package.main.clone(),
247                            format!(
248                                "font \"{}\" is not installed here and is drawn with {} ({})",
249                                font.requested,
250                                font.physical,
251                                font.step.as_str()
252                            ),
253                        ));
254                    }
255                }
256            }
257        }
258    }
259    Ok(AuditReport {
260        findings,
261        rules: selected.iter().map(|rule| rule.0.to_string()).collect(),
262        #[cfg(feature = "render")]
263        layout: laid_out.is_some(),
264        #[cfg(not(feature = "render"))]
265        layout: false,
266    })
267}
268
269/// The rules `requested` names, in [`RULES`] order. Without a layout pass
270/// the default leaves out `FONT_SUBSTITUTED`, and naming it is an error.
271fn select(
272    requested: &[&str],
273    can_lay_out: bool,
274) -> Result<Vec<(&'static str, &'static str, &'static str)>, AuditError> {
275    let names = |rule: &(&str, &str, &str), item: &str| rule.0 == item || rule.1 == item;
276    let mut wanted = BTreeSet::new();
277    for item in requested.iter().map(|item| item.trim()) {
278        if !RULES.iter().any(|rule| names(rule, item)) {
279            return Err(AuditError::UnknownRule(item.to_string()));
280        }
281        wanted.extend(
282            RULES
283                .iter()
284                .filter(|rule| names(rule, item))
285                .map(|rule| rule.0),
286        );
287    }
288    if requested.is_empty() {
289        wanted.extend(RULES.iter().map(|rule| rule.0));
290        if !can_lay_out {
291            wanted.remove("FONT_SUBSTITUTED");
292        }
293    } else if !can_lay_out && wanted.contains("FONT_SUBSTITUTED") {
294        return Err(AuditError::Layout(
295            "FONT_SUBSTITUTED needs a layout pass, which this build does not have".to_string(),
296        ));
297    }
298    Ok(RULES
299        .iter()
300        .filter(|rule| wanted.contains(rule.0))
301        .copied()
302        .collect())
303}
304
305#[cfg(feature = "render")]
306/// The layout report, computed by `pass` on first use.
307fn lay_out<'a>(
308    docx: &[u8],
309    pass: &mut dyn FnMut(&[u8]) -> Result<RenderReport, AuditError>,
310    slot: &'a mut Option<RenderReport>,
311) -> Result<&'a RenderReport, AuditError> {
312    if slot.is_none() {
313        *slot = Some(pass(docx)?);
314    }
315    Ok(slot.as_ref().expect("layout report was just stored"))
316}
317
318fn finding(code: &str, location: String, message: String) -> AuditFinding {
319    let &(code, rule_set, severity) = RULES
320        .iter()
321        .find(|rule| rule.0 == code)
322        .expect("finding codes come from RULES");
323    AuditFinding {
324        code: code.to_string(),
325        rule_set: rule_set.to_string(),
326        severity: severity.to_string(),
327        location,
328        message,
329    }
330}
331
332fn on(value: Option<&str>) -> bool {
333    !matches!(value, Some("0" | "false" | "off"))
334}
335
336/// One parsed part with its addressable paragraphs.
337struct Story {
338    /// `body`, or the story id (`header1`, `footnotes`, ...).
339    id: String,
340    /// Part name, the location when no paragraph applies.
341    part: String,
342    dom: Dom,
343    root: NodeId,
344    paragraphs: Vec<NodeId>,
345}
346
347impl Story {
348    /// The id of the indexed paragraph holding `node` (the nearest one,
349    /// so an image in a text box reports the paragraph that anchors it).
350    fn location(&self, node: NodeId) -> String {
351        std::iter::once(node)
352            .chain(self.dom.ancestors(node, Some(&W::p())))
353            .find_map(|p| self.paragraphs.iter().position(|&q| q == p))
354            .map_or_else(|| self.part.clone(), |index| self.paragraph_id(index))
355    }
356
357    fn paragraph_id(&self, index: usize) -> String {
358        crate::ids::paragraph_id(&self.id, index)
359    }
360}
361
362/// A style's facts the rules read.
363#[derive(Default)]
364struct StyleFacts {
365    name: Option<String>,
366    based_on: Option<String>,
367    numbering: Option<bool>,
368    font: Option<String>,
369    size: Option<String>,
370    lang: bool,
371}
372
373/// The package, read once.
374struct Package {
375    main: String,
376    stories: Vec<Story>,
377    styles_part: Option<String>,
378    styles: BTreeMap<String, StyleFacts>,
379    default_paragraph_style: String,
380    defaults_font: Option<String>,
381    defaults_size: Option<String>,
382    defaults_lang: bool,
383    theme_font_lang: bool,
384}
385
386impl Package {
387    fn read(opened: Opened) -> Result<Self, AuditError> {
388        let story_parts = opened.story_parts();
389        let styles_part = opened.related("styles").into_iter().next();
390        let settings_part = opened.related("settings").into_iter().next();
391        let Opened {
392            pkg,
393            main,
394            dom,
395            body,
396            ..
397        } = opened;
398        let mut stories = vec![Story {
399            id: "body".to_string(),
400            part: main.clone(),
401            paragraphs: body_paragraph_nodes(&dom, body),
402            dom,
403            root: body,
404        }];
405        for (id, _, part) in story_parts {
406            let (dom, _, root) = parse_part(&pkg, &part)?;
407            stories.push(Story {
408                id,
409                paragraphs: story_paragraph_nodes(&dom, root),
410                part,
411                dom,
412                root,
413            });
414        }
415        let mut package = Self {
416            main,
417            stories,
418            styles_part,
419            styles: BTreeMap::new(),
420            default_paragraph_style: "Normal".to_string(),
421            defaults_font: None,
422            defaults_size: None,
423            defaults_lang: false,
424            theme_font_lang: false,
425        };
426        if let Some(part) = package.styles_part.clone() {
427            let (dom, _, root) = parse_part(&pkg, &part)?;
428            package.read_styles(&dom, root);
429        }
430        if let Some(part) = settings_part {
431            let (dom, _, root) = parse_part(&pkg, &part)?;
432            package.theme_font_lang = dom
433                .element(root, &W::name("themeFontLang"))
434                .is_some_and(|lang| has_lang(&dom, lang));
435        }
436        Ok(package)
437    }
438
439    fn read_styles(&mut self, dom: &Dom, root: NodeId) {
440        if let Some(defaults) = dom.element(root, &W::name("docDefaults")) {
441            let rpr = dom
442                .element(defaults, &W::name("rPrDefault"))
443                .and_then(|default| dom.element(default, &W::r_pr()));
444            if let Some(rpr) = rpr {
445                (self.defaults_font, self.defaults_size) = run_font_and_size(dom, rpr);
446            }
447            self.defaults_lang = dom
448                .descendants(defaults, Some(&W::name("lang")))
449                .into_iter()
450                .any(|lang| has_lang(dom, lang));
451        }
452        let mut marked_default = None;
453        let mut named_normal = None;
454        for style in dom.elements(root, Some(&W::name("style"))) {
455            let Some(id) = dom.attribute(style, &W::name("styleId")) else {
456                continue;
457            };
458            let paragraph = dom.attribute(style, &W::type_()).unwrap_or("paragraph") == "paragraph";
459            if !paragraph {
460                continue;
461            }
462            if dom
463                .attribute(style, &W::name("default"))
464                .is_some_and(|value| matches!(value, "1" | "true" | "on"))
465            {
466                marked_default.get_or_insert_with(|| id.to_string());
467            }
468            let child_val = |name: &str| {
469                dom.element(style, &W::name(name))
470                    .and_then(|node| dom.attribute(node, &W::val()))
471                    .map(str::to_string)
472            };
473            let mut facts = StyleFacts {
474                name: child_val("name"),
475                based_on: child_val("basedOn"),
476                numbering: dom
477                    .element(style, &W::p_pr())
478                    .and_then(|ppr| dom.element(ppr, &W::num_pr()))
479                    .map(|num_pr| numbering_on(dom, num_pr).unwrap_or(true)),
480                ..StyleFacts::default()
481            };
482            if let Some(rpr) = dom.element(style, &W::r_pr()) {
483                (facts.font, facts.size) = run_font_and_size(dom, rpr);
484                facts.lang = dom
485                    .elements(rpr, Some(&W::name("lang")))
486                    .into_iter()
487                    .any(|lang| has_lang(dom, lang));
488            }
489            if facts
490                .name
491                .as_deref()
492                .is_some_and(|name| name.eq_ignore_ascii_case("normal"))
493            {
494                named_normal.get_or_insert_with(|| id.to_string());
495            }
496            self.styles.insert(id.to_string(), facts);
497        }
498        // The style marked default; failing that the one named Normal
499        // (LibreOffice writes it as `style0` without `w:default`).
500        if let Some(id) = marked_default.or(named_normal) {
501            self.default_paragraph_style = id;
502        }
503    }
504
505    /// Paragraph styles from `id` up its `basedOn` chain (cycles cut).
506    fn style_chain(&self, id: &str) -> Vec<&StyleFacts> {
507        let mut chain = Vec::new();
508        let mut seen = BTreeSet::new();
509        let mut next = Some(id.to_string());
510        while let Some(id) = next {
511            if !seen.insert(id.clone()) {
512                break;
513            }
514            let Some(facts) = self.styles.get(&id) else {
515                break;
516            };
517            chain.push(facts);
518            next = facts.based_on.clone();
519        }
520        chain
521    }
522
523    fn paragraph_style<'a>(&self, dom: &'a Dom, p: NodeId) -> Option<&'a str> {
524        dom.element(p, &W::p_pr())
525            .and_then(|ppr| dom.element(ppr, &W::p_style()))
526            .and_then(|style| dom.attribute(style, &W::val()))
527    }
528
529    /// The heading level of a paragraph style: its `w:name` is
530    /// `heading N` (how Word names them in every UI language), else its id
531    /// is `HeadingN`.
532    fn heading_level(&self, style: &str) -> Option<u32> {
533        let from_name = self
534            .styles
535            .get(style)
536            .and_then(|facts| facts.name.as_deref())
537            .and_then(|name| level_after(name, "heading "));
538        from_name.or_else(|| level_after(style, "heading"))
539    }
540
541    /// Direct `w:numPr` decides (a `numId` of 0 removes numbering);
542    /// otherwise the style chain's.
543    fn numbered(&self, dom: &Dom, p: NodeId) -> bool {
544        let direct = dom
545            .element(p, &W::p_pr())
546            .and_then(|ppr| dom.element(ppr, &W::num_pr()))
547            .and_then(|num_pr| numbering_on(dom, num_pr));
548        direct.unwrap_or_else(|| {
549            self.paragraph_style(dom, p).is_some_and(|style| {
550                self.style_chain(style)
551                    .into_iter()
552                    .find_map(|facts| facts.numbering)
553                    .unwrap_or(false)
554            })
555        })
556    }
557
558    fn body(&self) -> &Story {
559        &self.stories[0]
560    }
561
562    fn heading_skip(&self, findings: &mut Vec<AuditFinding>) {
563        let body = self.body();
564        let mut previous: Option<u32> = None;
565        for (index, &p) in body.paragraphs.iter().enumerate() {
566            let Some(level) = self
567                .paragraph_style(&body.dom, p)
568                .and_then(|style| self.heading_level(style))
569            else {
570                continue;
571            };
572            let message = match previous {
573                None if level > 1 => {
574                    Some(format!("the first heading is level {level}, not level 1"))
575                }
576                Some(before) if level > before + 1 => Some(format!(
577                    "a level {level} heading follows a level {before} heading"
578                )),
579                _ => None,
580            };
581            if let Some(message) = message {
582                findings.push(finding("HEADING_SKIP", body.paragraph_id(index), message));
583            }
584            previous = Some(level);
585        }
586    }
587
588    fn image_no_descr(&self, findings: &mut Vec<AuditFinding>) {
589        let descr = XName::get("descr", "");
590        for story in &self.stories {
591            let dom = &story.dom;
592            for doc_pr in dom.descendants(story.root, Some(&WP::doc_pr())) {
593                if under_fallback(dom, doc_pr) {
594                    continue;
595                }
596                let described = dom
597                    .attribute(doc_pr, &descr)
598                    .is_some_and(|text| !text.trim().is_empty());
599                if described || decorative(dom, doc_pr) {
600                    continue;
601                }
602                let name = dom
603                    .attribute(doc_pr, &XName::get("name", ""))
604                    .unwrap_or("unnamed");
605                findings.push(finding(
606                    "IMAGE_NO_DESCR",
607                    story.location(doc_pr),
608                    format!(
609                        "drawing \"{name}\" has no alternative text and is not marked decorative"
610                    ),
611                ));
612            }
613        }
614    }
615
616    fn table_no_header_row(&self, findings: &mut Vec<AuditFinding>) {
617        for story in &self.stories {
618            let dom = &story.dom;
619            for table in dom.descendants(story.root, Some(&W::tbl())) {
620                let rows = dom.elements(table, Some(&W::tr()));
621                if rows.len() < 2 {
622                    continue;
623                }
624                let header = dom
625                    .element(rows[0], &W::tr_pr())
626                    .and_then(|tr_pr| dom.element(tr_pr, &W::name("tblHeader")))
627                    .is_some_and(|header| on(dom.attribute(header, &W::val())));
628                if header {
629                    continue;
630                }
631                let location = dom
632                    .descendants(table, Some(&W::p()))
633                    .first()
634                    .map_or_else(|| story.part.clone(), |&p| story.location(p));
635                findings.push(finding(
636                    "TABLE_NO_HEADER_ROW",
637                    location,
638                    format!(
639                        "a {}-row table does not mark its first row as a header row",
640                        rows.len()
641                    ),
642                ));
643            }
644        }
645    }
646
647    fn missing_lang(&self, findings: &mut Vec<AuditFinding>) {
648        let normal = self
649            .style_chain(&self.default_paragraph_style)
650            .into_iter()
651            .any(|facts| facts.lang);
652        if self.defaults_lang || normal || self.theme_font_lang {
653            return;
654        }
655        findings.push(finding(
656            "MISSING_LANG",
657            self.styles_part
658                .clone()
659                .unwrap_or_else(|| self.main.clone()),
660            "no document language is set (docDefaults, the default paragraph style and \
661             themeFontLang carry no w:lang)"
662                .to_string(),
663        ));
664    }
665
666    fn literal_bullet(&self, findings: &mut Vec<AuditFinding>) {
667        for story in &self.stories {
668            for (index, &p) in story.paragraphs.iter().enumerate() {
669                let text = project_paragraph(&story.dom, p).text;
670                let mut chars = text.trim_start_matches([' ', '\u{a0}']).chars();
671                let (Some(marker), Some(gap)) = (chars.next(), chars.next()) else {
672                    continue;
673                };
674                if !LITERAL_MARKERS.contains(&marker) || !matches!(gap, ' ' | '\t' | '\u{a0}') {
675                    continue;
676                }
677                if self.numbered(&story.dom, p) {
678                    continue;
679                }
680                findings.push(finding(
681                    "LITERAL_BULLET",
682                    story.paragraph_id(index),
683                    format!(
684                        "the paragraph starts with a typed \"{marker}\" instead of list numbering"
685                    ),
686                ));
687            }
688        }
689    }
690
691    fn empty_spacers(&self, findings: &mut Vec<AuditFinding>) {
692        for story in &self.stories {
693            let dom = &story.dom;
694            let breaks_section = |p: NodeId| {
695                dom.element(p, &W::p_pr())
696                    .is_some_and(|ppr| dom.element(ppr, &W::sect_pr()).is_some())
697            };
698            let empty = |p: NodeId| {
699                if !dom.ancestors(p, Some(&W::tc())).is_empty() {
700                    return false;
701                }
702                let projection = project_paragraph(dom, p);
703                projection.text.trim().is_empty()
704                    && !projection.page_break
705                    && projection.limitations.is_empty()
706            };
707            let mut index = 0;
708            while index < story.paragraphs.len() {
709                let first = story.paragraphs[index];
710                if !empty(first) {
711                    index += 1;
712                    continue;
713                }
714                let mut end = index + 1;
715                while end < story.paragraphs.len()
716                    && dom.parent(story.paragraphs[end]) == dom.parent(first)
717                    && empty(story.paragraphs[end])
718                    && !breaks_section(story.paragraphs[end - 1])
719                {
720                    end += 1;
721                }
722                let count = end - index;
723                let last = story.paragraphs[end - 1];
724                let before_break = breaks_section(last)
725                    || story.paragraphs.get(end).is_some_and(|&next| {
726                        dom.parent(next) == dom.parent(first) && breaks_section(next)
727                    });
728                if count >= 2 && !before_break {
729                    findings.push(finding(
730                        "EMPTY_SPACER_PARAGRAPH",
731                        story.paragraph_id(index),
732                        format!(
733                            "{count} consecutive empty paragraphs ({} to {}) are used as vertical space",
734                            crate::ids::short_paragraph(&story.paragraph_id(index)),
735                            crate::ids::short_paragraph(&story.paragraph_id(end - 1))
736                        ),
737                    ));
738                }
739                index = end;
740            }
741        }
742    }
743
744    fn direct_formatting(&self, findings: &mut Vec<AuditFinding>) {
745        let chain = self.style_chain(&self.default_paragraph_style);
746        let font = chain
747            .iter()
748            .find_map(|facts| facts.font.clone())
749            .or_else(|| self.defaults_font.clone());
750        let size = chain
751            .iter()
752            .find_map(|facts| facts.size.clone())
753            .or_else(|| self.defaults_size.clone());
754        let body = self.body();
755        let dom = &body.dom;
756        let (mut runs, mut overrides) = (0usize, 0usize);
757        for &p in &body.paragraphs {
758            let default_style = self
759                .paragraph_style(dom, p)
760                .is_none_or(|style| style == self.default_paragraph_style);
761            if !default_style {
762                continue;
763            }
764            for run in dom.descendants(p, Some(&W::r())) {
765                let own = dom.ancestors(run, Some(&W::p())).first() == Some(&p);
766                if !own || dom.element(run, &W::t()).is_none() {
767                    continue;
768                }
769                runs += 1;
770                let Some(rpr) = dom.element(run, &W::r_pr()) else {
771                    continue;
772                };
773                let (run_font, run_size) = run_font_and_size(dom, rpr);
774                let font_differs = run_font.is_some() && run_font != font;
775                let size_differs = run_size.is_some() && run_size != size;
776                if font_differs || size_differs {
777                    overrides += 1;
778                }
779            }
780        }
781        if runs > 0 && overrides * 10 > runs * 3 {
782            findings.push(finding(
783                "DIRECT_FORMATTING_OVERRIDES_STYLE",
784                self.main.clone(),
785                format!(
786                    "{overrides} of {runs} runs in default-style paragraphs set a font or size \
787                     that differs from the style"
788                ),
789            ));
790        }
791    }
792
793    /// Every complex and simple field, story by story in document order.
794    fn fields(&self) -> Vec<Field> {
795        let mut out = Vec::new();
796        for (story_index, story) in self.stories.iter().enumerate() {
797            let dom = &story.dom;
798            let mut open: Vec<Field> = Vec::new();
799            for node in dom.descendants(story.root, None) {
800                if under_fallback(dom, node) {
801                    continue;
802                }
803                if dom.name_is(node, &W::fld_char()) {
804                    match dom.attribute(node, &W::name("fldCharType")) {
805                        Some("begin") => open.push(Field::new(story_index, node)),
806                        Some("separate") => {
807                            if let Some(field) = open.last_mut() {
808                                field.separated = true;
809                            }
810                        }
811                        Some("end") => {
812                            if let Some(mut field) = open.pop() {
813                                field.finish(self);
814                                out.push(field);
815                            }
816                        }
817                        _ => {}
818                    }
819                } else if dom.name_is(node, &W::instr_text()) {
820                    if let Some(field) = open.last_mut().filter(|field| !field.separated) {
821                        field.instruction.push_str(&dom.value_str(node));
822                    }
823                } else if dom.name_is(node, &W::t()) {
824                    let text = dom.value_str(node);
825                    for field in open.iter_mut().filter(|field| field.separated) {
826                        field.result.push_str(&text);
827                    }
828                } else if dom.name_is(node, &W::fld_simple()) {
829                    let mut field = Field::new(story_index, node);
830                    field.instruction = dom
831                        .attribute(node, &W::name("instr"))
832                        .unwrap_or_default()
833                        .to_string();
834                    field.separated = true;
835                    field.result = dom
836                        .descendants(node, Some(&W::t()))
837                        .into_iter()
838                        .map(|t| dom.value(t))
839                        .collect();
840                    field.finish(self);
841                    out.push(field);
842                }
843            }
844            for mut field in open.into_iter().rev() {
845                field.finish(self);
846                out.push(field);
847            }
848        }
849        out
850    }
851}
852
853/// One field's instruction and cached result.
854struct Field {
855    story: usize,
856    node: NodeId,
857    instruction: String,
858    separated: bool,
859    result: String,
860    /// Upper-cased first word of the instruction, set by `finish`.
861    keyword: String,
862    location: String,
863}
864
865impl Field {
866    fn new(story: usize, node: NodeId) -> Self {
867        Self {
868            story,
869            node,
870            instruction: String::new(),
871            separated: false,
872            result: String::new(),
873            keyword: String::new(),
874            location: String::new(),
875        }
876    }
877
878    fn finish(&mut self, package: &Package) {
879        self.keyword = self
880            .instruction
881            .split_whitespace()
882            .next()
883            .unwrap_or("-")
884            .to_ascii_uppercase();
885        self.location = package.stories[self.story].location(self.node);
886    }
887
888    fn cached(&self) -> bool {
889        self.separated && !self.result.trim().is_empty()
890    }
891
892    fn number(&self) -> Option<usize> {
893        self.cached()
894            .then(|| self.result.trim().parse().ok())
895            .flatten()
896    }
897}
898
899fn stale_fields(fields: &[Field], pages: Option<usize>, findings: &mut Vec<AuditFinding>) {
900    for field in fields {
901        let message = match field.keyword.as_str() {
902            "TOC" if !field.cached() => {
903                Some("the table of contents has no cached entries; update fields".to_string())
904            }
905            "NUMPAGES" if !field.cached() => {
906                Some("the NUMPAGES field has no cached page count; update fields".to_string())
907            }
908            "NUMPAGES" => match (field.number(), pages) {
909                (Some(cached), Some(pages)) if cached != pages => Some(format!(
910                    "the NUMPAGES field caches {cached} pages but the document lays out to {pages}"
911                )),
912                _ => None,
913            },
914            _ => None,
915        };
916        if let Some(message) = message {
917            findings.push(finding(
918                "STALE_FIELD_CACHE",
919                field.location.clone(),
920                message,
921            ));
922        }
923    }
924}
925
926/// `rFonts` (`ascii`, else `hAnsi`) and `sz` of an `rPr`.
927fn run_font_and_size(dom: &Dom, rpr: NodeId) -> (Option<String>, Option<String>) {
928    let font = dom.element(rpr, &W::name("rFonts")).and_then(|fonts| {
929        dom.attribute(fonts, &W::name("ascii"))
930            .or_else(|| dom.attribute(fonts, &W::name("hAnsi")))
931            .map(str::to_string)
932    });
933    let size = dom
934        .element(rpr, &W::name("sz"))
935        .and_then(|sz| dom.attribute(sz, &W::val()))
936        .map(str::to_string);
937    (font, size)
938}
939
940/// A `w:lang`-shaped element naming any language.
941fn has_lang(dom: &Dom, lang: NodeId) -> bool {
942    ["val", "eastAsia", "bidi"].iter().any(|attribute| {
943        dom.attribute(lang, &W::name(attribute))
944            .is_some_and(|value| !value.trim().is_empty())
945    })
946}
947
948/// `Some(false)` when a `numPr` names `numId` 0 (numbering removed),
949/// `Some(true)` for any other `numId`, `None` when it names none.
950fn numbering_on(dom: &Dom, num_pr: NodeId) -> Option<bool> {
951    dom.element(num_pr, &W::name("numId"))
952        .and_then(|num_id| dom.attribute(num_id, &W::val()))
953        .map(|id| id.trim() != "0")
954}
955
956/// `N` from `{prefix}N` (case-insensitive), for heading levels 1-9.
957fn level_after(text: &str, prefix: &str) -> Option<u32> {
958    let head = text.get(..prefix.len())?;
959    if !head.eq_ignore_ascii_case(prefix) {
960        return None;
961    }
962    text[prefix.len()..]
963        .trim()
964        .parse()
965        .ok()
966        .filter(|level| (1..=9).contains(level))
967}
968
969/// The Office 2019 decorative flag (`adec:decorative val="1"` in the
970/// `docPr`'s extension list). Matched by local name: OOXML defines no
971/// `w:decorative`.
972fn decorative(dom: &Dom, doc_pr: NodeId) -> bool {
973    dom.descendants(doc_pr, None).into_iter().any(|node| {
974        dom.name(node)
975            .is_some_and(|name| name.local_name() == "decorative")
976            && matches!(
977                dom.attribute(node, &XName::get("val", "")),
978                Some("1" | "true")
979            )
980    })
981}
982
983/// Inside an `mc:Fallback`, which repeats its `mc:Choice` for old readers.
984fn under_fallback(dom: &Dom, node: NodeId) -> bool {
985    !dom.ancestors(node, Some(&MC::name("Fallback"))).is_empty()
986}
987
988// Its one test reads the layout's page facts.
989#[cfg(all(test, feature = "render"))]
990#[cfg_attr(all(coverage_nightly, test), coverage(off))]
991mod public_memory_spacer_ownership_tests {
992    use super::*;
993    use crate::opc::PartFs;
994
995    fn package(body: &str) -> PartFs {
996        let mut pkg = PartFs::open(include_bytes!(
997            "../../../tests/fixtures/redline/original.docx"
998        ))
999        .unwrap();
1000        pkg.set_part("word/document.xml",format!("<w:document xmlns:w='{}'><w:body>{body}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>",W::URI).into_bytes());
1001        pkg
1002    }
1003    fn snapshot(pkg: &PartFs) -> Vec<(String, Vec<u8>)> {
1004        let mut parts = pkg.parts();
1005        parts.sort();
1006        parts
1007            .into_iter()
1008            .map(|name| {
1009                let bytes = pkg.part_bytes(&name).unwrap().to_vec();
1010                (name, bytes)
1011            })
1012            .collect()
1013    }
1014
1015    #[cfg(feature = "render")]
1016    #[test]
1017    fn spacer_audit_respects_authored_sections_page_breaks_and_table_cell_ownership() {
1018        let blank = "<w:p><w:pPr><w:spacing w:after='80'/></w:pPr></w:p>";
1019        let section =
1020            "<w:p><w:pPr><w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:pPr></w:p>";
1021        let page = "<w:p><w:r><w:br w:type='page'/></w:r></w:p>";
1022        let table = format!(
1023            "<w:tbl><w:tblPr><w:tblW w:w='1800' w:type='dxa'/></w:tblPr><w:tblGrid><w:gridCol w:w='1800'/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w='1800' w:type='dxa'/></w:tcPr>{blank}{blank}</w:tc></w:tr></w:tbl>"
1024        );
1025        for (label, body, warns) in [
1026            ("authored vertical spacer", format!("{blank}{blank}"), true),
1027            ("single authored blank", blank.to_string(), false),
1028            (
1029                "second blank closes source section",
1030                format!("{blank}{section}"),
1031                false,
1032            ),
1033            (
1034                "section carrier precedes two independent blanks",
1035                format!("{section}{blank}{blank}"),
1036                true,
1037            ),
1038            (
1039                "page break splits blank run",
1040                format!("{blank}{page}{blank}"),
1041                false,
1042            ),
1043            ("cell blanks own their geometry", table.clone(), false),
1044            (
1045                "table separates body spacer owners",
1046                format!("{blank}{table}{blank}"),
1047                false,
1048            ),
1049        ] {
1050            let pkg = package(&body);
1051            let original = snapshot(&pkg);
1052            let bytes = pkg.to_zip().unwrap();
1053            let report = audit_report_with(&bytes, &["EMPTY_SPACER_PARAGRAPH"], None).unwrap();
1054            assert_eq!(report.rules, ["EMPTY_SPACER_PARAGRAPH"]);
1055            assert!(!report.layout);
1056            let expected = if warns {
1057                vec![AuditFinding {
1058                    code: "EMPTY_SPACER_PARAGRAPH".into(),
1059                    rule_set: "style".into(),
1060                    severity: "info".into(),
1061                    location: if label == "section carrier precedes two independent blanks" {
1062                        "p1".into()
1063                    } else {
1064                        "p0".into()
1065                    },
1066                    message: if label == "section carrier precedes two independent blanks" {
1067                        "2 consecutive empty paragraphs (p1 to p2) are used as vertical space"
1068                            .into()
1069                    } else {
1070                        "2 consecutive empty paragraphs (p0 to p1) are used as vertical space"
1071                            .into()
1072                    },
1073                }]
1074            } else {
1075                Vec::new()
1076            };
1077            assert_eq!(report.findings, expected, "{label}");
1078            assert_eq!(
1079                audit_report_with(&bytes, &["EMPTY_SPACER_PARAGRAPH"], None).unwrap(),
1080                report
1081            );
1082            assert_eq!(
1083                snapshot(&PartFs::open(&bytes).unwrap()),
1084                original,
1085                "{label}: audit is source read-only"
1086            );
1087        }
1088    }
1089}