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