1use std::fmt;
6
7use super::Place;
8use crate::text_blocks::{Address, AddressStep, TextBlock, TextBlockKind};
9
10#[derive(Clone, Debug, PartialEq, Eq)]
12pub(super) enum Outcome {
13 Replace {
15 at: Address,
16 find: String,
17 with: String,
18 },
19 Insert {
21 at: Address,
22 place: Place,
23 text: String,
24 style: Option<String>,
25 },
26 Delete { at: Address },
28 Style { at: Address, style: Option<String> },
30 SetText {
33 at: Address,
34 text: String,
35 style: Option<String>,
36 },
37 InsertRow {
39 at: Address,
40 place: Place,
41 cells: Vec<(Option<String>, String)>,
42 },
43}
44
45#[derive(Clone, Debug, PartialEq, Eq)]
48enum Node {
49 Paragraph {
50 from: Option<Address>,
51 style: Option<String>,
52 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#[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#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct ExpectedBlocks {
82 blocks: Vec<(Address, Expected)>,
83}
84
85#[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#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct Mismatch {
100 pub at: String,
102 pub expected: String,
104 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 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 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
193fn 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
205fn 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
234fn 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
260fn 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
277fn 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
286fn 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 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 fn from(&self) -> Option<&Address> {
313 match self {
314 Self::Paragraph { from, .. } | Self::Table { from, .. } => from.as_ref(),
315 }
316 }
317}
318
319fn 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
372fn 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
386fn 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
399fn 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
464fn number(count: usize) -> std::num::NonZeroUsize {
466 std::num::NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
467}