Skip to main content

f_office_docx/named_edits/
expected.rs

1//! The check after the named edits: the text blocks that the new file must have, made from the
2//! text blocks of the file before and what each edit does, and their comparison with the text
3//! blocks of the new file.
4
5use std::fmt;
6
7use super::Place;
8use crate::text_blocks::{Address, AddressStep, TextBlock, TextBlockKind};
9
10/// What one named edit does to the text blocks.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub(super) enum Outcome {
13    /// The paragraph's text with `find` replaced by `with`.
14    Replace {
15        at: Address,
16        find: String,
17        with: String,
18    },
19    /// A new paragraph with `text` and `style`.
20    Insert {
21        at: Address,
22        place: Place,
23        text: String,
24        style: Option<String>,
25    },
26    /// The block or the row goes.
27    Delete { at: Address },
28    /// The block takes the style; none for a table, whose text block has no style.
29    Style { at: Address, style: Option<String> },
30    /// All the text of a paragraph becomes `text`; all the blocks of a cell become one
31    /// paragraph with `style` and `text`.
32    SetText {
33        at: Address,
34        text: String,
35        style: Option<String>,
36    },
37    /// A new row with one paragraph in each cell, with its style and its text.
38    InsertRow {
39        at: Address,
40        place: Place,
41        cells: Vec<(Option<String>, String)>,
42    },
43}
44
45/// A block of the expected tree: what the new file must have where the block was, or a new
46/// block.
47#[derive(Clone, Debug, PartialEq, Eq)]
48enum Node {
49    Paragraph {
50        from: Option<Address>,
51        style: Option<String>,
52        /// The text, or none when the check cannot know it.
53        text: Option<String>,
54        gone: bool,
55        before: Vec<Node>,
56        after: Vec<Node>,
57    },
58    Table {
59        from: Option<Address>,
60        rows: Vec<Row>,
61        gone: bool,
62        before: Vec<Node>,
63        after: Vec<Node>,
64    },
65}
66
67/// A row of the expected tree: its cells, each with its blocks, and the new rows before and
68/// after it.
69#[derive(Clone, Debug, Default, PartialEq, Eq)]
70struct Row {
71    cells: Vec<Vec<Node>>,
72    gone: bool,
73    before: Vec<Row>,
74    after: Vec<Row>,
75}
76
77/// The text blocks that the new file must have after a list's named edits, in order: each with
78/// its address, its kind, and for a paragraph its style and its text, which is none where the
79/// check cannot know it.
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct ExpectedBlocks {
82    blocks: Vec<(Address, Expected)>,
83}
84
85/// One expected block.
86#[derive(Clone, Debug, PartialEq, Eq)]
87enum Expected {
88    Paragraph {
89        style: Option<String>,
90        text: Option<String>,
91    },
92    Table {
93        rows: usize,
94    },
95}
96
97/// How the new file's text blocks differ from the expected ones: the first difference.
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct Mismatch {
100    /// The address where they differ.
101    pub at: String,
102    /// What the edits expect there.
103    pub expected: String,
104    /// What the new file has there.
105    pub found: String,
106}
107
108impl fmt::Display for Mismatch {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(
111            f,
112            "at {} the new file has {}, and the edits expect {}",
113            self.at, self.found, self.expected
114        )
115    }
116}
117
118impl std::error::Error for Mismatch {}
119
120impl ExpectedBlocks {
121    /// The text blocks that `outcomes` make of `blocks`.
122    pub(super) fn new(blocks: &[TextBlock], outcomes: &[Outcome]) -> Self {
123        let mut body = tree(blocks);
124        for outcome in outcomes {
125            apply(&mut body, outcome);
126        }
127        let mut flat = Vec::new();
128        flatten(&body, None, &mut flat);
129        Self { blocks: flat }
130    }
131
132    /// Compares the text blocks of the new file with the expected ones.
133    ///
134    /// # Errors
135    ///
136    /// Returns the first difference.
137    pub fn compare(&self, after: &[TextBlock]) -> Result<(), Mismatch> {
138        for index in 0..self.blocks.len().max(after.len()) {
139            let expected = self.blocks.get(index);
140            let found = after.get(index);
141            let same = match (expected, found) {
142                (Some((address, expected)), Some(block)) => {
143                    *address == block.address && expected.matches(&block.kind)
144                }
145                _ => false,
146            };
147            if !same {
148                return Err(Mismatch {
149                    at: expected
150                        .map(|(address, _)| address.to_string())
151                        .or_else(|| found.map(|block| block.address.to_string()))
152                        .unwrap_or_default(),
153                    expected: expected
154                        .map_or_else(|| "no block".to_owned(), |(a, e)| e.describe(a)),
155                    found: found.map_or_else(|| "no block".to_owned(), describe_block),
156                });
157            }
158        }
159        Ok(())
160    }
161}
162
163impl Expected {
164    fn matches(&self, kind: &TextBlockKind) -> bool {
165        match (self, kind) {
166            (
167                Self::Paragraph { style, text },
168                TextBlockKind::Paragraph {
169                    style: found_style,
170                    text: found_text,
171                },
172            ) => style == found_style && text.as_ref().is_none_or(|text| text == found_text),
173            (Self::Table { rows }, TextBlockKind::Table { rows: found }) => rows == found,
174            _ => false,
175        }
176    }
177
178    fn describe(&self, address: &Address) -> String {
179        match self {
180            Self::Paragraph { style, text } => format!(
181                "the paragraph {address} with the style {} and the text {}",
182                style.as_deref().unwrap_or("of the default"),
183                text.as_ref().map_or_else(
184                    || "that the edits do not know".to_owned(),
185                    |text| format!("{text:?}")
186                )
187            ),
188            Self::Table { rows } => format!("the table {address} of {rows} rows"),
189        }
190    }
191}
192
193/// A text block of the new file, for a message.
194fn describe_block(block: &TextBlock) -> String {
195    match &block.kind {
196        TextBlockKind::Paragraph { style, text } => format!(
197            "the paragraph {} with the style {} and the text {text:?}",
198            block.address,
199            style.as_deref().unwrap_or("of the default")
200        ),
201        TextBlockKind::Table { rows } => format!("the table {} of {rows} rows", block.address),
202    }
203}
204
205/// The tree of the text blocks `blocks`, which come in the order of the document, a table
206/// before the blocks of its cells.
207fn tree(blocks: &[TextBlock]) -> Vec<Node> {
208    let mut body = Vec::new();
209    for block in blocks {
210        let node = match &block.kind {
211            TextBlockKind::Paragraph { style, text } => Node::Paragraph {
212                from: Some(block.address.clone()),
213                style: style.clone(),
214                text: Some(text.clone()),
215                gone: false,
216                before: Vec::new(),
217                after: Vec::new(),
218            },
219            TextBlockKind::Table { rows } => Node::Table {
220                from: Some(block.address.clone()),
221                rows: vec![Row::default(); *rows],
222                gone: false,
223                before: Vec::new(),
224                after: Vec::new(),
225            },
226        };
227        if let Some(container) = container(&mut body, block.address.container()) {
228            container.push(node);
229        }
230    }
231    body
232}
233
234/// The blocks of the cell or the body that `steps` name, in the tree `body`, as the blocks of
235/// the file before number them.
236fn container<'t>(body: &'t mut Vec<Node>, steps: &[AddressStep]) -> Option<&'t mut Vec<Node>> {
237    let [
238        AddressStep::Table(table),
239        AddressStep::Row(row),
240        AddressStep::Cell(cell),
241        rest @ ..,
242    ] = steps
243    else {
244        return steps.is_empty().then_some(body);
245    };
246    let Node::Table { rows, .. } = body
247        .iter_mut()
248        .filter(|node| matches!(node, Node::Table { .. }))
249        .nth(table.get() - 1)?
250    else {
251        return None;
252    };
253    let row = rows.get_mut(row.get() - 1)?;
254    if row.cells.len() < cell.get() {
255        row.cells.resize_with(cell.get(), Vec::new);
256    }
257    container(row.cells.get_mut(cell.get() - 1)?, rest)
258}
259
260/// The block of the file before at `at` in the tree `nodes`.
261fn node<'t>(nodes: &'t mut [Node], at: &Address) -> Option<&'t mut Node> {
262    for node in nodes {
263        if node.from() == Some(at) {
264            return Some(node);
265        }
266        if let Node::Table { rows, .. } = node {
267            for cell in rows.iter_mut().flat_map(|row| row.cells.iter_mut()) {
268                if let Some(found) = self::node(cell, at) {
269                    return Some(found);
270                }
271            }
272        }
273    }
274    None
275}
276
277/// The cell `number` of the row `row` of the file before, in the tree `body`.
278fn cell<'t>(body: &'t mut [Node], row: &Address, number: usize) -> Option<&'t mut Vec<Node>> {
279    let row = self::row(body, row)?;
280    if row.cells.len() < number {
281        row.cells.resize_with(number, Vec::new);
282    }
283    row.cells.get_mut(number.checked_sub(1)?)
284}
285
286/// The row `at` of the file before, in the tree `body`.
287fn row<'t>(body: &'t mut [Node], at: &Address) -> Option<&'t mut Row> {
288    let table = at.table_of_row()?;
289    let Some(AddressStep::Row(number)) = at.steps().last() else {
290        return None;
291    };
292    match node(body, &table)? {
293        Node::Table { rows, .. } => rows.get_mut(number.get() - 1),
294        Node::Paragraph { .. } => None,
295    }
296}
297
298impl Node {
299    /// A new paragraph with `style` and `text`.
300    const fn new_paragraph(style: Option<String>, text: String) -> Self {
301        Self::Paragraph {
302            from: None,
303            style,
304            text: Some(text),
305            gone: false,
306            before: Vec::new(),
307            after: Vec::new(),
308        }
309    }
310
311    /// The address of the block of the file before, or none for a new block.
312    fn from(&self) -> Option<&Address> {
313        match self {
314            Self::Paragraph { from, .. } | Self::Table { from, .. } => from.as_ref(),
315        }
316    }
317}
318
319/// Makes `outcome` in the tree `body`.
320fn apply(body: &mut [Node], outcome: &Outcome) {
321    match outcome {
322        Outcome::Replace { at, find, with } => {
323            if let Some(Node::Paragraph { text, .. }) = node(body, at) {
324                *text = text
325                    .take()
326                    .filter(|text| text.matches(find.as_str()).count() == 1)
327                    .map(|text| text.replacen(find.as_str(), with, 1));
328            }
329        }
330        Outcome::Insert {
331            at,
332            place,
333            text,
334            style,
335        } => {
336            let new = Node::new_paragraph(style.clone(), text.clone());
337            if let Some(Node::Paragraph { before, after, .. } | Node::Table { before, after, .. }) =
338                node(body, at)
339            {
340                match place {
341                    Place::Before => before.push(new),
342                    Place::After => after.push(new),
343                }
344            }
345        }
346        Outcome::Delete { at } => delete(body, at),
347        Outcome::Style { at, style } => {
348            if let (Some(Node::Paragraph { style: old, .. }), Some(style)) = (node(body, at), style)
349            {
350                *old = Some(style.clone());
351            }
352        }
353        Outcome::SetText { at, text, style } => set_text(body, at, text, style.as_ref()),
354        Outcome::InsertRow { at, place, cells } => {
355            let new = Row {
356                cells: cells
357                    .iter()
358                    .map(|(style, text)| vec![Node::new_paragraph(style.clone(), text.clone())])
359                    .collect(),
360                ..Row::default()
361            };
362            if let Some(row) = row(body, at) {
363                match place {
364                    Place::Before => row.before.push(new),
365                    Place::After => row.after.push(new),
366                }
367            }
368        }
369    }
370}
371
372/// Gives the paragraph `at` the text `new`, or the cell `at` one paragraph with `style` and
373/// `new` in place of its blocks.
374fn set_text(body: &mut [Node], at: &Address, new: &str, style: Option<&String>) {
375    if let Some((row, number)) = at.row_of_cell() {
376        if let Some(cell) = cell(body, &row, number.get()) {
377            *cell = vec![Node::new_paragraph(style.cloned(), new.to_owned())];
378        }
379        return;
380    }
381    if let Some(Node::Paragraph { text, .. }) = node(body, at) {
382        *text = Some(new.to_owned());
383    }
384}
385
386/// Marks the block or the row `at` as gone.
387fn delete(body: &mut [Node], at: &Address) {
388    if at.table_of_row().is_some() {
389        if let Some(row) = row(body, at) {
390            row.gone = true;
391        }
392        return;
393    }
394    if let Some(Node::Paragraph { gone, .. } | Node::Table { gone, .. }) = node(body, at) {
395        *gone = true;
396    }
397}
398
399/// The expected blocks of `nodes`, the blocks of the body when `within` is none, or else of the
400/// cell at that address, numbered as the new file numbers them.
401fn flatten(nodes: &[Node], within: Option<&Address>, out: &mut Vec<(Address, Expected)>) {
402    let (mut paragraphs, mut tables) = (0, 0);
403    let mut emit = |node: &Node, out: &mut Vec<(Address, Expected)>| match node {
404        Node::Paragraph { style, text, .. } => {
405            paragraphs += 1;
406            let step = AddressStep::Paragraph(number(paragraphs));
407            out.push((
408                Address::within(within, step),
409                Expected::Paragraph {
410                    style: style.clone(),
411                    text: text.clone(),
412                },
413            ));
414        }
415        Node::Table { rows, .. } => {
416            tables += 1;
417            let table = Address::within(within, AddressStep::Table(number(tables)));
418            let kept: Vec<&Row> = rows
419                .iter()
420                .flat_map(|row| {
421                    row.before
422                        .iter()
423                        .chain((!row.gone).then_some(row))
424                        .chain(row.after.iter())
425                })
426                .collect();
427            out.push((table.clone(), Expected::Table { rows: kept.len() }));
428            for (row_index, row) in kept.iter().enumerate() {
429                let row_address = table.then(AddressStep::Row(number(row_index + 1)));
430                for (cell_index, cell) in row.cells.iter().enumerate() {
431                    let cell_address = row_address.then(AddressStep::Cell(number(cell_index + 1)));
432                    flatten(cell, Some(&cell_address), out);
433                }
434            }
435        }
436    };
437    for node in nodes {
438        let (gone, before, after) = match node {
439            Node::Paragraph {
440                gone,
441                before,
442                after,
443                ..
444            }
445            | Node::Table {
446                gone,
447                before,
448                after,
449                ..
450            } => (*gone, before, after),
451        };
452        for new in before {
453            emit(new, out);
454        }
455        if !gone {
456            emit(node, out);
457        }
458        for new in after {
459            emit(new, out);
460        }
461    }
462}
463
464/// The number, from 1, of the block, row or cell that `count` ends.
465fn number(count: usize) -> std::num::NonZeroUsize {
466    std::num::NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
467}