diff --git a/docs/cli.md b/docs/cli.md index 437dee9..b22f4ca 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -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 ``` -Text reports start with the result and counts of modified, added, and removed -cells. Added and removed cells show their object counts and group references by -target. Modified cells show counts of rectangles, polygons, and boxes changed, -moved, added, or removed on each layer. Repeated reference additions or removals -to the same target also appear as a count. Object details use `-` for removals, -`+` for additions, and `~` for likely replacements. Unmatched paths with five -or more vertices show their width, vertex count, and vertex bounds in one line. +Text reports start with the result. The headline includes cell counts for +reports with more than three changed cells, incomplete comparisons, or omitted +changes. The `Cells:` section lists removals with `-`, additions with `+`, and +modifications with `*`. Modified cells show counts of rectangles, polygons, and +boxes changed, moved, added, or removed on each layer. Repeated reference +additions or removals to the same target appear as a count. When both occur for +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 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 without a numeric layer. `--max-changes N` limits displayed object occurrences 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 -hidden by filters or the limit. JSON has no default object limit and reports +when both objects fit within the limit. Grouped rows count each object toward +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`. See the [JSON reference](diff-reports.md) for the selection counters. The diff hierarchy shows directly changed cells, affected ancestors, and targets of modified references. It includes references from both revisions so removed branches remain visible. Counts represent direct placements, with symbolic -counts for arrays. ASCII omits the section when there are no cell changes and -marks reference changes whose placement count stays the same. Use `--depth` -with text output. +counts for arrays. ASCII uses the cell list's change markers and marks +reference changes whose placement count stays the same. When the cell list +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 `--format json --hierarchy graph` without `--depth`. Display filters leave the graph intact. diff --git a/docs/native-api.md b/docs/native-api.md index f953d71..14f3c6e 100644 --- a/docs/native-api.md +++ b/docs/native-api.md @@ -33,8 +33,8 @@ single revision. A comparison captures reference counts and analyzes the union graph and ancestors when a hierarchy is requested. `TextComparison::between` captures the data needed for text and hierarchy -reports. Layered objects in added and removed cells contribute to the cell's -object count. +reports. Both comparison types provide `render_text_with_ascii_hierarchy` +to render a combined report with redundant terminal edges omitted. Use `RevisionPair::parse(&old_bytes, &new_bytes)` for an unscoped comparison that can reuse matching cells. Its `compare` and `compare_text` methods return diff --git a/src/bin/pheon.rs b/src/bin/pheon.rs index 33a891e..ca92916 100644 --- a/src/bin/pheon.rs +++ b/src/bin/pheon.rs @@ -403,13 +403,19 @@ fn run(args: &[OsString]) -> Result { output.push_str(&format!("mode {:?} -> {:?}\n", paths[3], paths[6])); } } - output.push_str(&diff.render_text(max_changes, &show, !old_missing && !new_missing)); - if format != "none" { + let show_library_presence = !old_missing && !new_missing; + 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" { output.push_str("Hierarchy\n```mermaid\n"); - } - output.push_str(&diff.hierarchy(format == "mermaid", depth)); - if format == "mermaid" { + output.push_str(&diff.hierarchy(true, depth)); output.push_str("```\n"); } } diff --git a/src/review.rs b/src/review.rs index 7c2ee16..05fadf5 100644 --- a/src/review.rs +++ b/src/review.rs @@ -886,7 +886,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) + render_hierarchy(&revision, &revision, None, mermaid, max_depth, None) } pub fn canonical_dump(&self) -> String { @@ -1194,7 +1194,7 @@ impl Revision { pub struct Comparison { pub old: 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, pub library_changes: Vec, pub layer_names: Vec, @@ -1202,12 +1202,10 @@ pub struct Comparison { pub diagnostics: Vec, } -/// A comparison for text and hierarchy reports. Layered objects in whole-cell -/// changes contribute to the cell's object count. +/// A comparison for text and hierarchy reports. #[derive(Debug)] pub struct TextComparison { comparison: Comparison, - whole_cell_objects: BTreeMap, } impl TextComparison { @@ -1216,11 +1214,8 @@ impl TextComparison { } 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 { - comparison, - whole_cell_objects, + comparison: Comparison::collect(old, new, reused_cells, false), } } @@ -1230,11 +1225,23 @@ impl TextComparison { show: &DisplayFilter, show_library_presence: bool, ) -> 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, show, show_library_presence, - &self.whole_cell_objects, + max_depth, ) } @@ -1249,14 +1256,14 @@ impl TextComparison { impl Comparison { pub fn between(old: &Document<'_>, new: &Document<'_>) -> Self { - Self::collect(old, new, &BTreeSet::new(), None) + Self::collect(old, new, &BTreeSet::new(), true) } fn collect( old: &Document<'_>, new: &Document<'_>, reused_cells: &BTreeSet<&str>, - mut whole_cell_objects: Option<&mut BTreeMap>, + include_whole_cell_objects: bool, ) -> Self { let mut result = Self { old: Revision::from_document(old), @@ -1350,27 +1357,20 @@ impl Comparison { added: Vec::new(), replacements: Vec::new(), }; - if let Some(counts) = whole_cell_objects.as_deref_mut() - && (a.is_none() || b.is_none()) - { + if !include_whole_cell_objects && (a.is_none() || b.is_none()) { let details = if a.is_some() { &mut change.removed } else { &mut change.added }; - let mut count = 0; - for object in a.or(b).into_iter().flat_map(|cell| &cell.objects) { - if object.metadata { - continue; - } - count += 1; - if object.layer.is_none() || object.target.is_some() { - details.push(object.into()); - } - } - if count != details.len() { - counts.insert(name.clone(), count); - } + // The hierarchy uses the changed reference targets. + details.extend( + a.or(b) + .into_iter() + .flat_map(|cell| &cell.objects) + .filter(|object| !object.metadata && object.target.is_some()) + .map(ObjectChange::from), + ); result.cells.push(change); 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 { - 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. @@ -1450,45 +1457,36 @@ impl Comparison { show: &DisplayFilter, show_library_presence: bool, ) -> 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, max_objects: usize, show: &DisplayFilter, show_library_presence: bool, - whole_cell_objects: &BTreeMap, + max_depth: usize, ) -> String { - let (mut modified, mut added, mut removed) = (0_usize, 0_usize, 0_usize); - 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() { + self.render_text_report(max_objects, show, show_library_presence, Some(max_depth)) + } + + fn render_text_report( + &self, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + ascii_depth: Option, + ) -> String { + let outcome = self.outcome(); + let mut out = match outcome { Outcome::Equal => "Equal", Outcome::Different => "Different", Outcome::Incomplete { .. } => "Incomplete", Outcome::Failed => "Failed", } .to_string(); - let mut cell_counts = [ - (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 headline_end = out.len(); let library_changes = self.library_changes.iter().filter(|change| { show_library_presence || !matches!(change, LibraryChange::Presence { .. }) }); @@ -1543,51 +1541,49 @@ impl Comparison { .unwrap(); } 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 selected = 0; let mut shown: usize = 0; let mut hidden_cell_changes = 0; - let presence = |action, count| { - let objects = if count == 1 { "object" } else { "objects" }; - Cow::Owned(format!(" ({action}, {count} {objects})")) - }; + let visible = + |object: &ObjectChange| show.layer.is_none_or(|layer| object.layer == Some(layer)); for cell in &self.cells { - let object_count = |details| { - whole_cell_objects - .get(&cell.name) - .copied() - .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() - }; + let marker = cell_marker(cell.old.is_some(), cell.new.is_some()); + let attributes_changed = marker == '*' && cell.attributes_changed(); + if marker == '*' { + detail_total += cell.removed.len() + cell.added.len(); + } 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; } + 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 previously_shown = shown; - writeln!(out, "cell {:?}{note}", cell.name).unwrap(); - let visible = |object: &ObjectChange| { - (!whole_cell || object.layer.is_none()) - && show.layer.is_none_or(|layer| object.layer == Some(layer)) - }; + writeln!(out, "* {name}{note}").unwrap(); let mut polygons = changes::PolygonChanges::default(); + let mut shown_refs = BTreeMap::<&str, changes::ShownReferences>::new(); let mut paired_old = BTreeSet::new(); let mut paired_new = BTreeSet::new(); for replacement in &cell.replacements { @@ -1599,18 +1595,28 @@ impl Comparison { if is_polygon(a.kind) { polygons.replacement(a, b); } 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; } } - for (removed, objects, paired) in [ - (true, &cell.removed, &paired_old), - (false, &cell.added, &paired_new), + let mut removed_refs = BTreeMap::new(); + let mut added_refs = BTreeMap::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 mut references = BTreeMap::new(); + let mut unmatched: Vec<(&ObjectChange, usize)> = Vec::new(); for (index, object) in objects.iter().enumerate() { if !visible(object) { continue; @@ -1624,33 +1630,102 @@ impl Comparison { .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 { - changes::write_unmatched(&mut out, sign, object); + unmatched.push((object, 1)); } - shown_layers.extend(object.layer); shown += 1; } } - for (target, (first, counts)) in references { - if whole_cell || counts.len() > 1 { - counts.write(&mut out, sign, target); - } else { - writeln!(out, " {sign} {first}").unwrap(); + // The comparison orders these objects by kind, fields, and properties. + for (object, count) in unmatched { + 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 { + 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); } } - let mut legend = String::new(); - for layer in shown_layers { - if let Some(name) = self.layer_legend.get(&layer) { - writeln!(legend, "{}/{}: name {name:?}", layer.0, layer.1).unwrap(); + let mut before_cells = String::new(); + layers.finish(&out, &mut annotations, &mut before_cells); + // Resolve row offsets before inserting the section headers. + 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(); for (count, label, reason) in [ (detail_total - selected, "object change", "filtered out"), @@ -1668,6 +1743,36 @@ impl Comparison { &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. if !self.diagnostics.is_empty() { out.push_str("Diagnostics\n"); @@ -1680,6 +1785,16 @@ impl Comparison { 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 } } @@ -1745,6 +1860,7 @@ fn render_hierarchy( changes: Option<&[CellChange]>, mermaid: bool, max_depth: usize, + covered_edges: Option<&BTreeSet<(String, String)>>, ) -> String { if !mermaid && changes.is_some_and(<[CellChange]>::is_empty) { return String::new(); @@ -1758,7 +1874,7 @@ fn render_hierarchy( affected, changed_refs, } = HierarchyAnalysis::between(old, new, changes); - let visible: BTreeSet<_> = if changes.is_some() { + let mut visible: BTreeSet<_> = if changes.is_some() { affected .iter() .cloned() @@ -1783,6 +1899,35 @@ fn render_hierarchy( 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(); // Distinguish rootless cycles from descendants hidden by the depth limit. let mut reachable = BTreeSet::new(); @@ -1826,15 +1971,7 @@ fn render_hierarchy( " [unresolved]" } } else if direct.contains(name) { - if mermaid { - " [cell changed]" - } else if !old.known_cells.contains(name) { - " [added]" - } else if !new.known_cells.contains(name) { - " [removed]" - } else { - " [changed]" - } + if mermaid { " [cell changed]" } else { "" } } else if affected.contains(name) { " [affected]" } else if mermaid && changes.is_some() { @@ -1899,7 +2036,16 @@ fn render_hierarchy( new.scope.write_restrictions(&mut out); } 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 { 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 { let mut out = "\"".to_string(); for byte in data { diff --git a/src/review/changes.rs b/src/review/changes.rs index 8131a66..0a5c8d3 100644 --- a/src/review/changes.rs +++ b/src/review/changes.rs @@ -112,7 +112,7 @@ fn object_xy(object: &ObjectChange) -> &[u8] { .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 && 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")); writeln!( 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(); return; } } - writeln!(out, " {sign} {object}").unwrap(); + writeln!(out, "{object}").unwrap(); } fn vertex_count(xy: &[u8]) -> usize { @@ -217,12 +217,14 @@ impl PolygonChanges { 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 { + out.push_str(" "); + layers.record(*layer, out.len()); if let Some((layer, datatype)) = layer { - write!(out, " {layer}/{datatype}: ").unwrap(); + write!(out, "{layer}/{datatype}: ").unwrap(); } else { - out.push_str(" unknown layer: "); + out.push_str("unknown layer: "); } let mut separator = ""; for (action, shapes) in [ @@ -261,41 +263,157 @@ pub(super) struct ReferenceCounts { } impl ReferenceCounts { - pub fn len(&self) -> usize { - self.singles + self.arrays - } - pub fn add(&mut self, object: &ObjectChange) { if object.kind == RTAG_AREF { self.arrays += 1; - if let Some([columns, rows]) = object.counts { - self.placements += u128::from(columns) * u128::from(rows); - } } else { 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(); + 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 { 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.singles > 0 { out.push_str(", "); } 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 { let suffix = if self.placements == 1 { "" } else { "s" }; 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, + rows: BTreeMap>, +} + +impl<'a> LayerRows<'a> { + pub fn new(names: &'a BTreeMap) -> Self { + Self { + names, + rows: BTreeMap::new(), + } + } + + pub fn record(&mut self, layer: Option, 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(); + } + } } } diff --git a/src/review/pair.rs b/src/review/pair.rs index a40128c..1b8352f 100644 --- a/src/review/pair.rs +++ b/src/review/pair.rs @@ -181,7 +181,7 @@ impl<'a> RevisionPair<'a> { } 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 { diff --git a/tests/golden/review-diff.txt b/tests/golden/review-diff.txt index d493fa4..60cb697 100644 --- a/tests/golden/review-diff.txt +++ b/tests/golden/review-diff.txt @@ -1,3 +1,4 @@ -Different · 1 cell modified -cell "CHIP" +Different +Cells: +* CHIP 1/0: 1 polygon changed diff --git a/tests/golden/review-hierarchy.txt b/tests/golden/review-hierarchy.txt index facae9e..ebaae5e 100644 --- a/tests/golden/review-hierarchy.txt +++ b/tests/golden/review-hierarchy.txt @@ -1,6 +1,6 @@ Hierarchy -"CHIP" [affected] - "left" x1 [affected] - "leaf" x2 [changed] - "right" x1 [affected] - "leaf" x3 [changed] [shown above] +CHIP [affected] + left x1 [affected] + * leaf x2 + right x1 [affected] + * leaf x3 [shown above] diff --git a/tests/review.rs b/tests/review.rs index 3c312e6..c30f5e2 100644 --- a/tests/review.rs +++ b/tests/review.rs @@ -513,11 +513,11 @@ fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() { diff.hierarchy(false, 8), concat!( "Hierarchy\n", - "\"CHIP\" [affected]\n", - " \"left\" x1 [affected]\n", - " \"leaf\" x2 [changed]\n", - " \"right\" x1 [affected]\n", - " \"leaf\" x3 [changed] [shown above]\n", + "CHIP [affected]\n", + " left x1 [affected]\n", + " * leaf x2\n", + " right x1 [affected]\n", + " * leaf x3 [shown above]\n", ) ); 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("x3")); let limited = diff.hierarchy(false, 1); - assert!(!limited.contains("\"leaf\"")); + assert!(!limited.contains("leaf")); assert!(limited.contains("children omitted")); + assert_eq!( + diff.hierarchy(false, 0), + "Hierarchy\nCHIP [affected] [children omitted]\n" + ); } #[test] @@ -540,9 +544,9 @@ fn reference_changes_keep_unchanged_targets_and_old_edges_visible() { let diff = Comparison::between(&old, &new); let tree = diff.hierarchy(false, 8); let edge = if pair.name == "array count" { - " \"leaf\" x2 -> x3\n" + " leaf x2 -> x3\n" } else { - " \"leaf\" x1 [reference changed]\n" + " leaf x1 [reference changed]\n" }; 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 b = Document::parse(&b).unwrap(); for (old, new, edge) in [ - (&a, &b, " \"leaf\" x1 -> x0 [removed]\n"), - (&b, &a, " \"leaf\" x0 -> x1 [added]\n"), + (&a, &b, " - leaf x1 -> x0\n"), + (&b, &a, " + leaf x0 -> x1\n"), ] { let tree = Comparison::between(old, new).hierarchy(false, 8); assert!(tree.ends_with(edge), "{tree}"); @@ -778,6 +782,34 @@ fn cli_uses_documented_exit_codes_and_accepts_paths_with_spaces() { .unwrap() .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(); assert_eq!( command() @@ -1139,7 +1171,7 @@ fn display_filters_never_change_equality_or_totals() { assert!(text.starts_with("Different · 1 cell modified\n")); assert!(text.contains("Display filter layer=42/0\n")); 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); } @@ -1152,24 +1184,31 @@ fn text_hides_empty_headings_and_counts_filtered_and_limited_changes() { let a = layout(&[ ("changed", vec![square()]), ("other", vec![square()]), - ("gone", vec![square(), triangle()]), + ( + "gone", + vec![square(), triangle(), reference("target", 0, 1)], + ), ("header", vec![]), + ("target", vec![]), ]); let b = layout(&[ ("changed", vec![triangle()]), ("other", vec![triangle()]), - ("new", vec![square()]), + ("new", vec![square(), reference("target", 0, 1)]), ("empty", vec![]), ("header", vec![attributes]), + ("target", vec![]), ]); let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); let text = diff.text(0); assert!(text.starts_with("Different · 3 cells modified, 2 added, 1 removed\n")); - assert!(text.contains("cell \"gone\" (removed, 2 objects)\n")); - assert!(text.contains("cell \"new\" (added, 1 object)\n")); - assert!(text.contains("cell \"empty\" (added, 0 objects)\n")); - assert!(text.contains("cell \"header\" (attributes changed)\n")); - assert!(!text.contains("cell \"changed\"")); + assert!(text.ends_with(concat!( + "Cells:\n", + "- gone\n", + "+ empty\n", + "+ new\n", + "* header (attributes changed)\n", + ))); assert!(text.contains("Omitted · 4 object changes over the limit")); 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", " · 4 cell-level changes filtered out\n", ))); - assert!(!text.contains("cell \"changed\"")); - assert!(!text.contains("cell \"other\"")); - assert!(!text.contains("cell \"new\"")); + assert!(!text.contains("Cells:\n")); +} + +#[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] @@ -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 existing_chip = Document::parse(&existing_chip).unwrap(); - for (old, new, action, sign) in [ - (&empty, &with_chip, "added", "+"), - (&with_chip, &empty, "removed", "-"), - ] { + for (old, new, sign) in [(&empty, &with_chip, '+'), (&with_chip, &empty, '-')] { let diff = Comparison::between(old, new); let text_diff = TextComparison::between(old, new); let text = diff.text(100); - assert!(text.contains(&format!("cell \"CHIP\" ({action}, 6 objects)\n"))); - assert!(text.contains(&format!( - " {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.ends_with(&format!("Cells:\n{sign} CHIP\n"))); + assert!(!text.contains("\n ")); assert!(!text.contains("1/0")); assert!(!text.contains("2/0")); assert!(!text.contains("Omitted")); - let limited = diff.text(2); - assert!(limited.contains(&format!(" {sign} 2 references to \"leaf\"\n"))); - assert!(limited.contains("Omitted · 2 object changes over the limit")); + assert_eq!(diff.text(0), text); assert_eq!(text_diff.outcome(), diff.outcome()); for mermaid in [false, true] { 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); 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(&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")); } +#[test] +fn reference_summaries_combine_visible_changes_to_a_target() { + let make_layout = |positions: std::ops::Range, 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] fn git_external_driver_handles_changes_additions_deletions_and_errors() { let directory = std::env::temp_dir().join(format!( @@ -1340,7 +1523,7 @@ fn git_external_driver_handles_changes_additions_deletions_and_errors() { assert!( String::from_utf8(changed.stdout) .unwrap() - .contains("Different · 1 cell modified\n") + .contains("Different\nCells:\n* CHIP\n") ); fs::write(&path, b"invalid").unwrap(); 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 text = String::from_utf8(result.stdout).unwrap(); 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("\nlibrary ")); fs::remove_file(&path).unwrap(); git(&["add", "-u"]); let result = git(&["diff", "--cached", "--", "chip layout.gds"]); let text = String::from_utf8(result.stdout).unwrap(); - assert!(text.starts_with("layout \"chip layout.gds\" deleted\nDifferent · 1 cell removed\n")); - assert!(!text.contains("\nmode ")); - assert!(!text.contains("\nlibrary ")); + assert_eq!( + text, + "layout \"chip layout.gds\" deleted\nDifferent\nCells:\n- CHIP\n" + ); // Textconv is an alternative to the external driver, with a separate cache. git(&["commit", "-qm", "replace fixture"]); 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 text = String::from_utf8(result.stdout).unwrap(); 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"]); fs::write(directory.join(".gitattributes"), "*.gds diff=pheon-text\n").unwrap(); fs::write(&renamed, shared(square())).unwrap(); @@ -1526,8 +1711,8 @@ fn polygon_diff_groups_shapes_by_layer_across_dimensions() { assert_eq!( diff.text(100), concat!( - "Different · 1 cell modified\n", - "cell \"CHIP\"\n", + "Different\n", + "Cells:\n* CHIP\n", " 1/0: 2 rectangles, 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" ))); } - 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!(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>| { + 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] fn label_replacements_show_only_changed_fields() { 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()); assert_eq!( 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] fn unchanged_layer_names_explain_geometry_changes_once() { - let named = |geometry| { - layout(&[( - "CHIP", - vec![ - geometry, - label((900, 7), LAYER_SENTINEL), - label((900, 7), "1:0:WG"), - ], - )]) + let named = |geometry, text| { + layout(&[ + ( + "CHIP", + vec![ + geometry, + label((900, 7), LAYER_SENTINEL), + label((900, 7), "1:0:WG"), + ], + ), + ("leaf", vec![label((1, 0), text)]), + ]) }; - let a = named(square()); - let b = named(triangle()); - let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); - let text = diff.text(100); - assert_eq!(text.matches("1/0: name \"WG\"").count(), 1); + let old = named(square(), "old"); + let a = Document::parse(&old).unwrap(); + let new = named(triangle(), "old"); + let diff = Comparison::between(&a, &Document::parse(&new).unwrap()); + assert_eq!( + diff.text(100), + "Different\nCells:\n* CHIP\n 1/0 (WG): 1 polygon changed\n" + ); 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() .into_iter() .find(|case| case.name == "layer name only")