Make Pheon structural review results self-contained

Capture revision metadata, cell presence and attributes, and structured
diagnostics in owned comparison results. Derive outcomes and render text,
JSON, and hierarchy reports without retaining source documents. Keep derived
descriptions and graph analysis in their renderers.

Use pheon-structural-v1 and PHEON_LAYER_NAMES_V1 consistently, expose helpers
through their defining modules, and remove obsolete re-exports. Update user
guides and report fixtures without changing schema version 1.

Cover dropped inputs, diagnostic ordering, absent and empty cells, offset
independence, and CLI failures. All 92 Rust tests pass in debug and release;
report and hierarchy goldens retain their behavior.
This commit is contained in:
Jan Petykiewicz 2026-11-16 20:45:06 -08:00
commit df62677f5c
21 changed files with 870 additions and 504 deletions

View file

@ -1,6 +1,6 @@
# Comparison rules # Comparison rules
Pheon compares GDSII objects using the `klamath-object-v2` profile. Use it to Pheon compares GDSII objects using the `pheon-structural-v1` profile. Use it to
review exact layout changes while ignoring incidental ordering and timestamps. review exact layout changes while ignoring incidental ordering and timestamps.
The [CLI guide](cli.md) explains how to choose cells and layers. The [CLI guide](cli.md) explains how to choose cells and layers.

View file

@ -1,7 +1,7 @@
{ {
"$schema": "https://json-schema.org/draft/2020-12/schema", "$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Pheon diff report version 1", "title": "Pheon diff report version 1",
"description": "Object-profile comparison evidence, not a layout serialization. Unknown additional fields are permitted for compatible extensions.", "description": "Structural comparison evidence, not a layout serialization. Unknown additional fields are permitted for compatible extensions.",
"type": "object", "type": "object",
"required": ["schema_version", "kind", "producer", "comparison_profile", "inputs", "scope", "coordinates", "status", "result", "exit_code", "summary", "report_selection", "layer_legend", "library_changes", "layer_name_changes", "cell_changes", "hierarchy", "diagnostics"], "required": ["schema_version", "kind", "producer", "comparison_profile", "inputs", "scope", "coordinates", "status", "result", "exit_code", "summary", "report_selection", "layer_legend", "library_changes", "layer_name_changes", "cell_changes", "hierarchy", "diagnostics"],
"properties": { "properties": {

View file

@ -3,7 +3,7 @@
Use JSON reports to automate layout review while retaining the evidence behind Use JSON reports to automate layout review while retaining the evidence behind
a result. The [comparison rules](comparison.md) define equality; the a result. The [comparison rules](comparison.md) define equality; the
[version 1 JSON Schema](diff-report-v1.schema.json) defines every field. [version 1 JSON Schema](diff-report-v1.schema.json) defines every field.
A [complete example](../tests/golden/report-geometry.json) shows geometry changes. A [complete example](https://mpxd.net/code/jan/pheon/src/branch/master/tests/golden/report-geometry.json) shows geometry changes.
```sh ```sh
pheon diff before.gds after.gds --format json > report.json pheon diff before.gds after.gds --format json > report.json
@ -114,7 +114,7 @@ object limits, and text depth do not trim the graph.
## Versions ## Versions
`schema_version` is 1, `comparison_profile` is `klamath-object-v2`, and `schema_version` is 1, `comparison_profile` is `pheon-structural-v1`, and
`producer.name` is `pheon`. Structure, equality rules, and producer version evolve `producer.name` is `pheon`. Structure, equality rules, and producer version evolve
independently. Understand the profile before interpreting equality. Consumers independently. Understand the profile before interpreting equality. Consumers
should tolerate additional optional fields and unknown codes/rules without should tolerate additional optional fields and unknown codes/rules without

View file

@ -23,7 +23,7 @@ byte. Input and annotation validation finish before the output is created.
## Annotation format ## Annotation format
A text label whose exact string is `KLAMATH_LAYER_NAMES_V1` identifies a carrier A text label whose exact string is `PHEON_LAYER_NAMES_V1` identifies a carrier
pair in its cell. Every other text label on that pair in the same cell is a pair in its cell. Every other text label on that pair in the same cell is a
mapping of the form: mapping of the form:
@ -33,7 +33,7 @@ layer:datatype:name
For example, `1:0:WG` names pair `(1, 0)` as WG. Numbers are unsigned 16-bit For example, `1:0:WG` names pair `(1, 0)` as WG. Numbers are unsigned 16-bit
decimals. The name must be nonempty UTF-8 and may contain colons; only the first decimals. The name must be nonempty UTF-8 and may contain colons; only the first
two colons separate fields. The legacy marker remains part of the format. two colons separate fields.
Mappings are collected across the library. Identical duplicates are accepted; Mappings are collected across the library. Identical duplicates are accepted;
conflicting names for the same pair are errors. Recognized annotation labels conflicting names for the same pair are errors. Recognized annotation labels

View file

@ -21,6 +21,16 @@ to load only those cells. Each range must span one complete cell. Readers return
`(remainder, StructArray)` on success. The selected reader returns the original `(remainder, StructArray)` on success. The selected reader returns the original
input as its remainder, since selection is random access. input as its remainder, since selection is random access.
Layout-review APIs live in `pheon::review`, with layer-name helpers in
`pheon::review::names` and scope/display selectors in `pheon::review::selection`.
`Comparison::between(&old, &new)` captures an owned result with revision metadata,
changes, and structured diagnostics. Use `outcome()` for completeness, equality,
and exit status. Its `text`, `json_report`, and `hierarchy` renderers work after
the source documents and byte buffers are dropped. Standalone hierarchy inspection
uses `Document::hierarchy`. Reference counts are captured with the result;
union-graph and ancestor analysis run only when a hierarchy is requested.
The `record`, `records`, and `basic` modules also provide low-level GDSII record The `record`, `records`, and `basic` modules also provide low-level GDSII record
writing. There is no high-level writer for the Arrow layout. REAL8 writing is writing. There is no high-level writer for the Arrow layout. REAL8 writing is
exact for representable in-range `f64` values: magnitudes below `2^-260` exact for representable in-range `f64` values: magnitudes below `2^-260`
@ -29,7 +39,7 @@ underflow to zero; magnitudes at least `2^252` and nonfinite values are rejected
## C API ## C API
Build the shared library with `cargo build --release --locked`. The Build the shared library with `cargo build --release --locked`. The
[header](../pheon/_ffi.h) defines the functions and Arrow C Data structures. [header](https://mpxd.net/code/jan/pheon/src/branch/master/pheon/_ffi.h) defines the functions and Arrow C Data structures.
The library is `libpheon.so`, `libpheon.dylib`, or `pheon.dll` on Linux, macOS, The library is `libpheon.so`, `libpheon.dylib`, or `pheon.dll` on Linux, macOS,
or Windows respectively. or Windows respectively.

View file

@ -1,11 +1,12 @@
use pheon::review::report::{ReportInputs, ReportOptions, failure_report}; use pheon::review::report::{ReportInputs, ReportOptions, failure_report};
use pheon::review::{ use pheon::review::{
Comparison, DisplayFilter, Document, Scope, dump_records, hierarchy, parse_layer, Comparison, Diagnostic, Document, Outcome, Side, dump_records,
parse_layer_name, write_layer_names, names::{parse_layer, parse_layer_name, write_layer_names},
selection::{DisplayFilter, Scope},
}; };
use std::{ use std::{
collections::BTreeMap, collections::BTreeMap,
ffi::OsString, ffi::{OsStr, OsString},
fs, fs,
io::{self, Write}, io::{self, Write},
path::PathBuf, path::PathBuf,
@ -18,7 +19,7 @@ const HELP: &str = "Usage:
pheon hierarchy FILE [--format ascii|mermaid] [--depth N] [--top NAME]\n pheon git-diff [OPTIONS] -- PATH OLD OLD_OID OLD_MODE NEW NEW_OID NEW_MODE pheon hierarchy FILE [--format ascii|mermaid] [--depth N] [--top NAME]\n pheon git-diff [OPTIONS] -- PATH OLD OLD_OID OLD_MODE NEW NEW_OID NEW_MODE
pheon name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ... pheon name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ...
Object profile: ignore timestamps and element order, normalize polygon start/winding, Structural comparison: ignore timestamps and element order, normalize polygon start/winding,
preserve duplicates, compare all retained fields exactly. No geometric XOR or tolerance. preserve duplicates, compare all retained fields exactly. No geometric XOR or tolerance.
Exit status: 0 equal/success, 1 different, 2 invalid/unsupported/incomplete. Exit status: 0 equal/success, 1 different, 2 invalid/unsupported/incomplete.
"; ";
@ -93,40 +94,68 @@ fn json_stdout(report: &serde_json::Value) -> Result<(), String> {
output.write_all(b"\n").map_err(|e| e.to_string()) output.write_all(b"\n").map_err(|e| e.to_string())
} }
fn prepare_comparison(
old_path: Option<&OsStr>,
new_path: Option<&OsStr>,
scope: &Scope,
) -> Result<Comparison, Diagnostic> {
let read = |path: Option<&OsStr>, side| {
path.map(|path| {
fs::read(path).map_err(|error| {
Diagnostic::new("io_error", format!("{path:?}: {error}"), Some(side))
})
})
.transpose()
};
let old_bytes = read(old_path, Side::Old)?;
let new_bytes = read(new_path, Side::New)?;
let old = old_bytes
.as_deref()
.map(Document::parse)
.transpose()
.map_err(|message| Diagnostic::new("invalid_input", message, Some(Side::Old)))?;
let new = new_bytes
.as_deref()
.map(Document::parse)
.transpose()
.map_err(|message| Diagnostic::new("invalid_input", message, Some(Side::New)))?;
let (old, new) = match (old, new) {
(Some(old), Some(new)) => (old, new),
(None, Some(new)) => (new.empty_like(), new),
(Some(old), None) => {
let new = old.empty_like();
(old, new)
}
(None, None) => {
return Err(Diagnostic::new(
"invalid_input",
"both Git revisions are absent",
None,
));
}
};
scope
.validate_pair(&old, &new)
.map_err(|message| Diagnostic::new("invalid_scope", message, None))?;
let old = old
.selected(scope, true)
.map_err(|message| Diagnostic::new("invalid_scope", message, Some(Side::Old)))?;
let new = new
.selected(scope, true)
.map_err(|message| Diagnostic::new("invalid_scope", message, Some(Side::New)))?;
Ok(Comparison::between(&old, &new))
}
fn json_diff(paths: &[OsString], scope: &Scope, options: &ReportOptions) -> Result<u8, String> { fn json_diff(paths: &[OsString], scope: &Scope, options: &ReportOptions) -> Result<u8, String> {
let inputs = ReportInputs { let inputs = ReportInputs {
old: Some(PathBuf::from(&paths[0])), old: Some(PathBuf::from(&paths[0])),
new: Some(PathBuf::from(&paths[1])), new: Some(PathBuf::from(&paths[1])),
}; };
let comparison = || { let (report, outcome) = match prepare_comparison(Some(&paths[0]), Some(&paths[1]), scope) {
let read = |index, side| { Ok(diff) => (diff.json_report(&inputs, options), diff.outcome()),
fs::read(&paths[index]) Err(error) => (
.map_err(|e| ("io_error", format!("{:?}: {e}", paths[index]), Some(side))) failure_report(&inputs, scope, options, &error),
}; Outcome::Failed,
let old_bytes = read(0, "old")?;
let new_bytes = read(1, "new")?;
let old = Document::parse(&old_bytes).map_err(|e| ("invalid_input", e, Some("old")))?;
let new = Document::parse(&new_bytes).map_err(|e| ("invalid_input", e, Some("new")))?;
scope
.validate_pair(&old, &new)
.map_err(|e| ("invalid_scope", e, None))?;
let old = old
.selected(scope, true)
.map_err(|e| ("invalid_scope", e, Some("old")))?;
let new = new
.selected(scope, true)
.map_err(|e| ("invalid_scope", e, Some("new")))?;
let diff = Comparison::between(&old, &new);
Ok::<_, (&str, String, Option<&str>)>((
diff.json_report(&old, &new, &inputs, options),
diff.exit_code(),
))
};
let (report, status) = match comparison() {
Ok(result) => result,
Err((code, message, side)) => (
failure_report(&inputs, scope, options, code, &message, side),
2,
), ),
}; };
if let Err(error) = json_stdout(&report) { if let Err(error) = json_stdout(&report) {
@ -134,7 +163,7 @@ fn json_diff(paths: &[OsString], scope: &Scope, options: &ReportOptions) -> Resu
eprintln!("pheon: {error}"); eprintln!("pheon: {error}");
return Ok(2); return Ok(2);
} }
Ok(status) Ok(outcome.exit_code())
} }
fn run(args: &[OsString]) -> Result<u8, String> { fn run(args: &[OsString]) -> Result<u8, String> {
@ -252,40 +281,25 @@ fn run(args: &[OsString]) -> Result<u8, String> {
let output = if command == "dump" { let output = if command == "dump" {
doc.canonical_dump() doc.canonical_dump()
} else { } else {
hierarchy(&doc, &doc, None, format == "mermaid", depth) doc.hierarchy(format == "mermaid", depth)
}; };
stdout(&output)?; stdout(&output)?;
if command == "hierarchy" { if command == "hierarchy" {
for issue in &doc.issues { for diagnostic in &doc.diagnostics {
eprintln!("INCOMPLETE: {issue}"); eprintln!("INCOMPLETE: {}", diagnostic.message);
} }
} }
return Ok(if doc.issues.is_empty() { 0 } else { 2 }); return Ok(if doc.diagnostics.is_empty() { 0 } else { 2 });
} }
let git = command == "git-diff"; let git = command == "git-diff";
let old_missing = git && (paths[3] == "000000" || paths[3] == "."); let old_missing = git && (paths[3] == "000000" || paths[3] == ".");
let new_missing = git && (paths[6] == "000000" || paths[6] == "."); let new_missing = git && (paths[6] == "000000" || paths[6] == ".");
if old_missing && new_missing { let diff = prepare_comparison(
return Err("both Git revisions are absent".to_string()); (!old_missing).then_some(paths[if git { 1 } else { 0 }].as_os_str()),
} (!new_missing).then_some(paths[if git { 4 } else { 1 }].as_os_str()),
let old_bytes = if old_missing { &scope,
None )
} else { .map_err(|error| error.message)?;
Some(read(&paths[if git { 1 } else { 0 }])?)
};
let new_bytes = if new_missing {
None
} else {
Some(read(&paths[if git { 4 } else { 1 }])?)
};
let old = old_bytes.as_ref().map(|b| Document::parse(b)).transpose()?;
let new = new_bytes.as_ref().map(|b| Document::parse(b)).transpose()?;
let old = old.unwrap_or_else(|| new.as_ref().unwrap().empty_like());
let new = new.unwrap_or_else(|| old.empty_like());
scope.validate_pair(&old, &new)?;
let old = old.selected(&scope, true)?;
let new = new.selected(&scope, true)?;
let diff = Comparison::between(&old, &new);
let mut output = String::new(); let mut output = String::new();
if git { if git {
if paths.len() == 9 { if paths.len() == 9 {
@ -307,13 +321,7 @@ fn run(args: &[OsString]) -> Result<u8, String> {
if format == "mermaid" { if format == "mermaid" {
output.push_str("```mermaid\n"); output.push_str("```mermaid\n");
} }
output.push_str(&hierarchy( output.push_str(&diff.hierarchy(format == "mermaid", depth));
&old,
&new,
Some(&diff),
format == "mermaid",
depth,
));
if format == "mermaid" { if format == "mermaid" {
output.push_str("```\n"); output.push_str("```\n");
} }
@ -321,10 +329,10 @@ fn run(args: &[OsString]) -> Result<u8, String> {
stdout(&output)?; stdout(&output)?;
// Git's external driver expects successful rendering for either equality // Git's external driver expects successful rendering for either equality
// or differences. Actual comparison/input failures remain nonzero. // or differences. Actual comparison/input failures remain nonzero.
Ok(if git && diff.exit_code() == 1 { Ok(if git && diff.outcome().exit_code() == 1 {
0 0
} else { } else {
diff.exit_code() diff.outcome().exit_code()
}) })
} }
@ -363,9 +371,7 @@ fn main() -> ExitCode {
&ReportInputs::default(), &ReportInputs::default(),
&Scope::default(), &Scope::default(),
&ReportOptions::default(), &ReportOptions::default(),
"command_error", &Diagnostic::new("command_error", message, None),
&message,
None,
); );
if let Err(error) = json_stdout(&report) { if let Err(error) = json_stdout(&report) {
eprintln!("pheon: {error}"); eprintln!("pheon: {error}");

View file

@ -5,22 +5,39 @@ use crate::{basic::decode_real8, record::RecordHeader, records::*};
use std::{ use std::{
borrow::Cow, borrow::Cow,
collections::{BTreeMap, BTreeSet}, collections::{BTreeMap, BTreeSet},
fmt::Write, fmt::{self, Write},
}; };
mod names; pub mod changes;
pub use names::{parse_layer, parse_layer_name, write_layer_names}; pub mod names;
mod selection;
pub use selection::{DisplayFilter, Scope};
mod changes;
pub use changes::Replacement;
pub mod report; pub mod report;
pub mod selection;
/// A comparison limitation with source context independent of its wording. use changes::Replacement;
use selection::{DisplayFilter, Scope};
/// Input revision associated with a diagnostic.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Side {
Old,
New,
}
impl fmt::Display for Side {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
out.write_str(match self {
Self::Old => "old",
Self::New => "new",
})
}
}
/// A review error or comparison limitation, with structured source context.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Diagnostic { pub struct Diagnostic {
pub code: &'static str, pub code: &'static str,
pub message: String, pub message: String,
pub side: Option<Side>,
pub offset: Option<usize>, pub offset: Option<usize>,
pub cell: Option<String>, pub cell: Option<String>,
pub layer: Option<Layer>, pub layer: Option<Layer>,
@ -28,20 +45,79 @@ pub struct Diagnostic {
} }
impl Diagnostic { impl Diagnostic {
fn at(code: &'static str, offset: usize, message: String) -> Self { pub fn new(code: &'static str, message: impl Into<String>, side: Option<Side>) -> Self {
Self { Self {
code, code,
message: error(offset, message), message: message.into(),
offset: Some(offset), side,
offset: None,
cell: None, cell: None,
layer: None, layer: None,
target: None, target: None,
} }
} }
fn at(code: &'static str, offset: usize, message: String) -> Self {
Self {
offset: Some(offset),
..Self::new(code, error(offset, message), None)
}
}
} }
pub const PROFILE: &str = "klamath-object-v2"; impl fmt::Display for Diagnostic {
pub const LAYER_SENTINEL: &str = "KLAMATH_LAYER_NAMES_V1"; fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(side) = self.side {
write!(out, "{side}: ")?;
}
out.write_str(&self.message)
}
}
/// The five meaningful combinations of completeness and comparison result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Outcome {
Equal,
Different,
Incomplete { different: bool },
Failed,
}
impl Outcome {
pub fn status(self) -> &'static str {
match self {
Self::Equal | Self::Different => "complete",
Self::Incomplete { .. } => "incomplete",
Self::Failed => "failed",
}
}
pub fn result(self) -> &'static str {
match self {
Self::Equal => "equal",
Self::Different | Self::Incomplete { different: true } => "different",
Self::Incomplete { different: false } | Self::Failed => "unknown",
}
}
pub fn exit_code(self) -> u8 {
match self {
Self::Equal => 0,
Self::Different => 1,
_ => 2,
}
}
pub fn is_equal(self) -> bool {
self == Self::Equal
}
pub fn is_complete(self) -> bool {
matches!(self, Self::Equal | Self::Different)
}
}
pub const PROFILE: &str = "pheon-structural-v1";
pub type Layer = (u16, u16); pub type Layer = (u16, u16);
pub type Bounds = [i32; 4]; pub type Bounds = [i32; 4];
@ -81,16 +157,35 @@ impl Object<'_> {
.find(|(t, _)| *t == tag) .find(|(t, _)| *t == tag)
.map(|(_, v)| v.as_ref()) .map(|(_, v)| v.as_ref())
} }
}
pub fn description(&self) -> String { fn format_object<'a>(
let mut out = kind_name(self.kind).to_string(); out: &mut fmt::Formatter<'_>,
for (tag, value) in &self.key.fields { kind: u16,
write!(out, " {}={}", tag_name(*tag), format_data(*tag, value)).unwrap(); fields: impl IntoIterator<Item = (u16, &'a [u8])>,
} properties: impl IntoIterator<Item = (u16, &'a [u8])>,
for (attribute, value) in &self.key.properties { ) -> fmt::Result {
write!(out, " property[{attribute}]={}", quoted(value)).unwrap(); out.write_str(kind_name(kind))?;
} for (tag, value) in fields {
out write!(out, " {}={}", tag_name(tag), format_data(tag, value))?;
}
for (attribute, value) in properties {
write!(out, " property[{attribute}]={}", quoted(value))?;
}
Ok(())
}
impl fmt::Display for Object<'_> {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
format_object(
out,
self.kind,
self.key
.fields
.iter()
.map(|(tag, data)| (*tag, data.as_ref())),
self.key.properties.iter().copied(),
)
} }
} }
@ -110,7 +205,6 @@ pub struct Document<'a> {
pub cells: BTreeMap<String, Cell<'a>>, pub cells: BTreeMap<String, Cell<'a>>,
pub layer_names: BTreeMap<Layer, String>, pub layer_names: BTreeMap<Layer, String>,
/// Unsupported features or invalid reference graphs prevent an equality claim. /// Unsupported features or invalid reference graphs prevent an equality claim.
pub issues: Vec<String>,
pub diagnostics: Vec<Diagnostic>, pub diagnostics: Vec<Diagnostic>,
header: Vec<(u16, &'a [u8])>, header: Vec<(u16, &'a [u8])>,
global_issues: Vec<Diagnostic>, global_issues: Vec<Diagnostic>,
@ -452,7 +546,6 @@ impl<'a> Document<'a> {
records, records,
cells: BTreeMap::new(), cells: BTreeMap::new(),
layer_names: BTreeMap::new(), layer_names: BTreeMap::new(),
issues: Vec::new(),
diagnostics: Vec::new(), diagnostics: Vec::new(),
header: Vec::new(), header: Vec::new(),
global_issues: Vec::new(), global_issues: Vec::new(),
@ -594,64 +687,10 @@ impl<'a> Document<'a> {
doc.header.sort(); doc.header.sort();
doc.read_metadata()?; doc.read_metadata()?;
doc.known_cells = doc.cells.keys().cloned().collect(); doc.known_cells = doc.cells.keys().cloned().collect();
doc.refresh_issues(); doc.refresh_diagnostics();
Ok(doc) Ok(doc)
} }
fn read_metadata(&mut self) -> Result<(), String> {
for (cell_name, cell) in &mut self.cells {
for object in cell.objects.iter().filter(|o| o.kind == RTAG_TEXT) {
let text = object.field(RTAG_STRING).unwrap();
if text.starts_with(b"KLAMATH_LAYER_NAMES_") && text != LAYER_SENTINEL.as_bytes() {
// Layer names apply across the library. An unknown version
// may describe layers used outside this carrier or cell, so
// geometry scope selection cannot establish its relevance.
let mut diagnostic = Diagnostic::at(
"unsupported_metadata_version",
object.offset,
"unsupported layer-name metadata version".to_string(),
);
diagnostic.cell = Some(cell_name.clone());
diagnostic.layer = object.layer;
diagnostic.message = format!("cell {cell_name:?}: {}", diagnostic.message);
self.global_issues.push(diagnostic);
}
}
let carriers: BTreeSet<_> = cell
.objects
.iter()
.filter(|o| {
o.kind == RTAG_TEXT && o.field(RTAG_STRING) == Some(LAYER_SENTINEL.as_bytes())
})
.filter_map(|o| o.layer)
.collect();
for object in &mut cell.objects {
if object.kind != RTAG_TEXT || !object.layer.is_some_and(|l| carriers.contains(&l))
{
continue;
}
let text = decoded_string(object.field(RTAG_STRING).unwrap(), object.offset)?;
if text != LAYER_SENTINEL {
let ((layer, dtype), name) =
parse_layer_name(&text).map_err(|message| error(object.offset, message))?;
if self
.layer_names
.get(&(layer, dtype))
.is_some_and(|old| old != &name)
{
return Err(error(
object.offset,
format!("conflicting names for {layer}/{dtype}"),
));
}
self.layer_names.insert((layer, dtype), name.to_string());
}
object.metadata = true;
}
}
Ok(())
}
fn check_graph(&mut self) { fn check_graph(&mut self) {
let mut unresolved = BTreeMap::new(); let mut unresolved = BTreeMap::new();
for (parent, cell) in &self.cells { for (parent, cell) in &self.cells {
@ -666,6 +705,7 @@ impl<'a> Document<'a> {
for ((parent, target), offset) in unresolved { for ((parent, target), offset) in unresolved {
self.diagnostics.push(Diagnostic { self.diagnostics.push(Diagnostic {
code: "unresolved_reference", code: "unresolved_reference",
side: None,
message: format!("cell {parent:?}: unresolved reference {target:?}"), message: format!("cell {parent:?}: unresolved reference {target:?}"),
offset: Some(offset), offset: Some(offset),
cell: Some(parent.clone()), cell: Some(parent.clone()),
@ -686,6 +726,7 @@ impl<'a> Document<'a> {
Some(1) => { Some(1) => {
self.diagnostics.push(Diagnostic { self.diagnostics.push(Diagnostic {
code: "hierarchy_cycle", code: "hierarchy_cycle",
side: None,
message: format!("cyclic hierarchy involving {name:?}"), message: format!("cyclic hierarchy involving {name:?}"),
offset: self.cells.get(name).map(|c| c.offset), offset: self.cells.get(name).map(|c| c.offset),
cell: Some(name.to_string()), cell: Some(name.to_string()),
@ -722,6 +763,11 @@ impl<'a> Document<'a> {
edges edges
} }
pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String {
let revision = Revision::from_document(self);
render_hierarchy(&revision, &revision, None, mermaid, max_depth)
}
pub fn canonical_dump(&self) -> String { pub fn canonical_dump(&self) -> String {
let mut out = format!( let mut out = format!(
"profile {PROFILE}\n{}\ncoordinates: integer database units; bounds: coordinate envelopes\n", "profile {PROFILE}\n{}\ncoordinates: integer database units; bounds: coordinate envelopes\n",
@ -739,11 +785,11 @@ impl<'a> Document<'a> {
writeln!(out, " {}={}", tag_name(*tag), format_data(*tag, data)).unwrap(); writeln!(out, " {}={}", tag_name(*tag), format_data(*tag, data)).unwrap();
} }
for object in cell.objects.iter().filter(|o| !o.metadata) { for object in cell.objects.iter().filter(|o| !o.metadata) {
writeln!(out, " {}", object.description()).unwrap(); writeln!(out, " {object}").unwrap();
} }
} }
for issue in &self.issues { for diagnostic in &self.diagnostics {
writeln!(out, "INCOMPLETE: {issue}").unwrap(); writeln!(out, "INCOMPLETE: {}", diagnostic.message).unwrap();
} }
out out
} }
@ -811,11 +857,25 @@ pub struct ObjectChange {
pub origin: Option<[i32; 2]>, pub origin: Option<[i32; 2]>,
pub width: Option<i32>, pub width: Option<i32>,
pub counts: Option<[u16; 2]>, pub counts: Option<[u16; 2]>,
pub description: String,
pub fields: Vec<FieldValue>, pub fields: Vec<FieldValue>,
pub properties: Vec<(u16, Vec<u8>)>, pub properties: Vec<(u16, Vec<u8>)>,
} }
impl fmt::Display for ObjectChange {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
format_object(
out,
self.kind,
self.fields
.iter()
.map(|field| (field.tag, field.data.as_slice())),
self.properties
.iter()
.map(|(attribute, data)| (*attribute, data.as_slice())),
)
}
}
impl From<&Object<'_>> for ObjectChange { impl From<&Object<'_>> for ObjectChange {
fn from(object: &Object<'_>) -> Self { fn from(object: &Object<'_>) -> Self {
Self { Self {
@ -842,7 +902,6 @@ impl From<&Object<'_>> for ObjectChange {
[1, 1] [1, 1]
} }
}), }),
description: object.description(),
fields: owned_fields( fields: owned_fields(
object object
.key .key
@ -860,19 +919,39 @@ impl From<&Object<'_>> for ObjectChange {
} }
} }
/// An existing cell's source location and retained attributes.
#[derive(Debug)]
pub struct CellRevision {
pub offset: usize,
pub attributes: Vec<FieldValue>,
}
impl From<&Cell<'_>> for CellRevision {
fn from(cell: &Cell<'_>) -> Self {
Self {
offset: cell.offset,
attributes: owned_fields(cell.attributes.iter().copied()),
}
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct CellChange { pub struct CellChange {
pub name: String, pub name: String,
pub old_offset: Option<usize>, pub old: Option<CellRevision>,
pub new_offset: Option<usize>, pub new: Option<CellRevision>,
pub attributes_changed: bool,
pub old_attributes: Vec<FieldValue>,
pub new_attributes: Vec<FieldValue>,
pub removed: Vec<ObjectChange>, pub removed: Vec<ObjectChange>,
pub added: Vec<ObjectChange>, pub added: Vec<ObjectChange>,
pub replacements: Vec<Replacement>, pub replacements: Vec<Replacement>,
} }
impl CellChange {
pub fn attributes_changed(&self) -> bool {
self.old.as_ref().map(|cell| &cell.attributes)
!= self.new.as_ref().map(|cell| &cell.attributes)
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct LayerNameChange { pub struct LayerNameChange {
pub layer: Layer, pub layer: Layer,
@ -880,59 +959,117 @@ pub struct LayerNameChange {
pub new: Option<String>, pub new: Option<String>,
} }
/// Library presence or exact record payloads, formatted only when rendered.
#[derive(Debug)] #[derive(Debug)]
pub struct LibraryFieldChange { pub enum LibraryChange {
pub field: String, Presence {
pub tag: Option<u16>, old: bool,
pub old_fields: Vec<FieldValue>, new: bool,
pub new_fields: Vec<FieldValue>, },
pub old: Vec<String>, Record {
pub new: Vec<String>, tag: u16,
old: Vec<Vec<u8>>,
new: Vec<Vec<u8>>,
},
}
impl fmt::Display for LibraryChange {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Presence { old, new } => {
let label = |present| if present { "present" } else { "absent" };
write!(out, "presence: {:?} -> {:?}", [label(*old)], [label(*new)])
}
Self::Record { tag, old, new } => {
write!(out, "{}: ", tag_name(*tag))?;
out.debug_list()
.entries(old.iter().map(|data| format_data(*tag, data)))
.finish()?;
out.write_str(" -> ")?;
out.debug_list()
.entries(new.iter().map(|data| format_data(*tag, data)))
.finish()
}
}
}
}
/// Owned revision metadata and reference counts captured before documents are dropped.
#[derive(Debug)]
pub struct Revision {
pub scope: Scope,
pub present: bool,
pub units: Option<Vec<u8>>,
cells: BTreeSet<String>,
known_cells: BTreeSet<String>,
edges: BTreeMap<(String, String), u64>,
}
impl Revision {
fn from_document(doc: &Document<'_>) -> Self {
Self {
scope: doc.scope.clone(),
present: doc.present,
units: doc
.header
.iter()
.find(|(tag, _)| *tag == RTAG_UNITS && doc.present)
.map(|(_, data)| data.to_vec()),
cells: doc.cells.keys().cloned().collect(),
known_cells: doc.known_cells.clone(),
edges: doc.edges(),
}
}
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Comparison { pub struct Comparison {
pub scope: Scope, pub old: Revision,
pub new: Revision,
/// Unchanged names are displayed once when objects on that layer change. /// Unchanged names are displayed once when objects on that layer change.
pub layer_legend: BTreeMap<Layer, String>, pub layer_legend: BTreeMap<Layer, String>,
pub library_fields: Vec<LibraryFieldChange>, pub library_changes: Vec<LibraryChange>,
pub layer_names: Vec<LayerNameChange>, pub layer_names: Vec<LayerNameChange>,
pub cells: Vec<CellChange>, pub cells: Vec<CellChange>,
pub issues: Vec<String>, pub diagnostics: Vec<Diagnostic>,
} }
impl Comparison { impl Comparison {
pub fn between(old: &Document<'_>, new: &Document<'_>) -> Self { pub fn between(old: &Document<'_>, new: &Document<'_>) -> Self {
let mut result = Self { let mut result = Self {
scope: old.scope.clone(), old: Revision::from_document(old),
new: Revision::from_document(new),
layer_legend: old layer_legend: old
.layer_names .layer_names
.iter() .iter()
.filter(|(pair, name)| new.layer_names.get(pair) == Some(*name)) .filter(|(pair, name)| new.layer_names.get(pair) == Some(*name))
.map(|(pair, name)| (*pair, name.clone())) .map(|(pair, name)| (*pair, name.clone()))
.collect(), .collect(),
library_fields: Vec::new(), library_changes: Vec::new(),
layer_names: Vec::new(), layer_names: Vec::new(),
cells: Vec::new(), cells: Vec::new(),
issues: Vec::new(), diagnostics: Vec::new(),
}; };
if old.scope != new.scope {
result.issues.push("comparison scopes differ".to_string());
}
if old.present != new.present { if old.present != new.present {
result.library_fields.push(LibraryFieldChange { result.library_changes.push(LibraryChange::Presence {
field: "presence".to_string(), old: old.present,
tag: None, new: new.present,
old_fields: Vec::new(),
new_fields: Vec::new(),
old: vec![if old.present { "present" } else { "absent" }.to_string()],
new: vec![if new.present { "present" } else { "absent" }.to_string()],
}); });
} }
for (side, doc) in [("old", old), ("new", new)] { for (side, doc) in [(Side::Old, old), (Side::New, new)] {
result result
.issues .diagnostics
.extend(doc.issues.iter().map(|i| format!("{side}: {i}"))); .extend(doc.diagnostics.iter().cloned().map(|mut diagnostic| {
diagnostic.side = Some(side);
diagnostic
}));
}
if old.scope != new.scope {
result.diagnostics.push(Diagnostic::new(
"scope_mismatch",
"comparison scopes differ",
None,
));
} }
let header_tags: BTreeSet<_> = old let header_tags: BTreeSet<_> = old
.header .header
@ -954,13 +1091,10 @@ impl Comparison {
.map(|(_, value)| *value) .map(|(_, value)| *value)
.collect(); .collect();
if a != b { if a != b {
result.library_fields.push(LibraryFieldChange { result.library_changes.push(LibraryChange::Record {
field: tag_name(tag), tag,
tag: Some(tag), old: a.into_iter().map(<[u8]>::to_vec).collect(),
old_fields: owned_fields(a.iter().map(|data| (tag, *data))), new: b.into_iter().map(<[u8]>::to_vec).collect(),
new_fields: owned_fields(b.iter().map(|data| (tag, *data))),
old: a.iter().map(|data| format_data(tag, data)).collect(),
new: b.iter().map(|data| format_data(tag, data)).collect(),
}); });
} }
} }
@ -985,15 +1119,8 @@ impl Comparison {
let b = new.cells.get(name); let b = new.cells.get(name);
let mut change = CellChange { let mut change = CellChange {
name: name.clone(), name: name.clone(),
old_offset: a.map(|c| c.offset), old: a.map(CellRevision::from),
new_offset: b.map(|c| c.offset), new: b.map(CellRevision::from),
attributes_changed: a.map(|c| &c.attributes) != b.map(|c| &c.attributes),
old_attributes: owned_fields(
a.into_iter().flat_map(|c| c.attributes.iter().copied()),
),
new_attributes: owned_fields(
b.into_iter().flat_map(|c| c.attributes.iter().copied()),
),
removed: Vec::new(), removed: Vec::new(),
added: Vec::new(), added: Vec::new(),
replacements: Vec::new(), replacements: Vec::new(),
@ -1030,11 +1157,7 @@ impl Comparison {
} }
} }
} }
if change.old_offset.is_none() if change.attributes_changed() || !change.removed.is_empty() || !change.added.is_empty()
|| change.new_offset.is_none()
|| change.attributes_changed
|| !change.removed.is_empty()
|| !change.added.is_empty()
{ {
change.replacements = changes::replacements(&change.removed, &change.added); change.replacements = changes::replacements(&change.removed, &change.added);
result.cells.push(change); result.cells.push(change);
@ -1043,21 +1166,21 @@ impl Comparison {
result result
} }
pub fn is_equal(&self) -> bool { pub fn outcome(&self) -> Outcome {
self.issues.is_empty() let different = !self.library_changes.is_empty()
&& self.library_fields.is_empty() || !self.layer_names.is_empty()
&& self.layer_names.is_empty() || !self.cells.is_empty();
&& self.cells.is_empty() if !self.diagnostics.is_empty() {
Outcome::Incomplete { different }
} else if different {
Outcome::Different
} else {
Outcome::Equal
}
} }
pub fn exit_code(&self) -> u8 { pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String {
if !self.issues.is_empty() { render_hierarchy(&self.old, &self.new, Some(&self.cells), mermaid, max_depth)
2
} else if self.is_equal() {
0
} else {
1
}
} }
/// Limit presentation only: the complete comparison has already been made. /// Limit presentation only: the complete comparison has already been made.
@ -1066,19 +1189,22 @@ impl Comparison {
} }
pub fn text_filtered(&self, max_objects: usize, show: &DisplayFilter) -> String { pub fn text_filtered(&self, max_objects: usize, show: &DisplayFilter) -> String {
let mut out = format!("profile {PROFILE}\n{}\n", self.scope.description()); let mut out = format!("profile {PROFILE}\n{}\n", self.old.scope.description());
if show.cell.is_some() || show.layer.is_some() { if show.cell.is_some() || show.layer.is_some() {
writeln!(out, "display-only filter cell={:?} layer={:?}; status, totals and hierarchy are unfiltered", show.cell, show.layer).unwrap(); writeln!(out, "display-only filter cell={:?} layer={:?}; status, totals and hierarchy are unfiltered", show.cell, show.layer).unwrap();
} }
for change in &self.library_fields { for change in &self.library_changes {
writeln!( writeln!(out, "library {change}").unwrap();
out,
"library {}: {:?} -> {:?}",
change.field, change.old, change.new
)
.unwrap();
} }
if self.library_fields.iter().any(|c| c.field == "UNITS") { if self.library_changes.iter().any(|change| {
matches!(
change,
LibraryChange::Record {
tag: RTAG_UNITS,
..
}
)
}) {
out.push_str("UNITS changed; coordinates remain in each file's database units\n"); out.push_str("UNITS changed; coordinates remain in each file's database units\n");
} }
for change in &self.layer_names { for change in &self.layer_names {
@ -1116,9 +1242,9 @@ impl Comparison {
out, out,
"cell {:?} old@{:?} new@{:?}{}", "cell {:?} old@{:?} new@{:?}{}",
cell.name, cell.name,
cell.old_offset, cell.old.as_ref().map(|revision| revision.offset),
cell.new_offset, cell.new.as_ref().map(|revision| revision.offset),
if cell.attributes_changed { if cell.attributes_changed() {
" [cell/header changed]" " [cell/header changed]"
} else { } else {
"" ""
@ -1135,19 +1261,9 @@ impl Comparison {
.layer .layer
.is_none_or(|layer| a.layer == Some(layer) && b.layer == Some(layer)) .is_none_or(|layer| a.layer == Some(layer) && b.layer == Some(layer))
{ {
writeln!(out, " ~ {}", replacement.explanation).unwrap(); writeln!(out, " ~ {}", changes::explain(a, b)).unwrap();
writeln!( writeln!(out, " - @{} bbox={:?} {}", a.offset, a.bounds, a).unwrap();
out, writeln!(out, " + @{} bbox={:?} {}", b.offset, b.bounds, b).unwrap();
" - @{} bbox={:?} {}",
a.offset, a.bounds, a.description
)
.unwrap();
writeln!(
out,
" + @{} bbox={:?} {}",
b.offset, b.bounds, b.description
)
.unwrap();
paired_old.insert(replacement.removed); paired_old.insert(replacement.removed);
paired_new.insert(replacement.added); paired_new.insert(replacement.added);
shown += 2; shown += 2;
@ -1168,7 +1284,7 @@ impl Comparison {
writeln!( writeln!(
out, out,
" {sign} @{} bbox={:?} {}", " {sign} @{} bbox={:?} {}",
object.offset, object.bounds, object.description object.offset, object.bounds, object
) )
.unwrap(); .unwrap();
shown += 1; shown += 1;
@ -1183,55 +1299,93 @@ impl Comparison {
self.layer_names.len() self.layer_names.len()
) )
.unwrap(); .unwrap();
for issue in &self.issues { // General comparison errors precede revision-specific errors in text.
writeln!(out, "INCOMPLETE: {issue}").unwrap(); for diagnostic in self
.diagnostics
.iter()
.filter(|d| d.side.is_none())
.chain(self.diagnostics.iter().filter(|d| d.side.is_some()))
{
writeln!(out, "INCOMPLETE: {diagnostic}").unwrap();
} }
if self.is_equal() { if self.outcome().is_equal() {
out.push_str("equal under this profile\n"); out.push_str("equal under this profile\n");
} }
out out
} }
} }
/// Graph facts shared by text, Mermaid, and JSON renderers.
struct HierarchyAnalysis<'a> {
old_edges: &'a BTreeMap<(String, String), u64>,
new_edges: &'a BTreeMap<(String, String), u64>,
edges: BTreeSet<(String, String)>,
direct: BTreeSet<String>,
affected: BTreeSet<String>,
changed_refs: BTreeSet<(String, String)>,
}
impl<'a> HierarchyAnalysis<'a> {
fn between(old: &'a Revision, new: &'a Revision, changes: Option<&[CellChange]>) -> Self {
let old_edges = &old.edges;
let new_edges = &new.edges;
let edges: BTreeSet<_> = old_edges.keys().chain(new_edges.keys()).cloned().collect();
let direct: BTreeSet<_> = changes
.into_iter()
.flatten()
.map(|cell| cell.name.clone())
.collect();
let changed_refs: BTreeSet<_> = changes
.into_iter()
.flatten()
.flat_map(|c| {
c.removed
.iter()
.chain(&c.added)
.filter_map(|o| o.target.as_ref().map(|t| (c.name.clone(), t.clone())))
})
.collect();
let mut parents = BTreeMap::<&str, Vec<&str>>::new();
for (parent, child) in &edges {
parents.entry(child).or_default().push(parent);
}
let mut affected = direct.clone();
let mut pending: Vec<_> = direct.iter().cloned().collect();
while let Some(child) = pending.pop() {
for parent in parents.get(child.as_str()).into_iter().flatten() {
if affected.insert((*parent).to_string()) {
pending.push((*parent).to_string());
}
}
}
Self {
old_edges,
new_edges,
edges,
direct,
affected,
changed_refs,
}
}
}
/// The graph joins both revisions, retaining removed branches and old callers. /// The graph joins both revisions, retaining removed branches and old callers.
pub fn hierarchy( fn render_hierarchy(
old: &Document<'_>, old: &Revision,
new: &Document<'_>, new: &Revision,
diff: Option<&Comparison>, changes: Option<&[CellChange]>,
mermaid: bool, mermaid: bool,
max_depth: usize, max_depth: usize,
) -> String { ) -> String {
let old_edges = old.edges(); let HierarchyAnalysis {
let new_edges = new.edges(); old_edges,
let edges: BTreeSet<_> = old_edges.keys().chain(new_edges.keys()).cloned().collect(); new_edges,
let direct: BTreeSet<_> = diff edges,
.into_iter() direct,
.flat_map(|d| d.cells.iter().map(|c| c.name.clone())) affected,
.collect(); changed_refs,
let changed_refs: BTreeSet<_> = diff } = HierarchyAnalysis::between(old, new, changes);
.into_iter() let visible: BTreeSet<_> = if changes.is_some() {
.flat_map(|d| &d.cells)
.flat_map(|c| {
c.removed
.iter()
.chain(&c.added)
.filter_map(|o| o.target.as_ref().map(|t| (c.name.clone(), t.clone())))
})
.collect();
let mut parents = BTreeMap::<&str, Vec<&str>>::new();
for (parent, child) in &edges {
parents.entry(child).or_default().push(parent);
}
let mut affected = direct.clone();
let mut pending: Vec<_> = direct.iter().cloned().collect();
while let Some(child) = pending.pop() {
for parent in parents.get(child.as_str()).into_iter().flatten() {
if affected.insert((*parent).to_string()) {
pending.push((*parent).to_string());
}
}
}
let visible: BTreeSet<_> = if diff.is_some() {
affected affected
.iter() .iter()
.cloned() .cloned()
@ -1239,8 +1393,8 @@ pub fn hierarchy(
.collect() .collect()
} else { } else {
old.cells old.cells
.keys() .iter()
.chain(new.cells.keys()) .chain(new.cells.iter())
.cloned() .cloned()
.chain(edges.iter().map(|(_, t)| t.clone())) .chain(edges.iter().map(|(_, t)| t.clone()))
.collect() .collect()
@ -1292,7 +1446,7 @@ pub fn hierarchy(
rows.push((name.clone(), 0, None, false, true)); rows.push((name.clone(), 0, None, false, true));
} }
let status = |name: &String| { let status = |name: &String| {
if !old.cells.contains_key(name) && !new.cells.contains_key(name) { if !old.cells.contains(name) && !new.cells.contains(name) {
if old.known_cells.contains(name) || new.known_cells.contains(name) { if old.known_cells.contains(name) || new.known_cells.contains(name) {
" [outside scope]" " [outside scope]"
} else { } else {
@ -1302,7 +1456,7 @@ pub fn hierarchy(
" [cell changed]" " [cell changed]"
} else if affected.contains(name) { } else if affected.contains(name) {
" [affected]" " [affected]"
} else if diff.is_some() { } else if changes.is_some() {
" [cell unchanged]" " [cell unchanged]"
} else { } else {
"" ""

View file

@ -1,10 +1,11 @@
//! Unique replacement matches that explain removed and added objects.
use super::*; use super::*;
#[derive(Debug)] #[derive(Debug)]
pub struct Replacement { pub struct Replacement {
pub removed: usize, pub removed: usize,
pub added: usize, pub added: usize,
pub explanation: String,
/// Explanation matching is never object identity or geometric equivalence. /// Explanation matching is never object identity or geometric equivalence.
pub match_rule: &'static str, pub match_rule: &'static str,
} }
@ -56,7 +57,6 @@ pub(super) fn replacements(old: &[ObjectChange], new: &[ObjectChange]) -> Vec<Re
result.push(Replacement { result.push(Replacement {
removed: i, removed: i,
added: j, added: j,
explanation: explain(&old[i], &new[j]),
match_rule: if old[i].target.is_some() { match_rule: if old[i].target.is_some() {
"unique_kind_target" "unique_kind_target"
} else if bounds { } else if bounds {
@ -74,7 +74,7 @@ pub(super) fn replacements(old: &[ObjectChange], new: &[ObjectChange]) -> Vec<Re
result result
} }
fn explain(old: &ObjectChange, new: &ObjectChange) -> String { pub(super) fn explain(old: &ObjectChange, new: &ObjectChange) -> String {
let mut parts = vec![format!( let mut parts = vec![format!(
"{} modified{}", "{} modified{}",
kind_name(old.kind), kind_name(old.kind),

View file

@ -1,5 +1,66 @@
//! Embedded layer names: parsing, recognition, and record-preserving updates.
use super::*; use super::*;
const LAYER_PREFIX: &[u8] = b"PHEON_LAYER_NAMES_";
pub const LAYER_SENTINEL: &str = "PHEON_LAYER_NAMES_V1";
impl Document<'_> {
pub(super) fn read_metadata(&mut self) -> Result<(), String> {
for (cell_name, cell) in &mut self.cells {
for object in cell.objects.iter().filter(|o| o.kind == RTAG_TEXT) {
let text = object.field(RTAG_STRING).unwrap();
if text.starts_with(LAYER_PREFIX) && text != LAYER_SENTINEL.as_bytes() {
// Layer names apply across the library. An unknown version
// may describe layers used outside this carrier or cell, so
// geometry scope selection cannot establish its relevance.
let mut diagnostic = Diagnostic::at(
"unsupported_metadata_version",
object.offset,
"unsupported layer-name metadata version".to_string(),
);
diagnostic.cell = Some(cell_name.clone());
diagnostic.layer = object.layer;
diagnostic.message = format!("cell {cell_name:?}: {}", diagnostic.message);
self.global_issues.push(diagnostic);
}
}
let carriers: BTreeSet<_> = cell
.objects
.iter()
.filter(|o| {
o.kind == RTAG_TEXT && o.field(RTAG_STRING) == Some(LAYER_SENTINEL.as_bytes())
})
.filter_map(|o| o.layer)
.collect();
for object in &mut cell.objects {
if object.kind != RTAG_TEXT || !object.layer.is_some_and(|l| carriers.contains(&l))
{
continue;
}
let text = decoded_string(object.field(RTAG_STRING).unwrap(), object.offset)?;
if text != LAYER_SENTINEL {
let ((layer, dtype), name) =
parse_layer_name(&text).map_err(|message| error(object.offset, message))?;
if self
.layer_names
.get(&(layer, dtype))
.is_some_and(|old| old != &name)
{
return Err(error(
object.offset,
format!("conflicting names for {layer}/{dtype}"),
));
}
self.layer_names.insert((layer, dtype), name.to_string());
}
object.metadata = true;
}
}
Ok(())
}
}
pub fn parse_layer(value: &str) -> Result<Layer, String> { pub fn parse_layer(value: &str) -> Result<Layer, String> {
let (a, b) = value let (a, b) = value
.split_once('/') .split_once('/')

View file

@ -27,32 +27,37 @@ fn scope(value: &Scope) -> Value {
json!({"top": value.top, "cell": value.cell, "layer": value.layer.map(layer)}) json!({"top": value.top, "cell": value.cell, "layer": value.layer.map(layer)})
} }
fn input(path: Option<&Path>, doc: Option<&Document<'_>>) -> Value { fn input(path: Option<&Path>, revision: Option<&Revision>) -> Value {
let units = doc let units = revision
.filter(|d| d.present) .and_then(|r| r.units.as_deref())
.and_then(|d| d.header.iter().find(|(tag, _)| *tag == RTAG_UNITS)) .map(|data| field(RTAG_UNITS, data));
.map(|(tag, data)| field(*tag, data));
json!({ json!({
"path": path.and_then(Path::to_str), "path": path.and_then(Path::to_str),
"path_encoded_hex": path.filter(|p| p.to_str().is_none()) "path_encoded_hex": path.filter(|p| p.to_str().is_none())
.map(|p| hex(p.as_os_str().as_encoded_bytes())), .map(|p| hex(p.as_os_str().as_encoded_bytes())),
"present": doc.map(|d| d.present), "present": revision.map(|r| r.present),
"units": units "units": units
}) })
} }
fn envelope(inputs: &ReportInputs, selection: &Scope, options: &ReportOptions) -> Value { fn envelope(
inputs: &ReportInputs,
selection: &Scope,
options: &ReportOptions,
outcome: Outcome,
revisions: Option<(&Revision, &Revision)>,
) -> Value {
json!({ json!({
"schema_version": SCHEMA_VERSION, "schema_version": SCHEMA_VERSION,
"kind": "diff", "kind": "diff",
"producer": {"name": "pheon", "version": env!("CARGO_PKG_VERSION")}, "producer": {"name": "pheon", "version": env!("CARGO_PKG_VERSION")},
"comparison_profile": PROFILE, "comparison_profile": PROFILE,
"inputs": {"old": input(inputs.old.as_deref(), None), "new": input(inputs.new.as_deref(), None)}, "inputs": {"old": input(inputs.old.as_deref(), revisions.map(|r| r.0)), "new": input(inputs.new.as_deref(), revisions.map(|r| r.1))},
"scope": scope(selection), "scope": scope(selection),
"coordinates": {"unit": "database_unit", "frame": "cell_local", "bounds": "coordinate_envelope"}, "coordinates": {"unit": "database_unit", "frame": "cell_local", "bounds": "coordinate_envelope"},
"status": "failed", "status": outcome.status(),
"result": "unknown", "result": outcome.result(),
"exit_code": 2, "exit_code": outcome.exit_code(),
"summary": null, "summary": null,
"report_selection": { "report_selection": {
"cell": options.filter.cell, "cell": options.filter.cell,
@ -74,18 +79,22 @@ pub fn failure_report(
inputs: &ReportInputs, inputs: &ReportInputs,
selection: &Scope, selection: &Scope,
options: &ReportOptions, options: &ReportOptions,
code: &str, error: &Diagnostic,
message: &str,
side: Option<&str>,
) -> Value { ) -> Value {
let mut report = envelope(inputs, selection, options); let mut report = envelope(inputs, selection, options, Outcome::Failed, None);
report["diagnostics"] = json!([{ report["diagnostics"] = json!([diagnostic(error)]);
"code": code, "severity": "error", "message": message,
"side": side, "byte_offset": null, "cell": null, "layer": null, "target": null
}]);
report report
} }
fn diagnostic(value: &Diagnostic) -> Value {
json!({
"code": value.code, "severity": "error", "message": value.message,
"side": value.side.map(|side| side.to_string()),
"byte_offset": value.offset.map(|offset| offset.to_string()),
"cell": value.cell, "layer": value.layer.map(layer), "target": value.target
})
}
fn field(tag: u16, data: &[u8]) -> Value { fn field(tag: u16, data: &[u8]) -> Value {
let (encoding, value) = if tag == RTAG_XY && data.len().is_multiple_of(8) { let (encoding, value) = if tag == RTAG_XY && data.len().is_multiple_of(8) {
("xy", json!(points(data))) ("xy", json!(points(data)))
@ -195,40 +204,24 @@ fn field_changes(old: &ObjectChange, new: &ObjectChange) -> Vec<Value> {
} }
impl Comparison { impl Comparison {
/// Render evidence from the same documents used to construct this comparison. /// Render the captured comparison evidence without retaining its source documents.
/// IDs are local to this report, not persistent object identities. /// IDs are local to this report, not persistent object identities.
pub fn json_report( pub fn json_report(&self, inputs: &ReportInputs, options: &ReportOptions) -> Value {
&self, let outcome = self.outcome();
old: &Document<'_>, let mut report = envelope(
new: &Document<'_>, inputs,
inputs: &ReportInputs, &self.old.scope,
options: &ReportOptions, options,
) -> Value { outcome,
let mut report = envelope(inputs, &self.scope, options); Some((&self.old, &self.new)),
report["inputs"] = json!({"old": input(inputs.old.as_deref(), Some(old)), "new": input(inputs.new.as_deref(), Some(new))}); );
let different = !self.cells.is_empty()
|| !self.library_fields.is_empty()
|| !self.layer_names.is_empty();
report["status"] = json!(if self.issues.is_empty() {
"complete"
} else {
"incomplete"
});
report["result"] = json!(if different {
"different"
} else if self.is_equal() {
"equal"
} else {
"unknown"
});
report["exit_code"] = json!(self.exit_code());
report["summary"] = json!({ report["summary"] = json!({
"counts": if self.issues.is_empty() { "exact" } else { "observed" }, "counts": if outcome.is_complete() { "exact" } else { "observed" },
"changed_cells": self.cells.len().to_string(), "changed_cells": self.cells.len().to_string(),
"removed_objects": self.cells.iter().map(|c| c.removed.len()).sum::<usize>().to_string(), "removed_objects": self.cells.iter().map(|c| c.removed.len()).sum::<usize>().to_string(),
"added_objects": self.cells.iter().map(|c| c.added.len()).sum::<usize>().to_string(), "added_objects": self.cells.iter().map(|c| c.added.len()).sum::<usize>().to_string(),
"layer_name_changes": self.layer_names.len().to_string(), "layer_name_changes": self.layer_names.len().to_string(),
"library_field_changes": self.library_fields.len().to_string() "library_field_changes": self.library_changes.len().to_string()
}); });
report["layer_legend"] = json!( report["layer_legend"] = json!(
self.layer_legend self.layer_legend
@ -244,11 +237,17 @@ impl Comparison {
})) }))
.collect::<Vec<_>>() .collect::<Vec<_>>()
); );
report["library_changes"] = json!(self.library_fields.iter().map(|c| { report["library_changes"] = json!(self.library_changes.iter().map(|change| {
if c.tag.is_none() { match change {
json!({"field": "presence", "tag": null, "before": old.present, "after": new.present}) LibraryChange::Presence { old, new } => {
} else { json!({"field": "presence", "tag": null, "before": old, "after": new})
json!({"field": c.field, "tag": c.tag, "before": fields(&c.old_fields), "after": fields(&c.new_fields)}) }
LibraryChange::Record { tag, old, new } => {
let values = |data: &[Vec<u8>]| {
data.iter().map(|bytes| field(*tag, bytes)).collect::<Vec<_>>()
};
json!({"field": tag_name(*tag), "tag": tag, "before": values(old), "after": values(new)})
}
} }
}).collect::<Vec<_>>()); }).collect::<Vec<_>>());
let (mut emitted, mut filtered_objects, mut limited, mut filtered_cells) = let (mut emitted, mut filtered_objects, mut limited, mut filtered_cells) =
@ -293,16 +292,16 @@ impl Comparison {
let b = format!("c{cell_index}:new:{}", r.added); let b = format!("c{cell_index}:new:{}", r.added);
(shown.contains(&a) && shown.contains(&b)).then(|| json!({ (shown.contains(&a) && shown.contains(&b)).then(|| json!({
"removed": a, "added": b, "match_rule": r.match_rule, "removed": a, "added": b, "match_rule": r.match_rule,
"explanation": r.explanation, "explanation": changes::explain(&cell.removed[r.removed], &cell.added[r.added]),
"field_changes": field_changes(&cell.removed[r.removed], &cell.added[r.added]), "field_changes": field_changes(&cell.removed[r.removed], &cell.added[r.added]),
"properties_changed": cell.removed[r.removed].properties != cell.added[r.added].properties "properties_changed": cell.removed[r.removed].properties != cell.added[r.added].properties
})) }))
}).collect(); }).collect();
cells.push(json!({ cells.push(json!({
"name": cell.name, "name": cell.name,
"before": cell.old_offset.map(|offset| json!({"byte_offset": offset.to_string(), "attributes": fields(&cell.old_attributes)})), "before": cell.old.as_ref().map(|revision| json!({"byte_offset": revision.offset.to_string(), "attributes": fields(&revision.attributes)})),
"after": cell.new_offset.map(|offset| json!({"byte_offset": offset.to_string(), "attributes": fields(&cell.new_attributes)})), "after": cell.new.as_ref().map(|revision| json!({"byte_offset": revision.offset.to_string(), "attributes": fields(&revision.attributes)})),
"attributes_changed": cell.attributes_changed, "attributes_changed": cell.attributes_changed(),
"removed": removed, "added": added, "replacements": replacements "removed": removed, "added": added, "replacements": replacements
})); }));
} }
@ -317,37 +316,29 @@ impl Comparison {
] { ] {
report["report_selection"][key] = json!(count.to_string()); report["report_selection"][key] = json!(count.to_string());
} }
let mut diagnostics: Vec<_> = [("old", old), ("new", new)] report["diagnostics"] = json!(self.diagnostics.iter().map(diagnostic).collect::<Vec<_>>());
.into_iter()
.flat_map(|(side, doc)| {
doc.diagnostics.iter().map(move |d| {
json!({
"code": d.code, "severity": "error", "message": d.message, "side": side,
"byte_offset": d.offset.map(|n| n.to_string()), "cell": d.cell,
"layer": d.layer.map(layer), "target": d.target
})
})
})
.collect();
if old.scope != new.scope {
diagnostics.push(json!({"code": "scope_mismatch", "severity": "error", "message": "comparison scopes differ", "side": null, "byte_offset": null, "cell": null, "layer": null, "target": null}));
}
report["diagnostics"] = json!(diagnostics);
if options.hierarchy { if options.hierarchy {
report["hierarchy"] = graph(old, new, self); report["hierarchy"] = graph(self);
} }
report report
} }
} }
fn graph(old: &Document<'_>, new: &Document<'_>, diff: &Comparison) -> Value { fn graph(diff: &Comparison) -> Value {
let a = old.edges(); let old = &diff.old;
let b = new.edges(); let new = &diff.new;
let edges: BTreeSet<_> = a.keys().chain(b.keys()).cloned().collect(); let HierarchyAnalysis {
old_edges,
new_edges,
edges,
direct,
affected,
changed_refs,
} = HierarchyAnalysis::between(old, new, Some(&diff.cells));
let names: BTreeSet<_> = old let names: BTreeSet<_> = old
.cells .cells
.keys() .iter()
.chain(new.cells.keys()) .chain(new.cells.iter())
.cloned() .cloned()
.chain( .chain(
edges edges
@ -355,34 +346,10 @@ fn graph(old: &Document<'_>, new: &Document<'_>, diff: &Comparison) -> Value {
.flat_map(|(parent, child)| [parent.clone(), child.clone()]), .flat_map(|(parent, child)| [parent.clone(), child.clone()]),
) )
.collect(); .collect();
let direct: BTreeSet<_> = diff.cells.iter().map(|c| c.name.clone()).collect(); let old_targets: BTreeSet<_> = old_edges.keys().map(|(_, t)| t.as_str()).collect();
let mut affected = direct.clone(); let new_targets: BTreeSet<_> = new_edges.keys().map(|(_, t)| t.as_str()).collect();
let mut parents = BTreeMap::<&str, Vec<&str>>::new(); let state = |doc: &Revision, targets: &BTreeSet<&str>, name: &String| {
for (parent, child) in &edges { if doc.cells.contains(name) {
parents.entry(child).or_default().push(parent);
}
let mut pending: Vec<_> = direct.iter().cloned().collect();
while let Some(child) = pending.pop() {
for parent in parents.get(child.as_str()).into_iter().flatten() {
if affected.insert((*parent).to_string()) {
pending.push((*parent).to_string());
}
}
}
let changed_refs: BTreeSet<_> = diff
.cells
.iter()
.flat_map(|c| {
c.removed
.iter()
.chain(&c.added)
.filter_map(|o| o.target.as_ref().map(|t| (c.name.clone(), t.clone())))
})
.collect();
let a_targets: BTreeSet<_> = a.keys().map(|(_, t)| t.as_str()).collect();
let b_targets: BTreeSet<_> = b.keys().map(|(_, t)| t.as_str()).collect();
let state = |doc: &Document<'_>, targets: &BTreeSet<&str>, name: &String| {
if doc.cells.contains_key(name) {
"included" "included"
} else if doc.known_cells.contains(name) { } else if doc.known_cells.contains(name) {
"outside_scope" "outside_scope"
@ -394,13 +361,13 @@ fn graph(old: &Document<'_>, new: &Document<'_>, diff: &Comparison) -> Value {
}; };
json!({ json!({
"nodes": names.iter().map(|name| json!({ "nodes": names.iter().map(|name| json!({
"cell": name, "before": state(old, &a_targets, name), "after": state(new, &b_targets, name), "cell": name, "before": state(old, &old_targets, name), "after": state(new, &new_targets, name),
"change": if direct.contains(name) { "direct" } else if affected.contains(name) { "affected" } else { "unchanged" } "change": if direct.contains(name) { "direct" } else if affected.contains(name) { "affected" } else { "unchanged" }
})).collect::<Vec<_>>(), })).collect::<Vec<_>>(),
"edges": edges.iter().map(|edge| json!({ "edges": edges.iter().map(|edge| json!({
"parent": edge.0, "target": edge.1, "parent": edge.0, "target": edge.1,
"before_count": a.get(edge).copied().unwrap_or(0).to_string(), "before_count": old_edges.get(edge).copied().unwrap_or(0).to_string(),
"after_count": b.get(edge).copied().unwrap_or(0).to_string(), "after_count": new_edges.get(edge).copied().unwrap_or(0).to_string(),
"reference_changed": changed_refs.contains(edge) "reference_changed": changed_refs.contains(edge)
})).collect::<Vec<_>>() })).collect::<Vec<_>>()
}) })

View file

@ -1,3 +1,5 @@
//! Comparison scope and display-only filters.
use super::*; use super::*;
#[derive(Clone, Debug, Default, Eq, PartialEq)] #[derive(Clone, Debug, Default, Eq, PartialEq)]
@ -64,7 +66,6 @@ impl<'a> Document<'a> {
records: Vec::new(), records: Vec::new(),
cells: BTreeMap::new(), cells: BTreeMap::new(),
layer_names: BTreeMap::new(), layer_names: BTreeMap::new(),
issues: Vec::new(),
diagnostics: Vec::new(), diagnostics: Vec::new(),
header: self.header.clone(), header: self.header.clone(),
global_issues: Vec::new(), global_issues: Vec::new(),
@ -86,7 +87,7 @@ impl<'a> Document<'a> {
found found
} }
pub(super) fn refresh_issues(&mut self) { pub(super) fn refresh_diagnostics(&mut self) {
self.diagnostics = self.global_issues.clone(); self.diagnostics = self.global_issues.clone();
for (name, cell) in &self.cells { for (name, cell) in &self.cells {
for issue in &cell.issues { for issue in &cell.issues {
@ -106,7 +107,6 @@ impl<'a> Document<'a> {
} }
} }
self.check_graph(); self.check_graph();
self.issues = self.diagnostics.iter().map(|d| d.message.clone()).collect();
} }
/// Project a parsed document. Missing selectors are allowed only for one /// Project a parsed document. Missing selectors are allowed only for one
@ -227,7 +227,7 @@ impl<'a> Document<'a> {
self.layer_names.retain(|pair, _| layers.contains(pair)); self.layer_names.retain(|pair, _| layers.contains(pair));
} }
self.scope = scope.clone(); self.scope = scope.clone();
self.refresh_issues(); self.refresh_diagnostics();
Ok(self) Ok(self)
} }
} }

View file

@ -1,6 +1,6 @@
{ {
"cell_changes": [], "cell_changes": [],
"comparison_profile": "klamath-object-v2", "comparison_profile": "pheon-structural-v1",
"coordinates": { "coordinates": {
"bounds": "coordinate_envelope", "bounds": "coordinate_envelope",
"frame": "cell_local", "frame": "cell_local",

View file

@ -1,6 +1,6 @@
{ {
"cell_changes": [], "cell_changes": [],
"comparison_profile": "klamath-object-v2", "comparison_profile": "pheon-structural-v1",
"coordinates": { "coordinates": {
"bounds": "coordinate_envelope", "bounds": "coordinate_envelope",
"frame": "cell_local", "frame": "cell_local",

View file

@ -225,7 +225,7 @@
] ]
} }
], ],
"comparison_profile": "klamath-object-v2", "comparison_profile": "pheon-structural-v1",
"coordinates": { "coordinates": {
"bounds": "coordinate_envelope", "bounds": "coordinate_envelope",
"frame": "cell_local", "frame": "cell_local",

View file

@ -1,6 +1,6 @@
{ {
"cell_changes": [], "cell_changes": [],
"comparison_profile": "klamath-object-v2", "comparison_profile": "pheon-structural-v1",
"coordinates": { "coordinates": {
"bounds": "coordinate_envelope", "bounds": "coordinate_envelope",
"frame": "cell_local", "frame": "cell_local",

View file

@ -1,6 +1,6 @@
{ {
"cell_changes": [], "cell_changes": [],
"comparison_profile": "klamath-object-v2", "comparison_profile": "pheon-structural-v1",
"coordinates": { "coordinates": {
"bounds": "coordinate_envelope", "bounds": "coordinate_envelope",
"frame": "cell_local", "frame": "cell_local",

View file

@ -1,4 +1,4 @@
profile klamath-object-v2 profile pheon-structural-v1
scope top=all cell=all layer=all scope top=all cell=all layer=all
coordinates: integer database units; bounds: coordinate envelopes coordinates: integer database units; bounds: coordinate envelopes
HEADER=[600] HEADER=[600]

View file

@ -1,4 +1,4 @@
profile klamath-object-v2 profile pheon-structural-v1
scope top=all cell=all layer=all scope top=all cell=all layer=all
cell "CHIP" old@Some(62) new@Some(62) cell "CHIP" old@Some(62) new@Some(62)
~ BOUNDARY modified; coordinate bounds unchanged ~ BOUNDARY modified; coordinate bounds unchanged

View file

@ -5,7 +5,7 @@ mod reports;
use common::{library_header, record}; use common::{library_header, record};
use pheon::{ use pheon::{
records::*, records::*,
review::{Comparison, Document, LAYER_SENTINEL, hierarchy}, review::{Comparison, Document, names::LAYER_SENTINEL},
}; };
use std::{fs, path::PathBuf, process::Command}; use std::{fs, path::PathBuf, process::Command};
@ -251,7 +251,12 @@ fn ten_fixture_pairs_have_explicit_expected_changes() {
let old = Document::parse(&pair.old).unwrap(); let old = Document::parse(&pair.old).unwrap();
let new = Document::parse(&pair.new).unwrap(); let new = Document::parse(&pair.new).unwrap();
let diff = Comparison::between(&old, &new); let diff = Comparison::between(&old, &new);
assert!(diff.issues.is_empty(), "{}: {:?}", pair.name, diff.issues); assert!(
diff.diagnostics.is_empty(),
"{}: {:?}",
pair.name,
diff.diagnostics
);
assert_eq!(diff.cells.len(), pair.changed_cells, "{}", pair.name); assert_eq!(diff.cells.len(), pair.changed_cells, "{}", pair.name);
assert_eq!( assert_eq!(
diff.cells.iter().map(|c| c.removed.len()).sum::<usize>(), diff.cells.iter().map(|c| c.removed.len()).sum::<usize>(),
@ -267,14 +272,14 @@ fn ten_fixture_pairs_have_explicit_expected_changes() {
); );
assert_eq!(diff.layer_names.len(), pair.metadata, "{}", pair.name); assert_eq!(diff.layer_names.len(), pair.metadata, "{}", pair.name);
let equal = pair.changed_cells + pair.metadata == 0; let equal = pair.changed_cells + pair.metadata == 0;
assert_eq!(diff.is_equal(), equal, "{}", pair.name); assert_eq!(diff.outcome().is_equal(), equal, "{}", pair.name);
assert_eq!( assert_eq!(
old.canonical_dump() == new.canonical_dump(), old.canonical_dump() == new.canonical_dump(),
equal, equal,
"{}", "{}",
pair.name pair.name
); );
assert_eq!(diff.exit_code(), if equal { 0 } else { 1 }); assert_eq!(diff.outcome().exit_code(), if equal { 0 } else { 1 });
} }
} }
@ -317,11 +322,11 @@ fn canonical_dump_and_hierarchy_match_versioned_goldens() {
let b = Document::parse(&b).unwrap(); let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b); let diff = Comparison::between(&a, &b);
assert_eq!( assert_eq!(
hierarchy(&a, &b, Some(&diff), false, 8), diff.hierarchy(false, 8),
include_str!("golden/review-hierarchy.txt") include_str!("golden/review-hierarchy.txt")
); );
assert_eq!( assert_eq!(
hierarchy(&a, &b, Some(&diff), true, 8), diff.hierarchy(true, 8),
include_str!("golden/review-hierarchy.mmd") include_str!("golden/review-hierarchy.mmd")
); );
} }
@ -352,7 +357,8 @@ fn cell_and_property_order_do_not_affect_comparison() {
let b = layout(&[("a", vec![]), ("z", vec![b])]); let b = layout(&[("a", vec![]), ("z", vec![b])]);
let a = Document::parse(&a).unwrap(); let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap(); let b = Document::parse(&b).unwrap();
assert!(Comparison::between(&a, &b).is_equal()); 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()); assert_eq!(a.canonical_dump(), b.canonical_dump());
} }
@ -393,9 +399,12 @@ fn metadata_requires_a_sentinel_in_the_same_cell_and_carrier_pair() {
.unwrap() .unwrap()
.contains("1:0:B") .contains("1:0:B")
); );
let future = layout(&[("CHIP", vec![label((9, 0), "KLAMATH_LAYER_NAMES_V2")])]); let future = layout(&[("CHIP", vec![label((9, 0), "PHEON_LAYER_NAMES_V2")])]);
let future = Document::parse(&future).unwrap(); let future = Document::parse(&future).unwrap();
assert_eq!(Comparison::between(&future, &future).exit_code(), 2); assert_eq!(
Comparison::between(&future, &future).outcome().exit_code(),
2
);
} }
#[test] #[test]
@ -407,8 +416,8 @@ fn unknown_records_never_produce_a_successful_equality_claim() {
let bytes = layout(&[("CHIP", vec![unknown])]); let bytes = layout(&[("CHIP", vec![unknown])]);
let doc = Document::parse(&bytes).unwrap(); let doc = Document::parse(&bytes).unwrap();
let diff = Comparison::between(&doc, &doc); let diff = Comparison::between(&doc, &doc);
assert!(!diff.is_equal()); assert!(!diff.outcome().is_equal());
assert_eq!(diff.exit_code(), 2); assert_eq!(diff.outcome().exit_code(), 2);
assert!(doc.record_dump().contains("7f00")); assert!(doc.record_dump().contains("7f00"));
assert!(diff.text(0).contains("INCOMPLETE")); assert!(diff.text(0).contains("INCOMPLETE"));
} }
@ -421,7 +430,7 @@ fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() {
let b = Document::parse(&b).unwrap(); let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b); let diff = Comparison::between(&a, &b);
assert_eq!( assert_eq!(
hierarchy(&a, &b, Some(&diff), false, 8), diff.hierarchy(false, 8),
concat!( concat!(
"scope top=all cell=all layer=all\n", "scope top=all cell=all layer=all\n",
"\"CHIP\" x1 [affected]\n", "\"CHIP\" x1 [affected]\n",
@ -431,11 +440,11 @@ fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() {
" \"leaf\" x3 [cell changed] [shown above]\n", " \"leaf\" x3 [cell changed] [shown above]\n",
) )
); );
let graph = hierarchy(&a, &b, Some(&diff), true, 8); let graph = diff.hierarchy(true, 8);
assert_eq!(graph.matches("leaf [cell changed]").count(), 1); assert_eq!(graph.matches("leaf [cell changed]").count(), 1);
assert!(graph.contains("x2")); assert!(graph.contains("x2"));
assert!(graph.contains("x3")); assert!(graph.contains("x3"));
let limited = hierarchy(&a, &b, Some(&diff), false, 1); let limited = diff.hierarchy(false, 1);
assert!(!limited.contains("\"leaf\"")); assert!(!limited.contains("\"leaf\""));
assert!(limited.contains("children omitted")); assert!(limited.contains("children omitted"));
} }
@ -449,7 +458,7 @@ fn reference_changes_keep_unchanged_targets_and_old_edges_visible() {
let old = Document::parse(&pair.old).unwrap(); let old = Document::parse(&pair.old).unwrap();
let new = Document::parse(&pair.new).unwrap(); let new = Document::parse(&pair.new).unwrap();
let diff = Comparison::between(&old, &new); let diff = Comparison::between(&old, &new);
let tree = hierarchy(&old, &new, Some(&diff), false, 8); let tree = diff.hierarchy(false, 8);
assert!(tree.contains("[cell unchanged]"), "{tree}"); assert!(tree.contains("[cell unchanged]"), "{tree}");
assert!(tree.contains("[reference changed]"), "{tree}"); assert!(tree.contains("[reference changed]"), "{tree}");
if pair.name == "array count" { if pair.name == "array count" {
@ -463,7 +472,7 @@ fn reference_changes_keep_unchanged_targets_and_old_edges_visible() {
let b = layout(&[("CHIP", vec![])]); let b = layout(&[("CHIP", vec![])]);
let a = Document::parse(&a).unwrap(); let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap(); let b = Document::parse(&b).unwrap();
let tree = hierarchy(&a, &b, Some(&Comparison::between(&a, &b)), false, 8); let tree = Comparison::between(&a, &b).hierarchy(false, 8);
assert!(tree.contains("\"leaf\" x1 -> x0"), "{tree}"); assert!(tree.contains("\"leaf\" x1 -> x0"), "{tree}");
} }
@ -479,7 +488,7 @@ fn same_bounds_changes_and_truncated_reports_remain_differences() {
diff.cells[0].added[0].bounds diff.cells[0].added[0].bounds
); );
assert!(diff.text(0).contains("0 of 2 object changes shown")); assert!(diff.text(0).contains("0 of 2 object changes shown"));
assert_eq!(diff.exit_code(), 1); assert_eq!(diff.outcome().exit_code(), 1);
assert!(diff.cells[0].removed[0].offset > 0); assert!(diff.cells[0].removed[0].offset > 0);
} }
@ -494,17 +503,19 @@ fn unit_changes_report_values_without_claiming_geometry_equivalence() {
.unwrap() .unwrap()
.offset; .offset;
let mut b = a.clone(); let mut b = a.clone();
b[units + 12..units + 20].copy_from_slice( b[units + 12..units + 20]
&pheon::basic::encode_real8(2e-9) .copy_from_slice(&pheon::basic::encode_real8(2e-9).unwrap().to_be_bytes());
.unwrap()
.to_be_bytes(),
);
let a = Document::parse(&a).unwrap(); let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap(); let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b); let diff = Comparison::between(&a, &b);
assert_eq!(diff.exit_code(), 1); assert_eq!(diff.outcome().exit_code(), 1);
assert_eq!(diff.library_fields.len(), 1); assert!(matches!(
assert_eq!(diff.library_fields[0].field, "UNITS"); diff.library_changes.as_slice(),
[pheon::review::LibraryChange::Record {
tag: RTAG_UNITS,
..
}]
));
assert!(diff.text(0).contains("UNITS changed")); assert!(diff.text(0).contains("UNITS changed"));
assert!(diff.cells.is_empty()); assert!(diff.cells.is_empty());
} }
@ -515,17 +526,22 @@ fn dangling_references_cycles_and_duplicate_cell_names_are_reported() {
let missing = Document::parse(&missing).unwrap(); let missing = Document::parse(&missing).unwrap();
assert!( assert!(
missing missing
.issues .diagnostics
.iter() .iter()
.any(|s| s.contains("unresolved reference")) .any(|d| d.code == "unresolved_reference")
); );
let cycle = layout(&[ let cycle = layout(&[
("a", vec![reference("b", 0, 1)]), ("a", vec![reference("b", 0, 1)]),
("b", vec![reference("a", 0, 1)]), ("b", vec![reference("a", 0, 1)]),
]); ]);
let cycle = Document::parse(&cycle).unwrap(); let cycle = Document::parse(&cycle).unwrap();
assert!(cycle.issues.iter().any(|s| s.contains("cyclic"))); assert!(
assert!(hierarchy(&cycle, &cycle, None, false, 8).len() < 200); cycle
.diagnostics
.iter()
.any(|d| d.code == "hierarchy_cycle")
);
assert!(cycle.hierarchy(false, 8).len() < 200);
let duplicate = layout(&[("a", vec![]), ("a", vec![])]); let duplicate = layout(&[("a", vec![]), ("a", vec![])]);
assert!( assert!(
Document::parse(&duplicate) Document::parse(&duplicate)
@ -547,6 +563,7 @@ fn absolute_transform_flags_are_not_discarded() {
let b = layout(&[("CHIP", vec![b]), ("leaf", vec![])]); let b = layout(&[("CHIP", vec![b]), ("leaf", vec![])]);
assert_eq!( assert_eq!(
Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()) Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap())
.outcome()
.exit_code(), .exit_code(),
1 1
); );
@ -568,7 +585,11 @@ fn polygon_normalization_handles_repeated_minimum_vertices() {
rotated.push(rotated[0]); rotated.push(rotated[0]);
let candidate = layout(&[("CHIP", vec![polygon(&rotated)])]); let candidate = layout(&[("CHIP", vec![polygon(&rotated)])]);
let candidate = Document::parse(&candidate).unwrap(); let candidate = Document::parse(&candidate).unwrap();
assert!(Comparison::between(&baseline, &candidate).is_equal()); assert!(
Comparison::between(&baseline, &candidate)
.outcome()
.is_equal()
);
} }
open.reverse(); open.reverse();
} }
@ -672,7 +693,7 @@ fn cli_uses_documented_exit_codes_and_accepts_paths_with_spaces() {
#[test] #[test]
fn metadata_writer_preserves_unrelated_bytes_and_consolidates_updates() { fn metadata_writer_preserves_unrelated_bytes_and_consolidates_updates() {
use pheon::review::write_layer_names; use pheon::review::names::write_layer_names;
use std::collections::BTreeMap; use std::collections::BTreeMap;
let mut bytes = shared(with_property(square(), "keep this")); let mut bytes = shared(with_property(square(), "keep this"));
bytes.extend_from_slice(&[0; 32]); bytes.extend_from_slice(&[0; 32]);
@ -720,7 +741,7 @@ fn metadata_writer_preserves_unrelated_bytes_and_consolidates_updates() {
#[test] #[test]
fn metadata_writer_rejects_ambiguous_carriers_versions_and_bad_names() { fn metadata_writer_rejects_ambiguous_carriers_versions_and_bad_names() {
use pheon::review::{parse_layer_name, write_layer_names}; use pheon::review::names::{parse_layer_name, write_layer_names};
use std::collections::BTreeMap; use std::collections::BTreeMap;
let bytes = layout(&[("CHIP", vec![label((900, 7), "ordinary label")])]); let bytes = layout(&[("CHIP", vec![label((900, 7), "ordinary label")])]);
assert!( assert!(
@ -733,7 +754,7 @@ fn metadata_writer_rejects_ambiguous_carriers_versions_and_bad_names() {
.unwrap_err() .unwrap_err()
.contains("does not exist") .contains("does not exist")
); );
let bytes = layout(&[("CHIP", vec![label((900, 7), "KLAMATH_LAYER_NAMES_V2")])]); let bytes = layout(&[("CHIP", vec![label((900, 7), "PHEON_LAYER_NAMES_V2")])]);
assert!( assert!(
write_layer_names(&bytes, "CHIP", (901, 7), &BTreeMap::new()) write_layer_names(&bytes, "CHIP", (901, 7), &BTreeMap::new())
.unwrap_err() .unwrap_err()
@ -788,7 +809,7 @@ fn metadata_cli_creates_a_separate_file_and_refuses_existing_output() {
#[test] #[test]
fn scope_selection_distinguishes_reachable_subtrees_from_exact_cells() { fn scope_selection_distinguishes_reachable_subtrees_from_exact_cells() {
use pheon::review::Scope; use pheon::review::selection::Scope;
let a = layout(&[ let a = layout(&[
("CHIP", vec![reference("leaf", 0, 1)]), ("CHIP", vec![reference("leaf", 0, 1)]),
("leaf", vec![square()]), ("leaf", vec![square()]),
@ -817,8 +838,8 @@ fn scope_selection_distinguishes_reachable_subtrees_from_exact_cells() {
}; };
let old = Document::parse(&a).unwrap().selected(&cell, false).unwrap(); let old = Document::parse(&a).unwrap().selected(&cell, false).unwrap();
let new = Document::parse(&b).unwrap().selected(&cell, false).unwrap(); let new = Document::parse(&b).unwrap().selected(&cell, false).unwrap();
assert!(old.issues.is_empty()); assert!(old.diagnostics.is_empty());
assert!(Comparison::between(&old, &new).is_equal()); assert!(Comparison::between(&old, &new).outcome().is_equal());
let missing = Scope { let missing = Scope {
top: Some("missing".to_string()), top: Some("missing".to_string()),
..Scope::default() ..Scope::default()
@ -843,7 +864,7 @@ fn scope_selection_distinguishes_reachable_subtrees_from_exact_cells() {
#[test] #[test]
fn layer_scope_filters_geometry_and_references_by_descendant_coverage() { fn layer_scope_filters_geometry_and_references_by_descendant_coverage() {
use pheon::review::Scope; use pheon::review::selection::Scope;
let mut other_layer = square(); let mut other_layer = square();
other_layer[8..10].copy_from_slice(&2_u16.to_be_bytes()); other_layer[8..10].copy_from_slice(&2_u16.to_be_bytes());
let a = layout(&[ let a = layout(&[
@ -875,14 +896,17 @@ fn layer_scope_filters_geometry_and_references_by_descendant_coverage() {
.unwrap() .unwrap()
.selected(&scope, false) .selected(&scope, false)
.unwrap(); .unwrap();
assert_eq!(Comparison::between(&old, &new).exit_code(), expected); assert_eq!(
assert!(old.issues.is_empty()); Comparison::between(&old, &new).outcome().exit_code(),
expected
);
assert!(old.diagnostics.is_empty());
} }
} }
#[test] #[test]
fn scoped_issues_do_not_hide_relevant_unsupported_objects_or_cycles() { fn scoped_issues_do_not_hide_relevant_unsupported_objects_or_cycles() {
use pheon::review::Scope; use pheon::review::selection::Scope;
let mut unknown = square(); let mut unknown = square();
unknown.truncate(unknown.len() - 4); unknown.truncate(unknown.len() - 4);
record(&mut unknown, 0x7f00, &[]); record(&mut unknown, 0x7f00, &[]);
@ -897,7 +921,7 @@ fn scoped_issues_do_not_hide_relevant_unsupported_objects_or_cycles() {
.unwrap() .unwrap()
.selected(&scope, false) .selected(&scope, false)
.unwrap() .unwrap()
.issues .diagnostics
.is_empty() .is_empty()
); );
let scope = Scope { let scope = Scope {
@ -909,7 +933,7 @@ fn scoped_issues_do_not_hide_relevant_unsupported_objects_or_cycles() {
.unwrap() .unwrap()
.selected(&scope, false) .selected(&scope, false)
.unwrap() .unwrap()
.issues .diagnostics
.is_empty() .is_empty()
); );
let bytes = layout(&[ let bytes = layout(&[
@ -925,15 +949,15 @@ fn scoped_issues_do_not_hide_relevant_unsupported_objects_or_cycles() {
.unwrap() .unwrap()
.selected(&scope, false) .selected(&scope, false)
.unwrap() .unwrap()
.issues .diagnostics
.iter() .iter()
.any(|s| s.contains("cyclic")) .any(|d| d.code == "hierarchy_cycle")
); );
} }
#[test] #[test]
fn display_filters_never_change_equality_or_totals() { fn display_filters_never_change_equality_or_totals() {
use pheon::review::DisplayFilter; use pheon::review::selection::DisplayFilter;
let a = layout(&[("CHIP", vec![square()])]); let a = layout(&[("CHIP", vec![square()])]);
let b = layout(&[("CHIP", vec![triangle()])]); let b = layout(&[("CHIP", vec![triangle()])]);
let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap()); let diff = Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap());
@ -946,7 +970,7 @@ fn display_filters_never_change_equality_or_totals() {
); );
assert!(text.contains("display-only")); assert!(text.contains("display-only"));
assert!(text.contains("0 of 2 object changes shown")); assert!(text.contains("0 of 2 object changes shown"));
assert_eq!(diff.exit_code(), 1); assert_eq!(diff.outcome().exit_code(), 1);
} }
#[test] #[test]
@ -1057,11 +1081,7 @@ fn git_external_driver_handles_changes_additions_deletions_and_errors() {
assert!(text.contains("renamed layout.gds"), "{text}"); assert!(text.contains("renamed layout.gds"), "{text}");
assert!(text.contains("2 of 2 object changes shown"), "{text}"); assert!(text.contains("2 of 2 object changes shown"), "{text}");
git(&["commit", "-qm", "rename fixture"]); git(&["commit", "-qm", "rename fixture"]);
fs::write( fs::write(directory.join(".gitattributes"), "*.gds diff=pheon-text\n").unwrap();
directory.join(".gitattributes"),
"*.gds diff=pheon-text\n",
)
.unwrap();
fs::write(&renamed, shared(square())).unwrap(); fs::write(&renamed, shared(square())).unwrap();
let result = git(&["diff", "--", "renamed layout.gds"]); let result = git(&["diff", "--", "renamed layout.gds"]);
assert!( assert!(
@ -1145,13 +1165,25 @@ fn unchanged_layer_names_explain_geometry_changes_once() {
} }
#[test] #[test]
fn an_added_empty_document_is_still_a_presence_change() { fn library_presence_changes_distinguish_empty_and_absent_revisions() {
let bytes = layout(&[]); let bytes = layout(&[]);
let doc = Document::parse(&bytes).unwrap(); let doc = Document::parse(&bytes).unwrap();
let diff = Comparison::between(&doc.empty_like(), &doc); let absent = doc.empty_like();
assert_eq!(diff.exit_code(), 1); let added = Comparison::between(&absent, &doc);
assert!(diff.text(0).contains("library presence:")); assert_eq!(added.outcome().exit_code(), 1);
assert!(!diff.text(0).contains("equal under")); assert!(
added
.text(0)
.contains("library presence: [\"absent\"] -> [\"present\"]\n")
);
assert!(!added.text(0).contains("equal under"));
let removed = Comparison::between(&doc, &absent);
assert_eq!(removed.outcome().exit_code(), 1);
assert!(
removed
.text(0)
.contains("library presence: [\"present\"] -> [\"absent\"]\n")
);
} }
#[test] #[test]
@ -1213,8 +1245,8 @@ fn large_polygons_and_billion_instance_arrays_stay_compact() {
32767 * 32767 32767 * 32767
); );
assert_eq!(doc.cells["CHIP"].objects.len(), 1); assert_eq!(doc.cells["CHIP"].objects.len(), 1);
assert!(hierarchy(&doc, &doc, None, false, 8).len() < 200); assert!(doc.hierarchy(false, 8).len() < 200);
assert!(Comparison::between(&doc, &doc).is_equal()); assert!(Comparison::between(&doc, &doc).outcome().is_equal());
} }
#[test] #[test]
@ -1241,7 +1273,7 @@ fn deep_hierarchy_comparison_and_rendering_are_iterative() {
let a = Document::parse(&a).unwrap(); let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap(); let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b); let diff = Comparison::between(&a, &b);
let tree = hierarchy(&a, &b, Some(&diff), false, 5); let tree = diff.hierarchy(false, 5);
assert_eq!(diff.cells.len(), 1); assert_eq!(diff.cells.len(), 1);
assert!(tree.contains("children omitted")); assert!(tree.contains("children omitted"));
assert!(tree.len() < 500); assert!(tree.len() < 500);

View file

@ -1,7 +1,8 @@
use super::*; use super::*;
use pheon::review::{ use pheon::review::{
DisplayFilter, Scope, Diagnostic, Outcome, Side,
report::{ReportInputs, ReportOptions, failure_report}, report::{ReportInputs, ReportOptions, failure_report},
selection::{DisplayFilter, Scope},
}; };
use serde_json::{Value, json}; use serde_json::{Value, json};
@ -15,7 +16,7 @@ fn inputs() -> ReportInputs {
fn report(old: &[u8], new: &[u8], options: &ReportOptions) -> Value { fn report(old: &[u8], new: &[u8], options: &ReportOptions) -> Value {
let a = Document::parse(old).unwrap(); let a = Document::parse(old).unwrap();
let b = Document::parse(new).unwrap(); let b = Document::parse(new).unwrap();
Comparison::between(&a, &b).json_report(&a, &b, &inputs(), options) Comparison::between(&a, &b).json_report(&inputs(), options)
} }
fn unknown(geometry: Vec<u8>) -> Vec<u8> { fn unknown(geometry: Vec<u8>) -> Vec<u8> {
@ -26,12 +27,109 @@ fn unknown(geometry: Vec<u8>) -> Vec<u8> {
layout(&[("CHIP", vec![object])]) layout(&[("CHIP", vec![object])])
} }
#[test]
fn comparison_reports_survive_dropped_documents_and_overwritten_inputs() {
let comparison = {
let mut old_bytes = shared(square());
let mut new_bytes = shared(triangle());
let old = Document::parse(&old_bytes).unwrap();
let new = Document::parse(&new_bytes).unwrap();
let comparison = Comparison::between(&old, &new);
drop(old);
drop(new);
old_bytes.fill(0);
new_bytes.fill(0);
comparison
};
assert_eq!(comparison.outcome(), Outcome::Different);
assert!(comparison.old.present && comparison.new.present);
assert_eq!(comparison.old.units.as_ref().unwrap().len(), 16);
let mut actual = comparison.json_report(
&inputs(),
&ReportOptions {
hierarchy: true,
..Default::default()
},
);
actual["producer"]["version"] = json!("test");
let expected: Value =
serde_json::from_str(include_str!("../golden/report-geometry.json")).unwrap();
assert_eq!(actual, expected);
assert_eq!(
comparison.hierarchy(false, 8),
include_str!("../golden/review-hierarchy.txt")
);
assert_eq!(
comparison.hierarchy(true, 8),
include_str!("../golden/review-hierarchy.mmd")
);
// Display choices affect evidence, not the captured outcome or full graph.
let limited = comparison.json_report(
&inputs(),
&ReportOptions {
hierarchy: true,
max_objects: Some(0),
..Default::default()
},
);
assert_eq!(limited["hierarchy"], actual["hierarchy"]);
assert_eq!(limited["summary"], actual["summary"]);
assert_eq!(limited["exit_code"], 1);
assert!(comparison.text(0).contains("0 of 2 object changes shown"));
}
#[test]
fn comparison_diagnostics_capture_both_sides_and_scope_mismatch_once() {
let comparison = {
let bytes = unknown(square());
let old = Document::parse(&bytes)
.unwrap()
.selected(
&Scope {
cell: Some("CHIP".to_string()),
..Default::default()
},
false,
)
.unwrap();
let mut new = Document::parse(&bytes).unwrap();
let comparison = Comparison::between(&old, &new);
// Changes to source documents cannot alter an existing result.
new.scope = old.scope.clone();
new.diagnostics.clear();
comparison
};
assert_eq!(
comparison.outcome(),
Outcome::Incomplete { different: false }
);
assert_eq!(comparison.diagnostics.len(), 3);
assert_eq!(comparison.diagnostics[0].side, Some(Side::Old));
assert_eq!(comparison.diagnostics[1].side, Some(Side::New));
assert_eq!(comparison.diagnostics[2].code, "scope_mismatch");
assert_eq!(comparison.diagnostics[2].side, None);
let report = comparison.json_report(&inputs(), &ReportOptions::default());
assert_eq!(report["status"], "incomplete");
assert_eq!(report["result"], "unknown");
assert_eq!(report["exit_code"], 2);
assert_eq!(report["scope"]["cell"], "CHIP");
assert_eq!(report["diagnostics"].as_array().unwrap().len(), 3);
assert_eq!(report["diagnostics"][0]["side"], "old");
assert_eq!(report["diagnostics"][1]["side"], "new");
assert_eq!(report["diagnostics"][2]["code"], "scope_mismatch");
let text = comparison.text(0);
let scope = text.find("INCOMPLETE: comparison scopes differ").unwrap();
let old = text.find("INCOMPLETE: old:").unwrap();
let new = text.find("INCOMPLETE: new:").unwrap();
assert!(scope < old && old < new);
}
#[test] #[test]
fn reports_preserve_fixture_results_totals_and_replacement_links() { fn reports_preserve_fixture_results_totals_and_replacement_links() {
for pair in corpus() { for pair in corpus() {
let r = report(&pair.old, &pair.new, &ReportOptions::default()); let r = report(&pair.old, &pair.new, &ReportOptions::default());
assert_eq!(r["schema_version"], 1); assert_eq!(r["schema_version"], 1);
assert_eq!(r["comparison_profile"], "klamath-object-v2"); assert_eq!(r["comparison_profile"], "pheon-structural-v1");
assert_eq!(r["producer"]["version"], env!("CARGO_PKG_VERSION")); assert_eq!(r["producer"]["version"], env!("CARGO_PKG_VERSION"));
assert_eq!(r["status"], "complete", "{}", pair.name); assert_eq!(r["status"], "complete", "{}", pair.name);
assert_eq!( assert_eq!(
@ -110,12 +208,12 @@ fn future_layer_metadata_remains_incomplete_under_geometry_scopes() {
let bytes = if location == "CHIP" { let bytes = if location == "CHIP" {
layout(&[( layout(&[(
"CHIP", "CHIP",
vec![square(), label((900, 7), "KLAMATH_LAYER_NAMES_V2")], vec![square(), label((900, 7), "PHEON_LAYER_NAMES_V2")],
)]) )])
} else { } else {
layout(&[ layout(&[
("CHIP", vec![square()]), ("CHIP", vec![square()]),
("legend", vec![label((900, 7), "KLAMATH_LAYER_NAMES_V2")]), ("legend", vec![label((900, 7), "PHEON_LAYER_NAMES_V2")]),
]) ])
}; };
let source = Document::parse(&bytes).unwrap().diagnostics[0].offset; let source = Document::parse(&bytes).unwrap().diagnostics[0].offset;
@ -159,10 +257,10 @@ fn future_layer_metadata_remains_incomplete_under_geometry_scopes() {
assert_eq!(diagnostic.layer, Some((900, 7))); assert_eq!(diagnostic.layer, Some((900, 7)));
assert_eq!(diagnostic.offset, source); assert_eq!(diagnostic.offset, source);
let diff = Comparison::between(&doc, &doc); let diff = Comparison::between(&doc, &doc);
assert_eq!(diff.exit_code(), 2); assert_eq!(diff.outcome().exit_code(), 2);
assert!(!diff.is_equal()); assert!(!diff.outcome().is_equal());
assert!(diff.text(0).contains("INCOMPLETE")); assert!(diff.text(0).contains("INCOMPLETE"));
let json = diff.json_report(&doc, &doc, &inputs(), &ReportOptions::default()); let json = diff.json_report(&inputs(), &ReportOptions::default());
assert_eq!(json["status"], "incomplete"); assert_eq!(json["status"], "incomplete");
assert_eq!(json["result"], "unknown"); assert_eq!(json["result"], "unknown");
assert_eq!(json["exit_code"], 2); assert_eq!(json["exit_code"], 2);
@ -339,7 +437,7 @@ fn hierarchy_reports_shared_ancestors_and_symbolic_arrays() {
.unwrap() .unwrap()
.selected(&scope, false) .selected(&scope, false)
.unwrap(); .unwrap();
let r = Comparison::between(&doc, &doc).json_report(&doc, &doc, &inputs(), &options); let r = Comparison::between(&doc, &doc).json_report(&inputs(), &options);
assert_eq!(r["scope"]["cell"], "CHIP"); assert_eq!(r["scope"]["cell"], "CHIP");
assert_eq!( assert_eq!(
r["hierarchy"]["nodes"] r["hierarchy"]["nodes"]
@ -369,6 +467,14 @@ fn library_attributes_empty_cells_units_and_absence_are_explicit() {
let r = report(&a, &b, &ReportOptions::default()); let r = report(&a, &b, &ReportOptions::default());
assert_eq!(r["cell_changes"][0]["before"], Value::Null); assert_eq!(r["cell_changes"][0]["before"], Value::Null);
assert_eq!(r["cell_changes"][0]["after"]["attributes"], json!([])); assert_eq!(r["cell_changes"][0]["after"]["attributes"], json!([]));
assert_eq!(r["cell_changes"][0]["attributes_changed"], true);
let removed = report(&b, &a, &ReportOptions::default());
assert_eq!(
removed["cell_changes"][0]["before"]["attributes"],
json!([])
);
assert_eq!(removed["cell_changes"][0]["after"], Value::Null);
assert_eq!(removed["cell_changes"][0]["attributes_changed"], true);
let mut b = b; let mut b = b;
let end = Document::parse(&b).unwrap().cells["empty"].end_offset; let end = Document::parse(&b).unwrap().cells["empty"].end_offset;
let mut attribute = Vec::new(); let mut attribute = Vec::new();
@ -379,15 +485,11 @@ fn library_attributes_empty_cells_units_and_absence_are_explicit() {
r["cell_changes"][0]["after"]["attributes"][0]["value"], r["cell_changes"][0]["after"]["attributes"][0]["value"],
json!([1]) json!([1])
); );
assert_eq!(r["cell_changes"][0]["attributes_changed"], true);
assert_eq!(r["inputs"]["old"]["units"]["encoding"], "real8"); assert_eq!(r["inputs"]["old"]["units"]["encoding"], "real8");
let doc = Document::parse(&a).unwrap(); let doc = Document::parse(&a).unwrap();
let absent = doc.empty_like(); let absent = doc.empty_like();
let r = Comparison::between(&absent, &doc).json_report( let r = Comparison::between(&absent, &doc).json_report(&inputs(), &ReportOptions::default());
&absent,
&doc,
&inputs(),
&ReportOptions::default(),
);
assert_eq!(r["inputs"]["old"]["present"], false); assert_eq!(r["inputs"]["old"]["present"], false);
assert_eq!(r["inputs"]["old"]["units"], Value::Null); assert_eq!(r["inputs"]["old"]["units"], Value::Null);
assert_eq!( assert_eq!(
@ -401,11 +503,8 @@ fn library_attributes_empty_cells_units_and_absence_are_explicit() {
.find(|r| r.tag == RTAG_UNITS) .find(|r| r.tag == RTAG_UNITS)
.unwrap() .unwrap()
.offset; .offset;
b[units + 12..units + 20].copy_from_slice( b[units + 12..units + 20]
&pheon::basic::encode_real8(2e-9) .copy_from_slice(&pheon::basic::encode_real8(2e-9).unwrap().to_be_bytes());
.unwrap()
.to_be_bytes(),
);
let r = report(&a, &b, &ReportOptions::default()); let r = report(&a, &b, &ReportOptions::default());
assert_eq!(r["library_changes"][0]["tag"], RTAG_UNITS); assert_eq!(r["library_changes"][0]["tag"], RTAG_UNITS);
assert_ne!(r["inputs"]["old"]["units"], r["inputs"]["new"]["units"]); assert_ne!(r["inputs"]["old"]["units"], r["inputs"]["new"]["units"]);
@ -530,9 +629,7 @@ fn machine_reports_match_versioned_goldens() {
&inputs(), &inputs(),
&Scope::default(), &Scope::default(),
&ReportOptions::default(), &ReportOptions::default(),
"invalid_input", &Diagnostic::new("invalid_input", "truncated record", Some(Side::New)),
"truncated record",
Some("new"),
), ),
), ),
]; ];
@ -580,6 +677,24 @@ fn cli_emits_json_for_success_input_errors_scope_errors_and_argument_errors() {
); );
report report
}; };
let check_text_failure = |report: &Value, extra: &[&str]| {
let output = Command::new(env!("CARGO_BIN_EXE_pheon"))
.arg("diff")
.arg(&a)
.arg(&b)
.args(extra)
.output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
assert!(output.stdout.is_empty());
assert_eq!(
String::from_utf8(output.stderr).unwrap(),
format!(
"pheon: {}\n",
report["diagnostics"][0]["message"].as_str().unwrap()
)
);
};
let full = command(&["--hierarchy", "graph"]); let full = command(&["--hierarchy", "graph"]);
assert_eq!(full["result"], "different"); assert_eq!(full["result"], "different");
assert!(full["hierarchy"].is_object()); assert!(full["hierarchy"].is_object());
@ -597,14 +712,35 @@ fn cli_emits_json_for_success_input_errors_scope_errors_and_argument_errors() {
assert_eq!(failure["status"], "failed"); assert_eq!(failure["status"], "failed");
assert_eq!(failure["result"], "unknown"); assert_eq!(failure["result"], "unknown");
assert_eq!(failure["summary"], Value::Null); assert_eq!(failure["summary"], Value::Null);
if extra.first() == Some(&"--top") {
assert_eq!(failure["diagnostics"][0]["code"], "invalid_scope");
assert_eq!(failure["diagnostics"][0]["side"], Value::Null);
check_text_failure(&failure, extra);
}
} }
fs::write(&b, b"invalid").unwrap(); fs::write(&b, b"invalid").unwrap();
let invalid = command(&[]); let invalid = command(&[]);
assert_eq!(invalid["diagnostics"][0]["code"], "invalid_input"); assert_eq!(invalid["diagnostics"][0]["code"], "invalid_input");
assert_eq!(invalid["diagnostics"][0]["side"], "new"); assert_eq!(invalid["diagnostics"][0]["side"], "new");
assert_eq!(invalid["inputs"]["new"]["path"], b.to_str().unwrap()); assert_eq!(invalid["inputs"]["new"]["path"], b.to_str().unwrap());
check_text_failure(&invalid, &[]);
fs::write(&a, b"invalid").unwrap();
let invalid = command(&[]);
assert_eq!(invalid["diagnostics"][0]["code"], "invalid_input");
assert_eq!(invalid["diagnostics"][0]["side"], "old");
check_text_failure(&invalid, &[]);
fs::write(&a, shared(square())).unwrap();
fs::remove_file(&b).unwrap(); fs::remove_file(&b).unwrap();
assert_eq!(command(&[])["diagnostics"][0]["code"], "io_error"); let missing = command(&[]);
assert_eq!(missing["diagnostics"][0]["code"], "io_error");
assert_eq!(missing["diagnostics"][0]["side"], "new");
check_text_failure(&missing, &[]);
fs::remove_file(&a).unwrap();
let missing = command(&[]);
assert_eq!(missing["diagnostics"][0]["code"], "io_error");
assert_eq!(missing["diagnostics"][0]["side"], "old");
check_text_failure(&missing, &[]);
fs::write(&a, shared(square())).unwrap();
fs::write(&b, fs::read(&a).unwrap()).unwrap(); fs::write(&b, fs::read(&a).unwrap()).unwrap();
assert_eq!(command(&[])["result"], "equal"); assert_eq!(command(&[])["result"], "equal");
fs::write(&b, unknown(square())).unwrap(); fs::write(&b, unknown(square())).unwrap();
@ -613,7 +749,7 @@ fn cli_emits_json_for_success_input_errors_scope_errors_and_argument_errors() {
&b, &b,
layout(&[ layout(&[
("CHIP", vec![square()]), ("CHIP", vec![square()]),
("legend", vec![label((900, 7), "KLAMATH_LAYER_NAMES_V2")]), ("legend", vec![label((900, 7), "PHEON_LAYER_NAMES_V2")]),
]), ]),
) )
.unwrap(); .unwrap();

Some files were not shown because too many files have changed in this diff Show more