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//! The comparison has two halves. The walk ([`walk`]) says *what* structurally
12//! differs, emitting one [`Change`] per difference with a [`Category`]; the
13//! classifier ([`classify`]) says which *direction* that difference moved
14//! in and settles its [`Verdict`]. Splitting them is what lets a single
15//! structural category — an appended interaction, a changed timing — carry
16//! opposite verdicts depending on the direction, without the walk needing both
17//! snapshots at every emission site.
18//!
19//! This module owns the vocabulary ([`Verdict`], [`Category`], [`Change`],
20//! [`DiffReport`]), the set-level comparison ([`diff_sets`], and
21//! [`diff_workspaces`] with the system headings of [`system`]), snapshot
22//! loading ([`load_ir_json`]), and rendering ([`render_text`],
23//! [`render_json`]). The
24//! classification table itself is documented per category by [`explain`], which
25//! `ridl diff --explain` prints.
26
27use std::path::Path;
28
29use ridl_ir::v2::{Package, System};
30
31mod classify;
32pub mod system;
33mod walk;
34
35pub use classify::{absence_refused, category_from_word, classify, explain};
36pub use system::{SystemChange, SystemHeading, diff_systems};
37
38#[cfg(test)]
39mod tests;
40
41/// The compatibility verdict of a change or of a whole report — ordered so
42/// `Breaking > Compatible > Identical` and a report's verdict is the maximum
43/// over its changes.
44#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
45pub enum Verdict {
46    /// No differences at all.
47    Identical,
48    /// A consumer built against the old snapshot still works.
49    Compatible,
50    /// A consumer built against the old snapshot may break.
51    Breaking,
52}
53
54/// Declares the [`Category`] vocabulary once (ADR-0008 decision 21).
55///
56/// One list of variants expands to both the enum and the [`CATEGORIES`] array
57/// that `ridl diff --explain` iterates, so a variant that never reaches
58/// `CATEGORIES` cannot be written: there is no second list to forget. This
59/// replaces the guard PR #163 shipped, which expanded one list into an
60/// exhaustive `match` and an array *inside the test* — that narrowed the gap but
61/// left `CATEGORIES` shadowed rather than produced, and an assertion comparing
62/// two lists can be defeated by editing what feeds it.
63///
64/// A new variant therefore stops three functions compiling — [`classify`],
65/// [`explain`], and [`category_word`] — and reaches `CATEGORIES` with no second
66/// edit. The escape rustc's own `help:` text proposes for those three errors is
67/// a wildcard arm. Each of the three functions denies
68/// `clippy::wildcard_enum_match_arm` and
69/// `clippy::match_wildcard_for_single_variants` for exactly that reason. The
70/// second lint is the load-bearing one: the first does not fire when the
71/// wildcard covers a single variant, which is precisely the added-variant case,
72/// so denying it alone leaves clippy green.
73///
74/// How far the wildcard gets before clippy stops it depends on what its body
75/// says. `_ => todo!()` panics the `--explain` coverage test, and a bare
76/// `_ => "unknown"` fails it — the row names no verdict. A wildcard whose text
77/// happens to contain "compatible" passes all 115 tests. So the escape is real
78/// but narrow, and `cargo test` alone catches the two careless spellings of it.
79/// `just build` runs clippy so that the third is caught too.
80///
81/// What this does **not** close: rustc forces *an* arm, not the right one. A
82/// new variant given an explicit arm that classifies compatible, or whose rule
83/// row describes the wrong rule, still compiles and still passes. The [`explain`]
84/// coverage test checks that each row names a verdict and that its word
85/// round-trips; neither is proof that the row is correct.
86macro_rules! declare_categories {
87    (
88        $(#[$enum_meta:meta])*
89        $vis:vis enum $name:ident {
90            $(
91                $(#[$variant_meta:meta])*
92                $variant:ident,
93            )+
94        }
95    ) => {
96        $(#[$enum_meta])*
97        $vis enum $name {
98            $(
99                $(#[$variant_meta])*
100                $variant,
101            )+
102        }
103
104        /// Every category, in the order `--explain` lists them when asked for an
105        /// unknown one.
106        ///
107        /// Generated from the [`Category`] declaration by
108        /// [`declare_categories!`], not maintained beside it.
109        //
110        // The length counts the variants rather than being written down:
111        // `${count(...)}` is still unstable (rust-lang/rust#83527), so the
112        // count comes from the same repetition that fills the array.
113        pub const CATEGORIES: [$name; [$(stringify!($variant)),+].len()] =
114            [$($name::$variant),+];
115    };
116}
117
118declare_categories! {
119    /// The kind of a single difference. The walk emits the structural categories;
120    /// the classifier maps them to directional verdicts.
121    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
122    pub enum Category {
123        /// A package-level declaration, interface, or service present only in the
124        /// new snapshot.
125        DeclAdded,
126        /// A package-level declaration, interface, or service present only in the
127        /// old snapshot. An interface is matched by its `interfaces.lock`
128        /// number (lock design §7), so an interface here is one whose number
129        /// is gone from the new snapshot and not retired there.
130        DeclRemoved,
131        /// An interface whose `interfaces.lock` number is the same on both
132        /// sides and whose name changed (lock design §7). The number is the
133        /// interface's identity and its routing key, so nothing moves on the
134        /// wire; a rename is visible in source — it changes the generated
135        /// identity-table names in both wire backends — so the text report
136        /// lists it under the heading ([`heading`]). The path carries the new
137        /// name; the detail carries the old and the new name.
138        InterfaceRenamed,
139        /// An interface whose number the old snapshot held and the new
140        /// snapshot's retired entries list (lock design §7): the sanctioned
141        /// removal of an interface, recorded by `ridl lock --retire`.
142        InterfaceRetired,
143        /// A surviving composite member whose slot in the body changed — a
144        /// struct field, enum value, enum-set bit or union arm — reported only
145        /// when both bodies hold the same member names. For a struct field or
146        /// union arm the slot is the ordinal, which is wire identity (typl
147        /// §7.4), and the detail carries the old and new ordinal. An enum value
148        /// or enum-set bit carries an explicit number instead (typl §8, §9),
149        /// but the walk compares positions, not those numbers, so a textual
150        /// reorder of an enum or enum-set body is reported the same way,
151        /// conservatively, even when no number changed; its detail carries the
152        /// old and new position.
153        MemberReordered,
154        /// A new interaction added at the end of an interface (no earlier
155        /// interaction shifted).
156        InteractionAppended,
157        /// A new interaction added before the end — an earlier interaction now
158        /// sits after it (ridl §11: insert shifts ordinals, a wire break).
159        InteractionInserted,
160        /// A surviving interaction whose relative order within the interface
161        /// changed (ridl §11: reorder shifts ordinals, a wire break).
162        InteractionReordered,
163        /// An interaction removed without leaving a `reserved` tombstone.
164        InteractionRemoved,
165        /// An interaction removed and replaced by a `reserved` tombstone in the
166        /// same slot (ridl §11).
167        InteractionRetired,
168        /// A surviving interaction whose kind changed (signal ↔ event, etc.).
169        KindChanged,
170        /// A signal/event/fixed payload type changed.
171        PayloadChanged,
172        /// A query return type changed.
173        ReturnChanged,
174        /// A command/query parameter list changed.
175        ParamsChanged,
176        /// A signal/event resolved timing changed.
177        TimingChanged,
178        /// A command/query declared RPC bound changed (ADR-0015 decision 8).
179        /// Separate from [`Category::TimingChanged`] because the direction of
180        /// `min` inverts: on an RPC it constrains the caller, not the
181        /// provider, so the signal/event rule must not be inherited silently.
182        RpcBoundChanged,
183        /// A command/query require/ensure clause set changed.
184        ContractChanged,
185        /// A derived wire width or scalar backing changed.
186        WidthChanged,
187        /// A scalar constraint (range, step, length, pattern) changed, or a
188        /// composite member changed in place.
189        ConstraintChanged,
190        /// A resolved or declared init value changed.
191        InitChanged,
192        /// A name that was a `reserved` tombstone is live again — an
193        /// interaction inside an interface body.
194        ReservedNameRedeclared,
195        /// A service switched between the named list and an inline shape.
196        /// Narrowed to the form switch by ADR-0015 decision 19: a changed
197        /// list is read as a set by the two `ServiceInterface*` categories
198        /// below.
199        ServiceChanged,
200        /// An interface in a service's set that the old snapshot's set did not
201        /// hold (ADR-0015 decision 19 as amended on 2026-09-15: a service's
202        /// list is a set of interface references).
203        ServiceInterfaceAdded,
204        /// An interface the old snapshot's set held that the new one does not.
205        /// Compatible on the wire — the routing key does not contain the
206        /// service — and visible in source, so the text report lists it under
207        /// that heading ([`heading`]).
208        ServiceInterfaceRemoved,
209        /// Only doc comment, labels, or deprecation metadata changed.
210        DocOnly,
211        /// The visibility a declaration is published at changed. Separate from
212        /// [`Category::DocOnly`] because `internal` removes the declaration from
213        /// every out-of-package consumer (ADR-0002 §8), so the change has a
214        /// direction.
215        VisibilityChanged,
216    }
217}
218
219/// One difference between two snapshots, with an honest path into the IR and
220/// the rendered before/after values where they apply.
221#[derive(Clone, Debug, PartialEq, Eq)]
222pub struct Change {
223    /// A slash-separated path, e.g. `veh.cluster/VehicleStatus/doorOpened`.
224    pub path: String,
225    pub category: Category,
226    pub verdict: Verdict,
227    /// The rendered old value, absent when the change is an addition.
228    pub before: Option<String>,
229    /// The rendered new value, absent when the change is a removal.
230    pub after: Option<String>,
231}
232
233/// The result of a comparison: every change and the report-level verdict (the
234/// maximum verdict over the changes; [`Verdict::Identical`] when there are
235/// none).
236#[derive(Clone, Debug, PartialEq, Eq)]
237pub struct DiffReport {
238    pub changes: Vec<Change>,
239    pub verdict: Verdict,
240    /// The changes to the lowered system, each under its heading and with no
241    /// verdict (rsdl reference §14). They never enter `verdict`. Empty unless
242    /// both sides carry a system ([`diff_workspaces`]).
243    pub system: Vec<SystemChange>,
244}
245
246/// An error loading an `.ir.json` snapshot.
247#[derive(Debug)]
248pub enum LoadError {
249    /// The file could not be read.
250    Io(std::io::Error),
251    /// The file was not valid IR v2 JSON.
252    Parse(String),
253}
254
255impl std::fmt::Display for LoadError {
256    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257        match self {
258            LoadError::Io(err) => write!(f, "cannot read the IR snapshot: {err}"),
259            LoadError::Parse(err) => write!(f, "the IR snapshot is not valid IR v2 JSON: {err}"),
260        }
261    }
262}
263
264impl std::error::Error for LoadError {}
265
266/// Appends one change.
267///
268/// The verdict is stamped breaking here and settled by [`classify`] once the
269/// walk of the containing package pair is complete — the classifier needs both
270/// snapshots, which the walk does not carry down to every emission site.
271/// Breaking is the safe placeholder: a change that somehow escaped
272/// classification would gate rather than pass.
273pub(crate) fn emit(
274    changes: &mut Vec<Change>,
275    path: String,
276    category: Category,
277    before: Option<String>,
278    after: Option<String>,
279) {
280    changes.push(Change {
281        path,
282        category,
283        verdict: Verdict::Breaking,
284        before,
285        after,
286    });
287}
288
289/// Whether an interface carries an identity: a frozen, non-zero number from
290/// its package's `interfaces.lock` (lock design §7). A provisional number is
291/// no identity, and `number` 0 — never allocated — marks a snapshot published
292/// before the lock existed. The walk matches by number only when both sides
293/// have one, and the classifier re-finds the old side the same way.
294pub(crate) fn frozen(interface: &ridl_ir::v2::Interface) -> bool {
295    interface.number != 0 && !interface.provisional
296}
297
298/// Settles the verdict of every change the walk of one package pair produced.
299/// `scope` is every package a reference to another package's declaration
300/// resolves against ([`classify::classify_in`]).
301fn classify_all(changes: &mut [Change], old: &Package, new: &Package, scope: &[&Package]) {
302    for change in changes {
303        change.verdict = classify::classify_in(change, old, new, scope);
304    }
305}
306
307/// Assembles a [`DiffReport`], deriving the report verdict as the maximum over
308/// its changes.
309pub(crate) fn report(changes: Vec<Change>) -> DiffReport {
310    let verdict = changes
311        .iter()
312        .map(|change| change.verdict)
313        .max()
314        .unwrap_or(Verdict::Identical);
315    DiffReport {
316        changes,
317        verdict,
318        system: Vec::new(),
319    }
320}
321
322/// Compares two resolved packages. Matched packages share a name; the new
323/// package's name is used as the path prefix.
324///
325/// Only the pair is in hand, so a type from another package does not resolve,
326/// and a type the diff cannot resolve is reported as breaking: a struct field
327/// appended with such a type classifies breaking (driftsys/ridl#598).
328/// [`diff_sets_in`] resolves it.
329pub fn diff_packages(old: &Package, new: &Package) -> DiffReport {
330    let mut changes = Vec::new();
331    walk::walk_packages(old, new, &mut changes);
332    classify_all(&mut changes, old, new, &[]);
333    report(changes)
334}
335
336/// Compares two sets of resolved packages, matching by package name. A package
337/// present only on one side is a [`Category::DeclRemoved`] or
338/// [`Category::DeclAdded`]; matched packages are walked pairwise.
339///
340/// [`diff_sets_in`] with no context: a type from a package outside `new`, such
341/// as `ridl.std`, which no snapshot carries, does not resolve, and a type the
342/// diff cannot resolve is reported as breaking.
343pub fn diff_sets(old: &[Package], new: &[Package]) -> DiffReport {
344    diff_sets_in(old, new, &[])
345}
346
347/// [`diff_sets`], with `context`: packages that a type reference resolves
348/// against without being compared. The `ridl` CLI passes the built-in
349/// `ridl.std` here, so a struct field appended with a `ridl.std` type is judged
350/// by that type's declaration (driftsys/ridl#598).
351pub fn diff_sets_in(old: &[Package], new: &[Package], context: &[Package]) -> DiffReport {
352    use std::collections::BTreeMap;
353
354    let scope: Vec<&Package> = new.iter().chain(context).collect();
355
356    let old_by: BTreeMap<&str, &Package> = old.iter().map(|pkg| (pkg.name.as_str(), pkg)).collect();
357    let new_by: BTreeMap<&str, &Package> = new.iter().map(|pkg| (pkg.name.as_str(), pkg)).collect();
358
359    // Each matched pair is walked and classified against its own two snapshots,
360    // because the classifier resolves a change's path back into the packages it
361    // came from.
362    let mut changes = Vec::new();
363    for (name, old_pkg) in &old_by {
364        match new_by.get(name) {
365            Some(new_pkg) => {
366                let mut pair = Vec::new();
367                walk::walk_packages(old_pkg, new_pkg, &mut pair);
368                classify_all(&mut pair, old_pkg, new_pkg, &scope);
369                changes.append(&mut pair);
370            }
371            // A package present on one side only: the change classifies on its
372            // category alone, so the one snapshot stands for both.
373            None => {
374                let mut pair = Vec::new();
375                emit(
376                    &mut pair,
377                    (*name).to_string(),
378                    Category::DeclRemoved,
379                    Some(format!("package {name}")),
380                    None,
381                );
382                classify_all(&mut pair, old_pkg, old_pkg, &[]);
383                changes.append(&mut pair);
384            }
385        }
386    }
387    for (name, new_pkg) in &new_by {
388        if !old_by.contains_key(name) {
389            let mut pair = Vec::new();
390            emit(
391                &mut pair,
392                (*name).to_string(),
393                Category::DeclAdded,
394                None,
395                Some(format!("package {name}")),
396            );
397            classify_all(&mut pair, new_pkg, new_pkg, &[]);
398            changes.append(&mut pair);
399        }
400    }
401    report(changes)
402}
403
404/// Compares two workspaces at the system (rsdl reference §14): the packages by
405/// the ridl categories, exactly as [`diff_sets`] does, and — when both sides
406/// carry a lowered system — the system's placement and composition changes,
407/// which carry no verdict. A system on one side only is not compared: there is
408/// nothing to compare it against.
409///
410/// `context` is passed to [`diff_sets_in`].
411pub fn diff_workspaces(
412    old: &[Package],
413    old_system: Option<&System>,
414    new: &[Package],
415    new_system: Option<&System>,
416    context: &[Package],
417) -> DiffReport {
418    let mut report = diff_sets_in(old, new, context);
419    if let (Some(old_system), Some(new_system)) = (old_system, new_system) {
420        report.system = diff_systems(old_system, new_system);
421    }
422    report
423}
424
425/// Loads an `.ir.json` snapshot written by `ridl build --emit ir-json` —
426/// canonical protobuf JSON, read through the one reader every surface shares
427/// (ADR-0014 decision 1).
428pub fn load_ir_json(path: &Path) -> Result<Package, LoadError> {
429    let text = std::fs::read_to_string(path).map_err(LoadError::Io)?;
430    ridl_ir::v2::from_json(&text).map_err(|err| LoadError::Parse(err.to_string()))
431}
432
433/// The stable lowercase word for a verdict — used by both the text and JSON
434/// renderers so the two stay in lockstep.
435pub(crate) fn verdict_word(verdict: Verdict) -> &'static str {
436    match verdict {
437        Verdict::Identical => "identical",
438        Verdict::Compatible => "compatible",
439        Verdict::Breaking => "breaking",
440    }
441}
442
443/// The stable snake_case word for a category — the single source of truth for
444/// both renderers and for `ridl diff --explain`, which takes a category exactly
445/// as the report prints it.
446// A new variant must be given a real arm here, not swept into a
447// catch-all: rustc forces *an* arm, and the arm its `help:` text
448// proposes is `_ =>`, which classifies the new variant silently. The
449// two lints below reject a wildcard over `Category` — the first when
450// it covers several variants, the second when it covers exactly one,
451// which is the case one added variant creates.
452#[deny(
453    clippy::wildcard_enum_match_arm,
454    clippy::match_wildcard_for_single_variants
455)]
456pub fn category_word(category: Category) -> &'static str {
457    match category {
458        Category::DeclAdded => "decl_added",
459        Category::DeclRemoved => "decl_removed",
460        Category::InterfaceRenamed => "interface_renamed",
461        Category::InterfaceRetired => "interface_retired",
462        Category::MemberReordered => "member_reordered",
463        Category::InteractionAppended => "interaction_appended",
464        Category::InteractionInserted => "interaction_inserted",
465        Category::InteractionReordered => "interaction_reordered",
466        Category::InteractionRemoved => "interaction_removed",
467        Category::InteractionRetired => "interaction_retired",
468        Category::KindChanged => "kind_changed",
469        Category::PayloadChanged => "payload_changed",
470        Category::ReturnChanged => "return_changed",
471        Category::ParamsChanged => "params_changed",
472        Category::TimingChanged => "timing_changed",
473        Category::RpcBoundChanged => "rpc_bound_changed",
474        Category::ContractChanged => "contract_changed",
475        Category::WidthChanged => "width_changed",
476        Category::ConstraintChanged => "constraint_changed",
477        Category::InitChanged => "init_changed",
478        Category::ReservedNameRedeclared => "reserved_name_redeclared",
479        Category::ServiceChanged => "service_changed",
480        Category::ServiceInterfaceAdded => "service_interface_added",
481        Category::ServiceInterfaceRemoved => "service_interface_removed",
482        Category::DocOnly => "doc_only",
483        Category::VisibilityChanged => "visibility_changed",
484    }
485}
486
487/// The heading a category's changes are grouped under in the text report, or
488/// `None` for a category listed plainly. One heading exists: "compatible on
489/// the wire, visible in source", for a change that exits 0 but that a
490/// consumer sees in its source — an interface renamed on its number changes
491/// the generated identity-table names in both wire backends, and an interface
492/// leaving a service's set stops the `service.member` addresses of that
493/// interface resolving under the service. Each such category's `--explain`
494/// text states its own consequence; the JSON report carries the category word
495/// and no heading field.
496///
497/// Wildcard arms are denied for the reason `category_word` gives.
498#[deny(
499    clippy::wildcard_enum_match_arm,
500    clippy::match_wildcard_for_single_variants
501)]
502pub fn heading(category: Category) -> Option<&'static str> {
503    match category {
504        Category::InterfaceRenamed | Category::ServiceInterfaceRemoved => {
505            Some("compatible on the wire, visible in source")
506        }
507        Category::DeclAdded
508        | Category::DeclRemoved
509        | Category::InterfaceRetired
510        | Category::MemberReordered
511        | Category::InteractionAppended
512        | Category::InteractionInserted
513        | Category::InteractionReordered
514        | Category::InteractionRemoved
515        | Category::InteractionRetired
516        | Category::KindChanged
517        | Category::PayloadChanged
518        | Category::ReturnChanged
519        | Category::ParamsChanged
520        | Category::TimingChanged
521        | Category::RpcBoundChanged
522        | Category::ContractChanged
523        | Category::WidthChanged
524        | Category::ConstraintChanged
525        | Category::InitChanged
526        | Category::ReservedNameRedeclared
527        | Category::ServiceChanged
528        | Category::ServiceInterfaceAdded
529        | Category::DocOnly
530        | Category::VisibilityChanged => None,
531    }
532}
533
534impl serde::Serialize for Verdict {
535    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
536        serializer.serialize_str(verdict_word(*self))
537    }
538}
539
540impl serde::Serialize for Category {
541    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
542        serializer.serialize_str(category_word(*self))
543    }
544}
545
546impl serde::Serialize for Change {
547    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
548        use serde::ser::SerializeStruct as _;
549        let mut state = serializer.serialize_struct("Change", 5)?;
550        state.serialize_field("path", &self.path)?;
551        state.serialize_field("category", &self.category)?;
552        state.serialize_field("verdict", &self.verdict)?;
553        state.serialize_field("before", &self.before)?;
554        state.serialize_field("after", &self.after)?;
555        state.end()
556    }
557}
558
559/// Renders a report as a human-readable summary: the report verdict on the
560/// first line, then one indented line per change. A change whose category has
561/// no [`heading`] is listed first, in report order; then each heading is
562/// printed once, as its own line ending in a colon, followed by the changes
563/// under it, in report order. Headings come in [`CATEGORIES`] order.
564///
565/// After the contract changes come the system headings (rsdl reference §14):
566/// each heading that has a change on its own line, then one indented line per
567/// change under it, in the `path: before -> after` form and with no verdict.
568pub fn render_text(report: &DiffReport) -> String {
569    let mut out = String::new();
570    out.push_str(verdict_word(report.verdict));
571    out.push('\n');
572    for change in &report.changes {
573        if heading(change.category).is_none() {
574            push_change_line(&mut out, change);
575        }
576    }
577    let mut printed: Vec<&'static str> = Vec::new();
578    for category in CATEGORIES {
579        let Some(title) = heading(category) else {
580            continue;
581        };
582        if printed.contains(&title) {
583            continue;
584        }
585        printed.push(title);
586        let mut under = report
587            .changes
588            .iter()
589            .filter(|change| heading(change.category) == Some(title))
590            .peekable();
591        if under.peek().is_none() {
592            continue;
593        }
594        out.push_str(title);
595        out.push_str(":\n");
596        for change in under {
597            push_change_line(&mut out, change);
598        }
599    }
600    for heading in [
601        SystemHeading::PlacementChanged,
602        SystemHeading::CompositionChanged,
603    ] {
604        let mut listed = report
605            .system
606            .iter()
607            .filter(|change| change.heading == heading)
608            .peekable();
609        if listed.peek().is_none() {
610            continue;
611        }
612        out.push_str(system::heading_text(heading));
613        out.push('\n');
614        for change in listed {
615            out.push_str("  ");
616            out.push_str(&change.path);
617            push_values(&mut out, change.before.as_ref(), change.after.as_ref());
618            out.push('\n');
619        }
620    }
621    out
622}
623
624/// One change of the text report: `  [verdict] category path`, then
625/// `: before -> after` where the sides apply.
626fn push_change_line(out: &mut String, change: &Change) {
627    out.push_str("  [");
628    out.push_str(verdict_word(change.verdict));
629    out.push_str("] ");
630    out.push_str(category_word(change.category));
631    out.push(' ');
632    out.push_str(&change.path);
633    push_values(out, change.before.as_ref(), change.after.as_ref());
634    out.push('\n');
635}
636
637/// The rendered `before -> after` tail of one change line, shared by contract
638/// changes and system changes.
639fn push_values(out: &mut String, before: Option<&String>, after: Option<&String>) {
640    match (before, after) {
641        (Some(before), Some(after)) => {
642            out.push_str(": ");
643            out.push_str(before);
644            out.push_str(" -> ");
645            out.push_str(after);
646        }
647        (Some(before), None) => {
648            out.push_str(": ");
649            out.push_str(before);
650            out.push_str(" -> (removed)");
651        }
652        (None, Some(after)) => {
653            out.push_str(": (absent) -> ");
654            out.push_str(after);
655        }
656        (None, None) => {}
657    }
658}
659
660/// Renders a report as machine-readable JSON with the stable schema
661/// `{"verdict", "changes": [{"path", "category", "verdict", "before",
662/// "after"}]}`.
663pub fn render_json(report: &DiffReport) -> String {
664    #[derive(serde::Serialize)]
665    struct JsonSystemChange<'a> {
666        path: &'a str,
667        before: Option<&'a str>,
668        after: Option<&'a str>,
669    }
670
671    #[derive(serde::Serialize)]
672    struct JsonReport<'a> {
673        verdict: Verdict,
674        changes: &'a [Change],
675        #[serde(skip_serializing_if = "Vec::is_empty")]
676        placement_changed: Vec<JsonSystemChange<'a>>,
677        #[serde(skip_serializing_if = "Vec::is_empty")]
678        composition_changed: Vec<JsonSystemChange<'a>>,
679    }
680
681    let under = |heading: SystemHeading| -> Vec<JsonSystemChange<'_>> {
682        report
683            .system
684            .iter()
685            .filter(|change| change.heading == heading)
686            .map(|change| JsonSystemChange {
687                path: &change.path,
688                before: change.before.as_deref(),
689                after: change.after.as_deref(),
690            })
691            .collect()
692    };
693    serde_json::to_string_pretty(&JsonReport {
694        verdict: report.verdict,
695        changes: &report.changes,
696        placement_changed: under(SystemHeading::PlacementChanged),
697        composition_changed: under(SystemHeading::CompositionChanged),
698    })
699    .expect("a diff report holds only string-representable values, so serialization cannot fail")
700}