pheon/src/review/changes.rs

406 lines
13 KiB
Rust
Raw Normal View History

//! Unique replacement matches that explain removed and added objects.
use super::*;
#[derive(Debug)]
pub struct Replacement {
pub removed: usize,
pub added: usize,
/// Explanation matching is never object identity or geometric equivalence.
pub match_rule: &'static str,
}
type Group = (u16, Option<Layer>, Option<String>, Option<Bounds>);
fn group(object: &ObjectChange, bounds: bool) -> Group {
(
object.kind,
object.layer,
object.target.clone(),
if bounds && object.target.is_none() {
object.bounds
} else {
None
},
)
}
/// Pair only unique candidates in the remaining multisets. Ambiguous groups
/// remain additions/removals; no identity or geometric equivalence is inferred.
pub(super) fn replacements(old: &[ObjectChange], new: &[ObjectChange]) -> Vec<Replacement> {
if old.is_empty() || new.is_empty() {
return Vec::new();
}
let (mut used_old, mut used_new) = (BTreeSet::new(), BTreeSet::new());
let mut result = Vec::new();
for bounds in [true, false] {
let (mut a, mut b) = (
BTreeMap::<Group, Vec<usize>>::new(),
BTreeMap::<Group, Vec<usize>>::new(),
);
for (i, object) in old
.iter()
.enumerate()
.filter(|(i, _)| !used_old.contains(i))
{
a.entry(group(object, bounds)).or_default().push(i);
}
for (i, object) in new
.iter()
.enumerate()
.filter(|(i, _)| !used_new.contains(i))
{
b.entry(group(object, bounds)).or_default().push(i);
}
for (key, indices) in a {
if let (1, Some(others)) = (indices.len(), b.get(&key))
&& others.len() == 1
{
let (i, j) = (indices[0], others[0]);
result.push(Replacement {
removed: i,
added: j,
match_rule: if old[i].target.is_some() {
"unique_kind_target"
} else if bounds {
"unique_kind_layer_bounds"
} else {
"unique_kind_layer"
},
});
used_old.insert(i);
used_new.insert(j);
}
}
}
result.sort_by_key(|r| (r.removed, r.added));
result
}
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);
}
for field in &new.fields {
fields.entry(field.tag).or_default().1 = Some(&field.data);
}
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 object_xy(object: &ObjectChange) -> &[u8] {
object
.fields
.iter()
.find(|field| field.tag == RTAG_XY)
.map_or(&[], |field| field.data.as_slice())
}
pub(super) fn write_unmatched(out: &mut String, sign: &str, object: &ObjectChange) {
if object.kind == RTAG_PATH
&& let Some([xmin, ymin, xmax, ymax]) = object.bounds
{
let vertices = XY::points(object_xy(object)).len();
if vertices > POINTS_PER_LINE {
let heading = object_heading(object, "path");
let width = object
.width
.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"
)
.unwrap();
return;
}
}
writeln!(out, " {sign} {object}").unwrap();
}
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(object_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(object_xy(old), object_xy(new)).is_some()
&& field_changes(old, new).all(|(tag, _, _)| tag == RTAG_XY);
let shapes = if moved {
&mut counts.moved
} else {
&mut counts.changed
};
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 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;
}
}
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 = object_xy(old);
let after = object_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 {
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();
}
out
}