use std::fmt;
use super::Place;
use crate::text_blocks::{Address, AddressStep, TextBlock, TextBlockKind};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Outcome {
Replace {
at: Address,
find: String,
with: String,
},
Insert {
at: Address,
place: Place,
text: String,
style: Option<String>,
},
Delete { at: Address },
Style { at: Address, style: Option<String> },
SetText {
at: Address,
text: String,
style: Option<String>,
},
InsertRow {
at: Address,
place: Place,
cells: Vec<(Option<String>, String)>,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Node {
Paragraph {
from: Option<Address>,
style: Option<String>,
text: Option<String>,
gone: bool,
before: Vec<Node>,
after: Vec<Node>,
},
Table {
from: Option<Address>,
rows: Vec<Row>,
gone: bool,
before: Vec<Node>,
after: Vec<Node>,
},
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Row {
cells: Vec<Vec<Node>>,
gone: bool,
before: Vec<Row>,
after: Vec<Row>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExpectedBlocks {
blocks: Vec<(Address, Expected)>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Expected {
Paragraph {
style: Option<String>,
text: Option<String>,
},
Table {
rows: usize,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Mismatch {
pub at: String,
pub expected: String,
pub found: String,
}
impl fmt::Display for Mismatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"at {} the new file has {}, and the edits expect {}",
self.at, self.found, self.expected
)
}
}
impl std::error::Error for Mismatch {}
impl ExpectedBlocks {
pub(super) fn new(blocks: &[TextBlock], outcomes: &[Outcome]) -> Self {
let mut body = tree(blocks);
for outcome in outcomes {
apply(&mut body, outcome);
}
let mut flat = Vec::new();
flatten(&body, None, &mut flat);
Self { blocks: flat }
}
pub fn compare(&self, after: &[TextBlock]) -> Result<(), Mismatch> {
for index in 0..self.blocks.len().max(after.len()) {
let expected = self.blocks.get(index);
let found = after.get(index);
let same = match (expected, found) {
(Some((address, expected)), Some(block)) => {
*address == block.address && expected.matches(&block.kind)
}
_ => false,
};
if !same {
return Err(Mismatch {
at: expected
.map(|(address, _)| address.to_string())
.or_else(|| found.map(|block| block.address.to_string()))
.unwrap_or_default(),
expected: expected
.map_or_else(|| "no block".to_owned(), |(a, e)| e.describe(a)),
found: found.map_or_else(|| "no block".to_owned(), describe_block),
});
}
}
Ok(())
}
}
impl Expected {
fn matches(&self, kind: &TextBlockKind) -> bool {
match (self, kind) {
(
Self::Paragraph { style, text },
TextBlockKind::Paragraph {
style: found_style,
text: found_text,
},
) => style == found_style && text.as_ref().is_none_or(|text| text == found_text),
(Self::Table { rows }, TextBlockKind::Table { rows: found }) => rows == found,
_ => false,
}
}
fn describe(&self, address: &Address) -> String {
match self {
Self::Paragraph { style, text } => format!(
"the paragraph {address} with the style {} and the text {}",
style.as_deref().unwrap_or("of the default"),
text.as_ref().map_or_else(
|| "that the edits do not know".to_owned(),
|text| format!("{text:?}")
)
),
Self::Table { rows } => format!("the table {address} of {rows} rows"),
}
}
}
fn describe_block(block: &TextBlock) -> String {
match &block.kind {
TextBlockKind::Paragraph { style, text } => format!(
"the paragraph {} with the style {} and the text {text:?}",
block.address,
style.as_deref().unwrap_or("of the default")
),
TextBlockKind::Table { rows } => format!("the table {} of {rows} rows", block.address),
}
}
fn tree(blocks: &[TextBlock]) -> Vec<Node> {
let mut body = Vec::new();
for block in blocks {
let node = match &block.kind {
TextBlockKind::Paragraph { style, text } => Node::Paragraph {
from: Some(block.address.clone()),
style: style.clone(),
text: Some(text.clone()),
gone: false,
before: Vec::new(),
after: Vec::new(),
},
TextBlockKind::Table { rows } => Node::Table {
from: Some(block.address.clone()),
rows: vec![Row::default(); *rows],
gone: false,
before: Vec::new(),
after: Vec::new(),
},
};
if let Some(container) = container(&mut body, block.address.container()) {
container.push(node);
}
}
body
}
fn container<'t>(body: &'t mut Vec<Node>, steps: &[AddressStep]) -> Option<&'t mut Vec<Node>> {
let [
AddressStep::Table(table),
AddressStep::Row(row),
AddressStep::Cell(cell),
rest @ ..,
] = steps
else {
return steps.is_empty().then_some(body);
};
let Node::Table { rows, .. } = body
.iter_mut()
.filter(|node| matches!(node, Node::Table { .. }))
.nth(table.get() - 1)?
else {
return None;
};
let row = rows.get_mut(row.get() - 1)?;
if row.cells.len() < cell.get() {
row.cells.resize_with(cell.get(), Vec::new);
}
container(row.cells.get_mut(cell.get() - 1)?, rest)
}
fn node<'t>(nodes: &'t mut [Node], at: &Address) -> Option<&'t mut Node> {
for node in nodes {
if node.from() == Some(at) {
return Some(node);
}
if let Node::Table { rows, .. } = node {
for cell in rows.iter_mut().flat_map(|row| row.cells.iter_mut()) {
if let Some(found) = self::node(cell, at) {
return Some(found);
}
}
}
}
None
}
fn cell<'t>(body: &'t mut [Node], row: &Address, number: usize) -> Option<&'t mut Vec<Node>> {
let row = self::row(body, row)?;
if row.cells.len() < number {
row.cells.resize_with(number, Vec::new);
}
row.cells.get_mut(number.checked_sub(1)?)
}
fn row<'t>(body: &'t mut [Node], at: &Address) -> Option<&'t mut Row> {
let table = at.table_of_row()?;
let Some(AddressStep::Row(number)) = at.steps().last() else {
return None;
};
match node(body, &table)? {
Node::Table { rows, .. } => rows.get_mut(number.get() - 1),
Node::Paragraph { .. } => None,
}
}
impl Node {
const fn new_paragraph(style: Option<String>, text: String) -> Self {
Self::Paragraph {
from: None,
style,
text: Some(text),
gone: false,
before: Vec::new(),
after: Vec::new(),
}
}
fn from(&self) -> Option<&Address> {
match self {
Self::Paragraph { from, .. } | Self::Table { from, .. } => from.as_ref(),
}
}
}
fn apply(body: &mut [Node], outcome: &Outcome) {
match outcome {
Outcome::Replace { at, find, with } => {
if let Some(Node::Paragraph { text, .. }) = node(body, at) {
*text = text
.take()
.filter(|text| text.matches(find.as_str()).count() == 1)
.map(|text| text.replacen(find.as_str(), with, 1));
}
}
Outcome::Insert {
at,
place,
text,
style,
} => {
let new = Node::new_paragraph(style.clone(), text.clone());
if let Some(Node::Paragraph { before, after, .. } | Node::Table { before, after, .. }) =
node(body, at)
{
match place {
Place::Before => before.push(new),
Place::After => after.push(new),
}
}
}
Outcome::Delete { at } => delete(body, at),
Outcome::Style { at, style } => {
if let (Some(Node::Paragraph { style: old, .. }), Some(style)) = (node(body, at), style)
{
*old = Some(style.clone());
}
}
Outcome::SetText { at, text, style } => set_text(body, at, text, style.as_ref()),
Outcome::InsertRow { at, place, cells } => {
let new = Row {
cells: cells
.iter()
.map(|(style, text)| vec![Node::new_paragraph(style.clone(), text.clone())])
.collect(),
..Row::default()
};
if let Some(row) = row(body, at) {
match place {
Place::Before => row.before.push(new),
Place::After => row.after.push(new),
}
}
}
}
}
fn set_text(body: &mut [Node], at: &Address, new: &str, style: Option<&String>) {
if let Some((row, number)) = at.row_of_cell() {
if let Some(cell) = cell(body, &row, number.get()) {
*cell = vec![Node::new_paragraph(style.cloned(), new.to_owned())];
}
return;
}
if let Some(Node::Paragraph { text, .. }) = node(body, at) {
*text = Some(new.to_owned());
}
}
fn delete(body: &mut [Node], at: &Address) {
if at.table_of_row().is_some() {
if let Some(row) = row(body, at) {
row.gone = true;
}
return;
}
if let Some(Node::Paragraph { gone, .. } | Node::Table { gone, .. }) = node(body, at) {
*gone = true;
}
}
fn flatten(nodes: &[Node], within: Option<&Address>, out: &mut Vec<(Address, Expected)>) {
let (mut paragraphs, mut tables) = (0, 0);
let mut emit = |node: &Node, out: &mut Vec<(Address, Expected)>| match node {
Node::Paragraph { style, text, .. } => {
paragraphs += 1;
let step = AddressStep::Paragraph(number(paragraphs));
out.push((
Address::within(within, step),
Expected::Paragraph {
style: style.clone(),
text: text.clone(),
},
));
}
Node::Table { rows, .. } => {
tables += 1;
let table = Address::within(within, AddressStep::Table(number(tables)));
let kept: Vec<&Row> = rows
.iter()
.flat_map(|row| {
row.before
.iter()
.chain((!row.gone).then_some(row))
.chain(row.after.iter())
})
.collect();
out.push((table.clone(), Expected::Table { rows: kept.len() }));
for (row_index, row) in kept.iter().enumerate() {
let row_address = table.then(AddressStep::Row(number(row_index + 1)));
for (cell_index, cell) in row.cells.iter().enumerate() {
let cell_address = row_address.then(AddressStep::Cell(number(cell_index + 1)));
flatten(cell, Some(&cell_address), out);
}
}
}
};
for node in nodes {
let (gone, before, after) = match node {
Node::Paragraph {
gone,
before,
after,
..
}
| Node::Table {
gone,
before,
after,
..
} => (*gone, before, after),
};
for new in before {
emit(new, out);
}
if !gone {
emit(node, out);
}
for new in after {
emit(new, out);
}
}
}
fn number(count: usize) -> std::num::NonZeroUsize {
std::num::NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
}