Compare commits

...
33 changed files with 3053 additions and 127 deletions

5
.gitignore vendored
View file

@ -4,3 +4,8 @@ Cargo.lock
*.swp *.swp
*.swo *.swo
__pycache__/
/build/
/dist/
/*.egg-info/

View file

@ -93,6 +93,12 @@ References point to other cells in the library.
- `xy1`: `UInt64` (Packed row basis vector increment) - `xy1`: `UInt64` (Packed row basis vector increment)
- `counts`: `UInt32` (Packed columns and rows) - `counts`: `UInt32` (Packed columns and rows)
Array increments must be exact signed 32-bit integer database-unit values. Full
reads, hierarchy scans, selected reads, and their FFI entry points reject arrays
whose endpoint/count division is fractional or outside that range. They never
round or truncate placements. The review CLI retains original endpoints and can
compare fractional arrays independently of this Arrow representation.
**SRefProp / ARefProp**: **SRefProp / ARefProp**:
- Same as above, plus a `properties` field. - Same as above, plus a `properties` field.

View file

@ -13,6 +13,7 @@ crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
byteorder = "^1" byteorder = "^1"
arrow = {version = "^54", features = ["ffi"]} arrow = {version = "^54", features = ["ffi"]}
serde_json = "1"
[profile.release] [profile.release]

6
MANIFEST.in Normal file
View file

@ -0,0 +1,6 @@
include Cargo.toml Cargo.lock README.md ARROW_SCHEMA.md
recursive-include src *.rs
recursive-include klamath_rs_ext *.py *.h py.typed
recursive-include tests *.rs *.py *.json *.txt *.mmd
recursive-include docs *.md *.json
recursive-include contrib *

View file

@ -18,6 +18,10 @@ A fast GDSII parser and writer in Rust, with Apache Arrow integration for effici
- Optimized "batch" representations for rectangles and boundaries sharing the same layer. - Optimized "batch" representations for rectangles and boundaries sharing the same layer.
- C-compatible FFI for integration with other languages (e.g., Python). - C-compatible FFI for integration with other languages (e.g., Python).
REAL8 writing uses normalized GDS encodings and represents every in-range `f64`
exactly. Finite magnitudes below `2^-260` underflow to canonical zero; nonfinite
values and magnitudes at or above `2^252` are rejected by the encoder.
## Usage ## Usage
`read_path` exports a library through the Arrow C Data Interface. Allocate `read_path` exports a library through the Arrow C Data Interface. Allocate
@ -54,9 +58,54 @@ range values must be aligned. Exported Arrow data owns its storage independently
of the input. See [Arrow Schema Documentation](ARROW_SCHEMA.md) for the scan of the input. See [Arrow Schema Documentation](ARROW_SCHEMA.md) for the scan
schema, offset definitions, and ID assignment. schema, offset definitions, and ID assignment.
## Python package and validation
The Python packing helpers require NumPy and CFFI, both declared as runtime
dependencies. Setuptools invokes `cargo build --release --lib` and bundles the
C ABI shared library in a platform-specific wheel. Its version comes from
`Cargo.toml`. The C declarations are in `klamath_rs_ext/_ffi.h`; the loader uses
CFFI ABI mode, so no Python extension compilation or Maturin is required.
```sh
python3 -m pip install .
```
To build a source archive and a wheel with the `build` frontend and installed
Setuptools/Wheel tooling:
```sh
python3 -m build --no-isolation
```
Source archives include a Cargo lockfile, and wheel builds use `--locked` so
building from an archive retains the resolved Rust dependency versions. Wheels
are tagged for the build platform and use the Python-independent `py3-none` ABI.
The CLI continues to build directly with Cargo and has no Python dependency.
For source-tree development, point the CFFI loader at a Cargo-built library:
```sh
cargo build --release --lib
KLAMATH_RS_LIBRARY="$PWD/target/release/libklamath_rs_ext.so" \
python3 -m unittest discover -s tests/python -v
```
Use `libklamath_rs_ext.dylib` on macOS or `klamath_rs_ext.dll` on Windows. Without
the explicit override, the loader uses the library bundled inside the package.
After installing a wheel, run its tests outside the source checkout to exercise
the installed package:
```sh
python3 -I -m unittest discover -s /absolute/path/to/klamath-rs/tests/python -v
```
The Python tests cover multidimensional and noncontiguous packing, input
preservation, range errors, and the C declarations for Arrow exports and release
callbacks. Run `cargo test` and `cargo test --release` for native validation.
## Layout review CLI ## Layout review CLI
The review CLI uses the existing Rust dependencies: The review CLI is a standalone Rust executable:
```sh ```sh
cargo build --bin klamath cargo build --bin klamath
@ -67,6 +116,8 @@ target/debug/klamath diff old.gds new.gds --hierarchy mermaid --max-changes 20
target/debug/klamath hierarchy chip.gds --format mermaid --depth 4 target/debug/klamath hierarchy chip.gds --format mermaid --depth 4
target/debug/klamath diff old.gds new.gds --top CHIP --layer 1/0 target/debug/klamath diff old.gds new.gds --top CHIP --layer 1/0
target/debug/klamath diff old.gds new.gds --show-layer 1/0 target/debug/klamath diff old.gds new.gds --show-layer 1/0
target/debug/klamath diff old.gds new.gds --format json
target/debug/klamath diff old.gds new.gds --format json --hierarchy graph
target/debug/klamath name-layers chip.gds named.gds --cell CHIP --carrier 900/7 --name 1:0:WG target/debug/klamath name-layers chip.gds named.gds --cell CHIP --carrier 900/7 --name 1:0:WG
``` ```
@ -98,6 +149,16 @@ and **2** for invalid input or incomplete comparison. `--max-changes` limits the
number of object details displayed, not the comparison. Source offsets are number of object details displayed, not the comparison. Source offsets are
included in changed-object reports for tracing changes back to record dumps. included in changed-object reports for tracing changes back to record dumps.
`diff --format json` emits a versioned report with typed before/after evidence,
structured diagnostics, and independent comparison status and completeness.
JSON includes all changes by default. Explicit display filters and `--max-changes`
record omitted evidence without changing totals or exit status. `--hierarchy graph`
adds the complete scoped reference graph, with symbolic array multiplicities;
`--depth` applies to text output only. Timestamp-only changes still return 0.
Input and argument errors also produce JSON when requested. See the
[report contract](docs/diff-reports.md) and
[version 1 JSON Schema](docs/diff-report-v1.schema.json).
Unmatched objects are paired for explanation only when candidates are unique by Unmatched objects are paired for explanation only when candidates are unique by
type/layer/bounding box, then by type/layer among the remaining objects. type/layer/bounding box, then by type/layer among the remaining objects.
References additionally match by target. Ambiguous groups stay additions and References additionally match by target. Ambiguous groups stay additions and
@ -118,7 +179,9 @@ side is an addition/deletion.
targets use that layer transitively. Cells with no relevant content are omitted. targets use that layer transitively. Cells with no relevant content are omitted.
Unresolved references, cycles, and unsupported records with unknown layer effect Unresolved references, cycles, and unsupported records with unknown layer effect
remain incomplete results. Unsupported objects on another known layer can be remain incomplete results. Unsupported objects on another known layer can be
excluded. Library fields, including units, remain compared. Scoped dumps and excluded. Library fields, including units, remain compared. Unsupported layer-name
version diagnostics are always retained, since those declarations can affect any
layer or cell in the library. Scoped dumps and
hierarchy views accept the same selectors. Scope selection parses the complete hierarchy views accept the same selectors. Scope selection parses the complete
input: malformed record grammar and conflicting metadata are still errors. input: malformed record grammar and conflicting metadata are still errors.

View file

@ -0,0 +1,206 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Klamath diff report version 1",
"description": "Object-profile comparison evidence, not a layout serialization. Unknown additional fields are permitted for compatible extensions.",
"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"],
"properties": {
"schema_version": {"const": 1},
"kind": {"const": "diff"},
"producer": {
"type": "object", "required": ["name", "version"],
"properties": {"name": {"const": "klamath"}, "version": {"type": "string"}}
},
"comparison_profile": {"type": "string"},
"inputs": {
"type": "object", "required": ["old", "new"],
"properties": {"old": {"$ref": "#/$defs/input"}, "new": {"$ref": "#/$defs/input"}}
},
"scope": {
"type": "object", "required": ["top", "cell", "layer"],
"properties": {"top": {"type": ["string", "null"]}, "cell": {"type": ["string", "null"]}, "layer": {"$ref": "#/$defs/nullableLayer"}}
},
"coordinates": {
"type": "object", "required": ["unit", "frame", "bounds"],
"properties": {"unit": {"const": "database_unit"}, "frame": {"const": "cell_local"}, "bounds": {"const": "coordinate_envelope"}}
},
"status": {"enum": ["complete", "incomplete", "failed"]},
"result": {"enum": ["equal", "different", "unknown"]},
"exit_code": {"enum": [0, 1, 2]},
"summary": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/summary"}]},
"report_selection": {"$ref": "#/$defs/selection"},
"layer_legend": {
"type": "array", "items": {
"type": "object", "required": ["layer", "name"],
"properties": {"layer": {"$ref": "#/$defs/layer"}, "name": {"type": "string"}}
}
},
"library_changes": {"type": "array", "items": {"$ref": "#/$defs/libraryChange"}},
"layer_name_changes": {
"type": "array", "items": {
"type": "object", "required": ["layer", "before", "after"],
"properties": {"layer": {"$ref": "#/$defs/layer"}, "before": {"type": ["string", "null"]}, "after": {"type": ["string", "null"]}}
}
},
"cell_changes": {"type": "array", "items": {"$ref": "#/$defs/cellChange"}},
"hierarchy": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/graph"}]},
"diagnostics": {"type": "array", "items": {"$ref": "#/$defs/diagnostic"}}
},
"allOf": [
{
"if": {"properties": {"status": {"const": "complete"}}},
"then": {
"properties": {"result": {"enum": ["equal", "different"]}, "summary": {"$ref": "#/$defs/summary", "properties": {"counts": {"const": "exact"}}}, "diagnostics": {"maxItems": 0}},
"if": {"properties": {"result": {"const": "equal"}}},
"then": {"properties": {"exit_code": {"const": 0}}},
"else": {"properties": {"exit_code": {"const": 1}}}
},
"else": {"properties": {"exit_code": {"const": 2}, "diagnostics": {"minItems": 1}}}
},
{
"if": {"properties": {"status": {"const": "incomplete"}}},
"then": {"properties": {"result": {"enum": ["different", "unknown"]}, "summary": {"$ref": "#/$defs/summary", "properties": {"counts": {"const": "observed"}}}}}
},
{
"if": {"properties": {"status": {"const": "failed"}}},
"then": {"properties": {"result": {"const": "unknown"}, "summary": {"type": "null"}, "library_changes": {"maxItems": 0}, "layer_name_changes": {"maxItems": 0}, "cell_changes": {"maxItems": 0}, "hierarchy": {"type": "null"}}}
}
],
"$defs": {
"decimal": {"type": "string", "pattern": "^(0|[1-9][0-9]*)$"},
"hex": {"type": "string", "pattern": "^0x([0-9a-f]{2})*$"},
"uint16": {"type": "integer", "minimum": 0, "maximum": 65535},
"int32": {"type": "integer", "minimum": -2147483648, "maximum": 2147483647},
"layer": {
"type": "object", "required": ["number", "purpose"],
"properties": {"number": {"$ref": "#/$defs/uint16"}, "purpose": {"$ref": "#/$defs/uint16"}}
},
"nullableLayer": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/layer"}]},
"point": {"type": "array", "minItems": 2, "maxItems": 2, "items": {"$ref": "#/$defs/int32"}},
"fields": {"type": "array", "items": {"$ref": "#/$defs/field"}},
"field": {
"type": "object", "required": ["tag", "name", "encoding", "value", "payload_hex"],
"properties": {
"tag": {"$ref": "#/$defs/uint16"}, "name": {"type": "string"},
"encoding": {"enum": ["xy", "uint16", "int16", "int32", "bits", "real8", "ascii", "none", "bytes"]},
"payload_hex": {"$ref": "#/$defs/hex"},
"value": {"type": ["array", "string", "null"]}
},
"allOf": [
{"if": {"properties": {"encoding": {"const": "xy"}}}, "then": {"properties": {"value": {"type": "array", "items": {"$ref": "#/$defs/point"}}}}},
{"if": {"properties": {"encoding": {"enum": ["uint16", "bits"]}}}, "then": {"properties": {"value": {"type": "array", "items": {"$ref": "#/$defs/uint16"}}}}},
{"if": {"properties": {"encoding": {"const": "int16"}}}, "then": {"properties": {"value": {"type": "array", "items": {"type": "integer", "minimum": -32768, "maximum": 32767}}}}},
{"if": {"properties": {"encoding": {"const": "int32"}}}, "then": {"properties": {"value": {"type": "array", "items": {"$ref": "#/$defs/int32"}}}}},
{"if": {"properties": {"encoding": {"const": "real8"}}}, "then": {"properties": {"value": {"type": "array", "items": {"type": ["number", "null"]}}}}},
{"if": {"properties": {"encoding": {"const": "ascii"}}}, "then": {"properties": {"value": {"type": ["string", "null"]}}}},
{"if": {"properties": {"encoding": {"enum": ["none", "bytes"]}}}, "then": {"properties": {"value": {"type": "null"}}}}
]
},
"input": {
"type": "object", "required": ["path", "path_encoded_hex", "present", "units"],
"properties": {
"path": {"type": ["string", "null"]},
"path_encoded_hex": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/hex"}]},
"present": {"type": ["boolean", "null"]},
"units": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/field"}]}
}
},
"summary": {
"type": "object", "required": ["counts", "changed_cells", "removed_objects", "added_objects", "layer_name_changes", "library_field_changes"],
"properties": {
"counts": {"enum": ["exact", "observed"]},
"changed_cells": {"$ref": "#/$defs/decimal"}, "removed_objects": {"$ref": "#/$defs/decimal"}, "added_objects": {"$ref": "#/$defs/decimal"},
"layer_name_changes": {"$ref": "#/$defs/decimal"}, "library_field_changes": {"$ref": "#/$defs/decimal"}
}
},
"selection": {
"type": "object", "required": ["cell", "layer", "max_objects", "truncated", "filtered_cells", "filtered_objects", "limited_objects", "emitted_objects"],
"properties": {
"cell": {"type": ["string", "null"]}, "layer": {"$ref": "#/$defs/nullableLayer"},
"max_objects": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/decimal"}]}, "truncated": {"type": "boolean"},
"filtered_cells": {"$ref": "#/$defs/decimal"}, "filtered_objects": {"$ref": "#/$defs/decimal"},
"limited_objects": {"$ref": "#/$defs/decimal"}, "emitted_objects": {"$ref": "#/$defs/decimal"}
}
},
"libraryChange": {
"oneOf": [
{
"type": "object", "required": ["field", "tag", "before", "after"],
"properties": {"field": {"const": "presence"}, "tag": {"type": "null"}, "before": {"type": "boolean"}, "after": {"type": "boolean"}}
},
{
"type": "object", "required": ["field", "tag", "before", "after"],
"properties": {"field": {"type": "string"}, "tag": {"$ref": "#/$defs/uint16"}, "before": {"$ref": "#/$defs/fields"}, "after": {"$ref": "#/$defs/fields"}}
}
]
},
"source": {
"type": "object", "required": ["side", "byte_offset", "end_offset"],
"properties": {"side": {"enum": ["old", "new"]}, "byte_offset": {"$ref": "#/$defs/decimal"}, "end_offset": {"$ref": "#/$defs/decimal"}}
},
"property": {
"type": "object", "required": ["attribute", "value", "payload_hex"],
"properties": {"attribute": {"$ref": "#/$defs/uint16"}, "value": {"type": ["string", "null"]}, "payload_hex": {"$ref": "#/$defs/hex"}}
},
"object": {
"type": "object", "required": ["id", "kind", "tag", "source", "layer", "bounds", "target", "origin", "width", "counts", "fields", "properties"],
"properties": {
"id": {"type": "string"}, "kind": {"type": "string"}, "tag": {"$ref": "#/$defs/uint16"}, "source": {"$ref": "#/$defs/source"},
"layer": {"$ref": "#/$defs/nullableLayer"},
"bounds": {"oneOf": [{"type": "null"}, {"type": "array", "minItems": 4, "maxItems": 4, "items": {"$ref": "#/$defs/int32"}}]},
"target": {"type": ["string", "null"]}, "origin": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/point"}]},
"width": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/int32"}]},
"counts": {"oneOf": [{"type": "null"}, {"type": "array", "minItems": 2, "maxItems": 2, "items": {"type": "integer", "minimum": 1, "maximum": 32767}}]},
"fields": {"$ref": "#/$defs/fields"}, "properties": {"type": "array", "items": {"$ref": "#/$defs/property"}}
}
},
"replacement": {
"type": "object", "required": ["removed", "added", "match_rule", "explanation", "field_changes", "properties_changed"],
"properties": {
"removed": {"type": "string"}, "added": {"type": "string"}, "match_rule": {"type": "string"}, "explanation": {"type": "string"}, "properties_changed": {"type": "boolean"},
"field_changes": {"type": "array", "items": {
"type": "object", "required": ["tag", "before", "after"],
"properties": {"tag": {"$ref": "#/$defs/uint16"}, "before": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/field"}]}, "after": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/field"}]}}
}}
}
},
"cellSide": {
"oneOf": [{"type": "null"}, {
"type": "object", "required": ["byte_offset", "attributes"],
"properties": {"byte_offset": {"$ref": "#/$defs/decimal"}, "attributes": {"$ref": "#/$defs/fields"}}
}]
},
"cellChange": {
"type": "object", "required": ["name", "before", "after", "attributes_changed", "removed", "added", "replacements"],
"properties": {
"name": {"type": "string"}, "before": {"$ref": "#/$defs/cellSide"}, "after": {"$ref": "#/$defs/cellSide"}, "attributes_changed": {"type": "boolean"},
"removed": {"type": "array", "items": {"$ref": "#/$defs/object"}}, "added": {"type": "array", "items": {"$ref": "#/$defs/object"}},
"replacements": {"type": "array", "items": {"$ref": "#/$defs/replacement"}}
}
},
"diagnostic": {
"type": "object", "required": ["code", "severity", "message", "side", "byte_offset", "cell", "layer", "target"],
"properties": {
"code": {"type": "string"}, "severity": {"const": "error"}, "message": {"type": "string"}, "side": {"enum": ["old", "new", null]},
"byte_offset": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/decimal"}]}, "cell": {"type": ["string", "null"]},
"layer": {"$ref": "#/$defs/nullableLayer"}, "target": {"type": ["string", "null"]}
}
},
"graph": {
"type": "object", "required": ["nodes", "edges"],
"properties": {
"nodes": {"type": "array", "items": {
"type": "object", "required": ["cell", "before", "after", "change"],
"properties": {
"cell": {"type": "string"}, "before": {"enum": ["included", "outside_scope", "unresolved", "absent"]}, "after": {"enum": ["included", "outside_scope", "unresolved", "absent"]},
"change": {"enum": ["direct", "affected", "unchanged"]}
}
}},
"edges": {"type": "array", "items": {
"type": "object", "required": ["parent", "target", "before_count", "after_count", "reference_changed"],
"properties": {"parent": {"type": "string"}, "target": {"type": "string"}, "before_count": {"$ref": "#/$defs/decimal"}, "after_count": {"$ref": "#/$defs/decimal"}, "reference_changed": {"type": "boolean"}}
}}
}
}
}
}

185
docs/diff-reports.md Normal file
View file

@ -0,0 +1,185 @@
# Machine-readable diff reports
```sh
klamath diff before.gds after.gds --format json > report.json
klamath diff before.gds after.gds --format json --hierarchy graph
klamath diff before.gds after.gds --format json --top CHIP --layer 1/0
```
The command writes one UTF-8 JSON document followed by a newline to stdout.
Comparison diagnostics belong to that document. Output write failures are
reported on stderr and return 2; interrupted output is not a valid report.
JSON output currently belongs to `diff`; `dump`, `hierarchy`, and the Git
external driver retain their existing text interfaces. No external process is
used to produce a report.
The [version 1 JSON Schema](diff-report-v1.schema.json) defines the structure.
[Golden reports](../tests/golden/report-geometry.json) illustrate complete
evidence; other `report-*.json` goldens cover equality, metadata, incomplete
comparison, and failure. Their producer version is replaced with `test` so
package version changes do not alter the fixtures.
## Versions and determinism
`schema_version` describes the report structure. `comparison_profile` names the
equality rules, currently `klamath-object-v2`. `producer.version` identifies the
implementation. These versions are independent. Consumers interpreting equality
must understand the comparison profile as well as the schema.
Compatible additions may introduce optional fields. Consumers should ignore
unfamiliar additional fields and handle unfamiliar diagnostic codes and matching
rules without treating them as equality. Removed fields or changed meanings
require a new schema version. The schema intentionally permits additional fields.
For the same inputs, paths, options, and producer version, serialization is
deterministic. Cells, layer pairs, fields, properties, and graph edges are sorted.
Duplicate objects and properties remain separate occurrences. Reports contain
no generation timestamp or required content fingerprint.
## Result and exit status
| `status` | `result` | Exit code | Interpretation |
| --- | --- | --- | --- |
| `complete` | `equal` | 0 | Equal under the recorded profile and scope. |
| `complete` | `different` | 1 | Differences found. |
| `incomplete` | `different` | 2 | Definite differences found, with comparison limitations. |
| `incomplete` | `unknown` | 2 | Equality cannot be established. |
| `failed` | `unknown` | 2 | No comparison result is available. |
Unsupported records, future metadata versions, unresolved references, and
hierarchy cycles make the comparison incomplete. Malformed input, read errors,
invalid scopes, and invalid command arguments produce failed reports. CI must
check completeness as well as differences. An exit code of 1 is a normal
comparison outcome, including when stdout is redirected to a report file.
Library and cell timestamps are excluded from the comparison profile. A valid,
complete timestamp-only comparison returns 0. Raw record dumps remain available
for examining those timestamps.
`summary` counts the entire scoped comparison, before display selection. Its
`counts` is `exact` for a complete comparison and `observed` for an incomplete
one. Failed reports have a null summary and empty change arrays. Replacement
suggestions and affected ancestors never add to change counts.
## Scope, selection, and numbers
`scope` records the actual `top`, `cell`, and numeric `layer` selectors. Null
means unrestricted. The complete file is parsed before applying scope, so an
invalid record outside the selected subtree still fails the command.
`report_selection` records display-only `cell`, `layer`, and `max_objects`.
JSON has no default object limit. Explicit `--max-changes N` limits the total
number of emitted object occurrences across both sides. Removals precede
additions within each cell. `filtered_cells`, `filtered_objects`,
`limited_objects`, and `emitted_objects` explain evidence selection. `truncated`
is true if filtering or a limit omits any changed cell or object. Library and
layer-name changes, diagnostics, summaries, and the optional graph are retained.
A replacement is emitted only when both linked objects are included.
All aggregate counts, limits, and byte offsets are unsigned decimal **strings**.
This avoids loss of precision in JSON consumers using binary64 numbers.
Coordinates, numeric tags, layer/type pairs, widths, and array dimensions are
bounded integers represented as JSON numbers. Null means absent or unavailable;
zero and empty arrays do not imply absence.
`inputs.old` and `inputs.new` contain input paths, presence, and UNITS fields.
Presence is distinct from an empty library. The Rust API also supports absent
Git revisions using `Document::empty_like`; no units are invented for absent
inputs. Failed reports may have null presence and units. Argument failures can
lack input/selection context because the command could not be parsed.
Paths are UTF-8 when representable. Otherwise `path` is null and
`path_encoded_hex` preserves Rust's platform-native encoded path bytes, prefixed
with `0x`. This is platform-dependent evidence rather than a portable path name.
## Change evidence
`library_changes` records changed header fields as typed before/after arrays.
Library presence changes use the special field `presence`, a null tag, and
boolean before/after values. Units are not rescaled to a common grid.
`layer_name_changes` records numeric pairs with before/after names. A layer
pair is `{ "number": 1, "purpose": 0 }`, where purpose is DATATYPE, TEXTTYPE,
BOXTYPE, or NODETYPE according to the object kind. `layer_legend` contains
unchanged names available in the scope. Embedded annotation labels are excluded
from ordinary object changes. A metadata rename appears once.
Each `cell_changes` entry has its name, nullable before/after cell records,
attribute evidence, removed and added objects, and replacement suggestions.
A null cell side means the cell is absent in that scope. An existing empty
cell has a byte offset and an empty attribute array.
Each object retains:
- Its kind and numeric tag, numeric layer pair, target cell, and coordinate envelope.
- Its original source side and byte range `[byte_offset, end_offset)`.
- Typed field records and the sorted property multiset, including duplicates.
- Convenience fields for text/reference origin, path/text width, and reference
array dimensions. SREF dimensions are `[1, 1]`; the kind and retained fields
distinguish an SREF from a one-element AREF and explicit fields from omission.
Coordinates are cell-local integer database units. `bounds` contains
`[xmin, ymin, xmax, ymax]` of stored coordinates. It excludes path stroke width,
rendered text dimensions, and recursively transformed target geometry.
Equal envelopes do not establish geometric equality. Unit changes must be
considered before deriving physical movements or dimensions.
A retained field has a numeric `tag`, convenience `name`, `encoding`, decoded
`value`, and `payload_hex`. The numeric tag is authoritative; names are display
aids. XY values are arrays of `[x, y]` pairs. Other numeric fields are arrays
of their declared type. Unsupported encodings retain bytes with a null value.
String and property values are null if their bytes are not valid UTF-8;
`payload_hex` always preserves them without replacement characters.
Payloads follow the comparison profile: boundary/box rings use canonical start
and winding, string padding is removed, and fields/properties are sorted. They
are comparison evidence, not a verbatim serialization of the source records.
REAL8 payload encodings are retained exactly alongside their decoded values.
Explicit defaults and omitted fields remain distinct. Source ranges allow raw
record inspection when original encoding or order is needed.
Replacement suggestions link report-local removed/added IDs, with a `match_rule`,
typed `field_changes`, and `properties_changed`. Their explanation is optional
for consumers to display and must not be parsed. Current matching rules are
`unique_kind_layer_bounds`, `unique_kind_layer`, and `unique_kind_target`.
These are explanatory matches, not persistent identity or shape equivalence.
Ambiguous candidates stay independent removals and additions. IDs are unique
within a report and have no meaning across reports.
## Diagnostics and hierarchy
Diagnostics have `code`, `severity`, `message`, input `side`, original byte
offset, cell, layer, and target context. Unknown context is null. Messages are
for display; codes and context support automation. Current limitation codes are
`unsupported_record`, `unsupported_metadata_version`, `unresolved_reference`,
`hierarchy_cycle`, and `scope_mismatch`. Failure codes are `invalid_input`,
`io_error`, `invalid_scope`, and `command_error`. Fatal parser errors currently
retain their location in the human message; their structured byte offset is
null. Consumers must not depend on message wording.
`--hierarchy graph` includes the full scoped union graph of both revisions.
Otherwise `hierarchy` is null. Nodes are keyed by cell name, with per-side
states `included`, `outside_scope`, `unresolved`, or `absent`. Their `change`
is `direct`, `affected` through a descendant, or `unchanged`.
Edges record parent, target, before/after direct placement counts, and whether
the underlying reference records changed. AREF columns times rows contribute
symbolically; arrays are never expanded. Counts are direct edge multiplicities,
not recursively accumulated placements. Shared cells occur once. Removed edges
remain visible, and ancestors are computed over the union of both revisions.
Graph content is independent of display filters and object limits. Text depth
limits and ASCII/Mermaid choices do not apply to JSON graphs.
## Development
`cargo test --test review` checks report semantics, CLI behavior, and versioned
goldens. To intentionally regenerate report goldens after reviewing a contract
change, run:
```sh
KLAMATH_UPDATE_REPORT_GOLDENS=1 cargo test --test review machine_reports_match_versioned_goldens
```
Schema validators can validate the goldens or actual CLI output against
`diff-report-v1.schema.json`. Schema validation does not replace semantic checks
such as replacement links, summary totals, or status/exit-code agreement.

View file

@ -2,5 +2,5 @@ from .basic import pack_int2 as pack_int2
from .basic import pack_int4 as pack_int4 from .basic import pack_int4 as pack_int4
__version__ = 0.2 __version__ = "0.2.0"

50
klamath_rs_ext/_ffi.h Normal file
View file

@ -0,0 +1,50 @@
#ifndef KLAMATH_RS_EXT_H
#define KLAMATH_RS_EXT_H
#include <stdint.h>
#include <stddef.h>
struct ArrowArray {
int64_t length;
int64_t null_count;
int64_t offset;
int64_t n_buffers;
int64_t n_children;
const void **buffers;
struct ArrowArray **children;
struct ArrowArray *dictionary;
void (*release)(struct ArrowArray *);
void *private_data;
};
struct ArrowSchema {
const char *format;
const char *name;
const char *metadata;
int64_t flags;
int64_t n_children;
struct ArrowSchema **children;
struct ArrowSchema *dictionary;
void (*release)(struct ArrowSchema *);
void *private_data;
};
int32_t read_path(const char *path, struct ArrowArray *array, struct ArrowSchema *schema);
int32_t scan_bytes(const uint8_t *data, size_t size, struct ArrowArray *array, struct ArrowSchema *schema);
int32_t read_cells_bytes(const uint8_t *data, size_t size, const uint64_t *ranges, size_t range_count, struct ArrowArray *array, struct ArrowSchema *schema);
const char *last_error_message(void);
double f64_to_i16(double *data, size_t size);
double f64_to_i32(double *data, size_t size);
float f32_to_i16(float *data, size_t size);
float f32_to_i32(float *data, size_t size);
int64_t i64_to_i16(int64_t *data, size_t size);
int64_t i64_to_i32(int64_t *data, size_t size);
int32_t i32_to_i16(int32_t *data, size_t size);
int32_t i32_to_i32(int32_t *data, size_t size);
int16_t i16_to_i16(int16_t *data, size_t size);
uint64_t u64_to_i16(uint64_t *data, size_t size);
uint64_t u64_to_i32(uint64_t *data, size_t size);
uint32_t u32_to_i16(uint32_t *data, size_t size);
uint32_t u32_to_i32(uint32_t *data, size_t size);
uint16_t u16_to_i16(uint16_t *data, size_t size);
#endif

View file

@ -49,7 +49,7 @@ def pack_int2(data: NDArray[numpy.integer] | Sequence[int] | int) -> bytes:
if result != 0: if result != 0:
raise ValueError(f'Invalid value for conversion to Int2: {result}') raise ValueError(f'Invalid value for conversion to Int2: {result}')
i2arr = arr.view('>i2')[::arr.itemsize // 2] i2arr = arr.reshape(-1).view('>i2')[::arr.itemsize // 2]
return i2arr.tobytes() return i2arr.tobytes()
if arr.dtype == numpy.dtype('>i2'): if arr.dtype == numpy.dtype('>i2'):
@ -79,7 +79,7 @@ def pack_int4(data: NDArray[numpy.integer] | Sequence[int] | int) -> bytes:
if result != 0: if result != 0:
raise ValueError(f'Invalid value for conversion to Int4: {result}') raise ValueError(f'Invalid value for conversion to Int4: {result}')
i4arr = arr.view('>i4')[::arr.itemsize // 4] i4arr = arr.reshape(-1).view('>i4')[::arr.itemsize // 4]
return i4arr.tobytes() return i4arr.tobytes()
if arr.dtype == numpy.dtype('>i4'): if arr.dtype == numpy.dtype('>i4'):

View file

@ -0,0 +1,23 @@
"""CFFI ABI access to the Cargo-built shared library."""
import os
from pathlib import Path
import sys
from cffi import FFI
ffi = FFI()
header = Path(__file__).with_name("_ffi.h").read_text()
ffi.cdef("\n".join(line for line in header.splitlines() if not line.lstrip().startswith("#")))
if sys.platform == "win32":
filename = "klamath_rs_ext.dll"
elif sys.platform == "darwin":
filename = "libklamath_rs_ext.dylib"
else:
filename = "libklamath_rs_ext.so"
# An explicit override supports source-tree development without copying binaries
# into the package. Installed wheels load only their bundled native library.
library = Path(os.environ["KLAMATH_RS_LIBRARY"]) if "KLAMATH_RS_LIBRARY" in os.environ else Path(__file__).with_name(filename)
lib = ffi.dlopen(str(library.resolve()))

View file

@ -1,6 +1,6 @@
[build-system] [build-system]
requires = ["maturin>1.0,<2.0"] requires = ["setuptools>=64", "wheel"]
build-backend = "maturin" build-backend = "setuptools.build_meta"
[project] [project]
name = "klamath_rs_ext" name = "klamath_rs_ext"
@ -10,8 +10,6 @@ description = "Compiled extensions for klamath GDS library"
authors = [ authors = [
{ name="Jan Petykiewicz", email="jan@mpxd.net" }, { name="Jan Petykiewicz", email="jan@mpxd.net" },
] ]
homepage = "https://mpxd.net/code/jan/klamath-rs"
repository = "https://mpxd.net/code/jan/klamath-rs"
classifiers = [ classifiers = [
"Programming Language :: Python :: 3", "Programming Language :: Python :: 3",
"Development Status :: 4 - Beta", "Development Status :: 4 - Beta",
@ -30,8 +28,16 @@ requires-python = ">=3.11"
dynamic = ["version"] dynamic = ["version"]
dependencies = [ dependencies = [
"cffi", "cffi",
"numpy",
] ]
[tool.maturin] [project.urls]
bindings = "cffi" Homepage = "https://mpxd.net/code/jan/klamath-rs"
Repository = "https://mpxd.net/code/jan/klamath-rs"
[tool.setuptools]
packages = ["klamath_rs_ext"]
[tool.setuptools.package-data]
klamath_rs_ext = ["py.typed", "_ffi.h"]

76
setup.py Normal file
View file

@ -0,0 +1,76 @@
"""Bundle Cargo's C ABI library in a platform wheel, without a Python ABI tie."""
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tomllib
from setuptools import Distribution, setup
from setuptools.command.build_py import build_py
from setuptools.command.sdist import sdist
from wheel.bdist_wheel import bdist_wheel
ROOT = Path(__file__).resolve().parent
VERSION = tomllib.loads((ROOT / "Cargo.toml").read_text())["package"]["version"]
def ensure_lockfile():
if not (ROOT / "Cargo.lock").is_file():
subprocess.run(["cargo", "generate-lockfile"], cwd=ROOT, check=True)
class CargoBuild(build_py):
def run(self):
ensure_lockfile()
super().run()
result = subprocess.run(
["cargo", "build", "--release", "--lib", "--locked", "--message-format=json"],
cwd=ROOT, capture_output=True, text=True,
)
sys.stderr.write(result.stderr)
library = None
for line in result.stdout.splitlines():
try:
message = json.loads(line)
except json.JSONDecodeError:
print(line, file=sys.stderr)
continue
if message.get("reason") == "compiler-message":
sys.stderr.write(message["message"].get("rendered") or "")
if (message.get("reason") == "compiler-artifact"
and message["target"]["name"] == "klamath_rs_ext"
and "cdylib" in message["target"]["crate_types"]):
for filename in message["filenames"]:
if Path(filename).suffix in (".so", ".dylib", ".dll"):
library = Path(filename)
result.check_returncode()
if library is None:
raise RuntimeError("Cargo did not produce the klamath_rs_ext shared library")
shutil.copy2(library, Path(self.build_lib) / "klamath_rs_ext" / library.name)
class CargoSdist(sdist):
def run(self):
ensure_lockfile()
super().run()
class NativeDistribution(Distribution):
def has_ext_modules(self):
return True
class NativeWheel(bdist_wheel):
def get_tag(self):
# CFFI ABI mode needs the host platform, but no CPython extension ABI.
_, _, platform = super().get_tag()
return "py3", "none", platform
setup(
version=VERSION,
distclass=NativeDistribution,
cmdclass={"build_py": CargoBuild, "sdist": CargoSdist, "bdist_wheel": NativeWheel},
)

View file

@ -166,79 +166,36 @@ impl fmt::Display for FloatTooBigError {
} }
} }
/// Convert from float64 to GDS REAL8 representation. /// Convert float64 to a normalized GDS REAL8 representation.
/// Finite magnitudes below 2^-260 underflow to canonical zero, including -0.0.
/// Nonfinite values and magnitudes at or above 2^252 return an error.
pub fn encode_real8(fnum: f64) -> Result<u64, FloatTooBigError> { pub fn encode_real8(fnum: f64) -> Result<u64, FloatTooBigError> {
// Split the ieee float bitfields
let ieee = fnum.to_bits(); let ieee = fnum.to_bits();
let ieee_exp = ((ieee >> 52) & 0x7ff) as i32;
if ieee_exp == 0x7ff {
return Err(FloatTooBigError { float_value: fnum });
}
let exp2 = ieee_exp - 1023;
if exp2 < -260 {
// This also handles both signed zeros and every IEEE subnormal.
return Ok(0);
}
let gds_exp = exp2.div_euclid(4) + 65;
if gds_exp > 0x7f {
return Err(FloatTooBigError { float_value: fnum });
}
// The 53-bit IEEE significand needs only 0..3 left shifts to become
// a normalized 56-bit GDS mantissa. Every in-range f64 is exact in REAL8.
let significand = (ieee & 0x000f_ffff_ffff_ffff) | (1_u64 << 52);
let mantissa = significand << exp2.rem_euclid(4);
let sign = ieee & 0x8000_0000_0000_0000; let sign = ieee & 0x8000_0000_0000_0000;
let ieee_exp = (ieee >> 52) as i32 & 0x7ff; Ok(sign | ((gds_exp as u64) << 56) | mantissa)
let ieee_mant = ieee & 0x000f_ffff_ffff_ffff;
let subnorm = (ieee_exp == 0) & (ieee_mant != 0);
if (ieee_exp == 0) & (ieee_mant == 0) {
return Ok(0)
}
// IEEE normal double is (1 + ieee_mant / 2^52) * 2^(ieee_exp - 1023)
// IEEE subnormal double is (ieee_mant / 2^52) * 2^(-1022)
// GDS real8 is (gds_mant / 2^(7*8)) * 16^(gds_exp - 64)
// = (gds_mant / 2^56) * 2^(4 * gds_exp - 256)
// Convert exponent.
let exp2 = if subnorm { -1022 } else {ieee_exp + 1 - 1023}; // +1 is due to mantissa (1.xxxx in IEEE vs 0.xxxxx in GDSII)
let mut exp16 = exp2 / 4;
let rest = exp2 % 4;
// Compensate for exponent coarseness
let comp = rest != 0;
let mut shift;
if comp {
exp16 += 1;
shift = 4 - rest;
} else {
shift = rest;
}
shift -= 3; // account for gds bit position
// add leading one
let mut gds_mant_unshifted = ieee_mant;
if !subnorm {
gds_mant_unshifted += 0x10_0000_0000_0000;
}
let mut gds_mant = if shift > 0 {
gds_mant_unshifted >> shift
} else {
gds_mant_unshifted << -shift
};
// add gds exponent bias
let mut gds_exp = exp16 + 64;
if gds_exp < -14 {
// number is too small
return Ok(0)
}
let neg_biased = gds_exp < 0;
if neg_biased {
gds_mant >>= gds_exp * 4;
gds_exp = 0;
}
let too_big = (gds_exp > 0x7f) & !subnorm;
if too_big {
return Err(FloatTooBigError{float_value: fnum});
}
let gds_exp_bits = (gds_exp as u64) << 56;
let real8 = sign | gds_exp_bits | gds_mant;
Ok(real8)
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#[test] #[test]

View file

@ -1,3 +1,4 @@
use klamath_rs_ext::review::report::{ReportInputs, ReportOptions, failure_report};
use klamath_rs_ext::review::{ use klamath_rs_ext::review::{
Comparison, DisplayFilter, Document, Scope, dump_records, hierarchy, parse_layer, Comparison, DisplayFilter, Document, Scope, dump_records, hierarchy, parse_layer,
parse_layer_name, write_layer_names, parse_layer_name, write_layer_names,
@ -7,12 +8,13 @@ use std::{
ffi::OsString, ffi::OsString,
fs, fs,
io::{self, Write}, io::{self, Write},
path::PathBuf,
process::ExitCode, process::ExitCode,
}; };
const HELP: &str = "Usage: const HELP: &str = "Usage:
klamath dump FILE [--records] klamath dump FILE [--records]
klamath diff OLD NEW [--top NAME] [--cell NAME] [--layer L/T]\n [--show-cell NAME] [--show-layer L/T] [--hierarchy ascii|mermaid|none]\n [--max-changes N] [--depth N] klamath diff OLD NEW [--top NAME] [--cell NAME] [--layer L/T]\n [--show-cell NAME] [--show-layer L/T] [--hierarchy ascii|mermaid|none|graph]\n [--max-changes N] [--depth N] [--format text|json]
klamath hierarchy FILE [--format ascii|mermaid] [--depth N] [--top NAME]\n klamath git-diff [OPTIONS] -- PATH OLD OLD_OID OLD_MODE NEW NEW_OID NEW_MODE klamath hierarchy FILE [--format ascii|mermaid] [--depth N] [--top NAME]\n klamath git-diff [OPTIONS] -- PATH OLD OLD_OID OLD_MODE NEW NEW_OID NEW_MODE
klamath name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ... klamath name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ...
@ -85,8 +87,57 @@ fn stdout(output: &str) -> Result<(), String> {
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
} }
fn run() -> Result<u8, String> { fn json_stdout(report: &serde_json::Value) -> Result<(), String> {
let args: Vec<_> = std::env::args_os().skip(1).collect(); let mut output = io::stdout().lock();
serde_json::to_writer_pretty(&mut output, report).map_err(|e| e.to_string())?;
output.write_all(b"\n").map_err(|e| e.to_string())
}
fn json_diff(paths: &[OsString], scope: &Scope, options: &ReportOptions) -> Result<u8, String> {
let inputs = ReportInputs {
old: Some(PathBuf::from(&paths[0])),
new: Some(PathBuf::from(&paths[1])),
};
let comparison = || {
let read = |index, side| {
fs::read(&paths[index])
.map_err(|e| ("io_error", format!("{:?}: {e}", paths[index]), Some(side)))
};
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) {
// Once output starts, never append a second report on a write failure.
eprintln!("klamath: {error}");
return Ok(2);
}
Ok(status)
}
fn run(args: &[OsString]) -> Result<u8, String> {
if args.is_empty() || args[0] == "--help" || args[0] == "-h" { if args.is_empty() || args[0] == "--help" || args[0] == "-h" {
stdout(HELP)?; stdout(HELP)?;
return Ok(0); return Ok(0);
@ -111,7 +162,10 @@ fn run() -> Result<u8, String> {
"ascii".to_string() "ascii".to_string()
}; };
let mut max_changes = 100; let mut max_changes = 100;
let mut explicit_max = None;
let mut output_format = "text".to_string();
let mut depth = 8; let mut depth = 8;
let mut explicit_depth = false;
let mut paths = Vec::new(); let mut paths = Vec::new();
let mut literal = false; let mut literal = false;
let mut i = 1; let mut i = 1;
@ -128,22 +182,25 @@ fn run() -> Result<u8, String> {
return Ok(0); return Ok(0);
} }
Some("--records") if command == "dump" => raw = true, Some("--records") if command == "dump" => raw = true,
Some("--top") => scope.top = Some(value(&args, &mut i)?), Some("--top") => scope.top = Some(value(args, &mut i)?),
Some("--cell") => scope.cell = Some(value(&args, &mut i)?), Some("--cell") => scope.cell = Some(value(args, &mut i)?),
Some("--layer") => scope.layer = Some(parse_layer(&value(&args, &mut i)?)?), Some("--layer") => scope.layer = Some(parse_layer(&value(args, &mut i)?)?),
Some("--show-cell") if compare => show.cell = Some(value(&args, &mut i)?), Some("--show-cell") if compare => show.cell = Some(value(args, &mut i)?),
Some("--show-layer") if compare => { Some("--show-layer") if compare => {
show.layer = Some(parse_layer(&value(&args, &mut i)?)?) show.layer = Some(parse_layer(&value(args, &mut i)?)?)
} }
Some("--hierarchy") if compare => format = value(&args, &mut i)?, Some("--hierarchy") if compare => format = value(args, &mut i)?,
Some("--format") if command == "hierarchy" => format = value(&args, &mut i)?, Some("--format") if command == "hierarchy" => format = value(args, &mut i)?,
Some("--format") if command == "diff" => output_format = value(args, &mut i)?,
Some("--max-changes") if compare => { Some("--max-changes") if compare => {
max_changes = value(&args, &mut i)? max_changes = value(args, &mut i)?
.parse() .parse()
.map_err(|_| "invalid change limit")? .map_err(|_| "invalid change limit")?;
explicit_max = Some(max_changes);
} }
Some("--depth") if command != "dump" => { Some("--depth") if command != "dump" => {
depth = value(&args, &mut i)?.parse().map_err(|_| "invalid depth")? depth = value(args, &mut i)?.parse().map_err(|_| "invalid depth")?;
explicit_depth = true;
} }
Some(s) if s.starts_with('-') => return Err(format!("unknown option {s:?}")), Some(s) if s.starts_with('-') => return Err(format!("unknown option {s:?}")),
_ => paths.push(args[i].clone()), _ => paths.push(args[i].clone()),
@ -153,6 +210,25 @@ fn run() -> Result<u8, String> {
if paths.len() != expected && !(command == "git-diff" && paths.len() == 9) { if paths.len() != expected && !(command == "git-diff" && paths.len() == 9) {
return Err(HELP.to_string()); return Err(HELP.to_string());
} }
if !matches!(output_format.as_str(), "text" | "json") {
return Err("diff format must be text or json".to_string());
}
if output_format == "json" {
if !matches!(format.as_str(), "none" | "graph") || explicit_depth {
return Err(
"JSON accepts --hierarchy graph|none; --depth applies to text output".to_string(),
);
}
return json_diff(
&paths,
&scope,
&ReportOptions {
filter: show,
max_objects: explicit_max,
hierarchy: format == "graph",
},
);
}
if !matches!(format.as_str(), "ascii" | "mermaid" | "none") if !matches!(format.as_str(), "ascii" | "mermaid" | "none")
|| (command == "hierarchy" && format == "none") || (command == "hierarchy" && format == "none")
{ {
@ -248,11 +324,51 @@ fn run() -> Result<u8, String> {
}) })
} }
fn wants_json(args: &[OsString]) -> bool {
if args.first().is_none_or(|arg| arg != "diff") {
return false;
}
let mut format = None;
let mut i = 1;
while i < args.len() {
match args[i].to_str() {
Some("--") => break,
Some("--format") => {
format = args.get(i + 1).and_then(|v| v.to_str());
i += 1;
}
Some(
"--top" | "--cell" | "--layer" | "--show-cell" | "--show-layer" | "--hierarchy"
| "--max-changes" | "--depth",
) => i += 1,
_ => (),
}
i += 1;
}
format == Some("json")
}
fn main() -> ExitCode { fn main() -> ExitCode {
match run() { let args: Vec<_> = std::env::args_os().skip(1).collect();
let json = wants_json(&args);
match run(&args) {
Ok(status) => ExitCode::from(status), Ok(status) => ExitCode::from(status),
Err(message) => { Err(message) => {
if json {
let report = failure_report(
&ReportInputs::default(),
&Scope::default(),
&ReportOptions::default(),
"command_error",
&message,
None,
);
if let Err(error) = json_stdout(&report) {
eprintln!("klamath: {error}");
}
} else {
eprintln!("klamath: {message}"); eprintln!("klamath: {message}");
}
ExitCode::from(2) ExitCode::from(2)
} }
} }

View file

@ -822,9 +822,9 @@ fn boundary_to_rect(vertices: &[i32]) -> Option<[i32; 4]> {
let mut seen_corners: u8 = 0; let mut seen_corners: u8 = 0;
for ii in 0..4 { for ii in 0..4 {
let jj = (ii + 1) % 4; let jj = (ii + 1) % 4;
let dx = xs[jj] - xs[ii]; let same_x = xs[jj] == xs[ii];
let dy = ys[jj] - ys[ii]; let same_y = ys[jj] == ys[ii];
if (dx == 0) == (dy == 0) { if same_x == same_y {
return None; return None;
} }
@ -922,7 +922,14 @@ fn read_ref<'a>(
} }
let pitch = |end: i32, origin: i32, count: i16| { let pitch = |end: i32, origin: i32, count: i16| {
let value = (i64::from(end) - i64::from(origin)) / i64::from(count); let delta = i64::from(end) - i64::from(origin);
let divisor = i64::from(count);
if delta % divisor != 0 {
return Err((input, crate::basic::ErrType::Failed(
"AREF pitch is not an integer database-unit increment; the Arrow schema cannot represent it exactly".to_string()
)));
}
let value = delta / divisor;
i32::try_from(value).map_err(|_| (input, crate::basic::ErrType::Failed( i32::try_from(value).map_err(|_| (input, crate::basic::ErrType::Failed(
"AREF pitch exceeds signed 32-bit coordinate range".to_string() "AREF pitch exceeds signed 32-bit coordinate range".to_string()
))) )))

View file

@ -14,6 +14,31 @@ mod selection;
pub use selection::{DisplayFilter, Scope}; pub use selection::{DisplayFilter, Scope};
mod changes; mod changes;
pub use changes::Replacement; pub use changes::Replacement;
pub mod report;
/// A comparison limitation with source context independent of its wording.
#[derive(Clone, Debug)]
pub struct Diagnostic {
pub code: &'static str,
pub message: String,
pub offset: Option<usize>,
pub cell: Option<String>,
pub layer: Option<Layer>,
pub target: Option<String>,
}
impl Diagnostic {
fn at(code: &'static str, offset: usize, message: String) -> Self {
Self {
code,
message: error(offset, message),
offset: Some(offset),
cell: None,
layer: None,
target: None,
}
}
}
pub const PROFILE: &str = "klamath-object-v2"; pub const PROFILE: &str = "klamath-object-v2";
pub const LAYER_SENTINEL: &str = "KLAMATH_LAYER_NAMES_V1"; pub const LAYER_SENTINEL: &str = "KLAMATH_LAYER_NAMES_V1";
@ -45,7 +70,7 @@ pub struct Object<'a> {
pub multiplicity: u64, pub multiplicity: u64,
key: Key<'a>, key: Key<'a>,
metadata: bool, metadata: bool,
issues: Vec<String>, issues: Vec<Diagnostic>,
} }
impl Object<'_> { impl Object<'_> {
@ -76,7 +101,7 @@ pub struct Cell<'a> {
pub end_offset: usize, pub end_offset: usize,
pub objects: Vec<Object<'a>>, pub objects: Vec<Object<'a>>,
attributes: Vec<(u16, &'a [u8])>, attributes: Vec<(u16, &'a [u8])>,
issues: Vec<String>, issues: Vec<Diagnostic>,
} }
#[derive(Debug)] #[derive(Debug)]
@ -86,8 +111,9 @@ pub struct Document<'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 issues: Vec<String>,
pub diagnostics: Vec<Diagnostic>,
header: Vec<(u16, &'a [u8])>, header: Vec<(u16, &'a [u8])>,
global_issues: Vec<String>, global_issues: Vec<Diagnostic>,
known_cells: BTreeSet<String>, known_cells: BTreeSet<String>,
pub scope: Scope, pub scope: Scope,
present: bool, present: bool,
@ -246,7 +272,7 @@ fn allowed_field(kind: u16, tag: u16) -> bool {
} }
} }
fn object<'a>(records: &[Record<'a>], issues: &mut Vec<String>) -> Result<Object<'a>, String> { fn object<'a>(records: &[Record<'a>], issues: &mut Vec<Diagnostic>) -> Result<Object<'a>, String> {
let first = &records[0]; let first = &records[0];
let mut fields = Vec::new(); let mut fields = Vec::new();
let mut properties = Vec::new(); let mut properties = Vec::new();
@ -264,7 +290,8 @@ fn object<'a>(records: &[Record<'a>], issues: &mut Vec<String>) -> Result<Object
continue; continue;
} }
if !allowed_field(first.tag, record.tag) { if !allowed_field(first.tag, record.tag) {
issues.push(error( issues.push(Diagnostic::at(
"unsupported_record",
record.offset, record.offset,
format!( format!(
"unsupported record 0x{:04x} in {}", "unsupported record 0x{:04x} in {}",
@ -424,6 +451,7 @@ impl<'a> Document<'a> {
cells: BTreeMap::new(), cells: BTreeMap::new(),
layer_names: BTreeMap::new(), layer_names: BTreeMap::new(),
issues: Vec::new(), issues: Vec::new(),
diagnostics: Vec::new(),
header: Vec::new(), header: Vec::new(),
global_issues: Vec::new(), global_issues: Vec::new(),
known_cells: BTreeSet::new(), known_cells: BTreeSet::new(),
@ -461,7 +489,8 @@ impl<'a> Document<'a> {
| RTAG_SRFNAME | RTAG_SRFNAME
| RTAG_LIBSECUR | RTAG_LIBSECUR
) { ) {
doc.global_issues.push(error( doc.global_issues.push(Diagnostic::at(
"unsupported_record",
record.offset, record.offset,
format!("unsupported library record 0x{:04x}", record.tag), format!("unsupported library record 0x{:04x}", record.tag),
)); ));
@ -534,7 +563,8 @@ impl<'a> Document<'a> {
return Err(error(record.offset, "missing ENDSTR")); return Err(error(record.offset, "missing ENDSTR"));
} }
if record.tag != RTAG_STRCLASS { if record.tag != RTAG_STRCLASS {
cell.issues.push(error( cell.issues.push(Diagnostic::at(
"unsupported_record",
record.offset, record.offset,
format!("unsupported cell record 0x{:04x}", record.tag), format!("unsupported cell record 0x{:04x}", record.tag),
)); ));
@ -567,14 +597,22 @@ impl<'a> Document<'a> {
} }
fn read_metadata(&mut self) -> Result<(), String> { fn read_metadata(&mut self) -> Result<(), String> {
for cell in self.cells.values_mut() { for (cell_name, cell) in &mut self.cells {
for object in cell.objects.iter_mut().filter(|o| o.kind == RTAG_TEXT) { for object in cell.objects.iter().filter(|o| o.kind == RTAG_TEXT) {
let text = object.field(RTAG_STRING).unwrap(); let text = object.field(RTAG_STRING).unwrap();
if text.starts_with(b"KLAMATH_LAYER_NAMES_") && text != LAYER_SENTINEL.as_bytes() { if text.starts_with(b"KLAMATH_LAYER_NAMES_") && text != LAYER_SENTINEL.as_bytes() {
object.issues.push(error( // 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, object.offset,
"unsupported layer-name metadata version", "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 let carriers: BTreeSet<_> = cell
@ -613,13 +651,26 @@ impl<'a> Document<'a> {
} }
fn check_graph(&mut self) { fn check_graph(&mut self) {
let edges = self.edges(); let mut unresolved = BTreeMap::new();
for (parent, target) in edges.keys() { for (parent, cell) in &self.cells {
if !self.known_cells.contains(target) { for object in &cell.objects {
self.issues if let Some(target) = &object.target
.push(format!("cell {parent:?}: unresolved reference {target:?}")); && !self.known_cells.contains(target)
{
unresolved.entry((parent, target)).or_insert(object.offset);
} }
} }
}
for ((parent, target), offset) in unresolved {
self.diagnostics.push(Diagnostic {
code: "unresolved_reference",
message: format!("cell {parent:?}: unresolved reference {target:?}"),
offset: Some(offset),
cell: Some(parent.clone()),
layer: None,
target: Some(target.clone()),
});
}
let mut state = BTreeMap::<&str, u8>::new(); let mut state = BTreeMap::<&str, u8>::new();
for root in self.cells.keys() { for root in self.cells.keys() {
let mut stack = vec![(root.as_str(), false)]; let mut stack = vec![(root.as_str(), false)];
@ -631,8 +682,14 @@ impl<'a> Document<'a> {
match state.get(name) { match state.get(name) {
Some(2) => continue, Some(2) => continue,
Some(1) => { Some(1) => {
self.issues self.diagnostics.push(Diagnostic {
.push(format!("cyclic hierarchy involving {name:?}")); code: "hierarchy_cycle",
message: format!("cyclic hierarchy involving {name:?}"),
offset: self.cells.get(name).map(|c| c.offset),
cell: Some(name.to_string()),
layer: None,
target: None,
});
continue; continue;
} }
_ => (), _ => (),
@ -723,9 +780,28 @@ fn format_records(records: &[Record<'_>]) -> String {
out out
} }
/// A retained comparison field. Polygon coordinates and string padding follow
/// the comparison profile; REAL encodings and unsupported payloads are exact.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FieldValue {
pub tag: u16,
pub data: Vec<u8>,
}
fn owned_fields<'a>(fields: impl IntoIterator<Item = (u16, &'a [u8])>) -> Vec<FieldValue> {
fields
.into_iter()
.map(|(tag, data)| FieldValue {
tag,
data: data.to_vec(),
})
.collect()
}
#[derive(Debug)] #[derive(Debug)]
pub struct ObjectChange { pub struct ObjectChange {
pub offset: usize, pub offset: usize,
pub end_offset: usize,
pub kind: u16, pub kind: u16,
pub layer: Option<Layer>, pub layer: Option<Layer>,
pub bounds: Option<Bounds>, pub bounds: Option<Bounds>,
@ -734,12 +810,15 @@ pub struct ObjectChange {
pub width: Option<i32>, pub width: Option<i32>,
pub counts: Option<[u16; 2]>, pub counts: Option<[u16; 2]>,
pub description: String, pub description: String,
pub fields: Vec<FieldValue>,
pub properties: Vec<(u16, Vec<u8>)>,
} }
impl From<&Object<'_>> for ObjectChange { impl From<&Object<'_>> for ObjectChange {
fn from(object: &Object<'_>) -> Self { fn from(object: &Object<'_>) -> Self {
Self { Self {
offset: object.offset, offset: object.offset,
end_offset: object.end_offset,
kind: object.kind, kind: object.kind,
layer: object.layer, layer: object.layer,
bounds: object.bounds, bounds: object.bounds,
@ -754,12 +833,27 @@ impl From<&Object<'_>> for ObjectChange {
.field(RTAG_WIDTH) .field(RTAG_WIDTH)
.map(|data| i32::from_be_bytes(data.try_into().unwrap())), .map(|data| i32::from_be_bytes(data.try_into().unwrap())),
counts: object.target.as_ref().map(|_| { counts: object.target.as_ref().map(|_| {
object if object.kind == RTAG_AREF {
.field(RTAG_COLROW) let data = object.field(RTAG_COLROW).unwrap();
.map(|data| [integer(&data[..2]), integer(&data[2..])]) [integer(&data[..2]), integer(&data[2..])]
.unwrap_or([1, 1]) } else {
[1, 1]
}
}), }),
description: object.description(), description: object.description(),
fields: owned_fields(
object
.key
.fields
.iter()
.map(|(tag, data)| (*tag, data.as_ref())),
),
properties: object
.key
.properties
.iter()
.map(|(a, v)| (*a, v.to_vec()))
.collect(),
} }
} }
} }
@ -770,6 +864,8 @@ pub struct CellChange {
pub old_offset: Option<usize>, pub old_offset: Option<usize>,
pub new_offset: Option<usize>, pub new_offset: Option<usize>,
pub attributes_changed: bool, 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>,
@ -785,6 +881,9 @@ pub struct LayerNameChange {
#[derive(Debug)] #[derive(Debug)]
pub struct LibraryFieldChange { pub struct LibraryFieldChange {
pub field: String, pub field: String,
pub tag: Option<u16>,
pub old_fields: Vec<FieldValue>,
pub new_fields: Vec<FieldValue>,
pub old: Vec<String>, pub old: Vec<String>,
pub new: Vec<String>, pub new: Vec<String>,
} }
@ -821,6 +920,9 @@ impl Comparison {
if old.present != new.present { if old.present != new.present {
result.library_fields.push(LibraryFieldChange { result.library_fields.push(LibraryFieldChange {
field: "presence".to_string(), field: "presence".to_string(),
tag: None,
old_fields: Vec::new(),
new_fields: Vec::new(),
old: vec![if old.present { "present" } else { "absent" }.to_string()], old: vec![if old.present { "present" } else { "absent" }.to_string()],
new: vec![if new.present { "present" } else { "absent" }.to_string()], new: vec![if new.present { "present" } else { "absent" }.to_string()],
}); });
@ -852,6 +954,9 @@ impl Comparison {
if a != b { if a != b {
result.library_fields.push(LibraryFieldChange { result.library_fields.push(LibraryFieldChange {
field: tag_name(tag), field: tag_name(tag),
tag: Some(tag),
old_fields: owned_fields(a.iter().map(|data| (tag, *data))),
new_fields: owned_fields(b.iter().map(|data| (tag, *data))),
old: a.iter().map(|data| format_data(tag, data)).collect(), old: a.iter().map(|data| format_data(tag, data)).collect(),
new: b.iter().map(|data| format_data(tag, data)).collect(), new: b.iter().map(|data| format_data(tag, data)).collect(),
}); });
@ -881,6 +986,12 @@ impl Comparison {
old_offset: a.map(|c| c.offset), old_offset: a.map(|c| c.offset),
new_offset: b.map(|c| c.offset), new_offset: b.map(|c| c.offset),
attributes_changed: a.map(|c| &c.attributes) != b.map(|c| &c.attributes), 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(),

View file

@ -5,6 +5,8 @@ pub struct Replacement {
pub removed: usize, pub removed: usize,
pub added: usize, pub added: usize,
pub explanation: String, pub explanation: String,
/// Explanation matching is never object identity or geometric equivalence.
pub match_rule: &'static str,
} }
type Group = (u16, Option<Layer>, Option<String>, Option<Bounds>); type Group = (u16, Option<Layer>, Option<String>, Option<Bounds>);
@ -54,6 +56,13 @@ pub(super) fn replacements(old: &[ObjectChange], new: &[ObjectChange]) -> Vec<Re
removed: i, removed: i,
added: j, added: j,
explanation: explain(&old[i], &new[j]), explanation: explain(&old[i], &new[j]),
match_rule: if old[i].target.is_some() {
"unique_kind_target"
} else if bounds {
"unique_kind_layer_bounds"
} else {
"unique_kind_layer"
},
}); });
used_old.insert(i); used_old.insert(i);
used_new.insert(j); used_new.insert(j);

View file

@ -63,9 +63,9 @@ pub fn write_layer_names(
) -> Result<Vec<u8>, String> { ) -> Result<Vec<u8>, String> {
let doc = Document::parse(input)?; let doc = Document::parse(input)?;
if doc if doc
.issues .diagnostics
.iter() .iter()
.any(|i| i.contains("unsupported layer-name metadata version")) .any(|i| i.code == "unsupported_metadata_version")
{ {
return Err("cannot rewrite an unsupported layer-name metadata version".to_string()); return Err("cannot rewrite an unsupported layer-name metadata version".to_string());
} }

385
src/review/report.rs Normal file
View file

@ -0,0 +1,385 @@
//! Versioned machine-readable diff reports. No consumer needs to parse prose.
use super::*;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub const SCHEMA_VERSION: u32 = 1;
#[derive(Clone, Debug, Default)]
pub struct ReportInputs {
pub old: Option<PathBuf>,
pub new: Option<PathBuf>,
}
/// Limits affect evidence only. The default includes every changed object.
#[derive(Clone, Debug, Default)]
pub struct ReportOptions {
pub filter: DisplayFilter,
pub max_objects: Option<usize>,
pub hierarchy: bool,
}
fn layer(pair: Layer) -> Value {
json!({"number": pair.0, "purpose": pair.1})
}
fn scope(value: &Scope) -> Value {
json!({"top": value.top, "cell": value.cell, "layer": value.layer.map(layer)})
}
fn input(path: Option<&Path>, doc: Option<&Document<'_>>) -> Value {
let units = doc
.filter(|d| d.present)
.and_then(|d| d.header.iter().find(|(tag, _)| *tag == RTAG_UNITS))
.map(|(tag, data)| field(*tag, data));
json!({
"path": path.and_then(Path::to_str),
"path_encoded_hex": path.filter(|p| p.to_str().is_none())
.map(|p| hex(p.as_os_str().as_encoded_bytes())),
"present": doc.map(|d| d.present),
"units": units
})
}
fn envelope(inputs: &ReportInputs, selection: &Scope, options: &ReportOptions) -> Value {
json!({
"schema_version": SCHEMA_VERSION,
"kind": "diff",
"producer": {"name": "klamath", "version": env!("CARGO_PKG_VERSION")},
"comparison_profile": PROFILE,
"inputs": {"old": input(inputs.old.as_deref(), None), "new": input(inputs.new.as_deref(), None)},
"scope": scope(selection),
"coordinates": {"unit": "database_unit", "frame": "cell_local", "bounds": "coordinate_envelope"},
"status": "failed",
"result": "unknown",
"exit_code": 2,
"summary": null,
"report_selection": {
"cell": options.filter.cell,
"layer": options.filter.layer.map(layer),
"max_objects": options.max_objects.map(|n| n.to_string()),
"truncated": false,
"filtered_cells": "0", "filtered_objects": "0", "limited_objects": "0", "emitted_objects": "0"
},
"layer_legend": [],
"library_changes": [], "layer_name_changes": [], "cell_changes": [],
"hierarchy": null,
"diagnostics": []
})
}
/// Input/selection failures still produce a valid report. Unknown locations are
/// null rather than inferred by parsing an error's human-readable message.
pub fn failure_report(
inputs: &ReportInputs,
selection: &Scope,
options: &ReportOptions,
code: &str,
message: &str,
side: Option<&str>,
) -> Value {
let mut report = envelope(inputs, selection, options);
report["diagnostics"] = json!([{
"code": code, "severity": "error", "message": message,
"side": side, "byte_offset": null, "cell": null, "layer": null, "target": null
}]);
report
}
fn field(tag: u16, data: &[u8]) -> Value {
let (encoding, value) = if tag == RTAG_XY && data.len().is_multiple_of(8) {
("xy", json!(points(data)))
} else if matches!(
tag,
RTAG_LAYER | RTAG_DATATYPE | RTAG_TEXTTYPE | RTAG_NODETYPE | RTAG_BOXTYPE
) && data.len().is_multiple_of(2)
{
(
"uint16",
json!(data.chunks_exact(2).map(integer).collect::<Vec<_>>()),
)
} else {
match tag & 0xff {
0 if data.is_empty() => ("none", Value::Null),
1 if data.len().is_multiple_of(2) => (
"bits",
json!(data.chunks_exact(2).map(integer).collect::<Vec<_>>()),
),
2 if data.len().is_multiple_of(2) => (
"int16",
json!(
data.chunks_exact(2)
.map(|v| i16::from_be_bytes(v.try_into().unwrap()))
.collect::<Vec<_>>()
),
),
3 if data.len().is_multiple_of(4) => (
"int32",
json!(
data.chunks_exact(4)
.map(|v| i32::from_be_bytes(v.try_into().unwrap()))
.collect::<Vec<_>>()
),
),
5 if data.len().is_multiple_of(8) => (
"real8",
json!(
data.chunks_exact(8)
.map(|v| decode_real8(u64::from_be_bytes(v.try_into().unwrap())))
.collect::<Vec<_>>()
),
),
6 => ("ascii", json!(std::str::from_utf8(data).ok())),
_ => ("bytes", Value::Null),
}
};
json!({"tag": tag, "name": tag_name(tag), "encoding": encoding, "value": value, "payload_hex": hex(data)})
}
fn fields(values: &[FieldValue]) -> Vec<Value> {
values.iter().map(|f| field(f.tag, &f.data)).collect()
}
fn object(value: &ObjectChange, id: &str, side: &str) -> Value {
json!({
"id": id, "kind": kind_name(value.kind), "tag": value.kind,
"source": {"side": side, "byte_offset": value.offset.to_string(), "end_offset": value.end_offset.to_string()},
"layer": value.layer.map(layer), "bounds": value.bounds, "target": value.target,
"origin": value.origin.filter(|_| matches!(value.kind, RTAG_SREF | RTAG_AREF | RTAG_TEXT)), "width": value.width, "counts": value.counts,
"fields": fields(&value.fields),
"properties": value.properties.iter().map(|(attribute, bytes)| json!({
"attribute": attribute, "value": std::str::from_utf8(bytes).ok(), "payload_hex": hex(bytes)
})).collect::<Vec<_>>()
})
}
fn field_changes(old: &ObjectChange, new: &ObjectChange) -> Vec<Value> {
let a: BTreeMap<_, _> = old.fields.iter().map(|f| (f.tag, &f.data)).collect();
let b: BTreeMap<_, _> = new.fields.iter().map(|f| (f.tag, &f.data)).collect();
a.keys()
.chain(b.keys())
.copied()
.collect::<BTreeSet<_>>()
.into_iter()
.filter(|tag| a.get(tag) != b.get(tag))
.map(|tag| {
json!({
"tag": tag,
"before": a.get(&tag).map(|data| field(tag, data)),
"after": b.get(&tag).map(|data| field(tag, data))
})
})
.collect()
}
impl Comparison {
/// Render evidence from the same documents used to construct this comparison.
/// IDs are local to this report, not persistent object identities.
pub fn json_report(
&self,
old: &Document<'_>,
new: &Document<'_>,
inputs: &ReportInputs,
options: &ReportOptions,
) -> Value {
let mut report = envelope(inputs, &self.scope, options);
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!({
"counts": if self.issues.is_empty() { "exact" } else { "observed" },
"changed_cells": self.cells.len().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(),
"layer_name_changes": self.layer_names.len().to_string(),
"library_field_changes": self.library_fields.len().to_string()
});
report["layer_legend"] = json!(
self.layer_legend
.iter()
.map(|(pair, name)| json!({"layer": layer(*pair), "name": name}))
.collect::<Vec<_>>()
);
report["layer_name_changes"] = json!(
self.layer_names
.iter()
.map(|c| json!({
"layer": layer(c.layer), "before": c.old, "after": c.new
}))
.collect::<Vec<_>>()
);
report["library_changes"] = json!(self.library_fields.iter().map(|c| {
if c.tag.is_none() {
json!({"field": "presence", "tag": null, "before": old.present, "after": new.present})
} else {
json!({"field": c.field, "tag": c.tag, "before": fields(&c.old_fields), "after": fields(&c.new_fields)})
}
}).collect::<Vec<_>>());
let (mut emitted, mut filtered_objects, mut limited, mut filtered_cells) =
(0_usize, 0_usize, 0_usize, 0_usize);
let mut cells = Vec::new();
for (cell_index, cell) in self.cells.iter().enumerate() {
if options
.filter
.cell
.as_ref()
.is_some_and(|name| name != &cell.name)
{
filtered_cells += 1;
filtered_objects += cell.removed.len() + cell.added.len();
continue;
}
let (mut removed, mut added) = (Vec::new(), Vec::new());
let mut shown = BTreeSet::new();
for (side, objects, output) in [
("old", &cell.removed, &mut removed),
("new", &cell.added, &mut added),
] {
for (index, change) in objects.iter().enumerate() {
if options
.filter
.layer
.is_some_and(|l| change.layer != Some(l))
{
filtered_objects += 1;
} else if options.max_objects.is_some_and(|max| emitted >= max) {
limited += 1;
} else {
let id = format!("c{cell_index}:{side}:{index}");
output.push(object(change, &id, side));
shown.insert(id);
emitted += 1;
}
}
}
let replacements: Vec<_> = cell.replacements.iter().filter_map(|r| {
let a = format!("c{cell_index}:old:{}", r.removed);
let b = format!("c{cell_index}:new:{}", r.added);
(shown.contains(&a) && shown.contains(&b)).then(|| json!({
"removed": a, "added": b, "match_rule": r.match_rule,
"explanation": r.explanation,
"field_changes": field_changes(&cell.removed[r.removed], &cell.added[r.added]),
"properties_changed": cell.removed[r.removed].properties != cell.added[r.added].properties
}))
}).collect();
cells.push(json!({
"name": cell.name,
"before": cell.old_offset.map(|offset| json!({"byte_offset": offset.to_string(), "attributes": fields(&cell.old_attributes)})),
"after": cell.new_offset.map(|offset| json!({"byte_offset": offset.to_string(), "attributes": fields(&cell.new_attributes)})),
"attributes_changed": cell.attributes_changed,
"removed": removed, "added": added, "replacements": replacements
}));
}
report["cell_changes"] = json!(cells);
report["report_selection"]["truncated"] =
json!(filtered_cells > 0 || filtered_objects > 0 || limited > 0);
for (key, count) in [
("filtered_cells", filtered_cells),
("filtered_objects", filtered_objects),
("limited_objects", limited),
("emitted_objects", emitted),
] {
report["report_selection"][key] = json!(count.to_string());
}
let mut diagnostics: Vec<_> = [("old", old), ("new", new)]
.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 {
report["hierarchy"] = graph(old, new, self);
}
report
}
}
fn graph(old: &Document<'_>, new: &Document<'_>, diff: &Comparison) -> Value {
let a = old.edges();
let b = new.edges();
let edges: BTreeSet<_> = a.keys().chain(b.keys()).cloned().collect();
let names: BTreeSet<_> = old
.cells
.keys()
.chain(new.cells.keys())
.cloned()
.chain(
edges
.iter()
.flat_map(|(parent, child)| [parent.clone(), child.clone()]),
)
.collect();
let direct: BTreeSet<_> = diff.cells.iter().map(|c| c.name.clone()).collect();
let mut affected = direct.clone();
let mut parents = BTreeMap::<&str, Vec<&str>>::new();
for (parent, child) in &edges {
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"
} else if doc.known_cells.contains(name) {
"outside_scope"
} else if targets.contains(name.as_str()) {
"unresolved"
} else {
"absent"
}
};
json!({
"nodes": names.iter().map(|name| json!({
"cell": name, "before": state(old, &a_targets, name), "after": state(new, &b_targets, name),
"change": if direct.contains(name) { "direct" } else if affected.contains(name) { "affected" } else { "unchanged" }
})).collect::<Vec<_>>(),
"edges": edges.iter().map(|edge| json!({
"parent": edge.0, "target": edge.1,
"before_count": a.get(edge).copied().unwrap_or(0).to_string(),
"after_count": b.get(edge).copied().unwrap_or(0).to_string(),
"reference_changed": changed_refs.contains(edge)
})).collect::<Vec<_>>()
})
}

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