Share GDSII reader logic and simplify review output

Share record framing, name decoding, payload validation, array reference
decoding, and Arrow cell-header parsing. Accept trailing NUL padding in
names and retain located diagnostics for malformed records.

Summarize text diffs by cell, layer, and reference target. Show comparison
and omission counts before detail. Compact canonical dumps while
preserving exact fields and duplicate counts for Git textconv. Simplify
hierarchy output and retain per-object evidence in JSON.
This commit is contained in:
Jan Petykiewicz 2026-11-17 21:49:26 -08:00
commit 15e8a3b7b5
3 changed files with 1717 additions and 828 deletions

View file

@ -74,54 +74,305 @@ pub(super) fn replacements(old: &[ObjectChange], new: &[ObjectChange]) -> Vec<Re
result
}
pub(super) fn explain(old: &ObjectChange, new: &ObjectChange) -> String {
let mut parts = vec![format!(
"{} modified{}",
kind_name(old.kind),
old.target
.as_ref()
.map(|t| format!(" target={t:?}"))
.unwrap_or_default()
)];
if old.target.is_some()
&& old.origin != new.origin
&& let (Some(a), Some(b)) = (old.origin, new.origin)
{
parts.push(format!(
"origin {a:?} -> {b:?}, delta=({}, {}) dbu",
i64::from(b[0]) - i64::from(a[0]),
i64::from(b[1]) - i64::from(a[1])
));
pub(super) fn field_changes<'a>(
old: &'a ObjectChange,
new: &'a ObjectChange,
) -> impl Iterator<Item = (u16, Option<&'a [u8]>, Option<&'a [u8]>)> {
let mut fields = BTreeMap::<u16, (Option<&[u8]>, Option<&[u8]>)>::new();
for field in &old.fields {
fields.entry(field.tag).or_default().0 = Some(&field.data);
}
if old.counts != new.counts {
let counts = |c: Option<[u16; 2]>| {
c.map(|[a, b]| format!("{a} x {b}"))
.unwrap_or_else(|| "absent".to_string())
};
parts.push(format!(
"columns/rows {} -> {}",
counts(old.counts),
counts(new.counts)
));
for field in &new.fields {
fields.entry(field.tag).or_default().1 = Some(&field.data);
}
if old.width != new.width {
let width = |n: Option<i32>| {
n.map(|n| n.to_string())
.unwrap_or_else(|| "absent".to_string())
fields
.into_iter()
.filter_map(|(tag, (before, after))| (before != after).then_some((tag, before, after)))
}
fn polygon_heading(object: &ObjectChange, rectangular: bool) -> String {
object_heading(object, object_name(object.kind, rectangular))
}
fn object_heading(object: &ObjectChange, kind: &str) -> String {
match object.layer {
Some((layer, datatype)) => format!("{layer}/{datatype}: {kind}"),
None => kind.to_string(),
}
}
fn polygon_xy(object: &ObjectChange) -> &[u8] {
object
.fields
.iter()
.find(|field| field.tag == RTAG_XY)
.map_or(&[], |field| field.data.as_slice())
}
fn vertex_count(xy: &[u8]) -> usize {
XY::points(xy).len().saturating_sub(1)
}
fn rectangle_size(xy: &[u8]) -> Option<[i64; 2]> {
let [xmin, ymin, xmax, ymax] = XY::closed_rectangle(xy)?;
Some([
i64::from(xmax) - i64::from(xmin),
i64::from(ymax) - i64::from(ymin),
])
}
fn translation(before: &[u8], after: &[u8]) -> Option<[i64; 2]> {
let mut old = XY::points(before);
let mut new = XY::points(after);
if old.len() != new.len() {
return None;
}
let (Some(a), Some(b)) = (old.next(), new.next()) else {
return None;
};
let displacement = |[x0, y0]: [i32; 2], [x1, y1]: [i32; 2]| {
[i64::from(x1) - i64::from(x0), i64::from(y1) - i64::from(y0)]
};
let shift = displacement(a, b);
(shift != [0, 0] && old.zip(new).all(|(a, b)| displacement(a, b) == shift)).then_some(shift)
}
#[derive(Default)]
struct ShapeCounts {
rectangles: usize,
polygons: usize,
boxes: usize,
}
impl ShapeCounts {
fn add(&mut self, object: &ObjectChange, replacement: Option<&ObjectChange>) {
let is_rectangle =
|object: &ObjectChange| XY::closed_rectangle(polygon_xy(object)).is_some();
match object.kind {
RTAG_BOX => self.boxes += 1,
_ if is_rectangle(object) && replacement.is_none_or(is_rectangle) => {
self.rectangles += 1
}
_ => self.polygons += 1,
}
}
}
#[derive(Default)]
struct LayerPolygonChanges {
changed: ShapeCounts,
moved: ShapeCounts,
removed: ShapeCounts,
added: ShapeCounts,
}
#[derive(Default)]
pub(super) struct PolygonChanges(BTreeMap<Option<Layer>, LayerPolygonChanges>);
impl PolygonChanges {
pub fn replacement(&mut self, old: &ObjectChange, new: &ObjectChange) {
let counts = self.0.entry(old.layer).or_default();
let moved = old.properties == new.properties
&& translation(polygon_xy(old), polygon_xy(new)).is_some()
&& field_changes(old, new).all(|(tag, _, _)| tag == RTAG_XY);
let shapes = if moved {
&mut counts.moved
} else {
&mut counts.changed
};
parts.push(format!(
"width {} -> {} dbu",
width(old.width),
width(new.width)
));
}
if old.bounds == new.bounds {
parts.push("coordinate bounds unchanged".to_string());
shapes.add(old, Some(new));
}
pub fn unmatched(&mut self, object: &ObjectChange, removed: bool) {
let counts = self.0.entry(object.layer).or_default();
let shapes = if removed {
&mut counts.removed
} else {
&mut counts.added
};
shapes.add(object, None);
}
pub fn write(&self, out: &mut String) {
for (layer, counts) in &self.0 {
if let Some((layer, datatype)) = layer {
write!(out, " {layer}/{datatype}: ").unwrap();
} else {
out.push_str(" unknown layer: ");
}
let mut separator = "";
for (action, shapes) in [
("changed", &counts.changed),
("moved", &counts.moved),
("removed", &counts.removed),
("added", &counts.added),
] {
let terms = [
(shapes.rectangles, "rectangle", "rectangles"),
(shapes.polygons, "polygon", "polygons"),
(shapes.boxes, "box", "boxes"),
]
.into_iter()
.filter(|(count, _, _)| *count != 0)
.map(|(count, singular, plural)| {
let shape = if count == 1 { singular } else { plural };
format!("{count} {shape}")
})
.collect::<Vec<_>>();
if !terms.is_empty() {
write!(out, "{separator}{} {action}", terms.join(", ")).unwrap();
separator = " · ";
}
}
out.push('\n');
}
}
}
#[derive(Default)]
pub(super) struct ReferenceCounts {
singles: usize,
arrays: usize,
placements: u128,
}
impl ReferenceCounts {
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;
}
}
pub fn write(&self, out: &mut String, sign: &str, target: &str) {
write!(out, " {sign} ").unwrap();
if self.singles > 0 {
let suffix = if self.singles == 1 { "" } else { "s" };
write!(out, "{} reference{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, " to {target:?}").unwrap();
if self.arrays > 0 {
let suffix = if self.placements == 1 { "" } else { "s" };
write!(out, " ({} placement{suffix})", self.placements).unwrap();
}
out.push('\n');
}
}
fn polygon_replacement(old: &ObjectChange, new: &ObjectChange) -> String {
let before = polygon_xy(old);
let after = polygon_xy(new);
let old_size = rectangle_size(before);
let new_size = rectangle_size(after);
let mut out = polygon_heading(old, old_size.is_some() && new_size.is_some());
if before == after {
out.push_str(" modified");
} else {
match (old_size, new_size) {
(Some(a), Some(b)) if a == b => out.push_str(" moved"),
(Some([w0, h0]), Some([w1, h1])) => {
write!(out, " dimensions changed ({w0} x {h0} -> {w1} x {h1} dbu)").unwrap();
}
_ if translation(before, after).is_some() => out.push_str(" moved"),
_ => {
out.push_str(" vertices changed");
let (a, b) = (vertex_count(before), vertex_count(after));
if a != b {
write!(out, " ({a} -> {b} vertices)").unwrap();
}
}
}
}
out
}
pub(super) fn replacement_summary(old: &ObjectChange, new: &ObjectChange) -> String {
let polygon = is_polygon(old.kind);
let mut out = if polygon {
polygon_replacement(old, new)
} else {
parts.push(format!(
"coordinate bounds {:?} -> {:?}",
old.bounds, new.bounds
));
let mut heading = object_heading(old, object_name(old.kind, false));
if let Some(target) = &old.target {
write!(heading, " {target:?}").unwrap();
}
heading
};
let mut separator = if polygon { "\n " } else { " " };
for (tag, before, after) in field_changes(old, new) {
if polygon && tag == RTAG_XY {
continue;
}
let change = match (tag, before, after) {
(RTAG_XY, Some(a), Some(b)) => {
if let Some([dx, dy]) = translation(a, b) {
format!("moved by ({dx}, {dy}) dbu")
} else if matches!(old.kind, RTAG_PATH | RTAG_NODE) {
let (a, b) = (XY::points(a).len(), XY::points(b).len());
if a == b {
"vertices changed".to_string()
} else {
format!("vertices changed ({a} -> {b} vertices)")
}
} else {
let points = |data: &[u8]| XY::points(data).collect::<Vec<_>>();
format!("coordinates {:?} -> {:?} dbu", points(a), points(b))
}
}
(RTAG_COLROW, _, _) if old.kind == RTAG_AREF => {
let counts = |dimensions: Option<[u16; 2]>| {
dimensions.map_or_else(|| "absent".to_string(), |[a, b]| format!("{a} x {b}"))
};
format!(
"columns/rows {} -> {}",
counts(old.counts),
counts(new.counts)
)
}
(RTAG_WIDTH, _, _) => {
let width =
|n: Option<i32>| n.map_or_else(|| "absent".to_string(), |n| n.to_string());
format!("width {} -> {} dbu", width(old.width), width(new.width))
}
_ => {
let name = if tag == RTAG_STRING {
"text".to_string()
} else {
tag_name(tag)
};
format!("{name} {}", format_field_change(tag, before, after))
}
};
write!(out, "{separator}{change}").unwrap();
separator = "\n ";
}
if old.properties != new.properties {
let properties = |items: &[(u16, Vec<u8>)]| {
items
.iter()
.map(|(attribute, value)| format!("{attribute}={}", quoted(value)))
.collect::<Vec<_>>()
.join(", ")
};
write!(
out,
"{separator}properties [{}] -> [{}]",
properties(&old.properties),
properties(&new.properties)
)
.unwrap();
}
parts.join("; ")
out
}

View file

@ -97,7 +97,7 @@ fn diagnostic(value: &Diagnostic) -> Value {
fn field(tag: u16, data: &[u8]) -> Value {
let (encoding, value) = if tag == RTAG_XY && data.len().is_multiple_of(8) {
("xy", json!(points(data)))
("xy", json!(XY::points(data).collect::<Vec<_>>()))
} else if matches!(
tag,
RTAG_LAYER | RTAG_DATATYPE | RTAG_TEXTTYPE | RTAG_NODETYPE | RTAG_BOXTYPE
@ -185,19 +185,12 @@ fn object(value: &ObjectChange, id: &str, side: &str) -> Value {
}
fn field_changes(old: &ObjectChange, new: &ObjectChange) -> Vec<Value> {
let a: BTreeMap<_, _> = old.fields.iter().map(|f| (f.tag, &f.data)).collect();
let b: BTreeMap<_, _> = new.fields.iter().map(|f| (f.tag, &f.data)).collect();
a.keys()
.chain(b.keys())
.copied()
.collect::<BTreeSet<_>>()
.into_iter()
.filter(|tag| a.get(tag) != b.get(tag))
.map(|tag| {
changes::field_changes(old, new)
.map(|(tag, before, after)| {
json!({
"tag": tag,
"before": a.get(&tag).map(|data| field(tag, data)),
"after": b.get(&tag).map(|data| field(tag, data))
"before": before.map(|data| field(tag, data)),
"after": after.map(|data| field(tag, data))
})
})
.collect()
@ -292,7 +285,7 @@ impl Comparison {
let b = format!("c{cell_index}:new:{}", r.added);
(shown.contains(&a) && shown.contains(&b)).then(|| json!({
"removed": a, "added": b, "match_rule": r.match_rule,
"explanation": changes::explain(&cell.removed[r.removed], &cell.added[r.added]),
"explanation": changes::replacement_summary(&cell.removed[r.removed], &cell.added[r.added]),
"field_changes": field_changes(&cell.removed[r.removed], &cell.added[r.added]),
"properties_changed": cell.removed[r.removed].properties != cell.added[r.added].properties
}))

View file

@ -17,6 +17,23 @@ pub struct DisplayFilter {
}
impl Scope {
pub(super) fn write_restrictions(&self, out: &mut String) {
if self == &Self::default() {
return;
}
out.push_str("Scope");
if let Some(top) = &self.top {
write!(out, " top={top:?}").unwrap();
}
if let Some(cell) = &self.cell {
write!(out, " cell={cell:?}").unwrap();
}
if let Some((layer, datatype)) = self.layer {
write!(out, " layer={layer}/{datatype}").unwrap();
}
out.push('\n');
}
pub fn description(&self) -> String {
let top = self
.top