From 4aa36a6d652df258fc9ff315005944b7d41e0060 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Thu, 19 Nov 2026 09:29:21 -0800 Subject: [PATCH] Separate hierarchy traversal and text report modules Build structured hierarchy rows and folded paths before rendering ASCII or Mermaid. Move compact and detailed diff writers alongside their text presentation helpers. --- src/review.rs | 807 +--------------------------------------- src/review/changes.rs | 2 +- src/review/hierarchy.rs | 495 ++++++++++++++++++++++++ src/review/report.rs | 3 +- src/review/text.rs | 451 +++++++++++++++++++++- 5 files changed, 951 insertions(+), 807 deletions(-) create mode 100644 src/review/hierarchy.rs diff --git a/src/review.rs b/src/review.rs index a9f23ae..baf99c4 100644 --- a/src/review.rs +++ b/src/review.rs @@ -13,6 +13,7 @@ use std::{ }; pub mod changes; +mod hierarchy; pub mod names; mod pair; pub mod report; @@ -23,8 +24,7 @@ use changes::Replacement; use pair::CellReuse; pub use pair::RevisionPair; use selection::{DisplayFilter, Scope}; -use text::CellText; -pub use text::{TextReport, TextStyle}; +pub use text::{TextReport, TextReportOptions, TextStyle}; /// Input revision associated with a diagnostic. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -909,7 +909,7 @@ impl<'a> Document<'a> { pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String { let revision = Revision::from_document(self); - render_hierarchy(&revision, &revision, None, mermaid, max_depth) + hierarchy::render_hierarchy(&revision, &revision, None, mermaid, max_depth) } pub fn canonical_dump(&self) -> String { @@ -1279,15 +1279,6 @@ pub struct Comparison { pub diagnostics: Vec, } -/// Additional presentation options for a text comparison. -#[derive(Clone, Copy, Debug, Default)] -pub struct TextReportOptions { - /// Print individual object evidence, including both sides of replacements. - pub details: bool, - /// Append the ASCII hierarchy at this depth when provided. - pub ascii_depth: Option, -} - /// A comparison for text and hierarchy reports. #[derive(Debug)] pub struct TextComparison { @@ -1305,55 +1296,6 @@ impl TextComparison { } } - pub fn render_text( - &self, - max_objects: usize, - show: &DisplayFilter, - show_library_presence: bool, - ) -> String { - self.comparison - .render_text(max_objects, show, show_library_presence) - } - - pub fn render_text_with_options( - &self, - max_objects: usize, - show: &DisplayFilter, - show_library_presence: bool, - options: TextReportOptions, - ) -> String { - self.comparison - .render_text_with_options(max_objects, show, show_library_presence, options) - } - - pub fn write_text_report( - &self, - out: &mut TextReport, - max_objects: usize, - show: &DisplayFilter, - show_library_presence: bool, - options: TextReportOptions, - ) { - self.comparison - .write_text_report(out, max_objects, show, show_library_presence, options); - } - - /// Render the cell changes and their ASCII hierarchy together. - pub fn render_text_with_ascii_hierarchy( - &self, - max_objects: usize, - show: &DisplayFilter, - show_library_presence: bool, - max_depth: usize, - ) -> String { - self.comparison.render_text_with_ascii_hierarchy( - max_objects, - show, - show_library_presence, - max_depth, - ) - } - pub fn outcome(&self) -> Outcome { self.comparison.outcome() } @@ -1539,748 +1481,7 @@ impl Comparison { /// Render the affected hierarchy. ASCII output shows relationships between cells. pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String { - render_hierarchy(&self.old, &self.new, Some(&self.cells), mermaid, max_depth) - } - - /// Limit presentation only: the complete comparison has already been made. - pub fn text(&self, max_objects: usize) -> String { - self.text_filtered(max_objects, &DisplayFilter::default()) - } - - pub fn text_filtered(&self, max_objects: usize, show: &DisplayFilter) -> String { - self.render_text(max_objects, show, true) - } - - /// Render a text report. Set `show_library_presence` to false when a file - /// header already announces the library addition or deletion. - pub fn render_text( - &self, - max_objects: usize, - show: &DisplayFilter, - show_library_presence: bool, - ) -> String { - self.render_text_with_options( - max_objects, - show, - show_library_presence, - TextReportOptions::default(), - ) - } - - /// Render the cell changes and omit simple hierarchy edges already shown there. - pub fn render_text_with_ascii_hierarchy( - &self, - max_objects: usize, - show: &DisplayFilter, - show_library_presence: bool, - max_depth: usize, - ) -> String { - self.render_text_with_options( - max_objects, - show, - show_library_presence, - TextReportOptions { - ascii_depth: Some(max_depth), - ..TextReportOptions::default() - }, - ) - } - - /// Render the selected changes with optional object details and ASCII hierarchy. - pub fn render_text_with_options( - &self, - max_objects: usize, - show: &DisplayFilter, - show_library_presence: bool, - options: TextReportOptions, - ) -> String { - let mut out = TextReport::default(); - self.write_text_report(&mut out, max_objects, show, show_library_presence, options); - out.into_string() - } - - /// Append the selected changes and their presentation roles to a text report. - pub fn write_text_report( - &self, - out: &mut TextReport, - max_objects: usize, - show: &DisplayFilter, - show_library_presence: bool, - options: TextReportOptions, - ) { - let selection = selection::TextSelection::new(&self.cells, show, max_objects); - let outcome = self.outcome(); - let headline = out.len(); - let (result, style) = match outcome { - Outcome::Equal => ("Equal", TextStyle::Success), - Outcome::Different => ("Different", TextStyle::Warning), - Outcome::Incomplete { .. } => ("Incomplete", TextStyle::Warning), - Outcome::Failed => ("Failed", TextStyle::Error), - }; - out.push_str(result); - let has_omissions = selection.filtered_objects != 0 - || selection.limited_objects != 0 - || selection.filtered_cells != 0; - if !self.cells.is_empty() - && (self.cells.len() > 3 || !outcome.is_complete() || has_omissions) - { - let (mut modified, mut added, mut removed) = (0, 0, 0); - for cell in &self.cells { - match cell_marker(cell.old.is_some(), cell.new.is_some()) { - '-' => removed += 1, - '+' => added += 1, - _ => modified += 1, - } - } - let mut counts = [ - (modified, "modified"), - (added, "added"), - (removed, "removed"), - ] - .into_iter() - .filter(|(count, _)| *count != 0); - if let Some((count, action)) = counts.next() { - let noun = if count == 1 { "cell" } else { "cells" }; - write!(out, " · {count} {noun} {action}").unwrap(); - for (count, action) in counts { - write!(out, ", {count} {action}").unwrap(); - } - } - } - let library_changes = self.library_changes.iter().filter(|change| { - show_library_presence || !matches!(change, LibraryChange::Presence { .. }) - }); - for (count, label) in [ - (library_changes.clone().count(), "library change"), - (self.layer_names.len(), "layer name change"), - ] { - if count != 0 { - let plural = if count == 1 { "" } else { "s" }; - write!(out, " · {count} {label}{plural}").unwrap(); - } - } - out.mark(headline, style); - out.push('\n'); - self.old.scope.write_restrictions(out); - if show.cell.is_some() || show.layer.is_some() { - let start = out.len(); - out.push_str("Display filter"); - if let Some(cell) = &show.cell { - write!(out, " cell={cell:?}").unwrap(); - } - if let Some((layer, datatype)) = show.layer { - write!(out, " layer={layer}/{datatype}").unwrap(); - } - out.mark(start, TextStyle::Heading); - out.push('\n'); - } - if has_omissions { - let start = out.len(); - out.push_str("Omitted"); - for (count, label, reason) in [ - (selection.filtered_objects, "object change", "filtered out"), - (selection.limited_objects, "object change", "over the limit"), - ( - selection.filtered_cells, - "cell-level change", - "filtered out", - ), - ] { - if count != 0 { - let plural = if count == 1 { "" } else { "s" }; - write!(out, " · {count} {label}{plural} {reason}").unwrap(); - } - } - out.mark(start, TextStyle::Warning); - out.push('\n'); - } - for change in library_changes { - writeln!(out, "library {change}").unwrap(); - } - if self.library_changes.iter().any(|change| { - matches!( - change, - LibraryChange::Record { - tag: RTAG_UNITS, - .. - } - ) - }) { - out.push_str("Coordinates use each file's database units\n"); - } - for change in &self.layer_names { - let name = |value: Option<&str>| { - value.map_or_else(|| "absent".to_string(), |value| format!("{value:?}")) - }; - writeln!( - out, - "{}/{}: name {} -> {}", - change.layer.0, - change.layer.1, - name(change.old.as_deref()), - name(change.new.as_deref()) - ) - .unwrap(); - } - - let mut body = CellText::new(&self.layer_legend, &self.layer_names, out.is_styled()); - let mut covered_edges = BTreeSet::new(); - for selected in &selection.modified_cells { - self.write_cell_details( - &mut body, - selected, - options.details, - (options.ascii_depth.is_some() && outcome.is_complete()) - .then_some(&mut covered_edges), - ); - } - body.write_legend(out); - if !selection.modified_cells.is_empty() - || !selection.removed_cells.is_empty() - || !selection.added_cells.is_empty() - { - out.write_styled(TextStyle::Heading, format_args!("Cells:")); - out.push('\n'); - for name in selection.removed_cells { - out.write_styled(TextStyle::Removed, format_args!("- {}", cell_label(name))); - out.push('\n'); - } - for name in selection.added_cells { - out.write_styled(TextStyle::Added, format_args!("+ {}", cell_label(name))); - out.push('\n'); - } - body.write_body(out); - } - // General comparison errors precede revision-specific errors in text. - if !self.diagnostics.is_empty() { - out.write_styled(TextStyle::Heading, format_args!("Diagnostics")); - out.push('\n'); - for diagnostic in self - .diagnostics - .iter() - .filter(|d| d.side.is_none()) - .chain(self.diagnostics.iter().filter(|d| d.side.is_some())) - { - writeln!(out, " {diagnostic}").unwrap(); - } - } - if let Some(max_depth) = options.ascii_depth { - write_hierarchy( - out, - &self.old, - &self.new, - Some(&self.cells), - false, - max_depth, - Some(&covered_edges), - ); - } - } - - fn write_cell_details( - &self, - out: &mut CellText<'_>, - selected: &selection::TextCellSelection<'_>, - details: bool, - mut covered_edges: Option<&mut BTreeSet<(String, String)>>, - ) { - let cell = selected.cell; - let name = cell_label(&cell.name); - let note = if selected.attributes_changed { - " (attributes changed)" - } else { - "" - }; - out.style(Some(TextStyle::Changed)); - writeln!(out, "* {name}{note}").unwrap(); - let mut polygons = changes::PolygonChanges::default(); - let mut shown_refs = BTreeMap::<&str, changes::ShownReferences>::new(); - for &(a, b) in &selected.replacements { - if !details && a.layer == b.layer && is_polygon(a.kind) { - polygons.replacement(a, b); - continue; - } - out.push_str(" "); - out.style(Some(TextStyle::Changed)); - out.push_str("~ "); - if a.layer != b.layer { - changes::write_layer_transition(out, a, b); - out.push('\n'); - } else { - if let Some(layer) = a.layer { - out.write_layer(layer, None); - out.push_str(": "); - } - let description = changes::replacement_description(a, b, details); - let (heading, rest) = match description.split_once('\n') { - Some((heading, rest)) => (heading, Some(rest)), - None => (description.as_str(), None), - }; - out.push_str(heading); - if let Some(target) = &a.target { - let placements = out.reserve_placements(); - shown_refs - .entry(target) - .or_default() - .replacement(a, b, placements); - } - out.push('\n'); - if let Some(rest) = rest { - writeln!(out, "{rest}").unwrap(); - } - } - if details { - changes::write_replacement_objects(out, a, b); - } - } - let mut removed_refs = BTreeMap::new(); - let mut added_refs = BTreeMap::new(); - for (removed, objects, references) in [ - (true, &selected.removed, &mut removed_refs), - (false, &selected.added, &mut added_refs), - ] { - let sign = if removed { '-' } else { '+' }; - let mut unmatched: Vec<(&ObjectChange, usize)> = Vec::new(); - for &object in objects { - if !details && is_polygon(object.kind) { - polygons.unmatched(object, removed); - } else if !details && let Some(target) = object.target.as_deref() { - let (_, counts) = references - .entry(target) - .or_insert_with(|| (object, changes::ReferenceCounts::default())); - counts.add(object); - } else if let Some((last, count)) = unmatched.last_mut() - && last.kind == object.kind - && last.fields == object.fields - && last.properties == object.properties - { - *count += 1; - } else { - unmatched.push((object, 1)); - } - } - // The comparison orders these objects by kind, fields, and properties. - for (object, count) in unmatched { - out.push_str(" "); - out.style(Some(TextStyle::change(sign))); - write!(out, "{sign} ").unwrap(); - if count > 1 { - write!(out, "{count}× ").unwrap(); - } - changes::write_unmatched(out, object, details); - if let Some(target) = object.target.as_deref() { - let placements = out.reserve_placements(); - shown_refs - .entry(target) - .or_default() - .individual(object, removed, count, placements); - } - out.push('\n'); - } - } - let no_refs = changes::ReferenceCounts::default(); - for (target, (first, counts)) in removed_refs { - if let Some((_, added)) = added_refs.remove(target) { - let placements = counts.write_change(out, target, &added); - shown_refs - .entry(target) - .or_default() - .unmatched(&counts, &added, placements); - } else { - let placements = counts.write(out, '-', target, first); - shown_refs - .entry(target) - .or_default() - .unmatched(&counts, &no_refs, placements); - } - } - for (target, (first, counts)) in added_refs { - let placements = counts.write(out, '+', target, first); - shown_refs - .entry(target) - .or_default() - .unmatched(&no_refs, &counts, placements); - } - if !shown_refs.is_empty() { - for target in cell - .removed - .iter() - .chain(&cell.added) - .filter_map(|o| o.target.as_deref()) - { - if let Some(shown) = shown_refs.get_mut(target) { - shown.count_change(); - } - } - for (target, shown) in shown_refs { - if shown.complete() { - let edge = (cell.name.clone(), target.to_owned()); - let old = self.old.edges.get(&edge).copied().unwrap_or(0); - let new = self.new.edges.get(&edge).copied().unwrap_or(0); - shown.write_placements(out, old, new); - if let Some(covered) = covered_edges.as_deref_mut() { - covered.insert(edge); - } - } - } - } - polygons.write(out); - } -} - -/// Graph facts shared by text, Mermaid, and JSON renderers. -struct HierarchyAnalysis<'a> { - old_edges: &'a BTreeMap<(String, String), u64>, - new_edges: &'a BTreeMap<(String, String), u64>, - edges: BTreeSet<(String, String)>, - direct: BTreeSet, - affected: BTreeSet, - changed_refs: BTreeSet<(String, String)>, -} - -impl<'a> HierarchyAnalysis<'a> { - fn between(old: &'a Revision, new: &'a Revision, changes: Option<&[CellChange]>) -> Self { - let old_edges = &old.edges; - let new_edges = &new.edges; - let edges: BTreeSet<_> = old_edges.keys().chain(new_edges.keys()).cloned().collect(); - let direct: BTreeSet<_> = changes - .into_iter() - .flatten() - .map(|cell| cell.name.clone()) - .collect(); - let changed_refs: BTreeSet<_> = changes - .into_iter() - .flatten() - .flat_map(|c| { - c.removed - .iter() - .chain(&c.added) - .filter_map(|o| o.target.as_ref().map(|t| (c.name.clone(), t.clone()))) - }) - .collect(); - let mut parents = BTreeMap::<&str, Vec<&str>>::new(); - for (parent, child) in &edges { - parents.entry(child).or_default().push(parent); - } - let mut affected = direct.clone(); - let mut pending: Vec<_> = direct.iter().cloned().collect(); - while let Some(child) = pending.pop() { - for parent in parents.get(child.as_str()).into_iter().flatten() { - if affected.insert((*parent).to_string()) { - pending.push((*parent).to_string()); - } - } - } - Self { - old_edges, - new_edges, - edges, - direct, - affected, - changed_refs, - } - } -} - -/// The graph joins both revisions, retaining removed branches and old callers. -fn render_hierarchy( - old: &Revision, - new: &Revision, - changes: Option<&[CellChange]>, - mermaid: bool, - max_depth: usize, -) -> String { - let mut out = TextReport::default(); - write_hierarchy(&mut out, old, new, changes, mermaid, max_depth, None); - out.into_string() -} - -fn write_hierarchy( - out: &mut TextReport, - old: &Revision, - new: &Revision, - changes: Option<&[CellChange]>, - mermaid: bool, - max_depth: usize, - covered_edges: Option<&BTreeSet<(String, String)>>, -) { - if !mermaid && changes.is_some_and(<[CellChange]>::is_empty) { - return; - } - - let HierarchyAnalysis { - old_edges, - new_edges, - edges, - direct, - affected, - changed_refs, - } = HierarchyAnalysis::between(old, new, changes); - let mut visible: BTreeSet<_> = if changes.is_some() { - affected - .iter() - .cloned() - .chain(changed_refs.iter().map(|(_, t)| t.clone())) - .collect() - } else { - old.cells - .iter() - .chain(new.cells.iter()) - .cloned() - .chain(edges.iter().map(|(_, t)| t.clone())) - .collect() - }; - let mut children = BTreeMap::>::new(); - let mut targets = BTreeSet::new(); - let fold_paths = !mermaid && changes.is_some(); - let mut shared = BTreeSet::new(); - for (parent, target) in &edges { - if visible.contains(parent) && visible.contains(target) { - children - .entry(parent.clone()) - .or_default() - .push(target.clone()); - if !targets.insert(target.clone()) && fold_paths { - shared.insert(target.clone()); - } - } - } - if let Some(covered) = covered_edges { - if !covered.is_empty() { - // Keep changed or shared descendants, branches, and target status notes. - let redundant: BTreeSet<_> = covered - .iter() - .map(|(_, target)| target) - .filter(|&target| { - targets.contains(target) - && !shared.contains(target) - && !children.contains_key(target) - && !affected.contains(target) - && old.cells.contains(target) - && new.cells.contains(target) - }) - .collect(); - children.retain(|_, children| { - children.retain(|target| !redundant.contains(target)); - !children.is_empty() - }); - targets.retain(|target| !redundant.contains(target)); - } - visible.retain(|name| children.contains_key(name) || targets.contains(name)); - } - if changes.is_some() && !mermaid && children.is_empty() { - return; - } - let roots: Vec<_> = visible.difference(&targets).cloned().collect(); - // Distinguish rootless cycles from descendants hidden by the depth limit. - let mut reachable = BTreeSet::new(); - let mut pending = roots.clone(); - while let Some(name) = pending.pop() { - if reachable.insert(name.clone()) { - pending.extend(children.get(&name).into_iter().flatten().cloned()); - } - } - let mut included = BTreeSet::new(); - struct Row { - name: String, - depth: usize, - parent: Option, - note: &'static str, - } - let mut rows = Vec::new(); - let mut stack: Vec<_> = roots - .iter() - .rev() - .map(|n| (n.clone(), 0, None::)) - .collect(); - while let Some((name, depth, parent)) = stack.pop() { - let seen = !included.insert(name.clone()); - let descendants = children.get(&name).map(Vec::as_slice).unwrap_or(&[]); - let note = if descendants.is_empty() { - "" - } else if depth >= max_depth { - " [children omitted]" - } else if seen { - " [subtree elided]" - } else { - "" - }; - rows.push(Row { - name: name.clone(), - depth, - parent, - note, - }); - if !seen && depth < max_depth { - for child in descendants.iter().rev() { - stack.push((child.clone(), depth + 1, Some(name.clone()))); - } - } - } - for name in visible.difference(&reachable) { - rows.push(Row { - name: name.clone(), - depth: 0, - parent: None, - note: " [children omitted]", - }); - } - let status = |name: &String| { - if !old.cells.contains(name) && !new.cells.contains(name) { - if old.known_cells.contains(name) || new.known_cells.contains(name) { - " [outside scope]" - } else { - " [unresolved]" - } - } else if direct.contains(name) { - if mermaid { " [cell changed]" } else { "" } - } else if affected.contains(name) { - " [affected]" - } else if mermaid && changes.is_some() { - " [cell unchanged]" - } else { - "" - } - }; - let edge_label = |parent: &String, target: &String| { - let key = (parent.clone(), target.clone()); - let a = old_edges.get(&key).copied().unwrap_or(0); - let b = new_edges.get(&key).copied().unwrap_or(0); - let count = if a == b { - format!("x{b}") - } else { - format!("x{a} -> x{b}") - }; - format!( - "{count}{}", - if (mermaid || a == b) && changed_refs.contains(&key) { - " [reference changed]" - } else { - "" - } - ) - }; - if mermaid { - let ids: BTreeMap<_, _> = rows - .iter() - .map(|row| &row.name) - .collect::>() - .into_iter() - .enumerate() - .map(|(i, n)| (n, i)) - .collect(); - out.push_str("flowchart TD\n"); - if changes.is_none() && new.scope != Scope::default() { - writeln!(out, " %% {}", new.scope.description()).unwrap(); - } - for (name, id) in &ids { - let label = format!("{name}{}", status(name)); - let label = label - .replace('&', "&") - .replace('"', """) - .replace('<', "<") - .replace('>', ">") - .replace(['\r', '\n'], " "); - writeln!(out, " n{id}[\"{label}\"]").unwrap(); - } - for (parent, target) in &edges { - if let (Some(a), Some(b)) = (ids.get(parent), ids.get(target)) { - writeln!(out, " n{a} -->|\"{}\"| n{b}", edge_label(parent, target)).unwrap(); - } - } - if rows.is_empty() { - out.push_str(" empty[\"No changed hierarchy\"]\n"); - } - } else { - let single_placement = |parent: &String, target: &String| { - let key = (parent.clone(), target.clone()); - old_edges.get(&key) == Some(&1) - && new_edges.get(&key) == Some(&1) - && !changed_refs.contains(&key) - }; - let unbranched = |name: &String| { - !shared.contains(name) - && children - .get(name) - .is_none_or(|descendants| descendants.len() == 1) - }; - let can_join = |parent: &Row, child: &Row| { - child.parent.as_ref() == Some(&parent.name) - && parent.note.is_empty() - && !direct.contains(&parent.name) - && affected.contains(&parent.name) - && unbranched(&child.name) - && (old.cells.contains(&child.name) || new.cells.contains(&child.name)) - && single_placement(&parent.name, &child.name) - }; - out.write_styled(TextStyle::Heading, format_args!("Hierarchy")); - out.push('\n'); - if changes.is_none() { - new.scope.write_restrictions(out); - } - let mut index = 0; - let mut ancestor_depths = Vec::new(); - while let Some(first) = rows.get(index) { - let mut end = index; - if fold_paths - && unbranched(&first.name) - && first - .parent - .as_ref() - .is_none_or(|parent| single_placement(parent, &first.name)) - { - while rows - .get(end + 1) - .is_some_and(|next| can_join(&rows[end], next)) - { - end += 1; - } - // Two rows are already easy to scan. - if end - index < 2 { - end = index; - } - } - while ancestor_depths - .last() - .is_some_and(|&depth| depth >= first.depth) - { - ancestor_depths.pop(); - } - out.push_str(&" ".repeat(ancestor_depths.len())); - let mut change = None; - for (i, row) in rows[index..=end].iter().enumerate() { - let name = &row.name; - if i != 0 { - out.push_str(" → "); - } - if direct.contains(name) { - let marker = cell_marker(old.cells.contains(name), new.cells.contains(name)); - change = Some((out.len(), TextStyle::change(marker))); - write!(out, "{marker} ").unwrap(); - } - if changes.is_some() { - out.push_str(&cell_label(name)); - } else { - write!(out, "{name:?}").unwrap(); - } - if i == 0 - && let Some(parent) = &row.parent - { - write!(out, " {}", edge_label(parent, name)).unwrap(); - } - } - let last = &rows[end]; - write!(out, "{}{}", status(&last.name), last.note).unwrap(); - if let Some((start, style)) = change { - out.mark(start, style); - } - out.push('\n'); - ancestor_depths.push(last.depth); - index = end + 1; - } - if visible.is_empty() { - out.push_str("No changed hierarchy\n"); - } + hierarchy::render_hierarchy(&self.old, &self.new, Some(&self.cells), mermaid, max_depth) } } diff --git a/src/review/changes.rs b/src/review/changes.rs index c5a69cf..157a349 100644 --- a/src/review/changes.rs +++ b/src/review/changes.rs @@ -1,6 +1,6 @@ //! Unique replacement matches that explain removed and added objects. -use super::*; +use super::{text::CellText, *}; #[derive(Debug)] pub struct Replacement { diff --git a/src/review/hierarchy.rs b/src/review/hierarchy.rs new file mode 100644 index 0000000..4d5342e --- /dev/null +++ b/src/review/hierarchy.rs @@ -0,0 +1,495 @@ +//! Hierarchy analysis, traversal, and presentation. + +use super::*; + +/// Graph facts shared by text, Mermaid, and JSON renderers. +pub(super) struct HierarchyAnalysis<'a> { + pub(super) old_edges: &'a BTreeMap<(String, String), u64>, + pub(super) new_edges: &'a BTreeMap<(String, String), u64>, + pub(super) edges: BTreeSet<(String, String)>, + pub(super) direct: BTreeSet, + pub(super) affected: BTreeSet, + pub(super) changed_refs: BTreeSet<(String, String)>, + old: &'a Revision, + new: &'a Revision, + comparison: bool, +} + +impl<'a> HierarchyAnalysis<'a> { + pub(super) fn between( + old: &'a Revision, + new: &'a Revision, + changes: Option<&[CellChange]>, + ) -> Self { + let old_edges = &old.edges; + let new_edges = &new.edges; + let edges: BTreeSet<_> = old_edges.keys().chain(new_edges.keys()).cloned().collect(); + let direct: BTreeSet<_> = changes + .into_iter() + .flatten() + .map(|cell| cell.name.clone()) + .collect(); + let changed_refs: BTreeSet<_> = changes + .into_iter() + .flatten() + .flat_map(|c| { + c.removed + .iter() + .chain(&c.added) + .filter_map(|o| o.target.as_ref().map(|t| (c.name.clone(), t.clone()))) + }) + .collect(); + let mut parents = BTreeMap::<&str, Vec<&str>>::new(); + for (parent, child) in &edges { + parents.entry(child).or_default().push(parent); + } + let mut affected = direct.clone(); + let mut pending: Vec<_> = direct.iter().cloned().collect(); + while let Some(child) = pending.pop() { + for parent in parents.get(child.as_str()).into_iter().flatten() { + if affected.insert((*parent).to_string()) { + pending.push((*parent).to_string()); + } + } + } + Self { + old_edges, + new_edges, + edges, + direct, + affected, + changed_refs, + old, + new, + comparison: changes.is_some(), + } + } + + fn visible_rows( + &self, + mermaid: bool, + max_depth: usize, + covered_edges: Option<&BTreeSet<(String, String)>>, + ) -> Option { + let mut visible: BTreeSet<_> = if self.comparison { + self.affected + .iter() + .cloned() + .chain(self.changed_refs.iter().map(|(_, t)| t.clone())) + .collect() + } else { + self.old + .cells + .iter() + .chain(self.new.cells.iter()) + .cloned() + .chain(self.edges.iter().map(|(_, t)| t.clone())) + .collect() + }; + let mut children = BTreeMap::>::new(); + let mut targets = BTreeSet::new(); + let mut shared = BTreeSet::new(); + let fold_paths = self.comparison && !mermaid; + for (parent, target) in &self.edges { + if visible.contains(parent) && visible.contains(target) { + children + .entry(parent.clone()) + .or_default() + .push(target.clone()); + if !targets.insert(target.clone()) && fold_paths { + shared.insert(target.clone()); + } + } + } + if let Some(covered) = covered_edges { + if !covered.is_empty() { + // Keep changed or shared descendants, branches, and target status notes. + let redundant: BTreeSet<_> = covered + .iter() + .map(|(_, target)| target) + .filter(|&target| { + targets.contains(target) + && !shared.contains(target) + && !children.contains_key(target) + && !self.affected.contains(target) + && self.old.cells.contains(target) + && self.new.cells.contains(target) + }) + .collect(); + children.retain(|_, children| { + children.retain(|target| !redundant.contains(target)); + !children.is_empty() + }); + targets.retain(|target| !redundant.contains(target)); + } + visible.retain(|name| children.contains_key(name) || targets.contains(name)); + } + if fold_paths && children.is_empty() { + return None; + } + let rows = traverse(&visible, &children, &targets, max_depth); + Some(VisibleHierarchy { + rows, + children, + shared, + }) + } + + fn single_placement(&self, parent: &str, target: &str) -> bool { + let key = (parent.to_string(), target.to_string()); + self.old_edges.get(&key) == Some(&1) + && self.new_edges.get(&key) == Some(&1) + && !self.changed_refs.contains(&key) + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RowNote { + ChildrenOmitted, + SubtreeElided, +} + +struct HierarchyRow { + name: String, + depth: usize, + parent: Option, + note: Option, +} + +fn traverse( + visible: &BTreeSet, + children: &BTreeMap>, + targets: &BTreeSet, + max_depth: usize, +) -> Vec { + let roots: Vec<_> = visible.difference(targets).cloned().collect(); + // Distinguish rootless cycles from descendants hidden by the depth limit. + let mut reachable = BTreeSet::new(); + let mut pending = roots.clone(); + while let Some(name) = pending.pop() { + if reachable.insert(name.clone()) { + pending.extend(children.get(&name).into_iter().flatten().cloned()); + } + } + let mut included = BTreeSet::new(); + let mut rows = Vec::new(); + let mut stack: Vec<_> = roots + .into_iter() + .rev() + .map(|name| (name, 0, None::)) + .collect(); + while let Some((name, depth, parent)) = stack.pop() { + let seen = !included.insert(name.clone()); + let descendants = children.get(&name).map(Vec::as_slice).unwrap_or(&[]); + let note = if descendants.is_empty() { + None + } else if depth >= max_depth { + Some(RowNote::ChildrenOmitted) + } else if seen { + Some(RowNote::SubtreeElided) + } else { + None + }; + if !seen && depth < max_depth { + for child in descendants.iter().rev() { + stack.push((child.clone(), depth + 1, Some(name.clone()))); + } + } + rows.push(HierarchyRow { + name, + depth, + parent, + note, + }); + } + for name in visible.difference(&reachable) { + rows.push(HierarchyRow { + name: name.clone(), + depth: 0, + parent: None, + note: Some(RowNote::ChildrenOmitted), + }); + } + rows +} + +struct VisibleHierarchy { + rows: Vec, + children: BTreeMap>, + shared: BTreeSet, +} + +struct AsciiPath<'a> { + indent: usize, + rows: &'a [HierarchyRow], +} + +impl VisibleHierarchy { + fn unbranched(&self, name: &str) -> bool { + !self.shared.contains(name) + && self + .children + .get(name) + .is_none_or(|descendants| descendants.len() == 1) + } + + fn can_join( + &self, + graph: &HierarchyAnalysis<'_>, + parent: &HierarchyRow, + child: &HierarchyRow, + ) -> bool { + child.parent.as_deref() == Some(&parent.name) + && parent.note.is_none() + && !graph.direct.contains(&parent.name) + && graph.affected.contains(&parent.name) + && self.unbranched(&child.name) + && (graph.old.cells.contains(&child.name) || graph.new.cells.contains(&child.name)) + && graph.single_placement(&parent.name, &child.name) + } + + fn ascii_paths<'a>( + &'a self, + graph: &'a HierarchyAnalysis<'_>, + ) -> impl Iterator> { + let mut index = 0; + let mut ancestor_depths = Vec::new(); + std::iter::from_fn(move || { + let first = self.rows.get(index)?; + let mut end = index; + if graph.comparison + && self.unbranched(&first.name) + && first + .parent + .as_ref() + .is_none_or(|parent| graph.single_placement(parent, &first.name)) + { + while self + .rows + .get(end + 1) + .is_some_and(|next| self.can_join(graph, &self.rows[end], next)) + { + end += 1; + } + // Fold paths with at least two edges. + if end - index < 2 { + end = index; + } + } + while ancestor_depths + .last() + .is_some_and(|&depth| depth >= first.depth) + { + ancestor_depths.pop(); + } + let rows = &self.rows[index..=end]; + let indent = ancestor_depths.len(); + ancestor_depths.push(self.rows[end].depth); + index = end + 1; + Some(AsciiPath { indent, rows }) + }) + } +} + +/// The graph joins both revisions, retaining removed branches and old callers. +pub(super) fn render_hierarchy( + old: &Revision, + new: &Revision, + changes: Option<&[CellChange]>, + mermaid: bool, + max_depth: usize, +) -> String { + let mut out = TextReport::default(); + write_hierarchy(&mut out, old, new, changes, mermaid, max_depth, None); + out.into_string() +} + +pub(super) fn write_hierarchy( + out: &mut TextReport, + old: &Revision, + new: &Revision, + changes: Option<&[CellChange]>, + mermaid: bool, + max_depth: usize, + covered_edges: Option<&BTreeSet<(String, String)>>, +) { + if !mermaid && changes.is_some_and(<[CellChange]>::is_empty) { + return; + } + let graph = HierarchyAnalysis::between(old, new, changes); + let Some(view) = graph.visible_rows(mermaid, max_depth, covered_edges) else { + return; + }; + if mermaid { + graph.write_mermaid(out, &view.rows); + } else { + graph.write_ascii(out, view.ascii_paths(&graph)); + } +} + +impl HierarchyAnalysis<'_> { + fn status(&self, name: &str, mermaid: bool) -> &'static str { + if !self.old.cells.contains(name) && !self.new.cells.contains(name) { + if self.old.known_cells.contains(name) || self.new.known_cells.contains(name) { + " [outside scope]" + } else { + " [unresolved]" + } + } else if self.direct.contains(name) { + if mermaid { " [cell changed]" } else { "" } + } else if self.affected.contains(name) { + " [affected]" + } else if mermaid && self.comparison { + " [cell unchanged]" + } else { + "" + } + } + + fn edge_label(&self, parent: &str, target: &str, mermaid: bool) -> String { + let key = (parent.to_string(), target.to_string()); + let a = self.old_edges.get(&key).copied().unwrap_or(0); + let b = self.new_edges.get(&key).copied().unwrap_or(0); + let count = if a == b { + format!("x{b}") + } else { + format!("x{a} -> x{b}") + }; + format!( + "{count}{}", + if (mermaid || a == b) && self.changed_refs.contains(&key) { + " [reference changed]" + } else { + "" + } + ) + } + + fn write_mermaid(&self, out: &mut TextReport, rows: &[HierarchyRow]) { + let ids: BTreeMap<_, _> = rows + .iter() + .map(|row| &row.name) + .collect::>() + .into_iter() + .enumerate() + .map(|(i, n)| (n, i)) + .collect(); + out.push_str("flowchart TD\n"); + if !self.comparison && self.new.scope != Scope::default() { + writeln!(out, " %% {}", self.new.scope.description()).unwrap(); + } + for (name, id) in &ids { + let label = format!("{name}{}", self.status(name, true)); + let label = label + .replace('&', "&") + .replace('"', """) + .replace('<', "<") + .replace('>', ">") + .replace(['\r', '\n'], " "); + writeln!(out, " n{id}[\"{label}\"]").unwrap(); + } + for (parent, target) in &self.edges { + if let (Some(a), Some(b)) = (ids.get(parent), ids.get(target)) { + writeln!( + out, + " n{a} -->|\"{}\"| n{b}", + self.edge_label(parent, target, true) + ) + .unwrap(); + } + } + if rows.is_empty() { + out.push_str(" empty[\"No changed hierarchy\"]\n"); + } + } + + fn write_ascii<'a>(&self, out: &mut TextReport, paths: impl Iterator>) { + out.write_styled(TextStyle::Heading, format_args!("Hierarchy")); + out.push('\n'); + if !self.comparison { + self.new.scope.write_restrictions(out); + } + let mut paths = paths.peekable(); + if paths.peek().is_none() { + out.push_str("No changed hierarchy\n"); + } + for path in paths { + out.push_str(&" ".repeat(path.indent)); + let mut change = None; + for (i, row) in path.rows.iter().enumerate() { + let name = &row.name; + if i != 0 { + out.push_str(" → "); + } + if self.direct.contains(name) { + let marker = + cell_marker(self.old.cells.contains(name), self.new.cells.contains(name)); + change = Some((out.len(), TextStyle::change(marker))); + write!(out, "{marker} ").unwrap(); + } + if self.comparison { + out.push_str(&cell_label(name)); + } else { + write!(out, "{name:?}").unwrap(); + } + if i == 0 + && let Some(parent) = &row.parent + { + write!(out, " {}", self.edge_label(parent, name, false)).unwrap(); + } + } + let last = path.rows.last().unwrap(); + let note = match last.note { + Some(RowNote::ChildrenOmitted) => " [children omitted]", + Some(RowNote::SubtreeElided) => " [subtree elided]", + None => "", + }; + write!(out, "{}{note}", self.status(&last.name, false)).unwrap(); + if let Some((start, style)) = change { + out.mark(start, style); + } + out.push('\n'); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn traversal_distinguishes_depth_limits_from_rootless_components() { + let children = BTreeMap::from([ + ("root".into(), vec!["branch".into()]), + ("branch".into(), vec!["leaf".into()]), + ("cycle_a".into(), vec!["cycle_b".into()]), + ("cycle_b".into(), vec!["cycle_a".into()]), + ]); + let visible = ["root", "branch", "leaf", "cycle_a", "cycle_b"] + .map(String::from) + .into_iter() + .collect(); + let targets = children.values().flatten().cloned().collect(); + let rows = traverse(&visible, &children, &targets, 1); + let rows: Vec<_> = rows + .iter() + .map(|row| { + ( + row.name.as_str(), + row.depth, + row.parent.as_deref(), + row.note, + ) + }) + .collect(); + assert_eq!( + rows, + [ + ("root", 0, None, None), + ("branch", 1, Some("root"), Some(RowNote::ChildrenOmitted)), + ("cycle_a", 0, None, Some(RowNote::ChildrenOmitted)), + ("cycle_b", 0, None, Some(RowNote::ChildrenOmitted)), + ] + ); + } +} diff --git a/src/review/report.rs b/src/review/report.rs index 6450755..8004f48 100644 --- a/src/review/report.rs +++ b/src/review/report.rs @@ -1,5 +1,5 @@ //! Versioned machine-readable diff reports. No consumer needs to parse prose. -use super::*; +use super::{hierarchy::HierarchyAnalysis, *}; use serde::{ Serialize, Serializer, ser::{SerializeMap, SerializeSeq}, @@ -445,6 +445,7 @@ fn graph(diff: &Comparison) -> Value { direct, affected, changed_refs, + .. } = HierarchyAnalysis::between(old, new, Some(&diff.cells)); let names: BTreeSet<_> = old .cells diff --git a/src/review/text.rs b/src/review/text.rs index f2692da..d47ed16 100644 --- a/src/review/text.rs +++ b/src/review/text.rs @@ -1,8 +1,17 @@ -//! Text output and presentation roles shared with the terminal. +//! Text comparison reports and presentation roles shared with the terminal. -use super::*; +use super::{hierarchy::write_hierarchy, *}; use std::ops::Range; +/// Additional presentation options for a text comparison. +#[derive(Clone, Copy, Debug, Default)] +pub struct TextReportOptions { + /// Print individual object evidence, including both sides of replacements. + pub details: bool, + /// Append the ASCII hierarchy at this depth when provided. + pub ascii_depth: Option, +} + /// A presentation role for a span of report text. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum TextStyle { @@ -250,3 +259,441 @@ impl fmt::Write for CellText<'_> { Ok(()) } } + +impl TextComparison { + pub fn render_text( + &self, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + ) -> String { + self.comparison + .render_text(max_objects, show, show_library_presence) + } + + pub fn render_text_with_options( + &self, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + options: TextReportOptions, + ) -> String { + self.comparison + .render_text_with_options(max_objects, show, show_library_presence, options) + } + + pub fn write_text_report( + &self, + out: &mut TextReport, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + options: TextReportOptions, + ) { + self.comparison + .write_text_report(out, max_objects, show, show_library_presence, options); + } + + /// Render the cell changes and their ASCII hierarchy together. + pub fn render_text_with_ascii_hierarchy( + &self, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + max_depth: usize, + ) -> String { + self.comparison.render_text_with_ascii_hierarchy( + max_objects, + show, + show_library_presence, + max_depth, + ) + } +} + +impl Comparison { + /// Limit presentation only: the complete comparison has already been made. + pub fn text(&self, max_objects: usize) -> String { + self.text_filtered(max_objects, &DisplayFilter::default()) + } + + pub fn text_filtered(&self, max_objects: usize, show: &DisplayFilter) -> String { + self.render_text(max_objects, show, true) + } + + /// Render a text report. Set `show_library_presence` to false when a file + /// header already announces the library addition or deletion. + pub fn render_text( + &self, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + ) -> String { + self.render_text_with_options( + max_objects, + show, + show_library_presence, + TextReportOptions::default(), + ) + } + + /// Render the cell changes and omit simple hierarchy edges already shown there. + pub fn render_text_with_ascii_hierarchy( + &self, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + max_depth: usize, + ) -> String { + self.render_text_with_options( + max_objects, + show, + show_library_presence, + TextReportOptions { + ascii_depth: Some(max_depth), + ..TextReportOptions::default() + }, + ) + } + + /// Render the selected changes with optional object details and ASCII hierarchy. + pub fn render_text_with_options( + &self, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + options: TextReportOptions, + ) -> String { + let mut out = TextReport::default(); + self.write_text_report(&mut out, max_objects, show, show_library_presence, options); + out.into_string() + } + + /// Append the selected changes and their presentation roles to a text report. + pub fn write_text_report( + &self, + out: &mut TextReport, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + options: TextReportOptions, + ) { + let selection = selection::TextSelection::new(&self.cells, show, max_objects); + let outcome = self.outcome(); + let headline = out.len(); + let (result, style) = match outcome { + Outcome::Equal => ("Equal", TextStyle::Success), + Outcome::Different => ("Different", TextStyle::Warning), + Outcome::Incomplete { .. } => ("Incomplete", TextStyle::Warning), + Outcome::Failed => ("Failed", TextStyle::Error), + }; + out.push_str(result); + let has_omissions = selection.filtered_objects != 0 + || selection.limited_objects != 0 + || selection.filtered_cells != 0; + if !self.cells.is_empty() + && (self.cells.len() > 3 || !outcome.is_complete() || has_omissions) + { + let (mut modified, mut added, mut removed) = (0, 0, 0); + for cell in &self.cells { + match cell_marker(cell.old.is_some(), cell.new.is_some()) { + '-' => removed += 1, + '+' => added += 1, + _ => modified += 1, + } + } + let mut counts = [ + (modified, "modified"), + (added, "added"), + (removed, "removed"), + ] + .into_iter() + .filter(|(count, _)| *count != 0); + if let Some((count, action)) = counts.next() { + let noun = if count == 1 { "cell" } else { "cells" }; + write!(out, " · {count} {noun} {action}").unwrap(); + for (count, action) in counts { + write!(out, ", {count} {action}").unwrap(); + } + } + } + let library_changes = self.library_changes.iter().filter(|change| { + show_library_presence || !matches!(change, LibraryChange::Presence { .. }) + }); + for (count, label) in [ + (library_changes.clone().count(), "library change"), + (self.layer_names.len(), "layer name change"), + ] { + if count != 0 { + let plural = if count == 1 { "" } else { "s" }; + write!(out, " · {count} {label}{plural}").unwrap(); + } + } + out.mark(headline, style); + out.push('\n'); + self.old.scope.write_restrictions(out); + if show.cell.is_some() || show.layer.is_some() { + let start = out.len(); + out.push_str("Display filter"); + if let Some(cell) = &show.cell { + write!(out, " cell={cell:?}").unwrap(); + } + if let Some((layer, datatype)) = show.layer { + write!(out, " layer={layer}/{datatype}").unwrap(); + } + out.mark(start, TextStyle::Heading); + out.push('\n'); + } + if has_omissions { + let start = out.len(); + out.push_str("Omitted"); + for (count, label, reason) in [ + (selection.filtered_objects, "object change", "filtered out"), + (selection.limited_objects, "object change", "over the limit"), + ( + selection.filtered_cells, + "cell-level change", + "filtered out", + ), + ] { + if count != 0 { + let plural = if count == 1 { "" } else { "s" }; + write!(out, " · {count} {label}{plural} {reason}").unwrap(); + } + } + out.mark(start, TextStyle::Warning); + out.push('\n'); + } + for change in library_changes { + writeln!(out, "library {change}").unwrap(); + } + if self.library_changes.iter().any(|change| { + matches!( + change, + LibraryChange::Record { + tag: RTAG_UNITS, + .. + } + ) + }) { + out.push_str("Coordinates use each file's database units\n"); + } + for change in &self.layer_names { + let name = |value: Option<&str>| { + value.map_or_else(|| "absent".to_string(), |value| format!("{value:?}")) + }; + writeln!( + out, + "{}/{}: name {} -> {}", + change.layer.0, + change.layer.1, + name(change.old.as_deref()), + name(change.new.as_deref()) + ) + .unwrap(); + } + + let mut body = CellText::new(&self.layer_legend, &self.layer_names, out.is_styled()); + let mut covered_edges = BTreeSet::new(); + for selected in &selection.modified_cells { + self.write_cell_details( + &mut body, + selected, + options.details, + (options.ascii_depth.is_some() && outcome.is_complete()) + .then_some(&mut covered_edges), + ); + } + body.write_legend(out); + if !selection.modified_cells.is_empty() + || !selection.removed_cells.is_empty() + || !selection.added_cells.is_empty() + { + out.write_styled(TextStyle::Heading, format_args!("Cells:")); + out.push('\n'); + for name in selection.removed_cells { + out.write_styled(TextStyle::Removed, format_args!("- {}", cell_label(name))); + out.push('\n'); + } + for name in selection.added_cells { + out.write_styled(TextStyle::Added, format_args!("+ {}", cell_label(name))); + out.push('\n'); + } + body.write_body(out); + } + // General comparison errors precede revision-specific errors in text. + if !self.diagnostics.is_empty() { + out.write_styled(TextStyle::Heading, format_args!("Diagnostics")); + out.push('\n'); + for diagnostic in self + .diagnostics + .iter() + .filter(|d| d.side.is_none()) + .chain(self.diagnostics.iter().filter(|d| d.side.is_some())) + { + writeln!(out, " {diagnostic}").unwrap(); + } + } + if let Some(max_depth) = options.ascii_depth { + write_hierarchy( + out, + &self.old, + &self.new, + Some(&self.cells), + false, + max_depth, + Some(&covered_edges), + ); + } + } + + fn write_cell_details( + &self, + out: &mut CellText<'_>, + selected: &selection::TextCellSelection<'_>, + details: bool, + mut covered_edges: Option<&mut BTreeSet<(String, String)>>, + ) { + let cell = selected.cell; + let name = cell_label(&cell.name); + let note = if selected.attributes_changed { + " (attributes changed)" + } else { + "" + }; + out.style(Some(TextStyle::Changed)); + writeln!(out, "* {name}{note}").unwrap(); + let mut polygons = changes::PolygonChanges::default(); + let mut shown_refs = BTreeMap::<&str, changes::ShownReferences>::new(); + for &(a, b) in &selected.replacements { + if !details && a.layer == b.layer && is_polygon(a.kind) { + polygons.replacement(a, b); + continue; + } + out.push_str(" "); + out.style(Some(TextStyle::Changed)); + out.push_str("~ "); + if a.layer != b.layer { + changes::write_layer_transition(out, a, b); + out.push('\n'); + } else { + if let Some(layer) = a.layer { + out.write_layer(layer, None); + out.push_str(": "); + } + let description = changes::replacement_description(a, b, details); + let (heading, rest) = match description.split_once('\n') { + Some((heading, rest)) => (heading, Some(rest)), + None => (description.as_str(), None), + }; + out.push_str(heading); + if let Some(target) = &a.target { + let placements = out.reserve_placements(); + shown_refs + .entry(target) + .or_default() + .replacement(a, b, placements); + } + out.push('\n'); + if let Some(rest) = rest { + writeln!(out, "{rest}").unwrap(); + } + } + if details { + changes::write_replacement_objects(out, a, b); + } + } + let mut removed_refs = BTreeMap::new(); + let mut added_refs = BTreeMap::new(); + for (removed, objects, references) in [ + (true, &selected.removed, &mut removed_refs), + (false, &selected.added, &mut added_refs), + ] { + let sign = if removed { '-' } else { '+' }; + let mut unmatched: Vec<(&ObjectChange, usize)> = Vec::new(); + for &object in objects { + if !details && is_polygon(object.kind) { + polygons.unmatched(object, removed); + } else if !details && let Some(target) = object.target.as_deref() { + let (_, counts) = references + .entry(target) + .or_insert_with(|| (object, changes::ReferenceCounts::default())); + counts.add(object); + } else if let Some((last, count)) = unmatched.last_mut() + && last.kind == object.kind + && last.fields == object.fields + && last.properties == object.properties + { + *count += 1; + } else { + unmatched.push((object, 1)); + } + } + // The comparison orders these objects by kind, fields, and properties. + for (object, count) in unmatched { + out.push_str(" "); + out.style(Some(TextStyle::change(sign))); + write!(out, "{sign} ").unwrap(); + if count > 1 { + write!(out, "{count}× ").unwrap(); + } + changes::write_unmatched(out, object, details); + if let Some(target) = object.target.as_deref() { + let placements = out.reserve_placements(); + shown_refs + .entry(target) + .or_default() + .individual(object, removed, count, placements); + } + out.push('\n'); + } + } + let no_refs = changes::ReferenceCounts::default(); + for (target, (first, counts)) in removed_refs { + if let Some((_, added)) = added_refs.remove(target) { + let placements = counts.write_change(out, target, &added); + shown_refs + .entry(target) + .or_default() + .unmatched(&counts, &added, placements); + } else { + let placements = counts.write(out, '-', target, first); + shown_refs + .entry(target) + .or_default() + .unmatched(&counts, &no_refs, placements); + } + } + for (target, (first, counts)) in added_refs { + let placements = counts.write(out, '+', target, first); + shown_refs + .entry(target) + .or_default() + .unmatched(&no_refs, &counts, placements); + } + if !shown_refs.is_empty() { + for target in cell + .removed + .iter() + .chain(&cell.added) + .filter_map(|o| o.target.as_deref()) + { + if let Some(shown) = shown_refs.get_mut(target) { + shown.count_change(); + } + } + for (target, shown) in shown_refs { + if shown.complete() { + let edge = (cell.name.clone(), target.to_owned()); + let old = self.old.edges.get(&edge).copied().unwrap_or(0); + let new = self.new.edges.get(&edge).copied().unwrap_or(0); + shown.write_placements(out, old, new); + if let Some(covered) = covered_edges.as_deref_mut() { + covered.insert(edge); + } + } + } + } + polygons.write(out); + } +}