Skip to main content

ridl_diff/
lib.rs

1//! The `ridl diff` IR-snapshot compare engine.
2//!
3//! The engine compares two resolved IR v2 snapshots and classifies every
4//! difference as a [`Change`] with a [`Category`] and a [`Verdict`]. It reads
5//! only the IR — never source — so the comparison is honest against exactly
6//! what a backend sees (ADR-0008 decision 14, concept note §9.1). Placement is
7//! deliberate: this crate is an engine surfaced by the `ridl` facade, never by
8//! `ridlc`, so the compiler stays a pure source→IR function (the ISO 26262
9//! tool-qualification boundary, ADR-0008 decision 9).
10//!
11//! Per-side context entry points also attribute remote layout growth, integer
12//! width changes, scalar constraint changes and strict enum appends to
13//! surviving old consumer uses (ADR-0031 decision 13; ADR-0008 decision 14 for
14//! scalar constraints).
15//!
16//! The comparison has two halves. The walk ([`walk`]) says *what* structurally
17//! differs, emitting one [`Change`] per difference with a [`Category`]; the
18//! classifier ([`classify`]) says which *direction* that difference moved
19//! in and settles its [`Verdict`]. Splitting them is what lets a single
20//! structural category — an appended interaction, a changed timing — carry
21//! opposite verdicts depending on the direction, without the walk needing both
22//! snapshots at every emission site.
23//!
24//! This module owns the vocabulary ([`Verdict`], [`Category`], [`Change`],
25//! [`DiffReport`]), the set-level comparison ([`diff_sets`], and
26//! [`diff_workspaces`] with the system headings of [`system`]), and rendering
27//! ([`render_text`], [`render_json`]). It re-exports the snapshot loader
28//! [`load_ir_json`] from `ridl-ir`, which owns it. The
29//! classification table itself is documented per category by [`explain`], which
30//! `ridl diff --explain` prints.
31
32use ridl_ir::v2::{Package, System};
33
34mod classify;
35mod direction;
36mod remote_inline;
37pub mod system;
38pub mod unit_verdict;
39mod walk;
40
41pub use classify::{absence_refused, category_from_word, classify, explain, is_above_high_water};
42// Re-exported under its earlier path (ADR-0008 decision 9).
43pub use ridl_ir::v2::{LoadError, load_ir_json};
44pub use system::{SystemChange, SystemHeading, diff_systems};
45pub use unit_verdict::{UnitVerdicts, unit_verdict};
46
47#[cfg(test)]
48mod tests;
49
50/// The compatibility verdict of a change or of a whole report — ordered so
51/// `Breaking > Compatible > Identical` and a report's verdict is the maximum
52/// over its changes.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub enum Verdict {
55    /// No differences at all.
56    Identical,
57    /// A consumer built against the old snapshot still works.
58    Compatible,
59    /// A consumer built against the old snapshot may break.
60    Breaking,
61}
62
63/// Declares the [`Category`] vocabulary once (ADR-0008 decision 21).
64///
65/// One list of variants expands to both the enum and the [`CATEGORIES`] array
66/// that `ridl diff --explain` iterates, so a variant that never reaches
67/// `CATEGORIES` cannot be written: there is no second list to forget. This
68/// replaces the guard PR #163 shipped, which expanded one list into an
69/// exhaustive `match` and an array *inside the test* — that narrowed the gap but
70/// left `CATEGORIES` shadowed rather than produced, and an assertion comparing
71/// two lists can be defeated by editing what feeds it.
72///
73/// A new variant therefore stops three functions compiling — [`classify`],
74/// [`explain`], and [`category_word`] — and reaches `CATEGORIES` with no second
75/// edit. The escape rustc's own `help:` text proposes for those three errors is
76/// a wildcard arm. Each of the three functions denies
77/// `clippy::wildcard_enum_match_arm` and
78/// `clippy::match_wildcard_for_single_variants` for exactly that reason. The
79/// second lint is the load-bearing one: the first does not fire when the
80/// wildcard covers a single variant, which is precisely the added-variant case,
81/// so denying it alone leaves clippy green.
82///
83/// How far the wildcard gets before clippy stops it depends on what its body
84/// says. `_ => todo!()` panics the `--explain` coverage test, and a bare
85/// `_ => "unknown"` fails it — the row names no verdict. A wildcard whose text
86/// happens to contain "compatible" passes all 115 tests. So the escape is real
87/// but narrow, and `cargo test` alone catches the two careless spellings of it.
88/// `just build` runs clippy so that the third is caught too.
89///
90/// What this does **not** close: rustc forces *an* arm, not the right one. A
91/// new variant given an explicit arm that classifies compatible, or whose rule
92/// row describes the wrong rule, still compiles and still passes. The [`explain`]
93/// coverage test checks that each row names a verdict and that its word
94/// round-trips; neither is proof that the row is correct.
95macro_rules! declare_categories {
96    (
97        $(#[$enum_meta:meta])*
98        $vis:vis enum $name:ident {
99            $(
100                $(#[$variant_meta:meta])*
101                $variant:ident,
102            )+
103        }
104    ) => {
105        $(#[$enum_meta])*
106        $vis enum $name {
107            $(
108                $(#[$variant_meta])*
109                $variant,
110            )+
111        }
112
113        /// Every category, in the order `--explain` lists them when asked for an
114        /// unknown one.
115        ///
116        /// Generated from the [`Category`] declaration by
117        /// [`declare_categories!`], not maintained beside it.
118        //
119        // The length counts the variants rather than being written down:
120        // `${count(...)}` is still unstable (rust-lang/rust#83527), so the
121        // count comes from the same repetition that fills the array.
122        pub const CATEGORIES: [$name; [$(stringify!($variant)),+].len()] =
123            [$($name::$variant),+];
124    };
125}
126
127declare_categories! {
128    /// The kind of a single difference. The walk emits the structural categories;
129    /// the classifier maps them to directional verdicts.
130    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
131    pub enum Category {
132        /// A package-level declaration, interface, or service present only in the
133        /// new snapshot.
134        DeclAdded,
135        /// A package-level declaration, interface, or service present only in the
136        /// old snapshot. An interface is matched by its `interfaces.lock`
137        /// number (lock design §7), so an interface here is one whose number
138        /// is gone from the new snapshot and not retired there.
139        DeclRemoved,
140        /// An interface whose `interfaces.lock` number is the same on both
141        /// sides and whose name changed (lock design §7). The number is the
142        /// interface's identity and its routing key, so nothing moves on the
143        /// wire; a rename is visible in source — it changes the generated
144        /// identity-table names in both wire backends — so the text report
145        /// lists it under the heading ([`heading`]). The path carries the new
146        /// name; the detail carries the old and the new name.
147        InterfaceRenamed,
148        /// An interface whose number the old snapshot held and the new
149        /// snapshot's retired entries list (lock design §7): the sanctioned
150        /// removal of an interface, recorded by `ridl lock --retire`.
151        InterfaceRetired,
152        /// An interface matched by name across a provisional old side whose
153        /// number is the same on both sides and whose provisional flag went
154        /// from true to false: the number `ridl lock` froze in place. Nothing
155        /// moves on the wire, but the catalog hash covers the number and the
156        /// flag, so the hash changes and the text report lists it under the
157        /// heading "compatible on the wire, may change the catalog hash"
158        /// ([`heading`]). A number 0 on
159        /// either side, from a snapshot written before the lock existed, is
160        /// not compared. The path carries the name; the detail carries the
161        /// old and the new number, each marked when it is provisional.
162        InterfaceFrozen,
163        /// A matched interface whose number differs between the two sides,
164        /// whatever the two flags: a provisional number moved by a sibling
165        /// added before it, or frozen as another number. The number is the
166        /// routing key, so the change is breaking. A number 0 on either side,
167        /// from a snapshot written before the lock existed, is not compared. The
168        /// detail carries the old and the new number, each marked when it is
169        /// provisional.
170        InterfaceNumberChanged,
171        /// A surviving composite member whose slot in the body changed — a
172        /// struct field, enum value, enum-set bit or union arm — reported only
173        /// when both bodies hold the same member names. For a struct field or
174        /// union arm the slot is the ordinal, which is wire identity (typl
175        /// §7.4), and the detail carries the old and new ordinal. An enum value
176        /// or enum-set bit takes its identity from the explicit number it
177        /// declares instead (typl §8, §9), so its slot is that number: the
178        /// category reports a member whose number changed, with the old and
179        /// new value or bit in the detail. When every difference between the
180        /// two bodies is a changed number, the container's
181        /// [`Category::ConstraintChanged`] is not reported beside it. A body
182        /// of an enum or an enum set that differs only in order is
183        /// [`Category::EnumReordered`] instead.
184        MemberReordered,
185        /// An enum or enum-set body whose difference is only order: its live
186        /// values or bits reordered with no number changed, the enum's
187        /// `reserved` list reordered with no entry added, removed or changed,
188        /// or both. A value or bit takes its identity from the explicit number
189        /// it declares (typl §8, §9), so nothing moves on the wire. The catalog
190        /// hash covers only the declarations an interface reaches; when an
191        /// interface reaches the enum or enum set, the order of its values or
192        /// bits, and of an enum's reserved list, is part of the hash, so the
193        /// hash changes then. The text report lists it under the heading that
194        /// [`Category::InterfaceFrozen`] shares ([`heading`]). The path is the
195        /// container's; there is no detail.
196        EnumReordered,
197        /// A new interaction added at the end of an interface (no earlier
198        /// interaction shifted).
199        InteractionAppended,
200        /// A new interaction added before the end — an earlier interaction now
201        /// sits after it (ridl §11: insert shifts ordinals, a wire break).
202        InteractionInserted,
203        /// A surviving interaction whose relative order within the interface
204        /// changed (ridl §11: reorder shifts ordinals, a wire break).
205        InteractionReordered,
206        /// An interaction removed without leaving a `reserved` tombstone.
207        InteractionRemoved,
208        /// An interaction removed and replaced by a `reserved` tombstone in the
209        /// same slot (ridl §11).
210        InteractionRetired,
211        /// A surviving interaction whose kind changed (signal ↔ event, etc.).
212        KindChanged,
213        /// A signal/event/fixed payload type changed.
214        PayloadChanged,
215        /// A query return type changed.
216        ReturnChanged,
217        /// A command/query parameter list changed.
218        ParamsChanged,
219        /// A signal/event resolved timing changed.
220        TimingChanged,
221        /// A command/query declared RPC bound changed (ADR-0015 decision 8).
222        /// Separate from [`Category::TimingChanged`] because the direction of
223        /// `min` inverts: on an RPC it constrains the caller, not the
224        /// provider, so the signal/event rule must not be inherited silently.
225        RpcBoundChanged,
226        /// The payload limit declared for an interaction changed, was added or
227        /// was removed (ADR-0030 decision 13). Any change is breaking: the
228        /// limit is part of the catalog hash, so peers with different limits
229        /// do not attach.
230        LimitChanged,
231        /// A command/query require/ensure clause set changed.
232        ContractChanged,
233        /// A name-paired interaction's family or operation shape changed
234        /// (ADR-0012 decision 6).
235        InteractionClassChanged,
236        /// A derived wire width or scalar backing changed.
237        WidthChanged,
238        /// A scalar constraint (range, step, length, pattern) changed, or a
239        /// composite member changed in place.
240        ConstraintChanged,
241        /// A resolved or declared init value changed.
242        InitChanged,
243        /// A name that was a `reserved` tombstone is live again — an
244        /// interaction inside an interface body.
245        ReservedNameRedeclared,
246        /// A service switched between the named list and an inline shape.
247        /// Narrowed to the form switch by ADR-0015 decision 19: a changed
248        /// list is read as a set by the two `ServiceInterface*` categories
249        /// below.
250        ServiceChanged,
251        /// An interface in a service's set that the old snapshot's set did not
252        /// hold (ADR-0015 decision 19 as amended on 2026-09-15: a service's
253        /// list is a set of interface references).
254        ServiceInterfaceAdded,
255        /// An interface the old snapshot's set held that the new one does not.
256        /// Compatible on the wire — the routing key does not contain the
257        /// service — and visible in source, so the text report lists it under
258        /// that heading ([`heading`]).
259        ServiceInterfaceRemoved,
260        /// Only doc comment, labels, or deprecation metadata changed.
261        DocOnly,
262        /// The visibility a declaration is published at changed. Separate from
263        /// [`Category::DocOnly`] because `internal` removes the declaration from
264        /// every out-of-package consumer (ADR-0002 §8), so the change has a
265        /// direction.
266        VisibilityChanged,
267        /// A struct field appended, compatible under the generic rule, to a
268        /// struct another head of the old side holds inline, when the field
269        /// does not fit entirely inside the old head: the layout law places
270        /// any of its bytes past the old head's size (ADR-0031 decision 10,
271        /// the inline-append rule;
272        /// `ridl diff --explain podbuf_inline_append` states it in full).
273        /// Breaking when the comparison is judged for the `podbuf` encoding,
274        /// compatible otherwise, listed under the heading "breaking under
275        /// podbuf" ([`heading`]). The path is the appended field's; the
276        /// detail names each inline use of the old side, a struct field as
277        /// `<package>/<struct>/<field>` and an interaction's request, reply
278        /// or fixed payload as `<package>/<interface>/<interaction>`.
279        PodbufInlineAppend,
280        /// A remote declaration held inline by an old consumer has a larger podbuf size.
281        PodbufRemoteInlineGrowth,
282        /// An enum value, an enum-set flag or a union arm appended, compatible
283        /// under the generic rule, after which the podbuf integer of the enum
284        /// or the enum set or the tag of the union is a different integer, by
285        /// width or by signedness (ADR-0031 decision 10, the width rule;
286        /// `ridl diff --explain podbuf_width_change` states it in full).
287        /// Breaking when `podbuf` is among the encodings the comparison is
288        /// judged for, compatible otherwise. Reported once per declaration,
289        /// at `<package>/<decl>`, with the old and the new integer.
290        PodbufWidthChange,
291        /// Superseded by [`Category::StrictEnumAppend`], which is breaking for
292        /// every encoding. The variant stays so that a report or a consumer
293        /// that names the category still compiles; `ridl diff` no longer
294        /// reports it.
295        PodbufStrictEnumAppend,
296        /// An enum value or an enum-set flag appended to an enum or an enum
297        /// set that is not `open` (ADR-0031 decision 12). A reader built from
298        /// the old declaration refuses a value or a flag it does not name, in
299        /// the `verify` of podbuf and in the codec of every other encoding
300        /// that checks the declaration, so the append is breaking for every
301        /// encoding. Reported once per compared declaration, at
302        /// `<package>/<decl>`, with the appended names in the detail. With
303        /// per-side contexts, a remote append is reported once per consumer
304        /// path and remote declaration reached by a surviving old use, at the
305        /// consumer path,
306        /// with `<remote declaration>: <names>` values. A side without remote
307        /// context draws no remote strict-append line; shared-context entry
308        /// points do not report remote appends. The same append to an `open`
309        /// declaration is compatible.
310        StrictEnumAppend,
311        /// An enum or an enum set that gained the `open` keyword: every
312        /// reader of the old declaration already accepts the values it
313        /// named, so the change is compatible. Reported at
314        /// `<package>/<decl>`.
315        EnumOpened,
316        /// An enum or an enum set that lost the `open` keyword: a reader of
317        /// the new declaration refuses a value that a producer of the old one
318        /// may still send, so the change is breaking. Reported at
319        /// `<package>/<decl>`.
320        EnumClosed,
321        /// An enum-set flag appended, compatible under the generic rule, after
322        /// which the FlatBuffers integer of the enum set is a different integer
323        /// (ADR-0019 decision 10;
324        /// `ridl diff --explain flatbuffers_width_change` states it in full).
325        /// Breaking when `flatbuffers` is among the encodings the comparison
326        /// is judged for, compatible otherwise. Reported once per declaration,
327        /// at `<package>/<decl>`, with the old and the new integer.
328        /// With per-side contexts, a remote declaration reached by a surviving
329        /// old consumer use is reported once per consumer path and remote
330        /// declaration, at the consumer path, with
331        /// `<remote declaration>: <integer>` values. A side without remote
332        /// context draws no remote width line; shared-context entry points
333        /// do not report remote widths.
334        FlatbuffersWidthChange,
335        /// An enum-set flag appended, compatible under the generic rule,
336        /// after which the proto3 scalar of the enum set is a different
337        /// scalar (ADR-0017 decision 9;
338        /// `ridl diff --explain proto3_width_change` states it in full).
339        /// Breaking when `proto3` is among the encodings the comparison is
340        /// judged for, compatible otherwise. Reported once per declaration,
341        /// at `<package>/<decl>`, with the old and the new proto3 scalar.
342        /// With per-side contexts, a remote declaration reached by a surviving
343        /// old consumer use is reported once per consumer path and remote
344        /// declaration, at the consumer path, with
345        /// `<remote declaration>: <integer>` values. A side without remote
346        /// context draws no remote width line; shared-context entry points
347        /// do not report remote widths.
348        Proto3WidthChange,
349    }
350}
351
352/// One difference between two snapshots, with an honest path into the IR and
353/// the rendered before/after values where they apply.
354#[derive(Clone, Debug, PartialEq, Eq)]
355pub struct Change {
356    /// A slash-separated path, e.g. `veh.cluster/VehicleStatus/doorOpened`.
357    pub path: String,
358    pub category: Category,
359    pub verdict: Verdict,
360    /// The rendered old value, absent when the change is an addition.
361    pub before: Option<String>,
362    /// The rendered new value, absent when the change is a removal.
363    pub after: Option<String>,
364}
365
366impl Change {
367    /// The dotted name of the package the change belongs to: the first
368    /// segment of [`path`](Change::path). The walk builds the path as
369    /// `<package>/<name>[/<member>...]`, and this accessor and
370    /// [`declaration`](Change::declaration) are the one place that reads that
371    /// layout back.
372    pub fn package(&self) -> &str {
373        self.path.split('/').next().unwrap_or_default()
374    }
375
376    /// The bare name of the package-level declaration, interface or service
377    /// the change belongs to: the second segment of [`path`](Change::path), or
378    /// `None` for a change to the package itself.
379    pub fn declaration(&self) -> Option<&str> {
380        self.path.split('/').nth(1)
381    }
382}
383
384/// The result of a comparison: every change and the report-level verdict (the
385/// maximum verdict over the changes; [`Verdict::Identical`] when there are
386/// none).
387#[derive(Clone, Debug, PartialEq, Eq)]
388pub struct DiffReport {
389    pub changes: Vec<Change>,
390    pub verdict: Verdict,
391    /// The changes to the lowered system, each under its heading (rsdl
392    /// reference §14). Only a change under
393    /// [`SystemHeading::InstanceNumberChanged`] enters `verdict`, as breaking;
394    /// the other headings carry no verdict. Empty unless
395    /// both sides carry a system ([`diff_workspaces`]).
396    pub system: Vec<SystemChange>,
397}
398
399/// Appends one change.
400///
401/// The verdict is stamped breaking here and settled by [`classify`] once the
402/// walk of the containing package pair is complete — the classifier needs both
403/// snapshots, which the walk does not carry down to every emission site.
404/// Breaking is the safe placeholder: a change that somehow escaped
405/// classification would gate rather than pass.
406pub(crate) fn emit(
407    changes: &mut Vec<Change>,
408    path: String,
409    category: Category,
410    before: Option<String>,
411    after: Option<String>,
412) {
413    changes.push(Change {
414        path,
415        category,
416        verdict: Verdict::Breaking,
417        before,
418        after,
419    });
420}
421
422/// Whether an interface carries an identity: a frozen, non-zero number from
423/// its unit's `interfaces.lock` (lock design §7). A provisional number is
424/// no identity, and `number` 0 — never allocated — marks a snapshot published
425/// before the lock existed. The walk matches by number only when both sides
426/// have one, and the classifier re-finds the old side the same way.
427pub(crate) fn frozen(interface: &ridl_ir::v2::Interface) -> bool {
428    interface.number != 0 && !interface.provisional
429}
430
431/// Settles the verdict of every change the walk of one package pair produced.
432/// `scope` is every package a reference to another package's declaration
433/// resolves against ([`classify::classify_in`]); `encodings` is the list the
434/// comparison is judged for ([`diff_refs_with`]).
435///
436/// A change's new side is in `new`, except for an interface whose number
437/// moved to another package of the unit: the walk puts that package first in
438/// the change's path, and the classifier reads the new side from it, so the
439/// package is taken from `scope`, which holds every package of the new set.
440fn classify_all(
441    changes: &mut [Change],
442    old: &Package,
443    new: &Package,
444    scope: &[&Package],
445    encodings: &[&str],
446    directions: &mut direction::DirectionCache,
447) {
448    for change in changes {
449        let held_by = change.path.split('/').next().unwrap_or_default();
450        let new = if held_by == new.name {
451            new
452        } else {
453            scope
454                .iter()
455                .copied()
456                .find(|package| package.name == held_by)
457                .unwrap_or(new)
458        };
459        change.verdict = classify::classify_in(change, old, new, scope, encodings, directions);
460    }
461}
462
463/// Assembles a [`DiffReport`], deriving the report verdict as the maximum over
464/// its changes.
465pub(crate) fn report(changes: Vec<Change>) -> DiffReport {
466    let verdict = changes
467        .iter()
468        .map(|change| change.verdict)
469        .max()
470        .unwrap_or(Verdict::Identical);
471    DiffReport {
472        changes,
473        verdict,
474        system: Vec::new(),
475    }
476}
477
478/// Compares two resolved packages. Matched packages share a name; the new
479/// package's name is used as the path prefix.
480///
481/// Only the pair is in hand, so a type from another package does not resolve,
482/// and a type the diff cannot resolve is reported as breaking: a struct field
483/// appended with such a type classifies breaking (driftsys/ridl#598).
484/// [`diff_sets_in`] resolves it.
485pub fn diff_packages(old: &Package, new: &Package) -> DiffReport {
486    let matching = walk::Matching::new(&[old], &[new]);
487    let mut changes = Vec::new();
488    walk::walk_packages(old, new, &matching, &mut changes);
489    let mut changes = walk::fold_strict_enum_appends(changes, old, new);
490    classify_all(&mut changes, old, new, &[], &[], &mut Default::default());
491    report(changes)
492}
493
494/// Compares two sets of resolved packages, matching by package name, and
495/// interface numbers within each unit ([`walk::Matching`]). A package present
496/// only on the new side is a [`Category::DeclAdded`]; matched packages are
497/// walked pairwise. A package present only on the old side is a
498/// [`Category::DeclRemoved`] when its whole unit is gone from the new side,
499/// and is walked declaration by declaration when the unit is still there, so
500/// that an interface whose number moved to another package of the unit is
501/// [`Category::InterfaceRenamed`] and one the unit retired is
502/// [`Category::InterfaceRetired`].
503///
504/// [`diff_sets_in`] with no context: a type from a package outside `new`, such
505/// as `ridl.std`, which no snapshot carries, does not resolve, and a type the
506/// diff cannot resolve is reported as breaking.
507pub fn diff_sets(old: &[Package], new: &[Package]) -> DiffReport {
508    diff_sets_in(old, new, &[])
509}
510
511/// [`diff_sets`], with `context`: packages that a type reference resolves
512/// against without being compared. This entry point shares one context.
513/// `ridl diff` and the MCP server use per-side contexts through
514/// [`diff_workspaces_with_contexts`]: the built-in `ridl.std` plus each side's
515/// own remote packages, compiled from source or retained in a snapshot
516/// directory, so historical layouts never borrow current remote definitions.
517/// `ridl check`'s baseline desk check passes one shared context and judges no encoding.
518pub fn diff_sets_in(old: &[Package], new: &[Package], context: &[Package]) -> DiffReport {
519    let old: Vec<&Package> = old.iter().collect();
520    let new: Vec<&Package> = new.iter().collect();
521    let context: Vec<&Package> = context.iter().collect();
522    diff_refs_in(&old, &new, &context)
523}
524
525/// [`diff_sets_in`] over borrowed packages, for a caller that holds the
526/// packages by reference and would otherwise clone them. The comparison is
527/// judged for no encoding: [`diff_refs_with`] with an empty list.
528pub fn diff_refs_in(old: &[&Package], new: &[&Package], context: &[&Package]) -> DiffReport {
529    diff_refs_with(old, new, context, &[])
530}
531
532/// [`diff_refs_in`], judged for `encodings`: the names a `[backend.<name>]
533/// encodings` list writes (`flatbuffers`, `proto3`, `podbuf`). A snapshot
534/// does not carry the encodings a workspace builds, so the caller names them.
535///
536/// Each of the three names has rules of its own: a struct field appended that
537/// does not fit inside the old head of a struct another head of the old
538/// side holds inline is [`Category::PodbufInlineAppend`], and an enum value,
539/// an enum-set flag or a union arm appended that changes the integer of the
540/// enum or the enum set or the union's tag is [`Category::PodbufWidthChange`];
541/// each is
542/// breaking when `podbuf` is in `encodings` and compatible otherwise. An enum
543/// value or an enum-set flag appended to a declaration that is not `open` is
544/// [`Category::StrictEnumAppend`], breaking under every list. An enum value or
545/// an enum-set flag appended that changes the FlatBuffers integer is
546/// [`Category::FlatbuffersWidthChange`], breaking when `flatbuffers` is in
547/// `encodings` and compatible otherwise. An enum-set flag appended that
548/// changes the proto3 scalar is [`Category::Proto3WidthChange`], breaking
549/// when `proto3` is in `encodings` and compatible otherwise. Every other
550/// category is judged the same under every list. The CLI and the MCP tool
551/// refuse a name that is not one of the three before calling this; the engine
552/// does not check it.
553/// The podbuf rule lays the old side out over `old` and the context packages
554/// `old` does not name, and the new side over `new` and `context`; a package
555/// in both `new` and `context` is read at its first occurrence.
556pub fn diff_refs_with(
557    old: &[&Package],
558    new: &[&Package],
559    context: &[&Package],
560    encodings: &[&str],
561) -> DiffReport {
562    diff_refs_scoped(old, new, context, context, encodings)
563}
564
565/// The side whose remote evidence cannot establish inline compatibility.
566#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
567pub enum ContextSide {
568    Old,
569    New,
570}
571
572impl std::fmt::Display for ContextSide {
573    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
574        f.write_str(match self {
575            Self::Old => "old",
576            Self::New => "new",
577        })
578    }
579}
580
581/// Why remote evidence cannot establish inline compatibility.
582#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
583pub enum ContextIssueReason {
584    Missing,
585    Unlayable,
586    KindChanged,
587}
588
589/// Unusable evidence for a consumer-owned podbuf comparison.
590#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
591pub struct ContextIssue {
592    pub path: String,
593    pub declaration: String,
594    pub side: ContextSide,
595    pub reason: ContextIssueReason,
596}
597
598impl std::fmt::Display for ContextIssue {
599    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
600        match self.reason {
601            ContextIssueReason::Missing => write!(
602                f,
603                "{}: {} context is missing {}",
604                self.path, self.side, self.declaration
605            ),
606            ContextIssueReason::Unlayable => write!(
607                f,
608                "{}: {} context cannot lay out {}",
609                self.path, self.side, self.declaration
610            ),
611            ContextIssueReason::KindChanged => write!(
612                f,
613                "{}: {} context changes {} from a struct to another declaration kind",
614                self.path, self.side, self.declaration
615            ),
616        }
617    }
618}
619
620/// An explicit podbuf comparison cannot use its own side's remote evidence.
621#[derive(Clone, Debug, PartialEq, Eq)]
622pub struct ContextError {
623    pub issues: Vec<ContextIssue>,
624}
625
626impl std::fmt::Display for ContextError {
627    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
628        for (index, issue) in self.issues.iter().enumerate() {
629            if index != 0 {
630                f.write_str("; ")?;
631            }
632            write!(f, "{issue}")?;
633        }
634        Ok(())
635    }
636}
637impl std::error::Error for ContextError {}
638
639/// Compares packages using independent source-side resolution scopes.
640/// Missing remote evidence prevents only an explicit podbuf judgment.
641/// Context packages resolve references without being compared themselves.
642/// Local packages take precedence over context packages with the same name.
643/// Growth is reported once per old consumer path and remote declaration;
644/// issues are sorted by consumer path, declaration, then side.
645pub fn diff_refs_with_contexts(
646    old: &[&Package],
647    new: &[&Package],
648    old_context: &[&Package],
649    new_context: &[&Package],
650    encodings: &[&str],
651) -> Result<DiffReport, ContextError> {
652    let (result, issues) =
653        diff_refs_with_contexts_partial(old, new, old_context, new_context, encodings);
654    if encodings.contains(&"podbuf") && !issues.is_empty() {
655        return Err(ContextError { issues });
656    }
657    Ok(result)
658}
659
660/// Compares complete scopes while retaining independent missing-evidence issues.
661/// Each issue names its consumer path and the remote declaration; callers decide
662/// what an issue means for the units that own or reach it (ADR-0031 decision 13).
663/// Remote FlatBuffers and proto3 widths are reported once per consumer path
664/// and remote declaration reached by a surviving old consumer use, at the
665/// consumer path, with `<remote declaration>: <integer>` values. Only the
666/// per-side context entry points report remote widths. They also report remote
667/// strict enum and enum-set appends under the same consumer-use gates, always
668/// breaking, with `<remote declaration>: <names>` values (ADR-0031 decision 13).
669/// They also report scalar constraint changes at surviving consumer interaction
670/// paths, with the direction rule of `constraint_changed`. A side without remote
671/// context draws no remote width, constraint or strict-append lines.
672/// A remote scalar's changed backing or resolved width also reports a breaking
673/// `width_changed` at each surviving consumer interaction path, even on send-only
674/// uses, once per path and remote declaration.
675pub fn diff_refs_with_contexts_partial(
676    old: &[&Package],
677    new: &[&Package],
678    old_context: &[&Package],
679    new_context: &[&Package],
680    encodings: &[&str],
681) -> (DiffReport, Vec<ContextIssue>) {
682    let old_scope: Vec<_> = old.iter().chain(old_context).copied().collect();
683    let new_scope: Vec<_> = new.iter().chain(new_context).copied().collect();
684    let (mut remote, issues) = remote_inline::compare(old, new, &old_scope, &new_scope, encodings);
685    let mut result = diff_refs_scoped(old, new, old_context, new_context, encodings);
686    result.changes.append(&mut remote);
687    (report(result.changes), issues)
688}
689
690fn diff_refs_scoped(
691    old: &[&Package],
692    new: &[&Package],
693    old_context: &[&Package],
694    new_context: &[&Package],
695    encodings: &[&str],
696) -> DiffReport {
697    use std::collections::BTreeMap;
698
699    use ridl_ir::v2::{members_of_unit, unit_of};
700
701    let scope: Vec<&Package> = new.iter().chain(new_context).copied().collect();
702    let matching = walk::Matching::new(old, new);
703    // The cache keys by package address, so it serves only packages that live
704    // for the whole comparison.
705    let mut directions = direction::DirectionCache::default();
706
707    let old_by: BTreeMap<&str, &Package> =
708        old.iter().map(|pkg| (pkg.name.as_str(), *pkg)).collect();
709    let new_by: BTreeMap<&str, &Package> =
710        new.iter().map(|pkg| (pkg.name.as_str(), *pkg)).collect();
711    // Old packages take precedence over their own context, independently
712    // of the new side's definitions.
713    let old_scope: Vec<&Package> = old
714        .iter()
715        .copied()
716        .chain(
717            old_context
718                .iter()
719                .copied()
720                .filter(|pkg| !old_by.contains_key(pkg.name.as_str())),
721        )
722        .collect();
723
724    // Each matched pair is walked and classified against its own two snapshots,
725    // because the classifier resolves a change's path back into the packages it
726    // came from.
727    let mut changes = Vec::new();
728    for (name, old_pkg) in &old_by {
729        match new_by.get(name) {
730            Some(new_pkg) => {
731                let mut pair = Vec::new();
732                walk::walk_packages(old_pkg, new_pkg, &matching, &mut pair);
733                let mut pair = walk::fold_strict_enum_appends(pair, old_pkg, new_pkg);
734                classify_all(
735                    &mut pair,
736                    old_pkg,
737                    new_pkg,
738                    &scope,
739                    encodings,
740                    &mut directions,
741                );
742                // The encoding rules read the settled verdicts of the pair
743                // and the heads of both whole sides, so they run after the
744                // walk and the classifier of the pair.
745                let mut encoding_changes =
746                    walk::podbuf_inline_appends(&pair, old, &old_scope, &scope);
747                encoding_changes.append(&mut walk::podbuf_width_changes(&pair, old_pkg, new_pkg));
748                encoding_changes.append(&mut walk::flatbuffers_width_changes(
749                    &pair, old_pkg, new_pkg,
750                ));
751                encoding_changes.append(&mut walk::proto3_width_changes(&pair, old_pkg, new_pkg));
752                classify_all(
753                    &mut encoding_changes,
754                    old_pkg,
755                    new_pkg,
756                    &scope,
757                    encodings,
758                    &mut directions,
759                );
760                pair.append(&mut encoding_changes);
761                changes.append(&mut pair);
762            }
763            // A package gone while its unit stays: walked against a package
764            // with nothing in it, so that each shape is matched in the unit,
765            // retired by the unit, or removed, and each other declaration is
766            // removed on its own line.
767            None if members_of_unit(unit_of(old_pkg), new).next().is_some() => {
768                let gone = Package {
769                    name: old_pkg.name.clone(),
770                    unit: old_pkg.unit.clone(),
771                    ..Default::default()
772                };
773                let mut pair = Vec::new();
774                walk::walk_packages(old_pkg, &gone, &matching, &mut pair);
775                classify_all(
776                    &mut pair,
777                    old_pkg,
778                    &gone,
779                    &scope,
780                    encodings,
781                    // `gone` is dropped after this arm and its address can be
782                    // reused, so it gets its own cache.
783                    &mut Default::default(),
784                );
785                changes.append(&mut pair);
786            }
787            // A package present on one side only: the change classifies on its
788            // category alone, so the one snapshot stands for both.
789            None => {
790                let mut pair = Vec::new();
791                emit(
792                    &mut pair,
793                    (*name).to_string(),
794                    Category::DeclRemoved,
795                    Some(format!("package {name}")),
796                    None,
797                );
798                classify_all(&mut pair, old_pkg, old_pkg, &[], encodings, &mut directions);
799                changes.append(&mut pair);
800            }
801        }
802    }
803    for (name, new_pkg) in &new_by {
804        if !old_by.contains_key(name) {
805            let mut pair = Vec::new();
806            emit(
807                &mut pair,
808                (*name).to_string(),
809                Category::DeclAdded,
810                None,
811                Some(format!("package {name}")),
812            );
813            classify_all(&mut pair, new_pkg, new_pkg, &[], encodings, &mut directions);
814            changes.append(&mut pair);
815        }
816    }
817    report(changes)
818}
819
820/// Compares two workspaces at the system (rsdl reference §14): the packages by
821/// the ridl categories, exactly as [`diff_sets`] does, and — when both sides
822/// carry a lowered system — the system's placement and composition changes,
823/// which carry no verdict, and its instance number changes, which make the
824/// report breaking. A system on one side only is not compared: there is
825/// nothing to compare it against.
826///
827/// `context` is passed to [`diff_sets_in`]. The comparison is judged for no
828/// encoding: [`diff_workspaces_with`] with an empty list.
829pub fn diff_workspaces(
830    old: &[Package],
831    old_system: Option<&System>,
832    new: &[Package],
833    new_system: Option<&System>,
834    context: &[Package],
835) -> DiffReport {
836    diff_workspaces_with(old, old_system, new, new_system, context, &[])
837}
838
839/// [`diff_workspaces`], judged for `encodings` ([`diff_refs_with`]).
840pub fn diff_workspaces_with(
841    old: &[Package],
842    old_system: Option<&System>,
843    new: &[Package],
844    new_system: Option<&System>,
845    context: &[Package],
846    encodings: &[&str],
847) -> DiffReport {
848    let old: Vec<&Package> = old.iter().collect();
849    let new: Vec<&Package> = new.iter().collect();
850    let context: Vec<&Package> = context.iter().collect();
851    let mut report = diff_refs_with(&old, &new, &context, encodings);
852    if let (Some(old_system), Some(new_system)) = (old_system, new_system) {
853        report.system = diff_systems(old_system, new_system);
854        if report
855            .system
856            .iter()
857            .any(|change| change.heading == SystemHeading::InstanceNumberChanged)
858        {
859            report.verdict = Verdict::Breaking;
860        }
861    }
862    report
863}
864
865/// Compares workspace packages with independent side contexts and, when both
866/// sides carry a system, lists the system changes, of which only an instance
867/// number change enters the verdict, as breaking ([`diff_workspaces_with`]).
868/// Missing remote evidence is an error for an explicit podbuf comparison.
869pub fn diff_workspaces_with_contexts(
870    old: &[Package],
871    old_system: Option<&System>,
872    new: &[Package],
873    new_system: Option<&System>,
874    old_context: &[Package],
875    new_context: &[Package],
876    encodings: &[&str],
877) -> Result<DiffReport, ContextError> {
878    let old: Vec<&Package> = old.iter().collect();
879    let new: Vec<&Package> = new.iter().collect();
880    let old_context: Vec<&Package> = old_context.iter().collect();
881    let new_context: Vec<&Package> = new_context.iter().collect();
882    let mut report = diff_refs_with_contexts(&old, &new, &old_context, &new_context, encodings)?;
883    if let (Some(old_system), Some(new_system)) = (old_system, new_system) {
884        report.system = diff_systems(old_system, new_system);
885        if report
886            .system
887            .iter()
888            .any(|change| change.heading == SystemHeading::InstanceNumberChanged)
889        {
890            report.verdict = Verdict::Breaking;
891        }
892    }
893    Ok(report)
894}
895
896/// The stable lowercase word for a verdict — used by both the text and JSON
897/// renderers so the two stay in lockstep.
898pub(crate) fn verdict_word(verdict: Verdict) -> &'static str {
899    match verdict {
900        Verdict::Identical => "identical",
901        Verdict::Compatible => "compatible",
902        Verdict::Breaking => "breaking",
903    }
904}
905
906/// The stable snake_case word for a category — the single source of truth for
907/// both renderers and for `ridl diff --explain`, which takes a category exactly
908/// as the report prints it.
909// A new variant must be given a real arm here, not swept into a
910// catch-all: rustc forces *an* arm, and the arm its `help:` text
911// proposes is `_ =>`, which classifies the new variant silently. The
912// two lints below reject a wildcard over `Category` — the first when
913// it covers several variants, the second when it covers exactly one,
914// which is the case one added variant creates.
915#[deny(
916    clippy::wildcard_enum_match_arm,
917    clippy::match_wildcard_for_single_variants
918)]
919pub fn category_word(category: Category) -> &'static str {
920    match category {
921        Category::DeclAdded => "decl_added",
922        Category::DeclRemoved => "decl_removed",
923        Category::InterfaceRenamed => "interface_renamed",
924        Category::InterfaceRetired => "interface_retired",
925        Category::InterfaceFrozen => "interface_frozen",
926        Category::InterfaceNumberChanged => "interface_number_changed",
927        Category::MemberReordered => "member_reordered",
928        Category::EnumReordered => "enum_reordered",
929        Category::InteractionAppended => "interaction_appended",
930        Category::InteractionInserted => "interaction_inserted",
931        Category::InteractionReordered => "interaction_reordered",
932        Category::InteractionRemoved => "interaction_removed",
933        Category::InteractionRetired => "interaction_retired",
934        Category::KindChanged => "kind_changed",
935        Category::PayloadChanged => "payload_changed",
936        Category::ReturnChanged => "return_changed",
937        Category::ParamsChanged => "params_changed",
938        Category::TimingChanged => "timing_changed",
939        Category::RpcBoundChanged => "rpc_bound_changed",
940        Category::LimitChanged => "limit_changed",
941        Category::ContractChanged => "contract_changed",
942        Category::InteractionClassChanged => "interaction_class_changed",
943        Category::WidthChanged => "width_changed",
944        Category::ConstraintChanged => "constraint_changed",
945        Category::InitChanged => "init_changed",
946        Category::ReservedNameRedeclared => "reserved_name_redeclared",
947        Category::ServiceChanged => "service_changed",
948        Category::ServiceInterfaceAdded => "service_interface_added",
949        Category::ServiceInterfaceRemoved => "service_interface_removed",
950        Category::DocOnly => "doc_only",
951        Category::VisibilityChanged => "visibility_changed",
952        Category::PodbufInlineAppend => "podbuf_inline_append",
953        Category::PodbufRemoteInlineGrowth => "podbuf_remote_inline_growth",
954        Category::PodbufWidthChange => "podbuf_width_change",
955        Category::PodbufStrictEnumAppend => "podbuf_strict_enum_append",
956        Category::StrictEnumAppend => "strict_enum_append",
957        Category::EnumOpened => "enum_opened",
958        Category::EnumClosed => "enum_closed",
959        Category::FlatbuffersWidthChange => "flatbuffers_width_change",
960        Category::Proto3WidthChange => "proto3_width_change",
961    }
962}
963
964/// The heading a category's changes are grouped under in the text report, or
965/// `None` for a category listed plainly. Five headings exist. "compatible on
966/// the wire, visible in source" is for a change that exits 0 but that a
967/// consumer sees in its source — an interface renamed on its number changes
968/// the generated identity-table names in both wire backends, and an interface
969/// leaving a service's set stops the `service.member` addresses of that
970/// interface resolving under the service. "compatible on the wire, may change
971/// the catalog hash" is for a change that exits 0 but can change the catalog
972/// hash, which a generated face compares with its peer's — a number `ridl
973/// lock` froze in place, which always changes it, and an enum or enum-set body
974/// reordered, which changes it when an interface reaches the enum or enum set
975/// (the hash covers only the declarations an interface reaches). "breaking
976/// under podbuf" is for a change whose verdict depends on the encodings the
977/// comparison is judged for ([`diff_refs_with`]): it exits 0 unless `podbuf`
978/// is among them. "breaking under flatbuffers" follows the same rule for
979/// `flatbuffers`, and "breaking under proto3" for `proto3`. Each such
980/// category's `--explain` text states its own consequence; the JSON report
981/// carries the category word and no heading field.
982///
983/// Wildcard arms are denied for the reason `category_word` gives.
984#[deny(
985    clippy::wildcard_enum_match_arm,
986    clippy::match_wildcard_for_single_variants
987)]
988pub fn heading(category: Category) -> Option<&'static str> {
989    match category {
990        Category::InterfaceRenamed | Category::ServiceInterfaceRemoved => {
991            Some("compatible on the wire, visible in source")
992        }
993        Category::InterfaceFrozen | Category::EnumReordered => {
994            Some("compatible on the wire, may change the catalog hash")
995        }
996        Category::PodbufInlineAppend
997        | Category::PodbufRemoteInlineGrowth
998        | Category::PodbufWidthChange
999        | Category::PodbufStrictEnumAppend => Some("breaking under podbuf"),
1000        Category::FlatbuffersWidthChange => Some("breaking under flatbuffers"),
1001        Category::Proto3WidthChange => Some("breaking under proto3"),
1002        Category::DeclAdded
1003        | Category::DeclRemoved
1004        | Category::InterfaceRetired
1005        | Category::InterfaceNumberChanged
1006        | Category::MemberReordered
1007        | Category::InteractionAppended
1008        | Category::InteractionInserted
1009        | Category::InteractionReordered
1010        | Category::InteractionRemoved
1011        | Category::InteractionRetired
1012        | Category::KindChanged
1013        | Category::PayloadChanged
1014        | Category::ReturnChanged
1015        | Category::ParamsChanged
1016        | Category::TimingChanged
1017        | Category::RpcBoundChanged
1018        | Category::LimitChanged
1019        | Category::ContractChanged
1020        | Category::InteractionClassChanged
1021        | Category::WidthChanged
1022        | Category::ConstraintChanged
1023        | Category::InitChanged
1024        | Category::ReservedNameRedeclared
1025        | Category::ServiceChanged
1026        | Category::ServiceInterfaceAdded
1027        | Category::StrictEnumAppend
1028        | Category::EnumOpened
1029        | Category::EnumClosed
1030        | Category::DocOnly
1031        | Category::VisibilityChanged => None,
1032    }
1033}
1034
1035impl serde::Serialize for Verdict {
1036    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1037        serializer.serialize_str(verdict_word(*self))
1038    }
1039}
1040
1041impl serde::Serialize for Category {
1042    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1043        serializer.serialize_str(category_word(*self))
1044    }
1045}
1046
1047impl serde::Serialize for Change {
1048    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1049        use serde::ser::SerializeStruct as _;
1050        let mut state = serializer.serialize_struct("Change", 5)?;
1051        state.serialize_field("path", &self.path)?;
1052        state.serialize_field("category", &self.category)?;
1053        state.serialize_field("verdict", &self.verdict)?;
1054        state.serialize_field("before", &self.before)?;
1055        state.serialize_field("after", &self.after)?;
1056        state.end()
1057    }
1058}
1059
1060/// Renders a report as a human-readable summary: the report verdict on the
1061/// first line, then one indented line per change. A change whose category has
1062/// no [`heading`] is listed first, in report order; then each heading is
1063/// printed once, as its own line ending in a colon, followed by the changes
1064/// under it, in report order. Headings come in [`CATEGORIES`] order.
1065///
1066/// After the contract changes come the system headings (rsdl reference §14):
1067/// each heading that has a change on its own line, then one indented line per
1068/// change under it, in the `path: before -> after` form. Only the instance
1069/// number heading carries a verdict, printed after it as `(breaking)`.
1070pub fn render_text(report: &DiffReport) -> String {
1071    let mut out = String::new();
1072    out.push_str(verdict_word(report.verdict));
1073    out.push('\n');
1074    for change in &report.changes {
1075        if heading(change.category).is_none() {
1076            push_change_line(&mut out, change);
1077        }
1078    }
1079    let mut printed: Vec<&'static str> = Vec::new();
1080    for category in CATEGORIES {
1081        let Some(title) = heading(category) else {
1082            continue;
1083        };
1084        if printed.contains(&title) {
1085            continue;
1086        }
1087        printed.push(title);
1088        let mut under = report
1089            .changes
1090            .iter()
1091            .filter(|change| heading(change.category) == Some(title))
1092            .peekable();
1093        if under.peek().is_none() {
1094            continue;
1095        }
1096        out.push_str(title);
1097        out.push_str(":\n");
1098        for change in under {
1099            push_change_line(&mut out, change);
1100        }
1101    }
1102    for heading in [
1103        SystemHeading::PlacementChanged,
1104        SystemHeading::CompositionChanged,
1105        SystemHeading::InstanceNumberChanged,
1106    ] {
1107        let mut listed = report
1108            .system
1109            .iter()
1110            .filter(|change| change.heading == heading)
1111            .peekable();
1112        if listed.peek().is_none() {
1113            continue;
1114        }
1115        out.push_str(system::heading_text(heading));
1116        if heading == SystemHeading::InstanceNumberChanged {
1117            out.push_str(" (breaking)");
1118        }
1119        out.push('\n');
1120        for change in listed {
1121            out.push_str("  ");
1122            out.push_str(&change.path);
1123            push_values(&mut out, change.before.as_ref(), change.after.as_ref());
1124            out.push('\n');
1125        }
1126    }
1127    out
1128}
1129
1130/// One change of the text report: `  [verdict] category path`, then
1131/// `: before -> after` where the sides apply.
1132fn push_change_line(out: &mut String, change: &Change) {
1133    out.push_str("  [");
1134    out.push_str(verdict_word(change.verdict));
1135    out.push_str("] ");
1136    out.push_str(category_word(change.category));
1137    out.push(' ');
1138    out.push_str(&change.path);
1139    push_values(out, change.before.as_ref(), change.after.as_ref());
1140    out.push('\n');
1141}
1142
1143/// The rendered `before -> after` tail of one change line, shared by contract
1144/// changes and system changes.
1145fn push_values(out: &mut String, before: Option<&String>, after: Option<&String>) {
1146    match (before, after) {
1147        (Some(before), Some(after)) => {
1148            out.push_str(": ");
1149            out.push_str(before);
1150            out.push_str(" -> ");
1151            out.push_str(after);
1152        }
1153        (Some(before), None) => {
1154            out.push_str(": ");
1155            out.push_str(before);
1156            out.push_str(" -> (removed)");
1157        }
1158        (None, Some(after)) => {
1159            out.push_str(": (absent) -> ");
1160            out.push_str(after);
1161        }
1162        (None, None) => {}
1163    }
1164}
1165
1166/// Renders a report as machine-readable JSON with the stable schema
1167/// `{"verdict", "changes": [{"path", "category", "verdict", "before",
1168/// "after"}]}`.
1169pub fn render_json(report: &DiffReport) -> String {
1170    #[derive(serde::Serialize)]
1171    struct JsonSystemChange<'a> {
1172        path: &'a str,
1173        before: Option<&'a str>,
1174        after: Option<&'a str>,
1175    }
1176
1177    #[derive(serde::Serialize)]
1178    struct JsonReport<'a> {
1179        verdict: Verdict,
1180        changes: &'a [Change],
1181        #[serde(skip_serializing_if = "Vec::is_empty")]
1182        placement_changed: Vec<JsonSystemChange<'a>>,
1183        #[serde(skip_serializing_if = "Vec::is_empty")]
1184        composition_changed: Vec<JsonSystemChange<'a>>,
1185        #[serde(skip_serializing_if = "Vec::is_empty")]
1186        instance_number_changed: Vec<JsonSystemChange<'a>>,
1187    }
1188
1189    let under = |heading: SystemHeading| -> Vec<JsonSystemChange<'_>> {
1190        report
1191            .system
1192            .iter()
1193            .filter(|change| change.heading == heading)
1194            .map(|change| JsonSystemChange {
1195                path: &change.path,
1196                before: change.before.as_deref(),
1197                after: change.after.as_deref(),
1198            })
1199            .collect()
1200    };
1201    serde_json::to_string_pretty(&JsonReport {
1202        verdict: report.verdict,
1203        changes: &report.changes,
1204        placement_changed: under(SystemHeading::PlacementChanged),
1205        composition_changed: under(SystemHeading::CompositionChanged),
1206        instance_number_changed: under(SystemHeading::InstanceNumberChanged),
1207    })
1208    .expect("a diff report holds only string-representable values, so serialization cannot fail")
1209}