pheon/tests/review.rs

2162 lines
70 KiB
Rust
Raw Normal View History

mod common;
#[path = "review/reports.rs"]
mod reports;
use common::{library_header, record};
use pheon::{
records::*,
review::{
Comparison, Document, TextComparison, names::LAYER_SENTINEL, selection::DisplayFilter,
},
};
use std::{fs, path::PathBuf, process::Command};
fn ascii(bytes: &mut Vec<u8>, tag: u16, value: &str) {
let mut value = value.as_bytes().to_vec();
if value.len() % 2 == 1 {
value.push(0);
}
record(bytes, tag, &value);
}
fn xy(bytes: &mut Vec<u8>, points: &[[i32; 2]]) {
record(
bytes,
RTAG_XY,
&points
.iter()
.flatten()
.flat_map(|v| v.to_be_bytes())
.collect::<Vec<_>>(),
);
}
fn layout(cells: &[(&str, Vec<Vec<u8>>)]) -> Vec<u8> {
let mut bytes = library_header();
for (name, objects) in cells {
record(&mut bytes, RTAG_BGNSTR, &[0; 24]);
ascii(&mut bytes, RTAG_STRNAME, name);
for object in objects {
bytes.extend_from_slice(object);
}
record(&mut bytes, RTAG_ENDSTR, &[]);
}
record(&mut bytes, RTAG_ENDLIB, &[]);
bytes
}
fn gzip(data: &[u8]) -> Vec<u8> {
use std::io::Write;
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(data).unwrap();
encoder.finish().unwrap()
}
fn polygon(points: &[[i32; 2]]) -> Vec<u8> {
ring(RTAG_BOUNDARY, RTAG_DATATYPE, 1, points)
}
fn ring(kind: u16, type_tag: u16, layer: u16, points: &[[i32; 2]]) -> Vec<u8> {
let mut bytes = Vec::new();
record(&mut bytes, kind, &[]);
record(&mut bytes, RTAG_LAYER, &layer.to_be_bytes());
record(&mut bytes, type_tag, &0_u16.to_be_bytes());
xy(&mut bytes, points);
record(&mut bytes, RTAG_ENDEL, &[]);
bytes
}
fn square() -> Vec<u8> {
polygon(&[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]])
}
fn triangle() -> Vec<u8> {
polygon(&[[0, 0], [10, 0], [0, 10], [0, 0]])
}
fn reference(target: &str, x: i32, count: i16) -> Vec<u8> {
let mut bytes = Vec::new();
record(
&mut bytes,
if count == 1 { RTAG_SREF } else { RTAG_AREF },
&[],
);
ascii(&mut bytes, RTAG_SNAME, target);
if count == 1 {
xy(&mut bytes, &[[x, 0]]);
} else {
let counts: Vec<_> = [count, 1].into_iter().flat_map(i16::to_be_bytes).collect();
record(&mut bytes, RTAG_COLROW, &counts);
xy(&mut bytes, &[[x, 0], [x + 100, 0], [x, 0]]);
}
record(&mut bytes, RTAG_ENDEL, &[]);
bytes
}
fn label(carrier: (u16, u16), text: &str) -> Vec<u8> {
let mut bytes = Vec::new();
record(&mut bytes, RTAG_TEXT, &[]);
record(&mut bytes, RTAG_LAYER, &carrier.0.to_be_bytes());
record(&mut bytes, RTAG_TEXTTYPE, &carrier.1.to_be_bytes());
xy(&mut bytes, &[[0, 0]]);
ascii(&mut bytes, RTAG_STRING, text);
record(&mut bytes, RTAG_ENDEL, &[]);
bytes
}
fn path(width: Option<i32>, points: &[[i32; 2]]) -> Vec<u8> {
let mut bytes = Vec::new();
record(&mut bytes, RTAG_PATH, &[]);
record(&mut bytes, RTAG_LAYER, &[0, 1]);
record(&mut bytes, RTAG_DATATYPE, &[0, 0]);
if let Some(width) = width {
record(&mut bytes, RTAG_WIDTH, &width.to_be_bytes());
}
xy(&mut bytes, points);
record(&mut bytes, RTAG_ENDEL, &[]);
bytes
}
fn with_property(mut object: Vec<u8>, value: &str) -> Vec<u8> {
object.truncate(object.len() - 4);
record(&mut object, RTAG_PROPATTR, &17_u16.to_be_bytes());
ascii(&mut object, RTAG_PROPVALUE, value);
record(&mut object, RTAG_ENDEL, &[]);
object
}
fn shared(geometry: Vec<u8>) -> Vec<u8> {
layout(&[
(
"CHIP",
vec![reference("left", 0, 1), reference("right", 20, 1)],
),
("left", vec![reference("leaf", 0, 2)]),
("right", vec![reference("leaf", 0, 3)]),
("leaf", vec![geometry]),
])
}
struct Pair {
name: &'static str,
old: Vec<u8>,
new: Vec<u8>,
changed_cells: usize,
removed: usize,
added: usize,
metadata: usize,
}
// Ten deliberately small fixture pairs specify the first object profile.
fn corpus() -> Vec<Pair> {
let base = layout(&[("CHIP", vec![square(), label((2, 0), "port")])]);
let mut timestamps = base.clone();
timestamps[10] = 1; // BGNLIB payload, ignored by the object profile.
let meta = |name| {
layout(&[(
"CHIP",
vec![
square(),
label((900, 7), LAYER_SENTINEL),
label((900, 7), name),
],
)])
};
vec![
Pair {
name: "record reordering",
old: base.clone(),
new: layout(&[("CHIP", vec![label((2, 0), "port"), square()])]),
changed_cells: 0,
removed: 0,
added: 0,
metadata: 0,
},
Pair {
name: "timestamp edit",
old: base,
new: timestamps,
changed_cells: 0,
removed: 0,
added: 0,
metadata: 0,
},
Pair {
name: "polygon start and winding",
old: layout(&[("CHIP", vec![square()])]),
new: layout(&[(
"CHIP",
vec![polygon(&[[10, 10], [10, 0], [0, 0], [0, 10], [10, 10]])],
)]),
changed_cells: 0,
removed: 0,
added: 0,
metadata: 0,
},
Pair {
name: "duplicate shape",
old: layout(&[("CHIP", vec![square()])]),
new: layout(&[("CHIP", vec![square(), square()])]),
changed_cells: 1,
removed: 0,
added: 1,
metadata: 0,
},
Pair {
name: "same bounds different geometry",
old: layout(&[("CHIP", vec![square()])]),
new: layout(&[("CHIP", vec![triangle()])]),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
Pair {
name: "moved reference",
old: layout(&[
("CHIP", vec![reference("leaf", 0, 1)]),
("leaf", vec![square()]),
]),
new: layout(&[
("CHIP", vec![reference("leaf", 5, 1)]),
("leaf", vec![square()]),
]),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
Pair {
name: "array count",
old: layout(&[
("CHIP", vec![reference("leaf", 0, 2)]),
("leaf", vec![square()]),
]),
new: layout(&[
("CHIP", vec![reference("leaf", 0, 3)]),
("leaf", vec![square()]),
]),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
Pair {
name: "element property",
old: layout(&[("CHIP", vec![with_property(square(), "old")])]),
new: layout(&[("CHIP", vec![with_property(square(), "new")])]),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
Pair {
name: "layer name only",
old: meta("1:0:WG"),
new: meta("1:0:CORE:WG"),
changed_cells: 0,
removed: 0,
added: 0,
metadata: 1,
},
Pair {
name: "shared changed descendant",
old: shared(square()),
new: shared(triangle()),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
]
}
#[test]
fn ten_fixture_pairs_have_explicit_expected_changes() {
for pair in corpus() {
let old = Document::parse(&pair.old).unwrap();
let new = Document::parse(&pair.new).unwrap();
let diff = Comparison::between(&old, &new);
assert!(
diff.diagnostics.is_empty(),
"{}: {:?}",
pair.name,
diff.diagnostics
);
assert_eq!(diff.cells.len(), pair.changed_cells, "{}", pair.name);
assert_eq!(
diff.cells.iter().map(|c| c.removed.len()).sum::<usize>(),
pair.removed,
"{}",
pair.name
);
assert_eq!(
diff.cells.iter().map(|c| c.added.len()).sum::<usize>(),
pair.added,
"{}",
pair.name
);
assert_eq!(diff.layer_names.len(), pair.metadata, "{}", pair.name);
let equal = pair.changed_cells + pair.metadata == 0;
assert_eq!(diff.outcome().is_equal(), equal, "{}", pair.name);
assert_eq!(
old.canonical_dump() == new.canonical_dump(),
equal,
"{}",
pair.name
);
assert_eq!(diff.outcome().exit_code(), if equal { 0 } else { 1 });
}
}
#[test]
fn review_identifies_gzip_and_oasis_input() {
for (bytes, expected) in [
(&b"\x1f\x8b\x08\x00"[..], "gzip-compressed input"),
(&b"%SEMI-OASIS\r\n"[..], "OASIS input"),
] {
let error = Document::parse(bytes).unwrap_err();
assert!(
error.starts_with(&format!("at byte 0: {expected}")),
"{error}"
);
assert_eq!(pheon::review::dump_records(bytes).unwrap_err(), error);
}
}
#[test]
fn canonical_polygon_dump_is_readable_and_offsets_are_separate() {
let bytes = layout(&[("CHIP", vec![square()])]);
let doc = Document::parse(&bytes).unwrap();
let dump = doc.canonical_dump();
assert!(
dump.ends_with("cell \"CHIP\"\n 1/0: rectangle (0, 0) to (10, 10)\n"),
"{dump}"
);
assert!(!dump.contains("BGNSTR"));
assert!(
doc.record_dump()
.contains("0000000000 0002 HEADER size=6 [600]")
);
assert!(doc.record_dump().contains("BGNSTR"));
let notched = polygon(&[[0, 0], [0, 3], [2, 3], [2, 2], [3, 2], [3, 0], [0, 0]]);
let bytes = layout(&[("CHIP", vec![notched])]);
let dump = Document::parse(&bytes).unwrap().canonical_dump();
assert!(
dump.ends_with(concat!(
" 1/0: polygon xy=[(0, 0), (0, 3), (2, 3), (2, 2),\n",
" (3, 2), (3, 0), (0, 0)]\n",
)),
"{dump}"
);
}
#[test]
fn canonical_dump_counts_duplicates_by_normalized_object_within_each_cell() {
let test_layout = |copies: usize| {
let mut objects = vec![square(); copies - 1];
objects.push(polygon(&[[10, 10], [10, 0], [0, 0], [0, 10], [10, 10]]));
objects.push(with_property(square(), "marked"));
layout(&[("A", objects), ("B", vec![square()])])
};
let a = test_layout(3);
let b = test_layout(2);
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let dump = a.canonical_dump();
assert!(
dump.ends_with(concat!(
"cell \"A\"\n",
" 3x 1/0: rectangle (0, 0) to (10, 10)\n",
" 1/0: rectangle (0, 0) to (10, 10) property[17]=\"marked\"\n",
"cell \"B\"\n",
" 1/0: rectangle (0, 0) to (10, 10)\n",
)),
"{dump}"
);
assert!(b.canonical_dump().contains(" 2x 1/0: rectangle"));
assert_ne!(dump, b.canonical_dump());
assert_eq!(Comparison::between(&a, &b).outcome().exit_code(), 1);
}
#[test]
fn canonical_dump_and_hierarchy_match_versioned_goldens() {
let bytes = layout(&[(
"CHIP",
vec![
square(),
label((900, 7), LAYER_SENTINEL),
label((900, 7), "1:0:WG"),
],
)]);
assert_eq!(
Document::parse(&bytes).unwrap().canonical_dump(),
include_str!("golden/review-canonical.txt")
);
let a = shared(square());
let b = shared(triangle());
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
assert_eq!(
diff.hierarchy(false, 8),
include_str!("golden/review-hierarchy.txt")
);
assert_eq!(
diff.hierarchy(true, 8),
include_str!("golden/review-hierarchy.mmd")
);
}
#[test]
fn misplaced_library_fields_and_nul_names_are_rejected() {
let mut late = layout(&[("CHIP", vec![])]);
late.truncate(late.len() - 4);
ascii(&mut late, RTAG_LIBNAME, "late");
record(&mut late, RTAG_ENDLIB, &[]);
assert!(
Document::parse(&late)
.unwrap_err()
.contains("library field outside")
);
assert!(
Document::parse(&layout(&[("CH\0IP", vec![])]))
.unwrap_err()
.contains("NUL")
);
}
#[test]
fn cell_and_property_order_do_not_affect_comparison() {
let a = with_property(with_property(square(), "a"), "b");
let b = with_property(with_property(square(), "b"), "a");
let a = layout(&[("z", vec![a]), ("a", vec![])]);
let b = layout(&[("a", vec![]), ("z", vec![b])]);
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
assert_ne!(a.cells["z"].offset, b.cells["z"].offset);
assert!(Comparison::between(&a, &b).outcome().is_equal());
assert_eq!(a.canonical_dump(), b.canonical_dump());
}
#[test]
fn metadata_requires_a_sentinel_in_the_same_cell_and_carrier_pair() {
let bytes = layout(&[
(
"CHIP",
vec![
label((900, 7), LAYER_SENTINEL),
label((900, 7), "1:0:WG"),
label((900, 8), "2:0:ordinary text"),
],
),
("OTHER", vec![label((900, 7), "3:0:ordinary text")]),
]);
let doc = Document::parse(&bytes).unwrap();
assert_eq!(doc.layer_names.len(), 1);
assert_eq!(doc.layer_names.get(&(1, 0)).unwrap(), "WG");
assert!(doc.canonical_dump().contains("2:0:ordinary text"));
assert!(doc.canonical_dump().contains("3:0:ordinary text"));
assert!(!doc.canonical_dump().contains(LAYER_SENTINEL));
let conflicts = layout(&[(
"CHIP",
vec![
label((9, 0), LAYER_SENTINEL),
label((9, 0), "1:0:A"),
label((9, 0), "1:0:B"),
],
)]);
assert!(
Document::parse(&conflicts)
.unwrap_err()
.contains("conflicting names")
);
assert!(
pheon::review::dump_records(&conflicts)
.unwrap()
.contains("1:0:B")
);
let future = layout(&[("CHIP", vec![label((9, 0), "PHEON_LAYER_NAMES_V2")])]);
let future = Document::parse(&future).unwrap();
assert_eq!(
Comparison::between(&future, &future).outcome().exit_code(),
2
);
}
#[test]
fn unknown_records_never_produce_a_successful_equality_claim() {
let mut unknown = square();
unknown.truncate(unknown.len() - 4);
record(&mut unknown, 0x7f00, &[]);
record(&mut unknown, RTAG_ENDEL, &[]);
let bytes = layout(&[("CHIP", vec![unknown])]);
let doc = Document::parse(&bytes).unwrap();
let diff = Comparison::between(&doc, &doc);
assert!(!diff.outcome().is_equal());
assert_eq!(diff.outcome().exit_code(), 2);
assert!(doc.record_dump().contains("7f00"));
let text = diff.text(0);
assert!(text.starts_with("Incomplete\nDiagnostics\n"));
assert!(text.contains("unsupported record 0x7f00"));
}
#[test]
fn shared_hierarchy_reports_ancestors_and_each_leaf_placement_count() {
let a = shared(square());
let b = shared(triangle());
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
assert_eq!(
diff.hierarchy(false, 8),
concat!(
"Hierarchy\n",
"CHIP [affected]\n",
" left x1 [affected]\n",
" * leaf x2\n",
" right x1 [affected]\n",
" * leaf x3\n",
)
);
let graph = diff.hierarchy(true, 8);
assert_eq!(graph.matches("leaf [cell changed]").count(), 1);
assert!(graph.contains("x2"));
assert!(graph.contains("x3"));
let limited = diff.hierarchy(false, 1);
assert!(!limited.contains("leaf"));
assert!(limited.contains("children omitted"));
assert_eq!(
diff.hierarchy(false, 0),
"Hierarchy\nCHIP [affected] [children omitted]\n"
);
}
#[test]
fn ascii_hierarchy_marks_repeated_subtrees_and_depth_limits() {
let bytes = layout(&[
(
"CHIP",
vec![reference("left", 0, 1), reference("right", 0, 1)],
),
("left", vec![reference("branch", 0, 2)]),
("right", vec![reference("branch", 0, 3)]),
("branch", vec![reference("leaf", 0, 1)]),
("leaf", vec![]),
]);
let doc = Document::parse(&bytes).unwrap();
assert_eq!(
doc.hierarchy(false, 8),
concat!(
"Hierarchy\n",
"\"CHIP\"\n",
" \"left\" x1\n",
" \"branch\" x2\n",
" \"leaf\" x1\n",
" \"right\" x1\n",
" \"branch\" x3 [subtree elided]\n",
)
);
assert_eq!(
doc.hierarchy(false, 2),
concat!(
"Hierarchy\n",
"\"CHIP\"\n",
" \"left\" x1\n",
" \"branch\" x2 [children omitted]\n",
" \"right\" x1\n",
" \"branch\" x3 [children omitted]\n",
)
);
}
#[test]
fn reference_changes_keep_unchanged_targets_and_old_edges_visible() {
for pair in corpus()
.into_iter()
.filter(|p| p.name == "moved reference" || p.name == "array count")
{
let old = Document::parse(&pair.old).unwrap();
let new = Document::parse(&pair.new).unwrap();
let diff = Comparison::between(&old, &new);
let tree = diff.hierarchy(false, 8);
let edge = if pair.name == "array count" {
" leaf x2 -> x3\n"
} else {
" leaf x1 [reference changed]\n"
};
assert!(tree.ends_with(edge), "{tree}");
}
let a = layout(&[
("CHIP", vec![reference("leaf", 0, 1)]),
("leaf", vec![square()]),
]);
let b = layout(&[("CHIP", vec![])]);
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
for (old, new, edge) in [
(&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}");
}
}
#[test]
fn same_bounds_changes_and_truncated_reports_remain_differences() {
let a = layout(&[("CHIP", vec![square()])]);
let b = layout(&[("CHIP", vec![triangle(), label((2, 0), "new label")])]);
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
assert_eq!(
diff.cells[0].removed[0].bounds,
diff.cells[0].added[0].bounds
);
let limited = diff.text(1);
assert!(limited.contains("Omitted · 2 object changes over the limit"));
assert!(limited.contains("+ 2/0: label"));
assert!(!limited.contains("1/0:"));
assert_eq!(diff.outcome().exit_code(), 1);
assert!(diff.cells[0].removed[0].offset > 0);
}
#[test]
fn unit_changes_report_values_without_claiming_geometry_equivalence() {
let a = layout(&[("CHIP", vec![square()])]);
let units = Document::parse(&a)
.unwrap()
.records
.iter()
.find(|r| r.tag == RTAG_UNITS)
.unwrap()
.offset;
let mut b = a.clone();
b[units + 12..units + 20]
.copy_from_slice(&pheon::basic::encode_real8(2e-9).unwrap().to_be_bytes());
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
assert_eq!(diff.outcome().exit_code(), 1);
assert!(matches!(
diff.library_changes.as_slice(),
[pheon::review::LibraryChange::Record {
tag: RTAG_UNITS,
..
}]
));
let text = diff.text(0);
assert!(text.contains("library UNITS [0.001, 1e-9] -> [0.001, 2e-9]"));
assert!(text.contains("Coordinates use each file's database units"));
assert!(!text.contains("raw="));
assert!(diff.cells.is_empty());
assert!(diff.hierarchy(false, 8).is_empty());
}
#[test]
fn dangling_references_cycles_and_duplicate_cell_names_are_reported() {
let missing = layout(&[("CHIP", vec![reference("missing", 0, 1)])]);
let missing = Document::parse(&missing).unwrap();
assert!(
missing
.diagnostics
.iter()
.any(|d| d.code == "unresolved_reference")
);
let cycle = layout(&[
("a", vec![reference("b", 0, 1)]),
("b", vec![reference("a", 0, 1)]),
]);
let cycle = Document::parse(&cycle).unwrap();
assert!(
cycle
.diagnostics
.iter()
.any(|d| d.code == "hierarchy_cycle")
);
assert!(cycle.hierarchy(false, 8).len() < 200);
let duplicate = layout(&[("a", vec![]), ("a", vec![])]);
assert!(
Document::parse(&duplicate)
.unwrap_err()
.contains("duplicate cell")
);
}
#[test]
fn absolute_transform_flags_are_not_discarded() {
let a = reference("leaf", 0, 1);
let mut b = Vec::new();
record(&mut b, RTAG_SREF, &[]);
ascii(&mut b, RTAG_SNAME, "leaf");
record(&mut b, RTAG_STRANS, &[0, 2]);
xy(&mut b, &[[0, 0]]);
record(&mut b, RTAG_ENDEL, &[]);
let a = layout(&[("CHIP", vec![a]), ("leaf", vec![])]);
let b = layout(&[("CHIP", vec![b]), ("leaf", vec![])]);
assert_eq!(
Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap())
.outcome()
.exit_code(),
1
);
}
#[test]
fn polygon_normalization_handles_repeated_minimum_vertices() {
let ring = [[0, 0], [4, 0], [4, 4], [0, 0], [-2, 2], [-2, 4], [0, 0]];
let baseline = layout(&[("CHIP", vec![polygon(&ring)])]);
let baseline = Document::parse(&baseline).unwrap();
let mut open = ring[..ring.len() - 1].to_vec();
for _ in 0..2 {
for start in 0..open.len() {
let mut rotated = open[start..]
.iter()
.chain(&open[..start])
.copied()
.collect::<Vec<_>>();
rotated.push(rotated[0]);
let candidate = layout(&[("CHIP", vec![polygon(&rotated)])]);
let candidate = Document::parse(&candidate).unwrap();
assert!(
Comparison::between(&baseline, &candidate)
.outcome()
.is_equal()
);
}
open.reverse();
}
}
#[test]
fn malformed_lengths_fields_and_units_return_errors_without_panicking() {
let good = layout(&[("CHIP", vec![square()])]);
for length in 0..good.len() {
assert!(
Document::parse(&good[..length]).is_err(),
"accepted truncated length {length}"
);
}
let mut bad = good.clone();
bad[0..2].copy_from_slice(&3_u16.to_be_bytes());
assert!(Document::parse(&bad).is_err());
let mut bad = good.clone();
let units = Document::parse(&good)
.unwrap()
.records
.iter()
.find(|r| r.tag == RTAG_UNITS)
.unwrap()
.offset;
bad[units + 4..units + 20].fill(0);
assert!(Document::parse(&bad).unwrap_err().contains("UNITS"));
let mut polygon = square();
polygon.truncate(polygon.len() - 4);
record(&mut polygon, RTAG_LAYER, &[0, 1]);
record(&mut polygon, RTAG_ENDEL, &[]);
assert!(
Document::parse(&layout(&[("CHIP", vec![polygon])]))
.unwrap_err()
.contains("duplicate element field")
);
}
#[test]
fn cli_uses_documented_exit_codes_and_accepts_paths_with_spaces() {
let directory = std::env::temp_dir().join(format!("pheon review {}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
struct Cleanup(PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
let _cleanup = Cleanup(directory.clone());
let old = directory.join("old file.gds");
let new = directory.join("new file.gds");
fs::write(&old, shared(square())).unwrap();
fs::write(&new, shared(triangle())).unwrap();
let command = || Command::new(env!("CARGO_BIN_EXE_pheon"));
let equal = command()
.arg("diff")
.arg(&old)
.arg(&old)
.args(["--hierarchy", "ascii"])
.output()
.unwrap();
assert_eq!(equal.status.code(), Some(0));
assert_eq!(equal.stdout, b"Equal\n");
let diff = command()
.arg("diff")
.arg(&old)
.arg(&new)
.args(["--hierarchy", "mermaid", "--max-changes", "0"])
.output()
.unwrap();
assert_eq!(diff.status.code(), Some(1));
let text = String::from_utf8(diff.stdout).unwrap();
assert!(text.contains("Omitted · 2 object changes over the limit"));
assert!(text.contains("Hierarchy\n```mermaid\nflowchart TD"));
assert!(!text.contains("scope top=all"));
let dump = command()
.arg("dump")
.arg(&old)
.args(["--records"])
.output()
.unwrap();
assert_eq!(dump.status.code(), Some(0));
assert!(String::from_utf8(dump.stdout).unwrap().contains("BGNSTR"));
let graph = command()
.arg("hierarchy")
.arg(&old)
.args(["--format", "mermaid"])
.output()
.unwrap();
assert_eq!(graph.status.code(), Some(0));
assert!(
String::from_utf8(graph.stdout)
.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()
.arg("diff")
.arg(&old)
.arg(&new)
.output()
.unwrap()
.status
.code(),
Some(2)
);
}
#[test]
fn cli_color_preserves_plain_output_and_machine_formats() {
let directory = std::env::temp_dir().join(format!("pheon color {}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
struct Cleanup(PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
let _cleanup = Cleanup(directory.clone());
let old = directory.join("old.gds");
let new = directory.join("new.gds");
let with_changes = |name, shape, positions: std::ops::Range<i32>| {
let objects = positions
.map(|x| reference("leaf", x, 1))
.chain([shape])
.collect();
layout(&[("CHIP", objects), ("leaf", vec![]), (name, vec![])])
};
fs::write(&old, with_changes("obsolete", square(), 0..2)).unwrap();
fs::write(&new, with_changes("new", triangle(), 10..13)).unwrap();
let command = || Command::new(env!("CARGO_BIN_EXE_pheon"));
let diff = |options: &[&str]| {
let output = command()
.arg("diff")
.arg(&old)
.arg(&new)
.args(options)
.output()
.unwrap();
assert_eq!(output.status.code(), Some(1));
String::from_utf8(output.stdout).unwrap()
};
let plain = diff(&["--hierarchy", "mermaid"]);
let colored = diff(&["--hierarchy", "mermaid", "--color=always"]);
for span in [
"\x1b[31m- obsolete",
"\x1b[32m+ new",
"\x1b[33m* CHIP",
"\x1b[31m-2 refs",
"\x1b[32m+3 refs",
"\x1b[33m1 polygon changed",
] {
assert!(colored.contains(span), "{span:?} in {colored:?}");
}
let strip_ansi = |text: &str| {
let mut parts = text.split("\x1b[");
let mut plain = parts.next().unwrap().to_string();
for part in parts {
let (code, text) = part.split_once('m').unwrap();
assert!(code.bytes().all(|b| b.is_ascii_digit() || b == b';'));
plain.push_str(text);
}
plain
};
assert_eq!(strip_ansi(&colored), plain);
assert_eq!(diff(&["--hierarchy", "mermaid", "--color", "never"]), plain);
assert_eq!(
colored.split_once("```mermaid\n").unwrap().1,
plain.split_once("```mermaid\n").unwrap().1
);
assert_eq!(
diff(&["--color", "always", "--format", "json"]),
diff(&["--format", "json"])
);
for (options, token) in [
(&[][..], "\x1b[36mcell \"CHIP\""),
(&["--records"][..], "\x1b[36mBGNSTR"),
] {
let dump = |choice| {
let output = command()
.arg("dump")
.arg(&old)
.args(options)
.args(["--color", choice])
.output()
.unwrap();
assert!(output.status.success());
String::from_utf8(output.stdout).unwrap()
};
let colored = dump("always");
assert!(colored.contains(token), "{colored:?}");
assert_eq!(strip_ansi(&colored), dump("auto"));
assert_eq!(dump("auto"), dump("never"));
}
}
#[test]
fn cli_decodes_gzip_by_header_and_checks_the_trailer() {
let directory = std::env::temp_dir().join(format!("pheon gzip {}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
struct Cleanup(PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
let _cleanup = Cleanup(directory.clone());
let plain = directory.join("plain.gds");
let compressed = directory.join("compressed.gds");
let data = shared(square());
// Splitting a record between gzip members must preserve the decompressed layout.
let mut encoded = [gzip(&data[..7]), gzip(&data[7..])].concat();
fs::write(&plain, &data).unwrap();
fs::write(&compressed, &encoded).unwrap();
let command = || Command::new(env!("CARGO_BIN_EXE_pheon"));
let dump = |path: &PathBuf| {
let output = command()
.arg("dump")
.arg(path)
.arg("--records")
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
output.stdout
};
assert_eq!(dump(&plain), dump(&compressed));
let compare = || {
let output = command()
.arg("diff")
.arg(&plain)
.arg(&compressed)
.args(["--format", "json"])
.output()
.unwrap();
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
(output.status.code(), report)
};
let (code, report) = compare();
assert_eq!(code, Some(0));
assert_eq!(report["result"], "equal");
// Corrupt the last CRC after all the GDSII bytes have already been decoded.
let crc = encoded.len() - 8;
encoded[crc] ^= 0xff;
fs::write(&compressed, encoded).unwrap();
let (code, report) = compare();
assert_eq!(code, Some(2));
assert_eq!(report["status"], "failed");
let diagnostic = &report["diagnostics"][0];
assert_eq!(diagnostic["code"], "invalid_input");
assert_eq!(diagnostic["side"], "new");
assert!(
diagnostic["message"]
.as_str()
.unwrap()
.contains("gzip decompression failed")
);
}
#[test]
fn metadata_writer_preserves_unrelated_bytes_and_consolidates_updates() {
use pheon::review::names::write_layer_names;
use std::collections::BTreeMap;
let mut bytes = shared(with_property(square(), "keep this"));
bytes.extend_from_slice(&[0; 32]);
let updates = BTreeMap::from([
((1, 0), "WG".to_string()),
((2, 3), "HEATER:draw".to_string()),
]);
let output = write_layer_names(&bytes, "CHIP", (900, 7), &updates).unwrap();
let doc = Document::parse(&output).unwrap();
assert_eq!(doc.layer_names, updates);
let meta: Vec<_> = doc.cells["CHIP"]
.objects
.iter()
.filter(|o| o.layer == Some((900, 7)))
.collect();
let start = meta.iter().map(|o| o.offset).min().unwrap();
let end = meta.iter().map(|o| o.end_offset).max().unwrap();
assert_eq!([&output[..start], &output[end..]].concat(), bytes);
let updated = write_layer_names(
&output,
"CHIP",
(900, 7),
&BTreeMap::from([((1, 0), "CORE".to_string())]),
)
.unwrap();
let parsed = Document::parse(&updated).unwrap();
assert_eq!(parsed.layer_names[&(1, 0)], "CORE");
assert_eq!(parsed.layer_names[&(2, 3)], "HEATER:draw");
assert_eq!(
parsed.cells["CHIP"]
.objects
.iter()
.filter(|o| o.layer == Some((900, 7)))
.count(),
3
);
let diff = Comparison::between(&Document::parse(&output).unwrap(), &parsed);
assert!(diff.cells.is_empty());
assert_eq!(diff.layer_names.len(), 1);
assert_eq!(
write_layer_names(&updated, "CHIP", (900, 7), &BTreeMap::new()).unwrap(),
updated
);
}
#[test]
fn metadata_writer_rejects_ambiguous_carriers_versions_and_bad_names() {
use pheon::review::names::{parse_layer_name, write_layer_names};
use std::collections::BTreeMap;
let bytes = layout(&[("CHIP", vec![label((900, 7), "ordinary label")])]);
assert!(
write_layer_names(&bytes, "CHIP", (900, 7), &BTreeMap::new())
.unwrap_err()
.contains("ordinary design")
);
assert!(
write_layer_names(&bytes, "missing", (901, 7), &BTreeMap::new())
.unwrap_err()
.contains("does not exist")
);
let bytes = layout(&[("CHIP", vec![label((900, 7), "PHEON_LAYER_NAMES_V2")])]);
assert!(
write_layer_names(&bytes, "CHIP", (901, 7), &BTreeMap::new())
.unwrap_err()
.contains("unsupported")
);
let bytes = layout(&[("CHIP", vec![square()])]);
for value in ["".to_string(), "bad\0name".to_string(), "x".repeat(65536)] {
assert!(
write_layer_names(&bytes, "CHIP", (901, 7), &BTreeMap::from([((1, 0), value)]))
.is_err()
);
}
for text in ["+1:0:name", "1:-1:name", "1:0:", "65536:0:name"] {
assert!(parse_layer_name(text).is_err());
}
}
#[test]
fn metadata_cli_creates_a_separate_file_and_refuses_existing_output() {
let directory = std::env::temp_dir().join(format!("pheon-metadata-{}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
let source = directory.join("source.gds.gz");
let output = directory.join("output.gds");
let bytes = gzip(&shared(square()));
fs::write(&source, &bytes).unwrap();
let _ = fs::remove_file(&output);
let mut command = Command::new(env!("CARGO_BIN_EXE_pheon"));
command.arg("name-layers").arg(&source).arg(&output).args([
"--cell",
"CHIP",
"--carrier",
"900/7",
"--name",
"1:0:WG",
]);
let result = command.output().unwrap();
assert!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stderr)
);
assert_eq!(fs::read(&source).unwrap(), bytes);
let generated = fs::read(&output).unwrap();
assert_eq!(
Document::parse(&generated).unwrap().layer_names[&(1, 0)],
"WG"
);
assert_eq!(command.output().unwrap().status.code(), Some(2));
assert_eq!(fs::read(&output).unwrap(), generated);
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn scope_selection_distinguishes_reachable_subtrees_from_exact_cells() {
use pheon::review::selection::Scope;
let a = layout(&[
("CHIP", vec![reference("leaf", 0, 1)]),
("leaf", vec![square()]),
("unused", vec![square()]),
]);
let b = layout(&[
("CHIP", vec![reference("leaf", 0, 1)]),
("leaf", vec![triangle()]),
("unused", vec![triangle()]),
]);
let top = Scope {
top: Some("CHIP".to_string()),
..Scope::default()
};
let old = Document::parse(&a).unwrap().selected(&top, false).unwrap();
let new = Document::parse(&b).unwrap().selected(&top, false).unwrap();
assert_eq!(
old.cells.keys().map(String::as_str).collect::<Vec<_>>(),
["CHIP", "leaf"]
);
assert_eq!(Comparison::between(&old, &new).cells.len(), 1);
assert!(old.canonical_dump().contains("Scope top=\"CHIP\"\n"));
let cell = Scope {
cell: Some("CHIP".to_string()),
..Scope::default()
};
let old = Document::parse(&a).unwrap().selected(&cell, false).unwrap();
let new = Document::parse(&b).unwrap().selected(&cell, false).unwrap();
assert!(old.diagnostics.is_empty());
assert!(Comparison::between(&old, &new).outcome().is_equal());
let missing = Scope {
top: Some("missing".to_string()),
..Scope::default()
};
assert!(
Document::parse(&a)
.unwrap()
.selected(&missing, false)
.is_err()
);
let wrong = Scope {
top: Some("CHIP".to_string()),
cell: Some("unused".to_string()),
layer: None,
};
assert!(
wrong
.validate_pair(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap())
.is_err()
);
}
#[test]
fn layer_scope_filters_geometry_and_references_by_descendant_coverage() {
use pheon::review::selection::Scope;
let mut other_layer = square();
other_layer[8..10].copy_from_slice(&2_u16.to_be_bytes());
let a = layout(&[
(
"CHIP",
vec![reference("wg", 0, 1), reference("heater", 0, 1)],
),
("wg", vec![square()]),
("heater", vec![other_layer.clone()]),
]);
let b = layout(&[
(
"CHIP",
vec![reference("wg", 0, 1), reference("heater", 5, 1)],
),
("wg", vec![square()]),
("heater", vec![other_layer]),
]);
for (layer, expected) in [((1, 0), 0), ((2, 0), 1)] {
let scope = Scope {
layer: Some(layer),
..Scope::default()
};
let old = Document::parse(&a)
.unwrap()
.selected(&scope, false)
.unwrap();
let new = Document::parse(&b)
.unwrap()
.selected(&scope, false)
.unwrap();
assert_eq!(
Comparison::between(&old, &new).outcome().exit_code(),
expected
);
assert!(old.diagnostics.is_empty());
}
}
#[test]
fn scoped_issues_do_not_hide_relevant_unsupported_objects_or_cycles() {
use pheon::review::selection::Scope;
let mut unknown = square();
unknown.truncate(unknown.len() - 4);
record(&mut unknown, 0x7f00, &[]);
record(&mut unknown, RTAG_ENDEL, &[]);
let bytes = layout(&[("CHIP", vec![square()]), ("unused", vec![unknown])]);
let scope = Scope {
cell: Some("CHIP".to_string()),
..Scope::default()
};
assert!(
Document::parse(&bytes)
.unwrap()
.selected(&scope, false)
.unwrap()
.diagnostics
.is_empty()
);
let scope = Scope {
cell: Some("unused".to_string()),
..Scope::default()
};
assert!(
!Document::parse(&bytes)
.unwrap()
.selected(&scope, false)
.unwrap()
.diagnostics
.is_empty()
);
let bytes = layout(&[
("a", vec![reference("b", 0, 1)]),
("b", vec![reference("a", 0, 1)]),
]);
let scope = Scope {
layer: Some((999, 0)),
..Scope::default()
};
assert!(
Document::parse(&bytes)
.unwrap()
.selected(&scope, false)
.unwrap()
.diagnostics
.iter()
.any(|d| d.code == "hierarchy_cycle")
);
}
#[test]
fn display_filters_never_change_equality_or_totals() {
use pheon::review::selection::DisplayFilter;
let a = layout(&[("CHIP", vec![square()])]);
let b = layout(&[("CHIP", vec![triangle()])]);
let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap());
let text = diff.text_filtered(
100,
&DisplayFilter {
cell: None,
layer: Some((42, 0)),
},
);
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("Cells:\n"));
assert_eq!(diff.outcome().exit_code(), 1);
}
#[test]
fn text_hides_empty_headings_and_counts_filtered_and_limited_changes() {
use pheon::review::selection::DisplayFilter;
let mut attributes = Vec::new();
record(&mut attributes, RTAG_STRCLASS, &[0, 1]);
let a = layout(&[
("changed", vec![square()]),
("other", vec![square()]),
(
"gone",
vec![square(), triangle(), reference("target", 0, 1)],
),
("header", vec![]),
("target", vec![]),
]);
let b = layout(&[
("changed", vec![triangle()]),
("other", vec![triangle()]),
("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.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(
1,
&DisplayFilter {
cell: Some("changed".to_string()),
layer: Some((1, 0)),
},
);
assert!(text.contains(concat!(
"Display filter cell=\"changed\" layer=1/0\n",
"Omitted · 2 object changes filtered out · 2 object changes over the limit",
" · 4 cell-level changes filtered out\n",
)));
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]
fn reference_summaries_group_repeated_targets_and_keep_full_placements_in_dumps() {
let empty = layout(&[("leaf", vec![]), ("other", vec![])]);
let with_chip = layout(&[
(
"CHIP",
vec![
square(),
label((2, 0), "chip label"),
label((900, 7), LAYER_SENTINEL),
label((900, 7), "3:0:WG"),
reference("leaf", 0, 1),
reference("leaf", 5, 1),
reference("leaf", 2, 2),
reference("other", 10, 1),
],
),
("leaf", vec![]),
("other", vec![]),
]);
let existing_chip = layout(&[("CHIP", vec![]), ("leaf", vec![]), ("other", vec![])]);
let empty = Document::parse(&empty).unwrap();
let with_chip = Document::parse(&with_chip).unwrap();
let existing_chip = Document::parse(&existing_chip).unwrap();
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.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"));
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));
}
for show in [
DisplayFilter::default(),
DisplayFilter {
cell: Some("other".into()),
layer: None,
},
DisplayFilter {
cell: None,
layer: Some((1, 0)),
},
] {
for max in [0, 2, 100] {
assert_eq!(
text_diff.render_text(max, &show, true),
diff.text_filtered(max, &show)
);
}
}
}
for (old, new, sign) in [
(&existing_chip, &with_chip, "+"),
(&with_chip, &existing_chip, "-"),
] {
let text = Comparison::between(old, new).text(100);
assert!(text.contains(&format!(
" {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")));
}
let dump = with_chip.canonical_dump();
assert!(dump.contains(" reference \"leaf\" xy=(5, 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]\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!(
"pheon-git-review-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&directory).unwrap();
let inherited_path = std::env::var_os("PATH").unwrap_or_default();
let git_path = std::env::join_paths(
std::iter::once(
PathBuf::from(env!("CARGO_BIN_EXE_pheon"))
.parent()
.unwrap()
.to_path_buf(),
)
.chain(std::env::split_paths(&inherited_path)),
)
.unwrap();
let git = |args: &[&str]| {
let result = Command::new("git")
.env("PATH", &git_path)
.arg("-C")
.arg(&directory)
.args(args)
.output()
.unwrap();
assert!(
result.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&result.stderr)
);
result
};
git(&["init", "-q"]);
git(&["config", "user.name", "Review Fixture"]);
git(&["config", "user.email", "fixture@example.invalid"]);
git(&["config", "commit.gpgsign", "false"]);
git(&["config", "core.hooksPath", "/dev/null"]);
git(&[
"config",
"include.path",
concat!(env!("CARGO_MANIFEST_DIR"), "/contrib/git/config"),
]);
assert_eq!(
String::from_utf8(git(&["config", "--get", "diff.pheon.trustExitCode"]).stdout)
.unwrap()
.trim(),
"false"
);
fs::write(
directory.join(".gitattributes"),
include_str!("../contrib/git/attributes"),
)
.unwrap();
let path = directory.join("chip layout.gds");
fs::write(&path, layout(&[("CHIP", vec![square()])])).unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "baseline"]);
fs::write(&path, layout(&[("CHIP", vec![triangle()])])).unwrap();
let changed = git(&["diff", "--", "chip layout.gds"]);
assert!(
String::from_utf8(changed.stdout)
.unwrap()
.contains("Different\nCells:\n* CHIP\n")
);
fs::write(&path, b"invalid").unwrap();
let invalid = Command::new("git")
.env("PATH", &git_path)
.arg("-C")
.arg(&directory)
.args(["diff", "--", "chip layout.gds"])
.output()
.unwrap();
assert!(!invalid.status.success());
assert!(String::from_utf8_lossy(&invalid.stderr).contains("pheon:"));
fs::write(&path, layout(&[("CHIP", vec![square()])])).unwrap();
let mode_change = Command::new(env!("CARGO_BIN_EXE_pheon"))
.args(["git-diff", "--hierarchy", "ascii", "--", "chip layout.gds"])
.arg(&path)
.args(["old", "100644"])
.arg(&path)
.args(["new", "100755"])
.output()
.unwrap();
assert!(mode_change.status.success());
assert_eq!(
mode_change.stdout,
b"layout \"chip layout.gds\"\nmode \"100644\" -> \"100755\"\nEqual\n"
);
let added = directory.join("added layout.gds");
fs::write(&added, shared(square())).unwrap();
git(&["add", "added layout.gds"]);
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_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"]);
let renamed = directory.join("renamed layout.gds");
fs::write(&renamed, shared(triangle())).unwrap();
git(&["add", "renamed layout.gds"]);
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\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();
let result = git(&["diff", "--", "renamed layout.gds"]);
assert!(
String::from_utf8(result.stdout)
.unwrap()
.contains("- 1/0: polygon")
);
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn replacement_explanations_are_unique_and_keep_full_evidence() {
for pair in corpus().into_iter().filter(|p| {
[
"same bounds different geometry",
"moved reference",
"array count",
]
.contains(&p.name)
}) {
let old = Document::parse(&pair.old).unwrap();
let new = Document::parse(&pair.new).unwrap();
let diff = Comparison::between(&old, &new);
assert_eq!(diff.cells[0].replacements.len(), 1);
let text = diff.text(100);
match pair.name {
"moved reference" => {
assert!(text.contains(" ~ reference \"leaf\" moved by (5, 0) dbu\n"))
}
"array count" => {
assert!(text.contains(" ~ array reference \"leaf\" columns/rows 2 x 1 -> 3 x 1\n"))
}
_ => assert_eq!(text, include_str!("golden/review-diff.txt")),
}
assert!(!text.contains(" - "));
assert!(!text.contains(" + "));
assert!(!text.contains("bbox="));
assert!(!diff.text(0).contains(" ~ "));
assert_eq!(
diff.text(1),
"Different · 1 cell modified\nOmitted · 2 object changes over the limit\n"
);
}
let a = layout(&[("CHIP", vec![square(), square()])]);
let b = layout(&[("CHIP", vec![triangle(), triangle()])]);
let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap());
assert!(diff.cells[0].replacements.is_empty());
let text = diff.text(100);
assert!(text.contains(" 1/0: 2 rectangles removed · 2 polygons added\n"));
assert!(!text.contains("bbox="));
assert!(!text.contains("xy="));
}
#[test]
fn polygon_diff_reports_single_displacements_and_groups_bulk_moves() {
let before = layout(&[("CHIP", vec![with_property(square(), "old")])]);
let before = Document::parse(&before).unwrap();
for (shape, label) in [
(
polygon(&[[-5, 2], [5, 2], [5, 12], [-5, 12], [-5, 2]]),
"1 rectangle changed",
),
(
polygon(&[[0, 0], [20, 0], [20, 10], [0, 10], [0, 0]]),
"1 rectangle changed",
),
(
polygon(&[[5, 0], [10, 5], [5, 10], [0, 5], [5, 0]]),
"1 polygon changed",
),
(square(), "1 rectangle changed"),
] {
let after = layout(&[("CHIP", vec![with_property(shape, "new")])]);
let after = Document::parse(&after).unwrap();
let diff = Comparison::between(&before, &after);
let text = diff.text(100);
assert!(text.contains(&format!(" 1/0: {label}\n")), "{text}");
assert!(!text.contains("dbu"));
assert!(!text.contains("bbox="));
assert!(!text.contains("xy="));
}
let moved_triangle = polygon(&[[2, -1], [12, -1], [2, 9], [2, -1]]);
let moved_square = polygon(&[[2, -1], [12, -1], [12, 9], [2, 9], [2, -1]]);
let named_layout = |mut objects: Vec<Vec<u8>>| {
objects.extend([label((900, 7), LAYER_SENTINEL), label((900, 7), "1:0:WG")]);
layout(&[("CHIP", objects)])
};
for (shape, shifted, name) in [
(triangle(), moved_triangle, "polygon"),
(square(), moved_square.clone(), "rectangle"),
(
ring(
RTAG_BOX,
RTAG_BOXTYPE,
1,
&[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]],
),
ring(
RTAG_BOX,
RTAG_BOXTYPE,
1,
&[[2, -1], [12, -1], [12, 9], [2, 9], [2, -1]],
),
"box",
),
] {
let before = named_layout(vec![shape]);
let after = named_layout(vec![shifted]);
let diff = Comparison::between(
&Document::parse(&before).unwrap(),
&Document::parse(&after).unwrap(),
);
assert!(
diff.text(100)
.contains(&format!(" 1/0 (WG): {name} moved by (2, -1) dbu\n"))
);
}
let before = named_layout(vec![square()]);
let after = named_layout(vec![
moved_square,
ring(
RTAG_BOX,
RTAG_BOXTYPE,
1,
&[[20, 0], [30, 0], [30, 10], [20, 10], [20, 0]],
),
]);
let diff = Comparison::between(
&Document::parse(&before).unwrap(),
&Document::parse(&after).unwrap(),
);
assert!(
diff.text(100)
.contains(" 1/0 (WG): 1 rectangle moved · 1 box added\n")
);
assert!(
diff.text(2)
.contains(" 1/0 (WG): rectangle moved by (2, -1) dbu\n")
);
}
#[test]
fn polygon_diff_groups_shapes_by_layer_across_dimensions() {
let shapes = [
square(),
polygon(&[[30, 0], [50, 0], [50, 5], [30, 5], [30, 0]]),
polygon(&[[70, 0], [80, 0], [71, 9], [70, 0]]),
ring(
RTAG_BOUNDARY,
RTAG_DATATYPE,
2,
&[[0, 0], [10, 0], [0, 10], [0, 0]],
),
];
let layout_with_property = |value| {
let objects = shapes
.iter()
.map(|shape| with_property(shape.clone(), value))
.collect();
layout(&[("CHIP", objects)])
};
let before = layout_with_property("old");
let after = layout_with_property("new");
let diff = Comparison::between(
&Document::parse(&before).unwrap(),
&Document::parse(&after).unwrap(),
);
assert_eq!(
diff.text(100),
concat!(
"Different\n",
"Cells:\n* CHIP\n",
" 1/0: 2 rectangles, 1 polygon changed\n",
" 2/0: 1 polygon changed\n",
)
);
}
#[test]
fn polygon_diff_distinguishes_boxes_from_rectangular_boundaries() {
let before = layout(&[("CHIP", vec![square()])]);
let points = [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]];
let after = layout(&[("CHIP", vec![ring(RTAG_BOX, RTAG_BOXTYPE, 1, &points)])]);
let diff = Comparison::between(
&Document::parse(&before).unwrap(),
&Document::parse(&after).unwrap(),
);
let text = diff.text(100);
assert!(text.contains(" 1/0: 1 rectangle removed · 1 box added\n"));
}
#[test]
fn path_width_explanation_preserves_absent_and_zero() {
let points = [[0, 0], [10, 10]];
let a = layout(&[("CHIP", vec![path(None, &points)])]);
let b = layout(&[("CHIP", vec![path(Some(0), &points)])]);
let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap());
assert!(
diff.text(100)
.contains(" ~ 1/0: path width absent -> 0 dbu\n")
);
}
#[test]
fn unmatched_paths_summarize_coordinates_that_would_wrap() {
let points = [[0, 0], [4, 0], [4, -5], [13, -5], [13, 9]];
let empty = layout(&[("CHIP", vec![])]);
let paths = layout(&[(
"CHIP",
vec![
path(None, &points),
path(Some(-8), &points),
path(Some(0), &points[..4]),
],
)]);
let empty = Document::parse(&empty).unwrap();
let paths = Document::parse(&paths).unwrap();
for (old, new, sign) in [(&empty, &paths, "+"), (&paths, &empty, "-")] {
let text = Comparison::between(old, new).text(100);
for width in ["absent", "-8 dbu"] {
assert!(text.contains(&format!(
" {sign} 1/0: path · width {width} · 5 vertices · bounds (0, -5) to (13, 9) dbu\n"
)));
}
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)]"));
let report =
Comparison::between(&empty, &paths).json_report(&Default::default(), &Default::default());
assert!(
report["cell_changes"][0]["added"]
.as_array()
.unwrap()
.iter()
.flat_map(|object| object["fields"].as_array().unwrap())
.any(|field| field["tag"] == RTAG_XY && field["value"] == serde_json::json!(points))
);
}
#[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]
fn label_replacements_show_only_changed_fields() {
let a = layout(&[("CHIP", vec![label((2, 0), "old")])]);
let b = layout(&[("CHIP", vec![label((2, 0), "new")])]);
let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap());
assert_eq!(
diff.text(100),
"Different\nCells:\n* CHIP\n ~ 2/0: label text \"old\" -> \"new\"\n"
);
}
#[test]
fn unchanged_layer_names_explain_geometry_changes_once() {
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 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")
.unwrap();
let old = Document::parse(&names.old).unwrap();
let new = Document::parse(&names.new).unwrap();
assert!(
Comparison::between(&old, &new)
.text(0)
.contains("1/0: name \"WG\" -> \"CORE:WG\"")
);
}
#[test]
fn library_presence_changes_distinguish_empty_and_absent_revisions() {
let bytes = layout(&[]);
let doc = Document::parse(&bytes).unwrap();
let absent = doc.empty_like();
let added = Comparison::between(&absent, &doc);
assert_eq!(added.outcome().exit_code(), 1);
assert!(added.text(0).contains("library added\n"));
assert!(added.text(0).starts_with("Different · 1 library change\n"));
assert_eq!(
added.render_text(0, &Default::default(), false),
"Different\n"
);
let removed = Comparison::between(&doc, &absent);
assert_eq!(removed.outcome().exit_code(), 1);
assert!(removed.text(0).contains("library removed\n"));
}
#[test]
fn cli_scope_and_display_filters_have_distinct_exit_behavior() {
let directory = std::env::temp_dir().join(format!("pheon-scope-{}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
let old = directory.join("old.gds");
let new = directory.join("new.gds");
fs::write(&old, shared(square())).unwrap();
fs::write(&new, shared(triangle())).unwrap();
for (options, expected) in [
(vec!["--cell", "CHIP"], 0),
(vec!["--top", "CHIP"], 1),
(vec!["--layer", "99/0"], 0),
(vec!["--show-cell", "missing"], 1),
(vec!["--show-layer", "99/0"], 1),
(vec!["--top", "missing"], 2),
] {
let output = Command::new(env!("CARGO_BIN_EXE_pheon"))
.arg("diff")
.args(&options)
.arg(&old)
.arg(&new)
.output()
.unwrap();
assert_eq!(
output.status.code(),
Some(expected),
"{options:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
}
fs::write(&old, layout(&[])).unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_pheon"))
.args(["diff", "--top", "CHIP"])
.arg(&old)
.arg(&new)
.output()
.unwrap();
assert_eq!(output.status.code(), Some(1));
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn large_polygons_and_billion_instance_arrays_stay_compact() {
let mut points = vec![[0, 0], [0, 1]];
points.extend((1..8187).map(|x| [x, 1]));
points.extend([[8186, 0], [0, 0]]);
let mut array = Vec::new();
record(&mut array, RTAG_AREF, &[]);
ascii(&mut array, RTAG_SNAME, "leaf");
record(&mut array, RTAG_COLROW, &[0x7f, 0xff, 0x7f, 0xff]);
xy(&mut array, &[[0, 0], [32767, 0], [0, 32767]]);
record(&mut array, RTAG_ENDEL, &[]);
let bytes = layout(&[("CHIP", vec![array]), ("leaf", vec![polygon(&points)])]);
let doc = Document::parse(&bytes).unwrap();
assert_eq!(
doc.edges()[&("CHIP".to_string(), "leaf".to_string())],
32767 * 32767
);
assert_eq!(doc.cells["CHIP"].objects.len(), 1);
assert!(doc.hierarchy(false, 8).len() < 200);
assert!(Comparison::between(&doc, &doc).outcome().is_equal());
}
#[test]
fn deep_hierarchy_comparison_and_rendering_are_iterative() {
let names: Vec<_> = (0..2048).map(|i| format!("cell_{i}")).collect();
let cells = |leaf: Vec<u8>| {
names
.iter()
.enumerate()
.map(|(i, name)| {
(
name.as_str(),
if i + 1 == names.len() {
vec![leaf.clone()]
} else {
vec![reference(&names[i + 1], 0, 1)]
},
)
})
.collect::<Vec<_>>()
};
let a = layout(&cells(square()));
let b = layout(&cells(triangle()));
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
let tree = diff.hierarchy(false, 5);
assert_eq!(diff.cells.len(), 1);
assert!(tree.contains("children omitted"));
assert!(tree.len() < 500);
}