mod common; use common::{library_header, record}; use klamath_rs_ext::{ records::*, review::{Comparison, Document, LAYER_SENTINEL, hierarchy}, }; use std::{fs, path::PathBuf, process::Command}; fn ascii(bytes: &mut Vec, 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, points: &[[i32; 2]]) { record( bytes, RTAG_XY, &points .iter() .flatten() .flat_map(|v| v.to_be_bytes()) .collect::>(), ); } fn layout(cells: &[(&str, Vec>)]) -> Vec { 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 polygon(points: &[[i32; 2]]) -> Vec { let mut bytes = Vec::new(); record(&mut bytes, RTAG_BOUNDARY, &[]); record(&mut bytes, RTAG_LAYER, &1_u16.to_be_bytes()); record(&mut bytes, RTAG_DATATYPE, &0_u16.to_be_bytes()); xy(&mut bytes, points); record(&mut bytes, RTAG_ENDEL, &[]); bytes } fn square() -> Vec { polygon(&[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]) } fn triangle() -> Vec { polygon(&[[0, 0], [10, 0], [0, 10], [0, 0]]) } fn reference(target: &str, x: i32, count: i16) -> Vec { 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 { 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 with_property(mut object: Vec, value: &str) -> Vec { 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) -> Vec { 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, new: Vec, changed_cells: usize, removed: usize, added: usize, metadata: usize, } // Ten deliberately small fixture pairs specify the first object profile. fn corpus() -> Vec { 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.issues.is_empty(), "{}: {:?}", pair.name, diff.issues); assert_eq!(diff.cells.len(), pair.changed_cells, "{}", pair.name); assert_eq!( diff.cells.iter().map(|c| c.removed.len()).sum::(), pair.removed, "{}", pair.name ); assert_eq!( diff.cells.iter().map(|c| c.added.len()).sum::(), 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.is_equal(), equal, "{}", pair.name); assert_eq!( old.canonical_dump() == new.canonical_dump(), equal, "{}", pair.name ); assert_eq!(diff.exit_code(), if equal { 0 } else { 1 }); } } #[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 BOUNDARY layer=1 datatype=0 xy=[0, 0, 0, 10, 10, 10, 10, 0, 0, 0]\n" ), "{dump}" ); assert!(!dump.contains("BGNSTR")); assert!( doc.record_dump() .contains("0000000000 0002 HEADER size=6 [600]") ); assert!(doc.record_dump().contains("BGNSTR")); } #[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!( hierarchy(&a, &b, Some(&diff), false, 8), include_str!("golden/review-hierarchy.txt") ); assert_eq!( hierarchy(&a, &b, Some(&diff), 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!(Comparison::between(&a, &b).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!( klamath_rs_ext::review::dump_records(&conflicts) .unwrap() .contains("1:0:B") ); let future = layout(&[("CHIP", vec![label((9, 0), "KLAMATH_LAYER_NAMES_V2")])]); let future = Document::parse(&future).unwrap(); assert_eq!(Comparison::between(&future, &future).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.is_equal()); assert_eq!(diff.exit_code(), 2); assert!(doc.record_dump().contains("7f00")); assert!(diff.text(0).contains("INCOMPLETE")); } #[test] fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() { 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!( hierarchy(&a, &b, Some(&diff), false, 8), concat!( "scope top=all cell=all layer=all\n", "\"CHIP\" x1 [affected]\n", " \"left\" x1 [affected]\n", " \"leaf\" x2 [cell changed]\n", " \"right\" x1 [affected]\n", " \"leaf\" x3 [cell changed] [shown above]\n", ) ); let graph = hierarchy(&a, &b, Some(&diff), true, 8); assert_eq!(graph.matches("leaf [cell changed]").count(), 1); assert!(graph.contains("x2")); assert!(graph.contains("x3")); let limited = hierarchy(&a, &b, Some(&diff), false, 1); assert!(!limited.contains("\"leaf\"")); assert!(limited.contains("children omitted")); } #[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 = hierarchy(&old, &new, Some(&diff), false, 8); assert!(tree.contains("[cell unchanged]"), "{tree}"); assert!(tree.contains("[reference changed]"), "{tree}"); if pair.name == "array count" { assert!(tree.contains("x2 -> x3"), "{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(); let tree = hierarchy(&a, &b, Some(&Comparison::between(&a, &b)), false, 8); assert!(tree.contains("\"leaf\" x1 -> x0"), "{tree}"); } #[test] fn same_bounds_changes_and_truncated_reports_remain_differences() { let a = layout(&[("CHIP", vec![square()])]); let b = layout(&[("CHIP", vec![triangle()])]); 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 ); assert!(diff.text(0).contains("0 of 2 object changes shown")); assert_eq!(diff.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( &klamath_rs_ext::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.exit_code(), 1); assert_eq!(diff.library_fields.len(), 1); assert_eq!(diff.library_fields[0].field, "UNITS"); assert!(diff.text(0).contains("UNITS changed")); assert!(diff.cells.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 .issues .iter() .any(|s| s.contains("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.issues.iter().any(|s| s.contains("cyclic"))); assert!(hierarchy(&cycle, &cycle, None, 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()) .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::>(); rotated.push(rotated[0]); let candidate = layout(&[("CHIP", vec![polygon(&rotated)])]); let candidate = Document::parse(&candidate).unwrap(); assert!(Comparison::between(&baseline, &candidate).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!("klamath 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_klamath")); let equal = command().arg("diff").arg(&old).arg(&old).output().unwrap(); assert_eq!(equal.status.code(), Some(0)); 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("0 of 2 object changes shown")); assert!(text.contains("```mermaid\nflowchart TD")); 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") ); fs::write(&new, b"invalid").unwrap(); assert_eq!( command() .arg("diff") .arg(&old) .arg(&new) .output() .unwrap() .status .code(), Some(2) ); } #[test] fn metadata_writer_preserves_unrelated_bytes_and_consolidates_updates() { use klamath_rs_ext::review::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 klamath_rs_ext::review::{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), "KLAMATH_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!("klamath-metadata-{}", std::process::id())); fs::create_dir_all(&directory).unwrap(); let source = directory.join("source.gds"); let output = directory.join("output.gds"); let bytes = shared(square()); fs::write(&source, &bytes).unwrap(); let _ = fs::remove_file(&output); let mut command = Command::new(env!("CARGO_BIN_EXE_klamath")); 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 klamath_rs_ext::review::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::>(), ["CHIP", "leaf"] ); assert_eq!(Comparison::between(&old, &new).cells.len(), 1); assert!(old.canonical_dump().contains("scope top=\"CHIP\"")); 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.issues.is_empty()); assert!(Comparison::between(&old, &new).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 klamath_rs_ext::review::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).exit_code(), expected); assert!(old.issues.is_empty()); } } #[test] fn scoped_issues_do_not_hide_relevant_unsupported_objects_or_cycles() { use klamath_rs_ext::review::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() .issues .is_empty() ); let scope = Scope { cell: Some("unused".to_string()), ..Scope::default() }; assert!( !Document::parse(&bytes) .unwrap() .selected(&scope, false) .unwrap() .issues .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() .issues .iter() .any(|s| s.contains("cyclic")) ); } #[test] fn display_filters_never_change_equality_or_totals() { use klamath_rs_ext::review::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.contains("display-only")); assert!(text.contains("0 of 2 object changes shown")); assert_eq!(diff.exit_code(), 1); } #[test] fn git_external_driver_handles_changes_additions_deletions_and_errors() { let directory = std::env::temp_dir().join(format!( "klamath-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_klamath")) .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.klamath.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("2 of 2 object changes shown") ); 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("klamath:")); fs::write(&path, layout(&[("CHIP", vec![square()])])).unwrap(); 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"]); assert!( String::from_utf8(result.stdout) .unwrap() .contains("layout added") ); fs::remove_file(&path).unwrap(); git(&["add", "-u"]); let result = git(&["diff", "--cached", "--", "chip layout.gds"]); assert!( String::from_utf8(result.stdout) .unwrap() .contains("layout deleted") ); // 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("2 of 2 object changes shown"), "{text}"); git(&["commit", "-qm", "rename fixture"]); fs::write( directory.join(".gitattributes"), "*.gds diff=klamath-text\n", ) .unwrap(); fs::write(&renamed, shared(square())).unwrap(); let result = git(&["diff", "--", "renamed layout.gds"]); assert!( String::from_utf8(result.stdout) .unwrap() .contains("- BOUNDARY") ); 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); assert!(text.contains(" ~ ")); assert!(text.contains(" - @")); assert!(text.contains(" + @")); match pair.name { "moved reference" => assert!(text.contains("delta=(5, 0) dbu")), "array count" => assert!(text.contains("columns/rows 2 x 1 -> 3 x 1")), _ => assert_eq!(text, include_str!("golden/review-diff.txt")), } assert!(!diff.text(0).contains(" ~ ")); assert!(diff.text(1).contains("1 of 2 object changes shown")); } 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()); } #[test] fn path_width_explanation_preserves_absent_and_zero() { let path = |width: Option| { 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(n) = width { record(&mut bytes, RTAG_WIDTH, &n.to_be_bytes()); } xy(&mut bytes, &[[0, 0], [10, 10]]); record(&mut bytes, RTAG_ENDEL, &[]); layout(&[("CHIP", vec![bytes])]) }; let a = path(None); let b = path(Some(0)); let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); assert!(diff.text(100).contains("width absent -> 0 dbu")); } #[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 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("name=\"WG\"").count(), 1); assert!(diff.layer_names.is_empty()); } #[test] fn an_added_empty_document_is_still_a_presence_change() { let bytes = layout(&[]); let doc = Document::parse(&bytes).unwrap(); let diff = Comparison::between(&doc.empty_like(), &doc); assert_eq!(diff.exit_code(), 1); assert!(diff.text(0).contains("library presence:")); assert!(!diff.text(0).contains("equal under")); } #[test] fn cli_scope_and_display_filters_have_distinct_exit_behavior() { let directory = std::env::temp_dir().join(format!("klamath-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_klamath")) .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_klamath")) .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!(hierarchy(&doc, &doc, None, false, 8).len() < 200); assert!(Comparison::between(&doc, &doc).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| { 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::>() }; 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 = hierarchy(&a, &b, Some(&diff), false, 5); assert_eq!(diff.cells.len(), 1); assert!(tree.contains("children omitted")); assert!(tree.len() < 500); }