Skip to main content

stella_docx_kernel/projection/
structure.rs

1use std::collections::{HashMap, HashSet};
2
3use crate::projection::numbering::NumberingCatalog;
4use crate::projection::review::ReviewPoint;
5use crate::{FormattingUnknownReason, ProjectionError};
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8pub enum StructuralFactUnknownReason {
9    ParagraphFragment,
10    DocumentPartOnly,
11    StylesPartUnavailable,
12    UnsupportedStyles,
13    UnsupportedNumbering,
14    IncompleteBookmarkRanges,
15    UnsupportedInternalReferences,
16}
17
18#[derive(Clone, Debug, Eq, PartialEq)]
19pub enum StructuralFactSet<T> {
20    Known(Vec<T>),
21    Unknown(StructuralFactUnknownReason),
22}
23
24impl<T> StructuralFactSet<T> {
25    pub fn known(items: impl IntoIterator<Item = T>) -> Self {
26        Self::Known(items.into_iter().collect())
27    }
28}
29
30#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
31pub struct ParagraphIndentation {
32    pub first_line_twips: Option<i32>,
33    pub hanging_twips: Option<i32>,
34    pub left_twips: Option<i32>,
35    pub right_twips: Option<i32>,
36    pub start_twips: Option<i32>,
37    pub end_twips: Option<i32>,
38    pub first_line_chars_hundredths: Option<i32>,
39    pub hanging_chars_hundredths: Option<i32>,
40    pub left_chars_hundredths: Option<i32>,
41    pub right_chars_hundredths: Option<i32>,
42    pub start_chars_hundredths: Option<i32>,
43    pub end_chars_hundredths: Option<i32>,
44}
45
46impl ParagraphIndentation {
47    fn is_empty(self) -> bool {
48        self == Self::default()
49    }
50
51    fn inherit(self, child: Self) -> Self {
52        let child_has_hanging =
53            child.hanging_twips.is_some() || child.hanging_chars_hundredths.is_some();
54        let child_has_first_line = !child_has_hanging
55            && (child.first_line_twips.is_some() || child.first_line_chars_hundredths.is_some());
56        let parent_first_line = if child_has_hanging {
57            (None, None)
58        } else {
59            (self.first_line_twips, self.first_line_chars_hundredths)
60        };
61        let parent_hanging = if child_has_first_line {
62            (None, None)
63        } else {
64            (self.hanging_twips, self.hanging_chars_hundredths)
65        };
66        let child_first_line = if child_has_hanging {
67            (None, None)
68        } else {
69            (child.first_line_twips, child.first_line_chars_hundredths)
70        };
71        let (first_line_twips, first_line_chars_hundredths) = inherit_character_indent(
72            parent_first_line.0,
73            parent_first_line.1,
74            child_first_line.0,
75            child_first_line.1,
76        );
77        let (hanging_twips, hanging_chars_hundredths) = inherit_character_indent(
78            parent_hanging.0,
79            parent_hanging.1,
80            child.hanging_twips,
81            child.hanging_chars_hundredths,
82        );
83        let (mut left_twips, left_chars_hundredths) = inherit_character_indent(
84            self.left_twips,
85            self.left_chars_hundredths,
86            child.left_twips,
87            child.left_chars_hundredths,
88        );
89        let (mut right_twips, right_chars_hundredths) = inherit_character_indent(
90            self.right_twips,
91            self.right_chars_hundredths,
92            child.right_twips,
93            child.right_chars_hundredths,
94        );
95        let (mut start_twips, start_chars_hundredths) = inherit_character_indent(
96            self.start_twips,
97            self.start_chars_hundredths,
98            child.start_twips,
99            child.start_chars_hundredths,
100        );
101        let (mut end_twips, end_chars_hundredths) = inherit_character_indent(
102            self.end_twips,
103            self.end_chars_hundredths,
104            child.end_twips,
105            child.end_chars_hundredths,
106        );
107        if left_chars_hundredths.is_some() || start_chars_hundredths.is_some() {
108            left_twips = None;
109            start_twips = None;
110        }
111        if right_chars_hundredths.is_some() || end_chars_hundredths.is_some() {
112            right_twips = None;
113            end_twips = None;
114        }
115        Self {
116            first_line_twips,
117            hanging_twips,
118            left_twips,
119            right_twips,
120            start_twips,
121            end_twips,
122            first_line_chars_hundredths,
123            hanging_chars_hundredths,
124            left_chars_hundredths,
125            right_chars_hundredths,
126            start_chars_hundredths,
127            end_chars_hundredths,
128        }
129    }
130
131    fn inherit_numbered_direct(self, mut direct: Self) -> Self {
132        if direct.first_line_twips == Some(0) {
133            direct.first_line_twips = None;
134        }
135        if direct.hanging_twips == Some(0) {
136            direct.hanging_twips = None;
137        }
138        self.inherit(direct)
139    }
140}
141
142fn inherit_character_indent(
143    parent_twips: Option<i32>,
144    parent_chars: Option<i32>,
145    child_twips: Option<i32>,
146    child_chars: Option<i32>,
147) -> (Option<i32>, Option<i32>) {
148    match child_chars {
149        Some(0) => (child_twips.or(parent_twips), None),
150        Some(value) => (None, Some(value)),
151        None => parent_chars.filter(|value| *value != 0).map_or_else(
152            || (child_twips.or(parent_twips), None),
153            |value| (None, Some(value)),
154        ),
155    }
156}
157
158#[derive(Clone, Debug, Eq, PartialEq)]
159pub struct ParagraphIndentationFact {
160    pub paragraph_ordinal: usize,
161    pub value: ParagraphIndentation,
162}
163
164/// Projected `w:jc/@w:val` tokens.
165#[derive(Clone, Copy, Debug, Eq, PartialEq)]
166pub enum ParagraphAlignmentValue {
167    Center,
168    Justify,
169    Left,
170    Right,
171}
172
173/// Cascade level that supplied a paragraph's effective `w:jc`.
174#[derive(Clone, Copy, Debug, Eq, PartialEq)]
175pub enum ParagraphAlignmentSource {
176    /// `w:pPr/w:jc` on the paragraph itself.
177    Direct,
178    /// The paragraph or table style chain.
179    Style,
180    /// `w:docDefaults/w:pPrDefault/w:pPr/w:jc`.
181    DocDefaults,
182}
183
184/// Effective paragraph alignment resolved for one paragraph.
185#[derive(Clone, Copy, Debug, Eq, PartialEq)]
186pub struct ParagraphAlignmentFact {
187    pub value: ParagraphAlignmentValue,
188    pub source: ParagraphAlignmentSource,
189}
190
191/// A `w:jc` element observed at one cascade level.
192#[derive(Clone, Copy, Debug, Eq, PartialEq)]
193pub(super) enum ParagraphAlignmentSetting {
194    Supported(ParagraphAlignmentValue),
195    /// A `w:val` token outside the projected set, or a `w:jc` without a usable
196    /// `w:val`. The element is present, so it still shadows lower cascade
197    /// levels; it projects no value, because a lower level's value would be a
198    /// guess at what the token renders as.
199    Unsupported,
200}
201
202#[derive(Clone, Copy, Debug, Eq, PartialEq)]
203pub struct ParagraphOutlineLevelFact {
204    pub paragraph_ordinal: usize,
205    pub outline_level: u8,
206}
207
208#[derive(Clone, Debug, Eq, PartialEq)]
209pub struct NumberingHierarchyFact {
210    pub paragraph_ordinal: usize,
211    pub parent_paragraph_ordinal: Option<usize>,
212    pub child_paragraph_ordinals: Vec<usize>,
213}
214
215#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
216pub enum SpanCoverage {
217    Complete,
218    ContinuesBefore,
219    ContinuesAfter,
220    ContinuesBeforeAndAfter,
221}
222
223#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
224pub struct StructuralSpan {
225    pub start_utf8: u32,
226    pub end_utf8: u32,
227    pub start_utf16: u32,
228    pub end_utf16: u32,
229    pub coverage: SpanCoverage,
230}
231
232#[derive(Clone, Debug, Eq, PartialEq)]
233pub struct BookmarkFact {
234    pub paragraph_ordinal: usize,
235    pub bookmark_id: u32,
236    pub name: String,
237    pub span: StructuralSpan,
238}
239
240#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
241pub enum InternalReferenceRole {
242    Source,
243    Target,
244}
245
246#[derive(Clone, Debug, Eq, PartialEq)]
247pub struct InternalReferenceFact {
248    pub paragraph_ordinal: usize,
249    pub reference_id: String,
250    pub role: InternalReferenceRole,
251    pub span: StructuralSpan,
252}
253
254#[derive(Clone, Debug, Eq, PartialEq)]
255pub struct DocumentStructureFacts {
256    pub indentation: StructuralFactSet<ParagraphIndentationFact>,
257    pub numbering_hierarchy: StructuralFactSet<NumberingHierarchyFact>,
258    pub bookmarks: StructuralFactSet<BookmarkFact>,
259    pub internal_references: StructuralFactSet<InternalReferenceFact>,
260    pub outline_levels: StructuralFactSet<ParagraphOutlineLevelFact>,
261}
262
263#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
264pub(super) struct NumberingProperties {
265    pub num_id: Option<u32>,
266    pub level: Option<u8>,
267    pub present: bool,
268}
269
270impl NumberingProperties {
271    fn inherit(self, child: Self) -> Self {
272        if !child.present {
273            return self;
274        }
275        Self {
276            num_id: child.num_id.or(self.num_id),
277            level: child.level.or(self.level),
278            present: true,
279        }
280    }
281}
282
283#[derive(Clone, Debug, Default, Eq, PartialEq)]
284pub(super) enum TableStyleSelection {
285    #[default]
286    OutsideTable,
287    Default,
288    Explicit(String),
289}
290
291#[derive(Clone, Debug, Default, Eq, PartialEq)]
292pub(super) struct ParagraphProperties {
293    pub style_id: Option<String>,
294    pub table_style: TableStyleSelection,
295    pub outline_level: Option<u8>,
296    pub indentation: ParagraphIndentation,
297    pub numbering: NumberingProperties,
298    pub alignment: Option<ParagraphAlignmentSetting>,
299}
300
301#[derive(Clone, Debug)]
302pub(super) struct RawBookmarkRange {
303    pub id: u32,
304    pub name: String,
305    pub start: ReviewPoint,
306    pub end: ReviewPoint,
307}
308
309#[derive(Clone, Debug)]
310pub(super) struct RawInternalReference {
311    pub reference_id: String,
312    pub source: ReviewPoint,
313}
314
315#[derive(Clone, Debug)]
316pub(super) struct StyleDefinition {
317    pub based_on: Option<String>,
318    pub properties: ParagraphProperties,
319    pub text_properties: TextProperties,
320    pub kind: StyleKind,
321    pub table_formatting: TableStyleFormatting,
322}
323
324#[derive(Clone, Copy, Debug, Eq, PartialEq)]
325pub(super) enum StyleKind {
326    Character,
327    Paragraph,
328    Table,
329}
330
331#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
332pub(super) enum TableStyleFormatting {
333    #[default]
334    Base,
335    Conditional,
336}
337
338pub(super) struct TextStyleInput<'a> {
339    pub paragraph: &'a ParagraphProperties,
340    pub character_style_id: Option<&'a str>,
341    pub direct: TextProperties,
342}
343
344#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
345pub(super) struct TextProperties {
346    pub bold: Option<bool>,
347    pub complex_script_bold: Option<bool>,
348    pub force_complex_script: Option<bool>,
349    pub right_to_left: Option<bool>,
350    pub highlighted: Option<bool>,
351    pub superscript: Option<bool>,
352}
353
354impl TextProperties {
355    const fn inherit(self, child: Self) -> Self {
356        Self {
357            bold: if child.bold.is_some() {
358                child.bold
359            } else {
360                self.bold
361            },
362            complex_script_bold: if child.complex_script_bold.is_some() {
363                child.complex_script_bold
364            } else {
365                self.complex_script_bold
366            },
367            force_complex_script: if child.force_complex_script.is_some() {
368                child.force_complex_script
369            } else {
370                self.force_complex_script
371            },
372            right_to_left: if child.right_to_left.is_some() {
373                child.right_to_left
374            } else {
375                self.right_to_left
376            },
377            highlighted: if child.highlighted.is_some() {
378                child.highlighted
379            } else {
380                self.highlighted
381            },
382            superscript: if child.superscript.is_some() {
383                child.superscript
384            } else {
385                self.superscript
386            },
387        }
388    }
389
390    fn inherit_style(self, child: Self) -> Self {
391        let mut inherited = self.inherit(child);
392        inherited.bold = inherit_style_toggle(self.bold, child.bold);
393        inherited.complex_script_bold =
394            inherit_style_toggle(self.complex_script_bold, child.complex_script_bold);
395        inherited
396    }
397}
398
399fn inherit_style_toggle(inherited: Option<bool>, child: Option<bool>) -> Option<bool> {
400    match child {
401        Some(true) => Some(!inherited.unwrap_or(false)),
402        Some(false) | None => inherited,
403    }
404}
405
406#[derive(Clone, Debug, Default)]
407pub(super) struct StyleSheet {
408    pub default_style_id: Option<String>,
409    pub default_table_style_id: Option<String>,
410    pub document_defaults: ParagraphProperties,
411    pub document_text_defaults: TextProperties,
412    pub styles: HashMap<String, StyleDefinition>,
413    resolved_character_text: HashMap<String, TextProperties>,
414    resolved_paragraph_styles: HashMap<String, ResolvedParagraphStyle>,
415    resolved_table_styles: HashMap<String, ResolvedParagraphStyle>,
416}
417
418#[derive(Clone, Copy, Debug, Default)]
419struct ResolvedParagraphStyle {
420    text: TextProperties,
421    properties: ResolvedParagraphStyleProperties,
422}
423
424impl ResolvedParagraphStyle {
425    fn inherit(self, child: &StyleDefinition) -> Self {
426        Self {
427            text: self.text.inherit_style(child.text_properties),
428            properties: self.properties.inherit(&child.properties),
429        }
430    }
431}
432
433#[derive(Clone, Copy, Debug, Default)]
434struct ResolvedParagraphStyleProperties {
435    indentation: ParagraphIndentation,
436    numbering: NumberingProperties,
437    outline_level: Option<u8>,
438    alignment: Option<ParagraphAlignmentSetting>,
439}
440
441impl ResolvedParagraphStyleProperties {
442    fn inherit(self, child: &ParagraphProperties) -> Self {
443        Self {
444            indentation: self.indentation.inherit(child.indentation),
445            numbering: self.numbering.inherit(child.numbering),
446            outline_level: child.outline_level.or(self.outline_level),
447            alignment: child.alignment.or(self.alignment),
448        }
449    }
450}
451
452#[derive(Clone, Debug)]
453struct ResolvedParagraphProperties {
454    indentation: Result<ParagraphIndentation, StructuralFactUnknownReason>,
455    numbering: NumberingProperties,
456    outline_level: Option<u8>,
457}
458
459impl StyleSheet {
460    pub(super) fn prepare_styles(&mut self) {
461        (self.resolved_character_text, _) = self.resolve_character_text_styles();
462        (self.resolved_paragraph_styles, _) = self.resolve_block_styles(StyleKind::Paragraph);
463        (self.resolved_table_styles, _) = self.resolve_block_styles(StyleKind::Table);
464    }
465
466    #[allow(clippy::map_unwrap_or)] // map_or_default grows the WebAssembly body here.
467    pub(super) fn resolve_text(
468        &self,
469        TextStyleInput {
470            paragraph: properties,
471            character_style_id,
472            direct,
473        }: TextStyleInput<'_>,
474    ) -> Result<TextProperties, ()> {
475        let table = self
476            .table_style(&properties.table_style)?
477            .map(|style| style.text)
478            .unwrap_or_default();
479        let paragraph = table.inherit_style(
480            self.paragraph_style(properties.style_id.as_deref())?
481                .map(|style| style.text)
482                .unwrap_or_default(),
483        );
484        let character = character_style_id
485            .filter(|style_id| {
486                self.styles
487                    .get(*style_id)
488                    .is_some_and(|style| style.kind == StyleKind::Character)
489            })
490            .map(|style_id| {
491                self.resolved_character_text
492                    .get(style_id)
493                    .copied()
494                    .ok_or(())
495            })
496            .transpose()?
497            .unwrap_or_default();
498        let mut effective = self
499            .document_text_defaults
500            .inherit(paragraph)
501            .inherit(character)
502            .inherit(direct);
503        effective.bold = Some(resolve_word_toggle(
504            self.document_text_defaults.bold,
505            paragraph.bold,
506            character.bold,
507            direct.bold,
508        ));
509        effective.complex_script_bold = Some(resolve_word_toggle(
510            self.document_text_defaults.complex_script_bold,
511            paragraph.complex_script_bold,
512            character.complex_script_bold,
513            direct.complex_script_bold,
514        ));
515        Ok(effective)
516    }
517
518    fn resolve_character_text_styles(&self) -> (HashMap<String, TextProperties>, usize) {
519        let mut resolved = HashMap::new();
520        let mut unresolved = HashSet::new();
521        let mut resolution_steps = 0usize;
522        for root_id in self.styles.iter().filter_map(|(style_id, style)| {
523            (style.kind == StyleKind::Character).then_some(style_id)
524        }) {
525            if resolved.contains_key(root_id) || unresolved.contains(root_id) {
526                continue;
527            }
528            let mut chain = Vec::new();
529            let mut seen = HashSet::new();
530            let mut current = Some(root_id.as_str());
531            let mut inherited = TextProperties::default();
532            let mut valid = true;
533            while let Some(style_id) = current {
534                resolution_steps = resolution_steps.saturating_add(1);
535                if let Some(properties) = resolved.get(style_id).copied() {
536                    inherited = properties;
537                    break;
538                }
539                if unresolved.contains(style_id) {
540                    valid = false;
541                    break;
542                }
543                if !seen.insert(style_id) {
544                    valid = false;
545                    break;
546                }
547                let Some(style) = self.styles.get(style_id) else {
548                    // A missing base contributes no inherited properties.
549                    valid = !chain.is_empty();
550                    break;
551                };
552                if style.kind != StyleKind::Character {
553                    // Inheritance cannot cross style kinds; the current style
554                    // remains a root with its own properties.
555                    valid = !chain.is_empty();
556                    break;
557                }
558                chain.push(style_id);
559                current = style.based_on.as_deref();
560            }
561            if !valid {
562                unresolved.extend(chain.into_iter().map(str::to_owned));
563                continue;
564            }
565            for style_id in chain.into_iter().rev() {
566                // Every ID in the chain was validated above.
567                if let Some(style) = self.styles.get(style_id) {
568                    inherited = inherited.inherit_style(style.text_properties);
569                    resolved.insert(style_id.to_owned(), inherited);
570                }
571            }
572        }
573        debug_assert!(
574            resolution_steps <= self.styles.len().saturating_mul(2).saturating_add(1),
575            "memoized style resolution exceeded its linear work budget"
576        );
577        (resolved, resolution_steps)
578    }
579
580    fn resolve_block_styles(
581        &self,
582        kind: StyleKind,
583    ) -> (HashMap<String, ResolvedParagraphStyle>, usize) {
584        let mut resolved = HashMap::new();
585        let mut unresolved = HashSet::new();
586        let mut resolution_steps = 0usize;
587        for root_id in self
588            .styles
589            .iter()
590            .filter_map(|(style_id, style)| (style.kind == kind).then_some(style_id))
591        {
592            if resolved.contains_key(root_id) || unresolved.contains(root_id) {
593                continue;
594            }
595            let mut chain = Vec::new();
596            let mut seen = HashSet::new();
597            let mut current = Some(root_id.as_str());
598            let mut inherited = ResolvedParagraphStyle::default();
599            let mut valid = true;
600            while let Some(style_id) = current {
601                resolution_steps = resolution_steps.saturating_add(1);
602                if let Some(properties) = resolved.get(style_id).copied() {
603                    inherited = properties;
604                    break;
605                }
606                if unresolved.contains(style_id) || !seen.insert(style_id) {
607                    valid = false;
608                    break;
609                }
610                let Some(style) = self.styles.get(style_id) else {
611                    valid = !chain.is_empty();
612                    break;
613                };
614                if style.kind != kind {
615                    valid = !chain.is_empty();
616                    break;
617                }
618                chain.push(style_id);
619                if kind == StyleKind::Table
620                    && style.table_formatting == TableStyleFormatting::Conditional
621                {
622                    valid = false;
623                    break;
624                }
625                current = style.based_on.as_deref();
626            }
627            if !valid {
628                unresolved.extend(chain.into_iter().map(str::to_owned));
629                continue;
630            }
631            for style_id in chain.into_iter().rev() {
632                if let Some(style) = self.styles.get(style_id) {
633                    inherited = inherited.inherit(style);
634                    resolved.insert(style_id.to_owned(), inherited);
635                }
636            }
637        }
638        debug_assert!(
639            resolution_steps <= self.styles.len().saturating_mul(2).saturating_add(1),
640            "memoized paragraph style resolution exceeded its linear work budget"
641        );
642        (resolved, resolution_steps)
643    }
644
645    fn table_style(
646        &self,
647        selection: &TableStyleSelection,
648    ) -> Result<Option<&ResolvedParagraphStyle>, ()> {
649        let style_id = match selection {
650            TableStyleSelection::OutsideTable => return Ok(None),
651            TableStyleSelection::Default => self.default_table_style_id.as_deref(),
652            TableStyleSelection::Explicit(id) => Some(id.as_str()),
653        };
654        let Some(style_id) = style_id.filter(|id| {
655            self.styles
656                .get(*id)
657                .is_some_and(|style| style.kind == StyleKind::Table)
658        }) else {
659            return Ok(None);
660        };
661        self.resolved_table_styles.get(style_id).map(Some).ok_or(())
662    }
663
664    fn paragraph_style(
665        &self,
666        explicit_style_id: Option<&str>,
667    ) -> Result<Option<&ResolvedParagraphStyle>, ()> {
668        let Some(style_id) = explicit_style_id
669            .filter(|id| {
670                self.styles
671                    .get(*id)
672                    .is_some_and(|style| style.kind == StyleKind::Paragraph)
673            })
674            .or(self.default_style_id.as_deref())
675        else {
676            return Ok(None);
677        };
678        self.resolved_paragraph_styles
679            .get(style_id)
680            .map(Some)
681            .ok_or(())
682    }
683
684    /// Missing, wrong-kind, and omitted paragraph references select the default.
685    /// Cyclic inheritance cannot supply an effective alignment.
686    fn style_alignment(
687        &self,
688        direct: &ParagraphProperties,
689    ) -> Result<Option<(ParagraphAlignmentSetting, ParagraphAlignmentSource)>, ()> {
690        let paragraph = self.paragraph_style(direct.style_id.as_deref())?;
691        if let Some(setting) = paragraph.and_then(|style| style.properties.alignment) {
692            return Ok(Some((setting, ParagraphAlignmentSource::Style)));
693        }
694        let table = self.table_style(&direct.table_style)?;
695        if let Some(setting) = table.and_then(|style| style.properties.alignment) {
696            return Ok(Some((setting, ParagraphAlignmentSource::Style)));
697        }
698        Ok(self
699            .document_defaults
700            .alignment
701            .map(|setting| (setting, ParagraphAlignmentSource::DocDefaults)))
702    }
703
704    #[allow(clippy::map_unwrap_or)] // map_or_default grows the WebAssembly body here.
705    fn resolve(
706        &self,
707        direct: &ParagraphProperties,
708        numbering_catalog: Result<&NumberingCatalog, StructuralFactUnknownReason>,
709    ) -> Result<ResolvedParagraphProperties, StructuralFactUnknownReason> {
710        let table = self
711            .table_style(&direct.table_style)
712            .map_err(|()| StructuralFactUnknownReason::UnsupportedStyles)?
713            .map(|style| style.properties)
714            .unwrap_or_default();
715        let style = self
716            .paragraph_style(direct.style_id.as_deref())
717            .map_err(|()| StructuralFactUnknownReason::UnsupportedStyles)?
718            .map(|style| style.properties)
719            .unwrap_or_default();
720        let style = ResolvedParagraphStyleProperties {
721            indentation: table.indentation.inherit(style.indentation),
722            numbering: table.numbering.inherit(style.numbering),
723            outline_level: style.outline_level.or(table.outline_level),
724            alignment: style.alignment.or(table.alignment),
725        };
726        let mut numbering = self.document_defaults.numbering.inherit(style.numbering);
727        let mut outline_level = style.outline_level.or(self.document_defaults.outline_level);
728        let inherited_numbering = numbering;
729        numbering = numbering.inherit(direct.numbering);
730        outline_level = direct.outline_level.or(outline_level);
731
732        let numbered = numbering.present && numbering.num_id != Some(0);
733        let numbering_is_direct = direct.numbering.present;
734        let numbering_removed = numbering_is_direct
735            && direct.numbering.num_id == Some(0)
736            && inherited_numbering.present
737            && inherited_numbering.num_id != Some(0);
738        let indentation = if numbered {
739            numbering
740                .num_id
741                .ok_or(StructuralFactUnknownReason::UnsupportedNumbering)
742                .and_then(|num_id| {
743                    numbering_catalog.and_then(|catalog| {
744                        catalog.indentation(num_id, numbering.level.unwrap_or(0))
745                    })
746                })
747        } else {
748            Ok(ParagraphIndentation::default())
749        }
750        .map(|level_indentation| {
751            let mut indentation = if numbering_removed {
752                ParagraphIndentation::default()
753            } else {
754                self.document_defaults.indentation
755            };
756            if !numbering_is_direct && !numbering_removed {
757                indentation = indentation.inherit(level_indentation);
758            }
759            if !numbering_removed {
760                indentation = indentation.inherit(style.indentation);
761            }
762            if numbering_is_direct {
763                indentation = indentation.inherit(level_indentation);
764            }
765            if numbered {
766                indentation.inherit_numbered_direct(direct.indentation)
767            } else {
768                indentation.inherit(direct.indentation)
769            }
770        });
771        Ok(ResolvedParagraphProperties {
772            indentation,
773            numbering,
774            outline_level,
775        })
776    }
777}
778
779/// Resolves the effective paragraph alignment for one paragraph.
780///
781/// Direct `w:pPr/w:jc` wins; otherwise the paragraph style chain and
782/// `w:docDefaults` apply. Without a style sheet only direct alignment is
783/// projected, which never claims a style-dependent value.
784///
785/// A present unsupported token shadows lower tiers and remains unknown; it
786/// cannot establish known absence. Table style and paragraph style resolution
787/// share the existing stylesheet owner. Numbering-level justification remains
788/// outside the projected alignment tiers.
789pub(super) fn resolve_paragraph_alignment(
790    styles: Result<&StyleSheet, StructuralFactUnknownReason>,
791    direct: &ParagraphProperties,
792) -> Result<Option<ParagraphAlignmentFact>, FormattingUnknownReason> {
793    let resolved = if let Some(setting) = direct.alignment {
794        Some((setting, ParagraphAlignmentSource::Direct))
795    } else {
796        styles
797            .map_err(super::formatting_unknown_reason)?
798            .style_alignment(direct)
799            .map_err(|()| FormattingUnknownReason::UnsupportedStyles)?
800    };
801    match resolved {
802        None => Ok(None),
803        Some((ParagraphAlignmentSetting::Supported(value), source)) => {
804            Ok(Some(ParagraphAlignmentFact { value, source }))
805        }
806        Some((ParagraphAlignmentSetting::Unsupported, _)) => {
807            Err(FormattingUnknownReason::UnsupportedAlignment)
808        }
809    }
810}
811
812fn resolve_word_toggle(
813    document_default: Option<bool>,
814    paragraph: Option<bool>,
815    character: Option<bool>,
816    direct: Option<bool>,
817) -> bool {
818    if let Some(value) = direct {
819        return value;
820    }
821    document_default.unwrap_or(false) ^ paragraph.unwrap_or(false) ^ character.unwrap_or(false)
822}
823
824#[derive(Clone, Copy)]
825pub(super) struct RawStructureInput<'a> {
826    pub paragraph_texts: &'a [&'a str],
827    pub properties: &'a [&'a ParagraphProperties],
828    pub bookmarks: Result<&'a [RawBookmarkRange], StructuralFactUnknownReason>,
829    pub references: Result<&'a [RawInternalReference], StructuralFactUnknownReason>,
830}
831
832struct StructuralFactBudget {
833    remaining: usize,
834}
835
836impl StructuralFactBudget {
837    const fn new(maximum_facts: usize) -> Self {
838        Self {
839            remaining: maximum_facts,
840        }
841    }
842
843    fn consume(&mut self, facts: usize) -> Result<(), ProjectionError> {
844        self.remaining = self
845            .remaining
846            .checked_sub(facts)
847            .ok_or(ProjectionError::TooManyStructuralFacts)?;
848        Ok(())
849    }
850}
851
852pub(super) fn materialize_structure(
853    input: RawStructureInput<'_>,
854    styles: Result<&StyleSheet, StructuralFactUnknownReason>,
855    numbering: Result<&NumberingCatalog, StructuralFactUnknownReason>,
856    maximum_facts: usize,
857) -> Result<DocumentStructureFacts, ProjectionError> {
858    let mut fact_budget = StructuralFactBudget::new(maximum_facts);
859    let resolved = styles.and_then(|styles| {
860        input
861            .properties
862            .iter()
863            .map(|properties| styles.resolve(properties, numbering))
864            .collect::<Result<Vec<_>, _>>()
865    });
866
867    let (indentation, numbering_hierarchy, outline_levels) = match resolved {
868        Ok(properties) => {
869            let indentation = properties
870                .iter()
871                .map(|properties| properties.indentation)
872                .collect::<Result<Vec<_>, _>>()
873                .map_or_else(StructuralFactSet::Unknown, |indentations| {
874                    StructuralFactSet::Known(
875                        indentations
876                            .into_iter()
877                            .enumerate()
878                            .filter(|(_, indentation)| !indentation.is_empty())
879                            .map(|(paragraph_ordinal, value)| ParagraphIndentationFact {
880                                paragraph_ordinal,
881                                value,
882                            })
883                            .collect(),
884                    )
885                });
886            (
887                indentation,
888                materialize_numbering(&properties),
889                StructuralFactSet::Known(
890                    properties
891                        .iter()
892                        .enumerate()
893                        .filter_map(|(paragraph_ordinal, properties)| {
894                            properties.outline_level.map(|outline_level| {
895                                ParagraphOutlineLevelFact {
896                                    paragraph_ordinal,
897                                    outline_level,
898                                }
899                            })
900                        })
901                        .collect(),
902                ),
903            )
904        }
905        Err(reason) => (
906            StructuralFactSet::Unknown(reason),
907            StructuralFactSet::Unknown(reason),
908            StructuralFactSet::Unknown(reason),
909        ),
910    };
911    if let StructuralFactSet::Known(facts) = &indentation {
912        fact_budget.consume(facts.len())?;
913    }
914    if let StructuralFactSet::Known(facts) = &numbering_hierarchy {
915        fact_budget.consume(facts.len())?;
916    }
917    if let StructuralFactSet::Known(facts) = &outline_levels {
918        fact_budget.consume(facts.len())?;
919    }
920
921    let bookmarks = match input.bookmarks {
922        Ok(ranges) => StructuralFactSet::Known(materialize_bookmarks(
923            input.paragraph_texts,
924            ranges,
925            &mut fact_budget,
926        )?),
927        Err(reason) => StructuralFactSet::Unknown(reason),
928    };
929    let internal_references = match (input.references, &bookmarks, input.bookmarks) {
930        (Ok([]), _, _) => StructuralFactSet::Known(Vec::new()),
931        (Ok(references), StructuralFactSet::Known(_), Ok(ranges)) => StructuralFactSet::Known(
932            materialize_references(references, ranges, input.paragraph_texts, &mut fact_budget)?,
933        ),
934        (Err(reason), _, _) => StructuralFactSet::Unknown(reason),
935        (_, StructuralFactSet::Unknown(_), _) => {
936            StructuralFactSet::Unknown(StructuralFactUnknownReason::IncompleteBookmarkRanges)
937        }
938        (_, _, Err(reason)) => StructuralFactSet::Unknown(reason),
939    };
940
941    Ok(DocumentStructureFacts {
942        indentation,
943        numbering_hierarchy,
944        bookmarks,
945        internal_references,
946        outline_levels,
947    })
948}
949
950fn materialize_numbering(
951    properties: &[ResolvedParagraphProperties],
952) -> StructuralFactSet<NumberingHierarchyFact> {
953    let mut stacks: HashMap<u32, [Option<usize>; 9]> = HashMap::new();
954    let mut parents = vec![None; properties.len()];
955    let mut children = vec![Vec::new(); properties.len()];
956
957    for (ordinal, paragraph_properties) in properties.iter().enumerate() {
958        if !paragraph_properties.numbering.present
959            || paragraph_properties.numbering.num_id == Some(0)
960        {
961            continue;
962        }
963        let Some(num_id) = paragraph_properties.numbering.num_id else {
964            return StructuralFactSet::Unknown(StructuralFactUnknownReason::UnsupportedNumbering);
965        };
966        let level = usize::from(paragraph_properties.numbering.level.unwrap_or(0));
967        if level >= 9 {
968            return StructuralFactSet::Unknown(StructuralFactUnknownReason::UnsupportedNumbering);
969        }
970        let stack = stacks.entry(num_id).or_insert([None; 9]);
971        if level > 0
972            && let Some(parent) = stack
973                .get(..level)
974                .and_then(|ancestors| ancestors.iter().rev().flatten().next().copied())
975        {
976            let Some(parent_slot) = parents.get_mut(ordinal) else {
977                return StructuralFactSet::Unknown(
978                    StructuralFactUnknownReason::UnsupportedNumbering,
979                );
980            };
981            *parent_slot = Some(parent);
982            let Some(parent_children) = children.get_mut(parent) else {
983                return StructuralFactSet::Unknown(
984                    StructuralFactUnknownReason::UnsupportedNumbering,
985                );
986            };
987            parent_children.push(ordinal);
988        }
989        let Some(level_slot) = stack.get_mut(level) else {
990            return StructuralFactSet::Unknown(StructuralFactUnknownReason::UnsupportedNumbering);
991        };
992        *level_slot = Some(ordinal);
993        let descendant_start = level.saturating_add(1);
994        let Some(descendant_slots) = stack.get_mut(descendant_start..) else {
995            return StructuralFactSet::Unknown(StructuralFactUnknownReason::UnsupportedNumbering);
996        };
997        for slot in descendant_slots {
998            *slot = None;
999        }
1000    }
1001
1002    StructuralFactSet::Known(
1003        properties
1004            .iter()
1005            .enumerate()
1006            .filter_map(|(ordinal, _)| {
1007                let parent = parents.get(ordinal).copied().flatten();
1008                let paragraph_children = children.get(ordinal)?;
1009                (parent.is_some() || !paragraph_children.is_empty()).then(|| {
1010                    NumberingHierarchyFact {
1011                        paragraph_ordinal: ordinal,
1012                        parent_paragraph_ordinal: parent,
1013                        child_paragraph_ordinals: paragraph_children.clone(),
1014                    }
1015                })
1016            })
1017            .collect(),
1018    )
1019}
1020
1021fn materialize_bookmarks(
1022    texts: &[&str],
1023    ranges: &[RawBookmarkRange],
1024    fact_budget: &mut StructuralFactBudget,
1025) -> Result<Vec<BookmarkFact>, ProjectionError> {
1026    let mut facts = Vec::new();
1027    for range in ranges {
1028        segment_range(texts, &range.start, &range.end, |paragraph, span| {
1029            fact_budget.consume(1)?;
1030            facts.push(BookmarkFact {
1031                paragraph_ordinal: paragraph,
1032                bookmark_id: range.id,
1033                name: range.name.clone(),
1034                span,
1035            });
1036            Ok(())
1037        })?;
1038    }
1039    facts.sort_by(|left, right| {
1040        (
1041            left.paragraph_ordinal,
1042            left.span.start_utf8,
1043            left.span.end_utf8,
1044            left.bookmark_id,
1045            left.name.as_str(),
1046            left.span.coverage,
1047        )
1048            .cmp(&(
1049                right.paragraph_ordinal,
1050                right.span.start_utf8,
1051                right.span.end_utf8,
1052                right.bookmark_id,
1053                right.name.as_str(),
1054                right.span.coverage,
1055            ))
1056    });
1057    Ok(facts)
1058}
1059
1060fn materialize_references(
1061    references: &[RawInternalReference],
1062    bookmarks: &[RawBookmarkRange],
1063    texts: &[&str],
1064    fact_budget: &mut StructuralFactBudget,
1065) -> Result<Vec<InternalReferenceFact>, ProjectionError> {
1066    let mut facts = Vec::new();
1067    let mut targets_by_name: HashMap<&str, &RawBookmarkRange> = HashMap::new();
1068    for bookmark in bookmarks {
1069        targets_by_name
1070            .entry(&bookmark.name)
1071            .and_modify(|first| {
1072                if (bookmark.start.paragraph_ordinal, bookmark.start.utf8)
1073                    < (first.start.paragraph_ordinal, first.start.utf8)
1074                {
1075                    *first = bookmark;
1076                }
1077            })
1078            .or_insert(bookmark);
1079    }
1080    let mut emitted_target_names = HashSet::new();
1081    for reference in references {
1082        fact_budget.consume(1)?;
1083        facts.push(InternalReferenceFact {
1084            paragraph_ordinal: reference.source.paragraph_ordinal,
1085            reference_id: reference.reference_id.clone(),
1086            role: InternalReferenceRole::Source,
1087            span: StructuralSpan {
1088                start_utf8: reference.source.utf8,
1089                end_utf8: reference.source.utf8,
1090                start_utf16: reference.source.utf16,
1091                end_utf16: reference.source.utf16,
1092                coverage: SpanCoverage::Complete,
1093            },
1094        });
1095        if emitted_target_names.insert(reference.reference_id.as_str())
1096            && let Some(targets) = targets_by_name.get(reference.reference_id.as_str())
1097        {
1098            segment_range(texts, &targets.start, &targets.end, |paragraph, span| {
1099                fact_budget.consume(1)?;
1100                facts.push(InternalReferenceFact {
1101                    paragraph_ordinal: paragraph,
1102                    reference_id: reference.reference_id.clone(),
1103                    role: InternalReferenceRole::Target,
1104                    span,
1105                });
1106                Ok(())
1107            })?;
1108        }
1109    }
1110    facts.sort_by(|left, right| {
1111        (
1112            left.paragraph_ordinal,
1113            left.span.start_utf8,
1114            left.span.end_utf8,
1115            left.reference_id.as_str(),
1116            left.role,
1117            left.span.coverage,
1118        )
1119            .cmp(&(
1120                right.paragraph_ordinal,
1121                right.span.start_utf8,
1122                right.span.end_utf8,
1123                right.reference_id.as_str(),
1124                right.role,
1125                right.span.coverage,
1126            ))
1127    });
1128    Ok(facts)
1129}
1130
1131fn segment_range(
1132    texts: &[&str],
1133    start: &ReviewPoint,
1134    end: &ReviewPoint,
1135    mut visit: impl FnMut(usize, StructuralSpan) -> Result<(), ProjectionError>,
1136) -> Result<(), ProjectionError> {
1137    if start.paragraph_ordinal > end.paragraph_ordinal || end.paragraph_ordinal >= texts.len() {
1138        return Err(ProjectionError::InvalidDocumentXml);
1139    }
1140    if start.paragraph_ordinal == end.paragraph_ordinal
1141        && (start.utf8 > end.utf8 || start.utf16 > end.utf16)
1142    {
1143        return Err(ProjectionError::InvalidDocumentXml);
1144    }
1145    for (paragraph, text) in texts
1146        .iter()
1147        .enumerate()
1148        .take(end.paragraph_ordinal.saturating_add(1))
1149        .skip(start.paragraph_ordinal)
1150    {
1151        let text_utf8 =
1152            u32::try_from(text.len()).map_err(|_| ProjectionError::InvalidDocumentXml)?;
1153        let text_utf16 = u32::try_from(text.encode_utf16().count())
1154            .map_err(|_| ProjectionError::InvalidDocumentXml)?;
1155        let (start_utf8, start_utf16) = if paragraph == start.paragraph_ordinal {
1156            (start.utf8, start.utf16)
1157        } else {
1158            (0, 0)
1159        };
1160        let (end_utf8, end_utf16) = if paragraph == end.paragraph_ordinal {
1161            (end.utf8, end.utf16)
1162        } else {
1163            (text_utf8, text_utf16)
1164        };
1165        if start_utf8 > text_utf8
1166            || end_utf8 > text_utf8
1167            || start_utf16 > text_utf16
1168            || end_utf16 > text_utf16
1169        {
1170            return Err(ProjectionError::InvalidDocumentXml);
1171        }
1172        let continues_before = paragraph > start.paragraph_ordinal;
1173        let continues_after = paragraph < end.paragraph_ordinal;
1174        let coverage = match (continues_before, continues_after) {
1175            (false, false) => SpanCoverage::Complete,
1176            (true, false) => SpanCoverage::ContinuesBefore,
1177            (false, true) => SpanCoverage::ContinuesAfter,
1178            (true, true) => SpanCoverage::ContinuesBeforeAndAfter,
1179        };
1180        visit(
1181            paragraph,
1182            StructuralSpan {
1183                start_utf8,
1184                end_utf8,
1185                start_utf16,
1186                end_utf16,
1187                coverage,
1188            },
1189        )?;
1190    }
1191    Ok(())
1192}
1193
1194#[cfg(test)]
1195mod tests {
1196    use super::{
1197        ParagraphProperties, StyleDefinition, StyleKind, StyleSheet, TableStyleFormatting,
1198        TextProperties, inherit_style_toggle,
1199    };
1200
1201    const WORD_STYLE_LIMIT: usize = 4_079;
1202
1203    fn style(based_on: Option<String>, kind: StyleKind) -> StyleDefinition {
1204        StyleDefinition {
1205            based_on,
1206            properties: ParagraphProperties::default(),
1207            text_properties: TextProperties {
1208                bold: Some(true),
1209                ..TextProperties::default()
1210            },
1211            kind,
1212            table_formatting: TableStyleFormatting::Base,
1213        }
1214    }
1215
1216    #[test]
1217    fn style_toggle_truth_table_preserves_false_and_toggles_true() {
1218        let cases = [
1219            (&[][..], None),
1220            (&[false][..], None),
1221            (&[true][..], Some(true)),
1222            (&[true, false][..], Some(true)),
1223            (&[true, true][..], Some(false)),
1224            (&[true, false, true][..], Some(false)),
1225            (&[true, true, true][..], Some(true)),
1226        ];
1227
1228        for (levels, expected) in cases {
1229            let actual = levels.iter().fold(None, |inherited, &level| {
1230                inherit_style_toggle(inherited, Some(level))
1231            });
1232            assert_eq!(actual, expected, "style levels {levels:?}");
1233        }
1234    }
1235
1236    #[test]
1237    fn style_resolution_stays_within_its_linear_work_budget() -> Result<(), &'static str> {
1238        let ids = (0..WORD_STYLE_LIMIT)
1239            .map(|index| format!("style-{index}"))
1240            .collect::<Vec<_>>();
1241
1242        let mut paragraph_chain = StyleSheet::default();
1243        let mut paragraph_parent = None;
1244        for id in &ids {
1245            paragraph_chain.styles.insert(
1246                id.clone(),
1247                style(paragraph_parent.clone(), StyleKind::Paragraph),
1248            );
1249            paragraph_parent = Some(id.clone());
1250        }
1251        let (resolved_paragraphs, paragraph_steps) =
1252            paragraph_chain.resolve_block_styles(StyleKind::Paragraph);
1253        assert_eq!(resolved_paragraphs.len(), WORD_STYLE_LIMIT);
1254        assert!(paragraph_steps <= WORD_STYLE_LIMIT.saturating_mul(2).saturating_add(1));
1255
1256        let mut character_chain = StyleSheet::default();
1257        let mut character_parent = None;
1258        for id in &ids {
1259            character_chain.styles.insert(
1260                id.clone(),
1261                style(character_parent.clone(), StyleKind::Character),
1262            );
1263            character_parent = Some(id.clone());
1264        }
1265        let (resolved_characters, character_steps) =
1266            character_chain.resolve_character_text_styles();
1267        assert_eq!(resolved_characters.len(), WORD_STYLE_LIMIT);
1268        assert!(character_steps <= WORD_STYLE_LIMIT.saturating_mul(2).saturating_add(1));
1269
1270        let mut cycle = StyleSheet::default();
1271        let first = ids.first().ok_or("the fixture must be non-empty")?;
1272        for (index, id) in ids.iter().enumerate() {
1273            let successor = ids.get(index.saturating_add(1)).unwrap_or(first);
1274            cycle.styles.insert(
1275                id.clone(),
1276                style(Some(successor.clone()), StyleKind::Paragraph),
1277            );
1278        }
1279        let (cycle_resolved, cycle_steps) = cycle.resolve_block_styles(StyleKind::Paragraph);
1280        assert!(cycle_resolved.is_empty());
1281        assert!(cycle_steps <= WORD_STYLE_LIMIT.saturating_add(1));
1282        Ok(())
1283    }
1284}
1285
1286#[cfg(test)]
1287mod collision_tests {
1288    use super::*;
1289    use proptest::prelude::*;
1290
1291    proptest! {
1292        #[test]
1293        fn later_matching_ranges_do_not_change_reference_navigation(id in 0_u32..100_000, repeats in 1_usize..24) {
1294            let point = |utf8| ReviewPoint { paragraph_ordinal: 0, utf8, utf16: utf8 };
1295            let first = RawBookmarkRange { id, name: "target".to_owned(), start: point(0), end: point(5) };
1296            let later = RawBookmarkRange { id, name: "target".to_owned(), start: point(6), end: point(11) };
1297            let reference = RawInternalReference { reference_id: "target".to_owned(), source: point(11) };
1298            let mut ranges = vec![later; repeats];
1299            // Completion order can differ from source start order for nested ranges.
1300            ranges.push(first.clone());
1301            let texts = ["First Later"];
1302            let clean = materialize_references(std::slice::from_ref(&reference), &[first], &texts, &mut StructuralFactBudget::new(128)).map_err(|error| TestCaseError::fail(format!("unexpected fixture error: {error:?}")))?;
1303            let collision = materialize_references(&[reference], &ranges, &texts, &mut StructuralFactBudget::new(128)).map_err(|error| TestCaseError::fail(format!("unexpected fixture error: {error:?}")))?;
1304            prop_assert_eq!(collision, clean);
1305        }
1306    }
1307}