Simplify text diff and hierarchy reports

Use signed cell rows and keep whole-cell contents out of the text diff. Group reference changes, fold redundant terminal edges into the cell list, and inline one-off layer names. Count identical unmatched objects while retaining occurrence-based display limits.
This commit is contained in:
Jan Petykiewicz 2026-11-18 20:12:42 -08:00
commit ed1e0595bc
9 changed files with 775 additions and 226 deletions

View file

@ -46,13 +46,23 @@ pheon diff before.gds after.gds --hierarchy ascii --max-changes 20
pheon diff before.gds after.gds --format json > report.json pheon diff before.gds after.gds --format json > report.json
``` ```
Text reports start with the result and counts of modified, added, and removed Text reports start with the result. The headline includes cell counts for
cells. Added and removed cells show their object counts and group references by reports with more than three changed cells, incomplete comparisons, or omitted
target. Modified cells show counts of rectangles, polygons, and boxes changed, changes. The `Cells:` section lists removals with `-`, additions with `+`, and
moved, added, or removed on each layer. Repeated reference additions or removals modifications with `*`. Modified cells show counts of rectangles, polygons, and
to the same target also appear as a count. Object details use `-` for removals, boxes changed, moved, added, or removed on each layer. Repeated reference
`+` for additions, and `~` for likely replacements. Unmatched paths with five additions or removals to the same target appear as a count. When both occur for
or more vertices show their width, vertex count, and vertex bounds in one line. one target, they share a row. A complete set of edits to a target also shows
the total direct placements when there are unchanged placements, for example
`leaf · -3 refs, +6 refs · placements 10 -> 13`.
An unchanged layer name appears inline when the layer occurs on one displayed
row, as in `1/0 (WG): 1 rectangle moved`. A layer on several displayed rows
gets one legend entry. Object details use `-` for removals, `+` for additions,
and `~` for likely replacements. Identical unmatched objects share a row
with a count such as `+ 12× 1/0: path …`. Unmatched paths with five or more
vertices show their width, vertex count, and vertex bounds in one line.
Use `--format json` for details of individual objects and `--hierarchy` to see Use `--format json` for details of individual objects and `--hierarchy` to see
which parent cells are affected. which parent cells are affected.
@ -101,17 +111,21 @@ pheon diff before.gds after.gds --hierarchy mermaid --depth 4
comparison, totals, or exit status. A layer display filter hides references comparison, totals, or exit status. A layer display filter hides references
without a numeric layer. `--max-changes N` limits displayed object occurrences without a numeric layer. `--max-changes N` limits displayed object occurrences
after filtering. Text defaults to 100 occurrences and shows a replacement only after filtering. Text defaults to 100 occurrences and shows a replacement only
when both objects fit within the limit. A single omission line lists changes when both objects fit within the limit. Grouped rows count each object toward
hidden by filters or the limit. JSON has no default object limit and reports the limit. A single omission line lists changes hidden by filters or the
limit. JSON has no default object limit and reports
omissions from both display filters and any explicit limit in `report_selection`. omissions from both display filters and any explicit limit in `report_selection`.
See the [JSON reference](diff-reports.md) for the selection counters. See the [JSON reference](diff-reports.md) for the selection counters.
The diff hierarchy shows directly changed cells, affected ancestors, and targets The diff hierarchy shows directly changed cells, affected ancestors, and targets
of modified references. It includes references from both revisions so removed of modified references. It includes references from both revisions so removed
branches remain visible. Counts represent direct placements, with symbolic branches remain visible. Counts represent direct placements, with symbolic
counts for arrays. ASCII omits the section when there are no cell changes and counts for arrays. ASCII uses the cell list's change markers and marks
marks reference changes whose placement count stays the same. Use `--depth` reference changes whose placement count stays the same. When the cell list
with text output. shows all edits to an unchanged target on a single branch, ASCII can omit
that terminal edge. The hierarchy retains ancestor paths, shared branches,
and edges with edits hidden by display filters or limits. ASCII appears when
there are relationships to show. Use `--depth` with text output.
For the complete graph within the comparison scope, use For the complete graph within the comparison scope, use
`--format json --hierarchy graph` without `--depth`. Display filters leave the `--format json --hierarchy graph` without `--depth`. Display filters leave the
graph intact. graph intact.

View file

@ -33,8 +33,8 @@ single revision. A comparison captures reference counts and analyzes the union
graph and ancestors when a hierarchy is requested. graph and ancestors when a hierarchy is requested.
`TextComparison::between` captures the data needed for text and hierarchy `TextComparison::between` captures the data needed for text and hierarchy
reports. Layered objects in added and removed cells contribute to the cell's reports. Both comparison types provide `render_text_with_ascii_hierarchy`
object count. to render a combined report with redundant terminal edges omitted.
Use `RevisionPair::parse(&old_bytes, &new_bytes)` for an unscoped comparison Use `RevisionPair::parse(&old_bytes, &new_bytes)` for an unscoped comparison
that can reuse matching cells. Its `compare` and `compare_text` methods return that can reuse matching cells. Its `compare` and `compare_text` methods return

View file

@ -403,13 +403,19 @@ fn run(args: &[OsString]) -> Result<u8, String> {
output.push_str(&format!("mode {:?} -> {:?}\n", paths[3], paths[6])); output.push_str(&format!("mode {:?} -> {:?}\n", paths[3], paths[6]));
} }
} }
output.push_str(&diff.render_text(max_changes, &show, !old_missing && !new_missing)); let show_library_presence = !old_missing && !new_missing;
if format != "none" { if format == "ascii" {
output.push_str(&diff.render_text_with_ascii_hierarchy(
max_changes,
&show,
show_library_presence,
depth,
));
} else {
output.push_str(&diff.render_text(max_changes, &show, show_library_presence));
if format == "mermaid" { if format == "mermaid" {
output.push_str("Hierarchy\n```mermaid\n"); output.push_str("Hierarchy\n```mermaid\n");
} output.push_str(&diff.hierarchy(true, depth));
output.push_str(&diff.hierarchy(format == "mermaid", depth));
if format == "mermaid" {
output.push_str("```\n"); output.push_str("```\n");
} }
} }

View file

@ -886,7 +886,7 @@ impl<'a> Document<'a> {
pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String { pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String {
let revision = Revision::from_document(self); let revision = Revision::from_document(self);
render_hierarchy(&revision, &revision, None, mermaid, max_depth) render_hierarchy(&revision, &revision, None, mermaid, max_depth, None)
} }
pub fn canonical_dump(&self) -> String { pub fn canonical_dump(&self) -> String {
@ -1194,7 +1194,7 @@ impl Revision {
pub struct Comparison { pub struct Comparison {
pub old: Revision, pub old: Revision,
pub new: Revision, pub new: Revision,
/// Unchanged names are displayed once when objects on that layer change. /// Unchanged layer names available to the text report.
pub layer_legend: BTreeMap<Layer, String>, pub layer_legend: BTreeMap<Layer, String>,
pub library_changes: Vec<LibraryChange>, pub library_changes: Vec<LibraryChange>,
pub layer_names: Vec<LayerNameChange>, pub layer_names: Vec<LayerNameChange>,
@ -1202,12 +1202,10 @@ pub struct Comparison {
pub diagnostics: Vec<Diagnostic>, pub diagnostics: Vec<Diagnostic>,
} }
/// A comparison for text and hierarchy reports. Layered objects in whole-cell /// A comparison for text and hierarchy reports.
/// changes contribute to the cell's object count.
#[derive(Debug)] #[derive(Debug)]
pub struct TextComparison { pub struct TextComparison {
comparison: Comparison, comparison: Comparison,
whole_cell_objects: BTreeMap<String, usize>,
} }
impl TextComparison { impl TextComparison {
@ -1216,11 +1214,8 @@ impl TextComparison {
} }
fn collect(old: &Document<'_>, new: &Document<'_>, reused_cells: &BTreeSet<&str>) -> Self { fn collect(old: &Document<'_>, new: &Document<'_>, reused_cells: &BTreeSet<&str>) -> Self {
let mut whole_cell_objects = BTreeMap::new();
let comparison = Comparison::collect(old, new, reused_cells, Some(&mut whole_cell_objects));
Self { Self {
comparison, comparison: Comparison::collect(old, new, reused_cells, false),
whole_cell_objects,
} }
} }
@ -1230,11 +1225,23 @@ impl TextComparison {
show: &DisplayFilter, show: &DisplayFilter,
show_library_presence: bool, show_library_presence: bool,
) -> String { ) -> String {
self.comparison.render_text_with_counts( self.comparison
.render_text(max_objects, show, show_library_presence)
}
/// 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, max_objects,
show, show,
show_library_presence, show_library_presence,
&self.whole_cell_objects, max_depth,
) )
} }
@ -1249,14 +1256,14 @@ impl TextComparison {
impl Comparison { impl Comparison {
pub fn between(old: &Document<'_>, new: &Document<'_>) -> Self { pub fn between(old: &Document<'_>, new: &Document<'_>) -> Self {
Self::collect(old, new, &BTreeSet::new(), None) Self::collect(old, new, &BTreeSet::new(), true)
} }
fn collect( fn collect(
old: &Document<'_>, old: &Document<'_>,
new: &Document<'_>, new: &Document<'_>,
reused_cells: &BTreeSet<&str>, reused_cells: &BTreeSet<&str>,
mut whole_cell_objects: Option<&mut BTreeMap<String, usize>>, include_whole_cell_objects: bool,
) -> Self { ) -> Self {
let mut result = Self { let mut result = Self {
old: Revision::from_document(old), old: Revision::from_document(old),
@ -1350,27 +1357,20 @@ impl Comparison {
added: Vec::new(), added: Vec::new(),
replacements: Vec::new(), replacements: Vec::new(),
}; };
if let Some(counts) = whole_cell_objects.as_deref_mut() if !include_whole_cell_objects && (a.is_none() || b.is_none()) {
&& (a.is_none() || b.is_none())
{
let details = if a.is_some() { let details = if a.is_some() {
&mut change.removed &mut change.removed
} else { } else {
&mut change.added &mut change.added
}; };
let mut count = 0; // The hierarchy uses the changed reference targets.
for object in a.or(b).into_iter().flat_map(|cell| &cell.objects) { details.extend(
if object.metadata { a.or(b)
continue; .into_iter()
} .flat_map(|cell| &cell.objects)
count += 1; .filter(|object| !object.metadata && object.target.is_some())
if object.layer.is_none() || object.target.is_some() { .map(ObjectChange::from),
details.push(object.into()); );
}
}
if count != details.len() {
counts.insert(name.clone(), count);
}
result.cells.push(change); result.cells.push(change);
continue; continue;
} }
@ -1428,9 +1428,16 @@ impl Comparison {
} }
} }
/// Render the affected hierarchy. ASCII output is empty when no cells changed. /// Render the affected hierarchy. ASCII output shows relationships between cells.
pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String { pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String {
render_hierarchy(&self.old, &self.new, Some(&self.cells), mermaid, max_depth) render_hierarchy(
&self.old,
&self.new,
Some(&self.cells),
mermaid,
max_depth,
None,
)
} }
/// Limit presentation only: the complete comparison has already been made. /// Limit presentation only: the complete comparison has already been made.
@ -1450,45 +1457,36 @@ impl Comparison {
show: &DisplayFilter, show: &DisplayFilter,
show_library_presence: bool, show_library_presence: bool,
) -> String { ) -> String {
self.render_text_with_counts(max_objects, show, show_library_presence, &BTreeMap::new()) self.render_text_report(max_objects, show, show_library_presence, None)
} }
fn render_text_with_counts( /// Render the cell changes and omit simple hierarchy edges already shown there.
pub fn render_text_with_ascii_hierarchy(
&self, &self,
max_objects: usize, max_objects: usize,
show: &DisplayFilter, show: &DisplayFilter,
show_library_presence: bool, show_library_presence: bool,
whole_cell_objects: &BTreeMap<String, usize>, max_depth: usize,
) -> String { ) -> String {
let (mut modified, mut added, mut removed) = (0_usize, 0_usize, 0_usize); self.render_text_report(max_objects, show, show_library_presence, Some(max_depth))
for cell in &self.cells {
match (&cell.old, &cell.new) {
(None, Some(_)) => added += 1,
(Some(_), None) => removed += 1,
_ => modified += 1,
} }
}
let mut out = match self.outcome() { fn render_text_report(
&self,
max_objects: usize,
show: &DisplayFilter,
show_library_presence: bool,
ascii_depth: Option<usize>,
) -> String {
let outcome = self.outcome();
let mut out = match outcome {
Outcome::Equal => "Equal", Outcome::Equal => "Equal",
Outcome::Different => "Different", Outcome::Different => "Different",
Outcome::Incomplete { .. } => "Incomplete", Outcome::Incomplete { .. } => "Incomplete",
Outcome::Failed => "Failed", Outcome::Failed => "Failed",
} }
.to_string(); .to_string();
let mut cell_counts = [ let headline_end = out.len();
(modified, "modified"),
(added, "added"),
(removed, "removed"),
]
.into_iter()
.filter(|(count, _)| *count != 0);
if let Some((count, action)) = cell_counts.next() {
let noun = if count == 1 { "cell" } else { "cells" };
write!(out, " · {count} {noun} {action}").unwrap();
for (count, action) in cell_counts {
write!(out, ", {count} {action}").unwrap();
}
}
let library_changes = self.library_changes.iter().filter(|change| { let library_changes = self.library_changes.iter().filter(|change| {
show_library_presence || !matches!(change, LibraryChange::Presence { .. }) show_library_presence || !matches!(change, LibraryChange::Presence { .. })
}); });
@ -1543,51 +1541,49 @@ impl Comparison {
.unwrap(); .unwrap();
} }
let body_start = out.len(); let body_start = out.len();
let mut shown_layers = BTreeSet::new(); let mut removed_cells = String::new();
let mut added_cells = String::new();
let mut layers = changes::LayerRows::new(&self.layer_legend);
let mut annotations = Vec::new();
let mut covered_edges = BTreeSet::new();
let mut detail_total = 0; let mut detail_total = 0;
let mut selected = 0; let mut selected = 0;
let mut shown: usize = 0; let mut shown: usize = 0;
let mut hidden_cell_changes = 0; let mut hidden_cell_changes = 0;
let presence = |action, count| { let visible =
let objects = if count == 1 { "object" } else { "objects" }; |object: &ObjectChange| show.layer.is_none_or(|layer| object.layer == Some(layer));
Cow::Owned(format!(" ({action}, {count} {objects})"))
};
for cell in &self.cells { for cell in &self.cells {
let object_count = |details| { let marker = cell_marker(cell.old.is_some(), cell.new.is_some());
whole_cell_objects let attributes_changed = marker == '*' && cell.attributes_changed();
.get(&cell.name) if marker == '*' {
.copied() detail_total += cell.removed.len() + cell.added.len();
.unwrap_or(details) }
};
let note = match (&cell.old, &cell.new) {
(None, Some(_)) => presence("added", object_count(cell.added.len())),
(Some(_), None) => presence("removed", object_count(cell.removed.len())),
_ if cell.attributes_changed() => Cow::Borrowed(" (attributes changed)"),
_ => Cow::Borrowed(""),
};
let whole_cell = cell.old.is_none() || cell.new.is_none();
// The heading accounts for layered objects in a whole-cell change.
detail_total += if whole_cell {
cell.removed
.iter()
.chain(&cell.added)
.filter(|object| object.layer.is_none())
.count()
} else {
cell.removed.len() + cell.added.len()
};
if show.cell.as_ref().is_some_and(|name| name != &cell.name) { if show.cell.as_ref().is_some_and(|name| name != &cell.name) {
hidden_cell_changes += usize::from(!note.is_empty()); hidden_cell_changes += usize::from(marker != '*' || attributes_changed);
continue; continue;
} }
let name = cell_label(&cell.name);
match marker {
'-' => {
writeln!(removed_cells, "- {name}").unwrap();
continue;
}
'+' => {
writeln!(added_cells, "+ {name}").unwrap();
continue;
}
_ => (),
};
let note = if attributes_changed {
" (attributes changed)"
} else {
""
};
let cell_start = out.len(); let cell_start = out.len();
let previously_shown = shown; let previously_shown = shown;
writeln!(out, "cell {:?}{note}", cell.name).unwrap(); writeln!(out, "* {name}{note}").unwrap();
let visible = |object: &ObjectChange| {
(!whole_cell || object.layer.is_none())
&& show.layer.is_none_or(|layer| object.layer == Some(layer))
};
let mut polygons = changes::PolygonChanges::default(); let mut polygons = changes::PolygonChanges::default();
let mut shown_refs = BTreeMap::<&str, changes::ShownReferences>::new();
let mut paired_old = BTreeSet::new(); let mut paired_old = BTreeSet::new();
let mut paired_new = BTreeSet::new(); let mut paired_new = BTreeSet::new();
for replacement in &cell.replacements { for replacement in &cell.replacements {
@ -1599,18 +1595,28 @@ impl Comparison {
if is_polygon(a.kind) { if is_polygon(a.kind) {
polygons.replacement(a, b); polygons.replacement(a, b);
} else { } else {
writeln!(out, " ~ {}", changes::replacement_summary(a, b)).unwrap(); out.push_str(" ~ ");
let row_start = out.len();
layers.record(a.layer, row_start);
writeln!(out, "{}", changes::replacement_summary(a, b)).unwrap();
if let Some(target) = &a.target {
shown_refs
.entry(target)
.or_default()
.replacement(a, b, row_start);
}
} }
shown_layers.extend(a.layer);
shown += 2; shown += 2;
} }
} }
for (removed, objects, paired) in [ let mut removed_refs = BTreeMap::new();
(true, &cell.removed, &paired_old), let mut added_refs = BTreeMap::new();
(false, &cell.added, &paired_new), for (removed, objects, paired, references) in [
(true, &cell.removed, &paired_old, &mut removed_refs),
(false, &cell.added, &paired_new, &mut added_refs),
] { ] {
let sign = if removed { "-" } else { "+" }; let sign = if removed { "-" } else { "+" };
let mut references = BTreeMap::new(); let mut unmatched: Vec<(&ObjectChange, usize)> = Vec::new();
for (index, object) in objects.iter().enumerate() { for (index, object) in objects.iter().enumerate() {
if !visible(object) { if !visible(object) {
continue; continue;
@ -1624,33 +1630,102 @@ impl Comparison {
.entry(target) .entry(target)
.or_insert_with(|| (object, changes::ReferenceCounts::default())); .or_insert_with(|| (object, changes::ReferenceCounts::default()));
counts.add(object); 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 { } else {
changes::write_unmatched(&mut out, sign, object); unmatched.push((object, 1));
} }
shown_layers.extend(object.layer);
shown += 1; shown += 1;
} }
} }
for (target, (first, counts)) in references { // The comparison orders these objects by kind, fields, and properties.
if whole_cell || counts.len() > 1 { for (object, count) in unmatched {
counts.write(&mut out, sign, target); write!(out, " {sign} ").unwrap();
if count > 1 {
write!(out, "{count}× ").unwrap();
}
layers.record(object.layer, out.len());
changes::write_unmatched(&mut out, object);
}
}
let no_refs = changes::ReferenceCounts::default();
for (target, (first, counts)) in removed_refs {
let row_start = out.len();
if let Some((_, added)) = added_refs.remove(target) {
counts.write_change(&mut out, target, &added);
shown_refs
.entry(target)
.or_default()
.unmatched(&counts, &added, row_start);
} else { } else {
writeln!(out, " {sign} {first}").unwrap(); counts.write(&mut out, "-", target, first);
shown_refs
.entry(target)
.or_default()
.unmatched(&counts, &no_refs, row_start);
}
}
for (target, (first, counts)) in added_refs {
let row_start = out.len();
counts.write(&mut out, "+", target, first);
shown_refs
.entry(target)
.or_default()
.unmatched(&no_refs, &counts, row_start);
}
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.annotate(&out, &mut annotations, old, new);
if ascii_depth.is_some() && outcome.is_complete() {
covered_edges.insert(edge);
} }
} }
} }
polygons.write(&mut out); }
if shown == previously_shown && note.is_empty() { polygons.write(&mut out, &mut layers);
if shown == previously_shown && !attributes_changed {
out.truncate(cell_start); out.truncate(cell_start);
} }
} }
let mut legend = String::new(); let mut before_cells = String::new();
for layer in shown_layers { layers.finish(&out, &mut annotations, &mut before_cells);
if let Some(name) = self.layer_legend.get(&layer) { // Resolve row offsets before inserting the section headers.
writeln!(legend, "{}/{}: name {name:?}", layer.0, layer.1).unwrap(); if !annotations.is_empty() {
annotations.sort_unstable_by_key(|(at, _)| *at);
let mut annotated = String::with_capacity(out.len());
let mut start = 0;
for (at, annotation) in annotations {
annotated.push_str(&out[start..at]);
annotated.push_str(&annotation);
start = at;
} }
annotated.push_str(&out[start..]);
out = annotated;
} }
out.insert_str(body_start, &legend); if out.len() > body_start || !removed_cells.is_empty() || !added_cells.is_empty() {
before_cells.push_str("Cells:\n");
before_cells.push_str(&removed_cells);
before_cells.push_str(&added_cells);
}
out.insert_str(body_start, &before_cells);
let mut omissions = Vec::new(); let mut omissions = Vec::new();
for (count, label, reason) in [ for (count, label, reason) in [
(detail_total - selected, "object change", "filtered out"), (detail_total - selected, "object change", "filtered out"),
@ -1668,6 +1743,36 @@ impl Comparison {
&format!("Omitted · {}\n", omissions.join(" · ")), &format!("Omitted · {}\n", omissions.join(" · ")),
); );
} }
const COMPACT_HEADLINE_CELL_LIMIT: usize = 3;
if !self.cells.is_empty()
&& (self.cells.len() > COMPACT_HEADLINE_CELL_LIMIT
|| !outcome.is_complete()
|| !omissions.is_empty())
{
let (mut modified, mut added, mut removed) = (0_usize, 0_usize, 0_usize);
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" };
let mut summary = format!(" · {count} {noun} {action}");
for (count, action) in counts {
write!(summary, ", {count} {action}").unwrap();
}
out.insert_str(headline_end, &summary);
}
}
// General comparison errors precede revision-specific errors in text. // General comparison errors precede revision-specific errors in text.
if !self.diagnostics.is_empty() { if !self.diagnostics.is_empty() {
out.push_str("Diagnostics\n"); out.push_str("Diagnostics\n");
@ -1680,6 +1785,16 @@ impl Comparison {
writeln!(out, " {diagnostic}").unwrap(); writeln!(out, " {diagnostic}").unwrap();
} }
} }
if let Some(max_depth) = ascii_depth {
out.push_str(&render_hierarchy(
&self.old,
&self.new,
Some(&self.cells),
false,
max_depth,
Some(&covered_edges),
));
}
out out
} }
} }
@ -1745,6 +1860,7 @@ fn render_hierarchy(
changes: Option<&[CellChange]>, changes: Option<&[CellChange]>,
mermaid: bool, mermaid: bool,
max_depth: usize, max_depth: usize,
covered_edges: Option<&BTreeSet<(String, String)>>,
) -> String { ) -> String {
if !mermaid && changes.is_some_and(<[CellChange]>::is_empty) { if !mermaid && changes.is_some_and(<[CellChange]>::is_empty) {
return String::new(); return String::new();
@ -1758,7 +1874,7 @@ fn render_hierarchy(
affected, affected,
changed_refs, changed_refs,
} = HierarchyAnalysis::between(old, new, changes); } = HierarchyAnalysis::between(old, new, changes);
let visible: BTreeSet<_> = if changes.is_some() { let mut visible: BTreeSet<_> = if changes.is_some() {
affected affected
.iter() .iter()
.cloned() .cloned()
@ -1783,6 +1899,35 @@ fn render_hierarchy(
targets.insert(target.clone()); targets.insert(target.clone());
} }
} }
if let Some(covered) = covered_edges {
if !covered.is_empty() {
let mut incoming = BTreeMap::new();
for target in children.values().flatten() {
*incoming.entry(target).or_insert(0_usize) += 1;
}
// Keep changed or shared descendants, branches, and target status notes.
let redundant: BTreeSet<_> = covered
.iter()
.map(|(_, target)| target)
.filter(|&target| {
incoming.get(target) == Some(&1)
&& !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 String::new();
}
let roots: Vec<_> = visible.difference(&targets).cloned().collect(); let roots: Vec<_> = visible.difference(&targets).cloned().collect();
// Distinguish rootless cycles from descendants hidden by the depth limit. // Distinguish rootless cycles from descendants hidden by the depth limit.
let mut reachable = BTreeSet::new(); let mut reachable = BTreeSet::new();
@ -1826,15 +1971,7 @@ fn render_hierarchy(
" [unresolved]" " [unresolved]"
} }
} else if direct.contains(name) { } else if direct.contains(name) {
if mermaid { if mermaid { " [cell changed]" } else { "" }
" [cell changed]"
} else if !old.known_cells.contains(name) {
" [added]"
} else if !new.known_cells.contains(name) {
" [removed]"
} else {
" [changed]"
}
} else if affected.contains(name) { } else if affected.contains(name) {
" [affected]" " [affected]"
} else if mermaid && changes.is_some() { } else if mermaid && changes.is_some() {
@ -1899,7 +2036,16 @@ fn render_hierarchy(
new.scope.write_restrictions(&mut out); new.scope.write_restrictions(&mut out);
} }
for (name, depth, parent, seen, limited) in rows { for (name, depth, parent, seen, limited) in rows {
write!(out, "{}{name:?}", " ".repeat(depth)).unwrap(); out.push_str(&" ".repeat(depth));
if direct.contains(&name) {
let marker = cell_marker(old.cells.contains(&name), new.cells.contains(&name));
write!(out, "{marker} ").unwrap();
}
if changes.is_some() {
out.push_str(&cell_label(&name));
} else {
write!(out, "{name:?}").unwrap();
}
if let Some(parent) = parent { if let Some(parent) = parent {
write!(out, " {}", edge_label(&parent, &name)).unwrap(); write!(out, " {}", edge_label(&parent, &name)).unwrap();
} }
@ -1919,6 +2065,25 @@ fn render_hierarchy(
} }
} }
fn cell_marker(old: bool, new: bool) -> char {
match (old, new) {
(true, false) => '-',
(false, true) => '+',
_ => '*',
}
}
fn cell_label(name: &str) -> Cow<'_, str> {
if name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'$' | b'?' | b'.' | b'-'))
{
Cow::Borrowed(name)
} else {
Cow::Owned(format!("{name:?}"))
}
}
fn quoted(data: &[u8]) -> String { fn quoted(data: &[u8]) -> String {
let mut out = "\"".to_string(); let mut out = "\"".to_string();
for byte in data { for byte in data {

View file

@ -112,7 +112,7 @@ fn object_xy(object: &ObjectChange) -> &[u8] {
.map_or(&[], |field| field.data.as_slice()) .map_or(&[], |field| field.data.as_slice())
} }
pub(super) fn write_unmatched(out: &mut String, sign: &str, object: &ObjectChange) { pub(super) fn write_unmatched(out: &mut String, object: &ObjectChange) {
if object.kind == RTAG_PATH if object.kind == RTAG_PATH
&& let Some([xmin, ymin, xmax, ymax]) = object.bounds && let Some([xmin, ymin, xmax, ymax]) = object.bounds
{ {
@ -124,13 +124,13 @@ pub(super) fn write_unmatched(out: &mut String, sign: &str, object: &ObjectChang
.map_or_else(|| "absent".to_string(), |width| format!("{width} dbu")); .map_or_else(|| "absent".to_string(), |width| format!("{width} dbu"));
writeln!( writeln!(
out, out,
" {sign} {heading} · width {width} · {vertices} vertices · bounds ({xmin}, {ymin}) to ({xmax}, {ymax}) dbu" "{heading} · width {width} · {vertices} vertices · bounds ({xmin}, {ymin}) to ({xmax}, {ymax}) dbu"
) )
.unwrap(); .unwrap();
return; return;
} }
} }
writeln!(out, " {sign} {object}").unwrap(); writeln!(out, "{object}").unwrap();
} }
fn vertex_count(xy: &[u8]) -> usize { fn vertex_count(xy: &[u8]) -> usize {
@ -217,12 +217,14 @@ impl PolygonChanges {
shapes.add(object, None); shapes.add(object, None);
} }
pub fn write(&self, out: &mut String) { pub fn write(&self, out: &mut String, layers: &mut LayerRows<'_>) {
for (layer, counts) in &self.0 { for (layer, counts) in &self.0 {
out.push_str(" ");
layers.record(*layer, out.len());
if let Some((layer, datatype)) = layer { if let Some((layer, datatype)) = layer {
write!(out, " {layer}/{datatype}: ").unwrap(); write!(out, "{layer}/{datatype}: ").unwrap();
} else { } else {
out.push_str(" unknown layer: "); out.push_str("unknown layer: ");
} }
let mut separator = ""; let mut separator = "";
for (action, shapes) in [ for (action, shapes) in [
@ -261,41 +263,157 @@ pub(super) struct ReferenceCounts {
} }
impl ReferenceCounts { impl ReferenceCounts {
pub fn len(&self) -> usize {
self.singles + self.arrays
}
pub fn add(&mut self, object: &ObjectChange) { pub fn add(&mut self, object: &ObjectChange) {
if object.kind == RTAG_AREF { if object.kind == RTAG_AREF {
self.arrays += 1; self.arrays += 1;
if let Some([columns, rows]) = object.counts {
self.placements += u128::from(columns) * u128::from(rows);
}
} else { } else {
self.singles += 1; self.singles += 1;
self.placements += 1;
} }
self.placements += reference_placements(object);
} }
pub fn write(&self, out: &mut String, sign: &str, target: &str) { pub fn write(&self, out: &mut String, sign: &str, target: &str, first: &ObjectChange) {
if self.len() == 1 {
writeln!(out, " {sign} {first}").unwrap();
return;
}
write!(out, " {sign} ").unwrap(); write!(out, " {sign} ").unwrap();
self.write_counts(out, "");
write!(out, " to {}", cell_label(target)).unwrap();
self.write_placements(out);
out.push('\n');
}
fn len(&self) -> usize {
self.singles + self.arrays
}
pub fn write_change(&self, out: &mut String, target: &str, added: &Self) {
write!(out, " {} · ", cell_label(target)).unwrap();
self.write_counts(out, "-");
self.write_placements(out);
out.push_str(", ");
added.write_counts(out, "+");
added.write_placements(out);
out.push('\n');
}
fn write_counts(&self, out: &mut String, sign: &str) {
if self.singles > 0 { if self.singles > 0 {
let suffix = if self.singles == 1 { "" } else { "s" }; let suffix = if self.singles == 1 { "" } else { "s" };
write!(out, "{} reference{suffix}", self.singles).unwrap(); write!(out, "{sign}{} ref{suffix}", self.singles).unwrap();
} }
if self.arrays > 0 { if self.arrays > 0 {
if self.singles > 0 { if self.singles > 0 {
out.push_str(", "); out.push_str(", ");
} }
let suffix = if self.arrays == 1 { "" } else { "s" }; let suffix = if self.arrays == 1 { "" } else { "s" };
write!(out, "{} array reference{suffix}", self.arrays).unwrap(); write!(out, "{sign}{} array ref{suffix}", self.arrays).unwrap();
} }
write!(out, " to {target:?}").unwrap(); }
fn write_placements(&self, out: &mut String) {
if self.arrays > 0 { if self.arrays > 0 {
let suffix = if self.placements == 1 { "" } else { "s" }; let suffix = if self.placements == 1 { "" } else { "s" };
write!(out, " ({} placement{suffix})", self.placements).unwrap(); write!(out, " ({} placement{suffix})", self.placements).unwrap();
} }
out.push('\n'); }
}
fn reference_placements(object: &ObjectChange) -> u128 {
match object.counts {
Some([columns, rows]) => u128::from(columns) * u128::from(rows),
None => 0,
}
}
#[derive(Default)]
pub(super) struct ShownReferences {
shown: usize,
total: usize,
removed: u128,
added: u128,
row_start: usize,
}
impl ShownReferences {
pub fn replacement(&mut self, old: &ObjectChange, new: &ObjectChange, row_start: usize) {
self.shown += 2;
self.removed += reference_placements(old);
self.added += reference_placements(new);
self.row_start = row_start;
}
pub fn unmatched(
&mut self,
removed: &ReferenceCounts,
added: &ReferenceCounts,
row_start: usize,
) {
self.shown += removed.len() + added.len();
self.removed += removed.placements;
self.added += added.placements;
self.row_start = row_start;
}
pub fn count_change(&mut self) {
self.total += 1;
}
pub fn complete(&self) -> bool {
self.shown == self.total
}
pub fn annotate(&self, text: &str, annotations: &mut Vec<(usize, String)>, old: u64, new: u64) {
if (u128::from(old), u128::from(new)) == (self.removed, self.added) {
return;
}
let at = self.row_start + text[self.row_start..].find('\n').unwrap();
let totals = if old == new {
let suffix = if new == 1 { "" } else { "s" };
format!(" · {new} total placement{suffix}")
} else {
format!(" · placements {old} -> {new}")
};
annotations.push((at, totals));
}
}
pub(super) struct LayerRows<'a> {
names: &'a BTreeMap<Layer, String>,
rows: BTreeMap<Layer, Option<usize>>,
}
impl<'a> LayerRows<'a> {
pub fn new(names: &'a BTreeMap<Layer, String>) -> Self {
Self {
names,
rows: BTreeMap::new(),
}
}
pub fn record(&mut self, layer: Option<Layer>, row_start: usize) {
if let Some(layer) = layer
&& self.names.contains_key(&layer)
{
self.rows
.entry(layer)
.and_modify(|first| *first = None)
.or_insert(Some(row_start));
}
}
pub fn finish(self, text: &str, annotations: &mut Vec<(usize, String)>, legend: &mut String) {
for (layer, first) in self.rows {
let name = &self.names[&layer];
if let Some(at) = first {
// Each recorded heading starts with the numeric layer/type and a colon.
let at = at + text[at..].find(':').unwrap();
annotations.push((at, format!(" ({})", cell_label(name))));
} else {
writeln!(legend, "{}/{}: name {name:?}", layer.0, layer.1).unwrap();
}
}
} }
} }

View file

@ -181,7 +181,7 @@ impl<'a> RevisionPair<'a> {
} }
pub fn compare(self) -> Comparison { pub fn compare(self) -> Comparison {
Comparison::collect(&self.old, &self.new, &self.reused_cells, None) Comparison::collect(&self.old, &self.new, &self.reused_cells, true)
} }
pub fn compare_text(self) -> TextComparison { pub fn compare_text(self) -> TextComparison {

View file

@ -1,3 +1,4 @@
Different · 1 cell modified Different
cell "CHIP" Cells:
* CHIP
1/0: 1 polygon changed 1/0: 1 polygon changed

View file

@ -1,6 +1,6 @@
Hierarchy Hierarchy
"CHIP" [affected] CHIP [affected]
"left" x1 [affected] left x1 [affected]
"leaf" x2 [changed] * leaf x2
"right" x1 [affected] right x1 [affected]
"leaf" x3 [changed] [shown above] * leaf x3 [shown above]

View file

@ -513,11 +513,11 @@ fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() {
diff.hierarchy(false, 8), diff.hierarchy(false, 8),
concat!( concat!(
"Hierarchy\n", "Hierarchy\n",
"\"CHIP\" [affected]\n", "CHIP [affected]\n",
" \"left\" x1 [affected]\n", " left x1 [affected]\n",
" \"leaf\" x2 [changed]\n", " * leaf x2\n",
" \"right\" x1 [affected]\n", " right x1 [affected]\n",
" \"leaf\" x3 [changed] [shown above]\n", " * leaf x3 [shown above]\n",
) )
); );
let graph = diff.hierarchy(true, 8); let graph = diff.hierarchy(true, 8);
@ -525,8 +525,12 @@ fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() {
assert!(graph.contains("x2")); assert!(graph.contains("x2"));
assert!(graph.contains("x3")); assert!(graph.contains("x3"));
let limited = diff.hierarchy(false, 1); let limited = diff.hierarchy(false, 1);
assert!(!limited.contains("\"leaf\"")); assert!(!limited.contains("leaf"));
assert!(limited.contains("children omitted")); assert!(limited.contains("children omitted"));
assert_eq!(
diff.hierarchy(false, 0),
"Hierarchy\nCHIP [affected] [children omitted]\n"
);
} }
#[test] #[test]
@ -540,9 +544,9 @@ fn reference_changes_keep_unchanged_targets_and_old_edges_visible() {
let diff = Comparison::between(&old, &new); let diff = Comparison::between(&old, &new);
let tree = diff.hierarchy(false, 8); let tree = diff.hierarchy(false, 8);
let edge = if pair.name == "array count" { let edge = if pair.name == "array count" {
" \"leaf\" x2 -> x3\n" " leaf x2 -> x3\n"
} else { } else {
" \"leaf\" x1 [reference changed]\n" " leaf x1 [reference changed]\n"
}; };
assert!(tree.ends_with(edge), "{tree}"); assert!(tree.ends_with(edge), "{tree}");
} }
@ -554,8 +558,8 @@ fn reference_changes_keep_unchanged_targets_and_old_edges_visible() {
let a = Document::parse(&a).unwrap(); let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap(); let b = Document::parse(&b).unwrap();
for (old, new, edge) in [ for (old, new, edge) in [
(&a, &b, " \"leaf\" x1 -> x0 [removed]\n"), (&a, &b, " - leaf x1 -> x0\n"),
(&b, &a, " \"leaf\" x0 -> x1 [added]\n"), (&b, &a, " + leaf x0 -> x1\n"),
] { ] {
let tree = Comparison::between(old, new).hierarchy(false, 8); let tree = Comparison::between(old, new).hierarchy(false, 8);
assert!(tree.ends_with(edge), "{tree}"); assert!(tree.ends_with(edge), "{tree}");
@ -778,6 +782,34 @@ fn cli_uses_documented_exit_codes_and_accepts_paths_with_spaces() {
.unwrap() .unwrap()
.starts_with("flowchart TD") .starts_with("flowchart TD")
); );
let with_reference = |x| layout(&[("CHIP", vec![reference("leaf", x, 1)]), ("leaf", vec![])]);
fs::write(&old, with_reference(0)).unwrap();
fs::write(&new, with_reference(5)).unwrap();
let moved = command()
.arg("diff")
.arg(&old)
.arg(&new)
.args(["--hierarchy", "ascii"])
.output()
.unwrap();
assert_eq!(moved.status.code(), Some(1));
assert_eq!(
moved.stdout,
b"Different\nCells:\n* CHIP\n ~ reference \"leaf\" moved by (5, 0) dbu\n"
);
let scoped = command()
.arg("diff")
.arg(&old)
.arg(&new)
.args(["--hierarchy", "ascii", "--cell", "CHIP"])
.output()
.unwrap();
assert_eq!(scoped.status.code(), Some(1));
assert!(
String::from_utf8(scoped.stdout)
.unwrap()
.ends_with("Hierarchy\n* CHIP\n leaf x1 [reference changed] [outside scope]\n")
);
fs::write(&new, b"invalid").unwrap(); fs::write(&new, b"invalid").unwrap();
assert_eq!( assert_eq!(
command() command()
@ -1139,7 +1171,7 @@ fn display_filters_never_change_equality_or_totals() {
assert!(text.starts_with("Different · 1 cell modified\n")); assert!(text.starts_with("Different · 1 cell modified\n"));
assert!(text.contains("Display filter layer=42/0\n")); assert!(text.contains("Display filter layer=42/0\n"));
assert!(text.contains("Omitted · 2 object changes filtered out")); assert!(text.contains("Omitted · 2 object changes filtered out"));
assert!(!text.contains("cell \"CHIP\"")); assert!(!text.contains("Cells:\n"));
assert_eq!(diff.outcome().exit_code(), 1); assert_eq!(diff.outcome().exit_code(), 1);
} }
@ -1152,24 +1184,31 @@ fn text_hides_empty_headings_and_counts_filtered_and_limited_changes() {
let a = layout(&[ let a = layout(&[
("changed", vec![square()]), ("changed", vec![square()]),
("other", vec![square()]), ("other", vec![square()]),
("gone", vec![square(), triangle()]), (
"gone",
vec![square(), triangle(), reference("target", 0, 1)],
),
("header", vec![]), ("header", vec![]),
("target", vec![]),
]); ]);
let b = layout(&[ let b = layout(&[
("changed", vec![triangle()]), ("changed", vec![triangle()]),
("other", vec![triangle()]), ("other", vec![triangle()]),
("new", vec![square()]), ("new", vec![square(), reference("target", 0, 1)]),
("empty", vec![]), ("empty", vec![]),
("header", vec![attributes]), ("header", vec![attributes]),
("target", vec![]),
]); ]);
let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap());
let text = diff.text(0); let text = diff.text(0);
assert!(text.starts_with("Different · 3 cells modified, 2 added, 1 removed\n")); assert!(text.starts_with("Different · 3 cells modified, 2 added, 1 removed\n"));
assert!(text.contains("cell \"gone\" (removed, 2 objects)\n")); assert!(text.ends_with(concat!(
assert!(text.contains("cell \"new\" (added, 1 object)\n")); "Cells:\n",
assert!(text.contains("cell \"empty\" (added, 0 objects)\n")); "- gone\n",
assert!(text.contains("cell \"header\" (attributes changed)\n")); "+ empty\n",
assert!(!text.contains("cell \"changed\"")); "+ new\n",
"* header (attributes changed)\n",
)));
assert!(text.contains("Omitted · 4 object changes over the limit")); assert!(text.contains("Omitted · 4 object changes over the limit"));
let text = diff.text_filtered( let text = diff.text_filtered(
@ -1184,9 +1223,29 @@ fn text_hides_empty_headings_and_counts_filtered_and_limited_changes() {
"Omitted · 2 object changes filtered out · 2 object changes over the limit", "Omitted · 2 object changes filtered out · 2 object changes over the limit",
" · 4 cell-level changes filtered out\n", " · 4 cell-level changes filtered out\n",
))); )));
assert!(!text.contains("cell \"changed\"")); assert!(!text.contains("Cells:\n"));
assert!(!text.contains("cell \"other\"")); }
assert!(!text.contains("cell \"new\""));
#[test]
fn cell_list_quotes_names_with_whitespace() {
let old = layout(&[("old name", vec![]), ("same\nname", vec![square()])]);
let new = layout(&[("new_name", vec![]), ("same\nname", vec![triangle()])]);
let diff = Comparison::between(
&Document::parse(&old).unwrap(),
&Document::parse(&new).unwrap(),
);
assert_eq!(
diff.text(100),
concat!(
"Different\n",
"Cells:\n",
"- \"old name\"\n",
"+ new_name\n",
"* \"same\\nname\"\n",
" 1/0: 1 polygon changed\n",
)
);
assert!(diff.hierarchy(false, 8).is_empty());
} }
#[test] #[test]
@ -1214,25 +1273,16 @@ fn reference_summaries_group_repeated_targets_and_keep_full_placements_in_dumps(
let with_chip = Document::parse(&with_chip).unwrap(); let with_chip = Document::parse(&with_chip).unwrap();
let existing_chip = Document::parse(&existing_chip).unwrap(); let existing_chip = Document::parse(&existing_chip).unwrap();
for (old, new, action, sign) in [ for (old, new, sign) in [(&empty, &with_chip, '+'), (&with_chip, &empty, '-')] {
(&empty, &with_chip, "added", "+"),
(&with_chip, &empty, "removed", "-"),
] {
let diff = Comparison::between(old, new); let diff = Comparison::between(old, new);
let text_diff = TextComparison::between(old, new); let text_diff = TextComparison::between(old, new);
let text = diff.text(100); let text = diff.text(100);
assert!(text.contains(&format!("cell \"CHIP\" ({action}, 6 objects)\n"))); assert!(text.ends_with(&format!("Cells:\n{sign} CHIP\n")));
assert!(text.contains(&format!( assert!(!text.contains("\n "));
" {sign} 2 references, 1 array reference to \"leaf\" (4 placements)\n"
)));
assert!(text.contains(&format!(" {sign} 1 reference to \"other\"\n")));
assert!(!text.contains("xy="));
assert!(!text.contains("1/0")); assert!(!text.contains("1/0"));
assert!(!text.contains("2/0")); assert!(!text.contains("2/0"));
assert!(!text.contains("Omitted")); assert!(!text.contains("Omitted"));
let limited = diff.text(2); assert_eq!(diff.text(0), text);
assert!(limited.contains(&format!(" {sign} 2 references to \"leaf\"\n")));
assert!(limited.contains("Omitted · 2 object changes over the limit"));
assert_eq!(text_diff.outcome(), diff.outcome()); assert_eq!(text_diff.outcome(), diff.outcome());
for mermaid in [false, true] { for mermaid in [false, true] {
assert_eq!(text_diff.hierarchy(mermaid, 8), diff.hierarchy(mermaid, 8)); assert_eq!(text_diff.hierarchy(mermaid, 8), diff.hierarchy(mermaid, 8));
@ -1263,7 +1313,7 @@ fn reference_summaries_group_repeated_targets_and_keep_full_placements_in_dumps(
] { ] {
let text = Comparison::between(old, new).text(100); let text = Comparison::between(old, new).text(100);
assert!(text.contains(&format!( assert!(text.contains(&format!(
" {sign} 2 references, 1 array reference to \"leaf\" (4 placements)\n" " {sign} 2 refs, 1 array ref to leaf (4 placements)\n"
))); )));
assert!(!text.contains("\"leaf\" xy=")); assert!(!text.contains("\"leaf\" xy="));
assert!(text.contains(&format!(" {sign} reference \"other\" xy=(10, 0)\n"))); assert!(text.contains(&format!(" {sign} reference \"other\" xy=(10, 0)\n")));
@ -1273,6 +1323,139 @@ fn reference_summaries_group_repeated_targets_and_keep_full_placements_in_dumps(
assert!(dump.contains(" array reference \"leaf\" (2 × 1) xy=[(2, 0), (102, 0), (2, 0)]\n")); assert!(dump.contains(" array reference \"leaf\" (2 × 1) xy=[(2, 0), (102, 0), (2, 0)]\n"));
} }
#[test]
fn reference_summaries_combine_visible_changes_to_a_target() {
let make_layout = |positions: std::ops::Range<i32>, moving_x| {
let mut refs: Vec<_> = positions
.chain(20..27)
.map(|x| reference("leaf", x, 1))
.collect();
refs.push(reference("moving", moving_x, 1));
refs.push(reference("moving", 99, 1));
layout(&[("CHIP", refs), ("leaf", vec![]), ("moving", vec![])])
};
let old = make_layout(0..3, 0);
let new = make_layout(10..16, 5);
let diff = Comparison::between(
&Document::parse(&old).unwrap(),
&Document::parse(&new).unwrap(),
);
assert_eq!(
diff.text(100),
concat!(
"Different\nCells:\n* CHIP\n",
" ~ reference \"moving\" moved by (5, 0) dbu · 2 total placements\n",
" leaf · -3 refs, +6 refs · placements 10 -> 13\n",
)
);
let ascii =
|max, show: &DisplayFilter| diff.render_text_with_ascii_hierarchy(max, show, true, 8);
assert_eq!(ascii(100, &Default::default()), diff.text(100));
assert!(diff.text(5).ends_with(" - 3 refs to leaf\n"));
let limited = diff.text(6);
assert!(
limited.starts_with(
"Different · 1 cell modified\nOmitted · 5 object changes over the limit\n"
)
);
assert!(limited.ends_with(" leaf · -3 refs, +1 ref\n"));
let limited_ascii = ascii(6, &Default::default());
assert!(limited_ascii.starts_with(&limited));
assert!(limited_ascii.ends_with("Hierarchy\n* CHIP\n leaf x10 -> x13\n"));
let filtered = ascii(
100,
&DisplayFilter {
cell: None,
layer: Some((1, 0)),
},
);
assert!(filtered.contains("11 object changes filtered out"));
assert!(filtered.ends_with(" leaf x10 -> x13\n moving x2 [reference changed]\n"));
}
#[test]
fn combined_ascii_hierarchy_preserves_paths_to_changed_and_shared_cells() {
let make_layout = |x, shape| {
layout(&[
(
"CHIP",
vec![reference("left", 0, 1), reference("right", 0, 1)],
),
(
"left",
vec![
reference("shared", x, 1),
reference("changed", x, 1),
reference("local", x, 1),
],
),
("right", vec![reference("shared", x, 1)]),
("shared", vec![]),
("changed", vec![shape]),
("local", vec![]),
])
};
let old = make_layout(0, square());
let new = make_layout(5, triangle());
let diff = Comparison::between(
&Document::parse(&old).unwrap(),
&Document::parse(&new).unwrap(),
);
let text = diff.render_text_with_ascii_hierarchy(100, &Default::default(), true, 8);
let (cells, hierarchy) = text.split_once("Hierarchy\n").unwrap();
assert!(cells.contains("reference \"local\" moved by (5, 0) dbu"));
assert_eq!(
hierarchy,
concat!(
"CHIP [affected]\n",
" * left x1\n",
" * changed x1 [reference changed]\n",
" shared x1 [reference changed]\n",
" * right x1\n",
" shared x1 [reference changed] [shown above]\n",
)
);
}
#[test]
fn combined_reference_summaries_keep_array_counts_and_placements() {
let old = layout(&[
(
"CHIP",
vec![
reference("leaf", 0, 1),
reference("leaf", 10, 2),
reference("leaf", 20, 3),
],
),
("leaf", vec![]),
]);
let new = layout(&[
(
"CHIP",
vec![
reference("leaf", 50, 1),
reference("leaf", 60, 1),
reference("leaf", 70, 2),
reference("leaf", 80, 4),
],
),
("leaf", vec![]),
]);
let diff = Comparison::between(
&Document::parse(&old).unwrap(),
&Document::parse(&new).unwrap(),
);
assert_eq!(
diff.text(100),
concat!(
"Different\nCells:\n* CHIP\n",
" leaf · -1 ref, -2 array refs (6 placements), +2 refs, +2 array refs (8 placements)\n",
)
);
}
#[test] #[test]
fn git_external_driver_handles_changes_additions_deletions_and_errors() { fn git_external_driver_handles_changes_additions_deletions_and_errors() {
let directory = std::env::temp_dir().join(format!( let directory = std::env::temp_dir().join(format!(
@ -1340,7 +1523,7 @@ fn git_external_driver_handles_changes_additions_deletions_and_errors() {
assert!( assert!(
String::from_utf8(changed.stdout) String::from_utf8(changed.stdout)
.unwrap() .unwrap()
.contains("Different · 1 cell modified\n") .contains("Different\nCells:\n* CHIP\n")
); );
fs::write(&path, b"invalid").unwrap(); fs::write(&path, b"invalid").unwrap();
let invalid = Command::new("git") let invalid = Command::new("git")
@ -1372,15 +1555,17 @@ fn git_external_driver_handles_changes_additions_deletions_and_errors() {
let result = git(&["diff", "--cached", "--", "added layout.gds"]); let result = git(&["diff", "--cached", "--", "added layout.gds"]);
let text = String::from_utf8(result.stdout).unwrap(); let text = String::from_utf8(result.stdout).unwrap();
assert!(text.starts_with("layout \"added layout.gds\" added\nDifferent · 4 cells added\n")); assert!(text.starts_with("layout \"added layout.gds\" added\nDifferent · 4 cells added\n"));
assert!(text.contains("Cells:\n+ CHIP\n+ leaf\n+ left\n+ right\nHierarchy\n"));
assert!(!text.contains("\nmode ")); assert!(!text.contains("\nmode "));
assert!(!text.contains("\nlibrary ")); assert!(!text.contains("\nlibrary "));
fs::remove_file(&path).unwrap(); fs::remove_file(&path).unwrap();
git(&["add", "-u"]); git(&["add", "-u"]);
let result = git(&["diff", "--cached", "--", "chip layout.gds"]); let result = git(&["diff", "--cached", "--", "chip layout.gds"]);
let text = String::from_utf8(result.stdout).unwrap(); let text = String::from_utf8(result.stdout).unwrap();
assert!(text.starts_with("layout \"chip layout.gds\" deleted\nDifferent · 1 cell removed\n")); assert_eq!(
assert!(!text.contains("\nmode ")); text,
assert!(!text.contains("\nlibrary ")); "layout \"chip layout.gds\" deleted\nDifferent\nCells:\n- CHIP\n"
);
// Textconv is an alternative to the external driver, with a separate cache. // Textconv is an alternative to the external driver, with a separate cache.
git(&["commit", "-qm", "replace fixture"]); git(&["commit", "-qm", "replace fixture"]);
git(&["mv", "added layout.gds", "renamed layout.gds"]); git(&["mv", "added layout.gds", "renamed layout.gds"]);
@ -1390,7 +1575,7 @@ fn git_external_driver_handles_changes_additions_deletions_and_errors() {
let result = git(&["diff", "--cached", "--find-renames"]); let result = git(&["diff", "--cached", "--find-renames"]);
let text = String::from_utf8(result.stdout).unwrap(); let text = String::from_utf8(result.stdout).unwrap();
assert!(text.contains("renamed layout.gds"), "{text}"); assert!(text.contains("renamed layout.gds"), "{text}");
assert!(text.contains("Different · 1 cell modified\n"), "{text}"); assert!(text.contains("Different\nCells:\n* leaf\n"), "{text}");
git(&["commit", "-qm", "rename fixture"]); git(&["commit", "-qm", "rename fixture"]);
fs::write(directory.join(".gitattributes"), "*.gds diff=pheon-text\n").unwrap(); fs::write(directory.join(".gitattributes"), "*.gds diff=pheon-text\n").unwrap();
fs::write(&renamed, shared(square())).unwrap(); fs::write(&renamed, shared(square())).unwrap();
@ -1526,8 +1711,8 @@ fn polygon_diff_groups_shapes_by_layer_across_dimensions() {
assert_eq!( assert_eq!(
diff.text(100), diff.text(100),
concat!( concat!(
"Different · 1 cell modified\n", "Different\n",
"cell \"CHIP\"\n", "Cells:\n* CHIP\n",
" 1/0: 2 rectangles, 1 polygon changed\n", " 1/0: 2 rectangles, 1 polygon changed\n",
" 2/0: 1 polygon changed\n", " 2/0: 1 polygon changed\n",
) )
@ -1580,7 +1765,11 @@ fn unmatched_paths_summarize_coordinates_that_would_wrap() {
" {sign} 1/0: path · width {width} · 5 vertices · bounds (0, -5) to (13, 9) dbu\n" " {sign} 1/0: path · width {width} · 5 vertices · bounds (0, -5) to (13, 9) dbu\n"
))); )));
} }
assert_eq!(text.lines().count(), 5, "{text}"); assert_eq!(
text.lines().filter(|line| line.starts_with(" ")).count(),
3,
"{text}"
);
assert!(text.contains("xy=[(0, 0), (4, 0), (4, -5), (13, -5)]")); assert!(text.contains("xy=[(0, 0), (4, 0), (4, -5), (13, -5)]"));
} }
assert!(paths.canonical_dump().contains("\n (13, 9)]")); assert!(paths.canonical_dump().contains("\n (13, 9)]"));
@ -1596,6 +1785,41 @@ fn unmatched_paths_summarize_coordinates_that_would_wrap() {
); );
} }
#[test]
fn repeated_unmatched_rows_group_only_identical_objects_within_the_limit() {
let points = [[0, 0], [4, 0], [4, -5], [13, -5], [13, 9]];
let mut other_points = points;
other_points[1][0] = 5;
let named_paths = |mut paths: Vec<Vec<u8>>| {
paths.extend([label((900, 7), LAYER_SENTINEL), label((900, 7), "1:0:WG")]);
layout(&[("CHIP", paths)])
};
let empty = named_paths(vec![]);
let paths = named_paths(vec![
path(None, &points),
path(None, &other_points),
path(None, &points),
]);
let empty = Document::parse(&empty).unwrap();
let paths = Document::parse(&paths).unwrap();
for (old, new, sign) in [(&empty, &paths, "+"), (&paths, &empty, "-")] {
let diff = Comparison::between(old, new);
let details = "path · width absent · 5 vertices · bounds (0, -5) to (13, 9) dbu";
let full = diff.text(3);
assert!(full.contains("1/0: name \"WG\"\nCells:\n"));
assert!(full.ends_with(&format!(
" {sign} 2× 1/0: {details}\n {sign} 1/0: {details}\n"
)));
assert!(
diff.text(2)
.ends_with(&format!(" {sign} 2× 1/0 (WG): {details}\n"))
);
let limited = diff.text(1);
assert!(limited.contains("2 object changes over the limit"));
assert!(limited.ends_with(&format!(" {sign} 1/0 (WG): {details}\n")));
}
}
#[test] #[test]
fn label_replacements_show_only_changed_fields() { fn label_replacements_show_only_changed_fields() {
let a = layout(&[("CHIP", vec![label((2, 0), "old")])]); let a = layout(&[("CHIP", vec![label((2, 0), "old")])]);
@ -1603,29 +1827,50 @@ fn label_replacements_show_only_changed_fields() {
let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap());
assert_eq!( assert_eq!(
diff.text(100), diff.text(100),
"Different · 1 cell modified\ncell \"CHIP\"\n ~ 2/0: label text \"old\" -> \"new\"\n" "Different\nCells:\n* CHIP\n ~ 2/0: label text \"old\" -> \"new\"\n"
); );
} }
#[test] #[test]
fn unchanged_layer_names_explain_geometry_changes_once() { fn unchanged_layer_names_explain_geometry_changes_once() {
let named = |geometry| { let named = |geometry, text| {
layout(&[( layout(&[
(
"CHIP", "CHIP",
vec![ vec![
geometry, geometry,
label((900, 7), LAYER_SENTINEL), label((900, 7), LAYER_SENTINEL),
label((900, 7), "1:0:WG"), label((900, 7), "1:0:WG"),
], ],
)]) ),
("leaf", vec![label((1, 0), text)]),
])
}; };
let a = named(square()); let old = named(square(), "old");
let b = named(triangle()); let a = Document::parse(&old).unwrap();
let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); let new = named(triangle(), "old");
let text = diff.text(100); let diff = Comparison::between(&a, &Document::parse(&new).unwrap());
assert_eq!(text.matches("1/0: name \"WG\"").count(), 1); assert_eq!(
diff.text(100),
"Different\nCells:\n* CHIP\n 1/0 (WG): 1 polygon changed\n"
);
assert!(diff.layer_names.is_empty()); assert!(diff.layer_names.is_empty());
let new = named(triangle(), "new");
let diff = Comparison::between(&a, &Document::parse(&new).unwrap());
let text = diff.text(100);
assert!(text.contains("1/0: name \"WG\"\nCells:\n"));
assert!(!text.contains("(WG)"));
assert!(diff.text(2).ends_with(" 1/0 (WG): 1 polygon changed\n"));
let show = DisplayFilter {
cell: Some("leaf".into()),
layer: None,
};
assert!(
diff.text_filtered(100, &show)
.ends_with(" ~ 1/0 (WG): label text \"old\" -> \"new\"\n")
);
let names = corpus() let names = corpus()
.into_iter() .into_iter()
.find(|case| case.name == "layer name only") .find(|case| case.name == "layer name only")