ridl-diff 0.6.0

The `ridl diff` engine: compares two resolved IR snapshots and classifies every difference.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! The `ridl diff` IR-snapshot compare engine.
//!
//! The engine compares two resolved IR v2 snapshots and classifies every
//! difference as a [`Change`] with a [`Category`] and a [`Verdict`]. It reads
//! only the IR — never source — so the comparison is honest against exactly
//! what a backend sees (ADR-0008 decision 14, concept note §9.1). Placement is
//! deliberate: this crate is an engine surfaced by the `ridl` facade, never by
//! `ridlc`, so the compiler stays a pure source→IR function (the ISO 26262
//! tool-qualification boundary, ADR-0008 decision 9).
//!
//! The comparison has two halves. The walk ([`walk`]) says *what* structurally
//! differs, emitting one [`Change`] per difference with a [`Category`]; the
//! classifier ([`classify`]) says which *direction* that difference moved
//! in and settles its [`Verdict`]. Splitting them is what lets a single
//! structural category — an appended interaction, a changed timing — carry
//! opposite verdicts depending on the direction, without the walk needing both
//! snapshots at every emission site.
//!
//! This module owns the vocabulary ([`Verdict`], [`Category`], [`Change`],
//! [`DiffReport`]), the set-level comparison ([`diff_sets`], and
//! [`diff_workspaces`] with the system headings of [`system`]), snapshot
//! loading ([`load_ir_json`]), and rendering ([`render_text`],
//! [`render_json`]). The
//! classification table itself is documented per category by [`explain`], which
//! `ridl diff --explain` prints.

use std::path::Path;

use ridl_ir::v2::{Package, System};

mod classify;
pub mod system;
mod walk;

pub use classify::{absence_refused, category_from_word, classify, explain};
pub use system::{SystemChange, SystemHeading, diff_systems};

#[cfg(test)]
mod tests;

/// The compatibility verdict of a change or of a whole report — ordered so
/// `Breaking > Compatible > Identical` and a report's verdict is the maximum
/// over its changes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Verdict {
    /// No differences at all.
    Identical,
    /// A consumer built against the old snapshot still works.
    Compatible,
    /// A consumer built against the old snapshot may break.
    Breaking,
}

/// Declares the [`Category`] vocabulary once (ADR-0008 decision 21).
///
/// One list of variants expands to both the enum and the [`CATEGORIES`] array
/// that `ridl diff --explain` iterates, so a variant that never reaches
/// `CATEGORIES` cannot be written: there is no second list to forget. This
/// replaces the guard PR #163 shipped, which expanded one list into an
/// exhaustive `match` and an array *inside the test* — that narrowed the gap but
/// left `CATEGORIES` shadowed rather than produced, and an assertion comparing
/// two lists can be defeated by editing what feeds it.
///
/// A new variant therefore stops three functions compiling — [`classify`],
/// [`explain`], and [`category_word`] — and reaches `CATEGORIES` with no second
/// edit. The escape rustc's own `help:` text proposes for those three errors is
/// a wildcard arm. Each of the three functions denies
/// `clippy::wildcard_enum_match_arm` and
/// `clippy::match_wildcard_for_single_variants` for exactly that reason. The
/// second lint is the load-bearing one: the first does not fire when the
/// wildcard covers a single variant, which is precisely the added-variant case,
/// so denying it alone leaves clippy green.
///
/// How far the wildcard gets before clippy stops it depends on what its body
/// says. `_ => todo!()` panics the `--explain` coverage test, and a bare
/// `_ => "unknown"` fails it — the row names no verdict. A wildcard whose text
/// happens to contain "compatible" passes all 115 tests. So the escape is real
/// but narrow, and `cargo test` alone catches the two careless spellings of it.
/// `just build` runs clippy so that the third is caught too.
///
/// What this does **not** close: rustc forces *an* arm, not the right one. A
/// new variant given an explicit arm that classifies compatible, or whose rule
/// row describes the wrong rule, still compiles and still passes. The [`explain`]
/// coverage test checks that each row names a verdict and that its word
/// round-trips; neither is proof that the row is correct.
macro_rules! declare_categories {
    (
        $(#[$enum_meta:meta])*
        $vis:vis enum $name:ident {
            $(
                $(#[$variant_meta:meta])*
                $variant:ident,
            )+
        }
    ) => {
        $(#[$enum_meta])*
        $vis enum $name {
            $(
                $(#[$variant_meta])*
                $variant,
            )+
        }

        /// Every category, in the order `--explain` lists them when asked for an
        /// unknown one.
        ///
        /// Generated from the [`Category`] declaration by
        /// [`declare_categories!`], not maintained beside it.
        //
        // The length counts the variants rather than being written down:
        // `${count(...)}` is still unstable (rust-lang/rust#83527), so the
        // count comes from the same repetition that fills the array.
        pub const CATEGORIES: [$name; [$(stringify!($variant)),+].len()] =
            [$($name::$variant),+];
    };
}

declare_categories! {
    /// The kind of a single difference. The walk emits the structural categories;
    /// the classifier maps them to directional verdicts.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum Category {
        /// A package-level declaration, interface, or service present only in the
        /// new snapshot.
        DeclAdded,
        /// A package-level declaration, interface, or service present only in the
        /// old snapshot. An interface is matched by its `interfaces.lock`
        /// number (lock design §7), so an interface here is one whose number
        /// is gone from the new snapshot and not retired there.
        DeclRemoved,
        /// An interface whose `interfaces.lock` number is the same on both
        /// sides and whose name changed (lock design §7). The number is the
        /// interface's identity and its routing key, so nothing moves on the
        /// wire; a rename is visible in source — it changes the generated
        /// identity-table names in both wire backends — so the text report
        /// lists it under the heading ([`heading`]). The path carries the new
        /// name; the detail carries the old and the new name.
        InterfaceRenamed,
        /// An interface whose number the old snapshot held and the new
        /// snapshot's retired entries list (lock design §7): the sanctioned
        /// removal of an interface, recorded by `ridl lock --retire`.
        InterfaceRetired,
        /// A surviving composite member whose slot in the body changed — a
        /// struct field, enum value, enum-set bit or union arm — reported only
        /// when both bodies hold the same member names. For a struct field or
        /// union arm the slot is the ordinal, which is wire identity (typl
        /// §7.4), and the detail carries the old and new ordinal. An enum value
        /// or enum-set bit carries an explicit number instead (typl §8, §9),
        /// but the walk compares positions, not those numbers, so a textual
        /// reorder of an enum or enum-set body is reported the same way,
        /// conservatively, even when no number changed; its detail carries the
        /// old and new position.
        MemberReordered,
        /// A new interaction added at the end of an interface (no earlier
        /// interaction shifted).
        InteractionAppended,
        /// A new interaction added before the end — an earlier interaction now
        /// sits after it (ridl §11: insert shifts ordinals, a wire break).
        InteractionInserted,
        /// A surviving interaction whose relative order within the interface
        /// changed (ridl §11: reorder shifts ordinals, a wire break).
        InteractionReordered,
        /// An interaction removed without leaving a `reserved` tombstone.
        InteractionRemoved,
        /// An interaction removed and replaced by a `reserved` tombstone in the
        /// same slot (ridl §11).
        InteractionRetired,
        /// A surviving interaction whose kind changed (signal ↔ event, etc.).
        KindChanged,
        /// A signal/event/fixed payload type changed.
        PayloadChanged,
        /// A query return type changed.
        ReturnChanged,
        /// A command/query parameter list changed.
        ParamsChanged,
        /// A signal/event resolved timing changed.
        TimingChanged,
        /// A command/query declared RPC bound changed (ADR-0015 decision 8).
        /// Separate from [`Category::TimingChanged`] because the direction of
        /// `min` inverts: on an RPC it constrains the caller, not the
        /// provider, so the signal/event rule must not be inherited silently.
        RpcBoundChanged,
        /// A command/query require/ensure clause set changed.
        ContractChanged,
        /// A derived wire width or scalar backing changed.
        WidthChanged,
        /// A scalar constraint (range, step, length, pattern) changed, or a
        /// composite member changed in place.
        ConstraintChanged,
        /// A resolved or declared init value changed.
        InitChanged,
        /// A name that was a `reserved` tombstone is live again — an
        /// interaction inside an interface body.
        ReservedNameRedeclared,
        /// A service switched between the named list and an inline shape.
        /// Narrowed to the form switch by ADR-0015 decision 19: a changed
        /// list is read as a set by the two `ServiceInterface*` categories
        /// below.
        ServiceChanged,
        /// An interface in a service's set that the old snapshot's set did not
        /// hold (ADR-0015 decision 19 as amended on 2026-09-15: a service's
        /// list is a set of interface references).
        ServiceInterfaceAdded,
        /// An interface the old snapshot's set held that the new one does not.
        /// Compatible on the wire — the routing key does not contain the
        /// service — and visible in source, so the text report lists it under
        /// that heading ([`heading`]).
        ServiceInterfaceRemoved,
        /// Only doc comment, labels, or deprecation metadata changed.
        DocOnly,
        /// The visibility a declaration is published at changed. Separate from
        /// [`Category::DocOnly`] because `internal` removes the declaration from
        /// every out-of-package consumer (ADR-0002 §8), so the change has a
        /// direction.
        VisibilityChanged,
    }
}

/// One difference between two snapshots, with an honest path into the IR and
/// the rendered before/after values where they apply.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Change {
    /// A slash-separated path, e.g. `veh.cluster/VehicleStatus/doorOpened`.
    pub path: String,
    pub category: Category,
    pub verdict: Verdict,
    /// The rendered old value, absent when the change is an addition.
    pub before: Option<String>,
    /// The rendered new value, absent when the change is a removal.
    pub after: Option<String>,
}

/// The result of a comparison: every change and the report-level verdict (the
/// maximum verdict over the changes; [`Verdict::Identical`] when there are
/// none).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiffReport {
    pub changes: Vec<Change>,
    pub verdict: Verdict,
    /// The changes to the lowered system, each under its heading and with no
    /// verdict (rsdl reference §14). They never enter `verdict`. Empty unless
    /// both sides carry a system ([`diff_workspaces`]).
    pub system: Vec<SystemChange>,
}

/// An error loading an `.ir.json` snapshot.
#[derive(Debug)]
pub enum LoadError {
    /// The file could not be read.
    Io(std::io::Error),
    /// The file was not valid IR v2 JSON.
    Parse(String),
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LoadError::Io(err) => write!(f, "cannot read the IR snapshot: {err}"),
            LoadError::Parse(err) => write!(f, "the IR snapshot is not valid IR v2 JSON: {err}"),
        }
    }
}

impl std::error::Error for LoadError {}

/// Appends one change.
///
/// The verdict is stamped breaking here and settled by [`classify`] once the
/// walk of the containing package pair is complete — the classifier needs both
/// snapshots, which the walk does not carry down to every emission site.
/// Breaking is the safe placeholder: a change that somehow escaped
/// classification would gate rather than pass.
pub(crate) fn emit(
    changes: &mut Vec<Change>,
    path: String,
    category: Category,
    before: Option<String>,
    after: Option<String>,
) {
    changes.push(Change {
        path,
        category,
        verdict: Verdict::Breaking,
        before,
        after,
    });
}

/// Whether an interface carries an identity: a frozen, non-zero number from
/// its package's `interfaces.lock` (lock design §7). A provisional number is
/// no identity, and `number` 0 — never allocated — marks a snapshot published
/// before the lock existed. The walk matches by number only when both sides
/// have one, and the classifier re-finds the old side the same way.
pub(crate) fn frozen(interface: &ridl_ir::v2::Interface) -> bool {
    interface.number != 0 && !interface.provisional
}

/// Settles the verdict of every change the walk of one package pair produced.
/// `scope` is every package a reference to another package's declaration
/// resolves against ([`classify::classify_in`]).
fn classify_all(changes: &mut [Change], old: &Package, new: &Package, scope: &[&Package]) {
    for change in changes {
        change.verdict = classify::classify_in(change, old, new, scope);
    }
}

/// Assembles a [`DiffReport`], deriving the report verdict as the maximum over
/// its changes.
pub(crate) fn report(changes: Vec<Change>) -> DiffReport {
    let verdict = changes
        .iter()
        .map(|change| change.verdict)
        .max()
        .unwrap_or(Verdict::Identical);
    DiffReport {
        changes,
        verdict,
        system: Vec::new(),
    }
}

/// Compares two resolved packages. Matched packages share a name; the new
/// package's name is used as the path prefix.
///
/// Only the pair is in hand, so a type from another package does not resolve,
/// and a type the diff cannot resolve is reported as breaking: a struct field
/// appended with such a type classifies breaking (driftsys/ridl#598).
/// [`diff_sets_in`] resolves it.
pub fn diff_packages(old: &Package, new: &Package) -> DiffReport {
    let mut changes = Vec::new();
    walk::walk_packages(old, new, &mut changes);
    classify_all(&mut changes, old, new, &[]);
    report(changes)
}

/// Compares two sets of resolved packages, matching by package name. A package
/// present only on one side is a [`Category::DeclRemoved`] or
/// [`Category::DeclAdded`]; matched packages are walked pairwise.
///
/// [`diff_sets_in`] with no context: a type from a package outside `new`, such
/// as `ridl.std`, which no snapshot carries, does not resolve, and a type the
/// diff cannot resolve is reported as breaking.
pub fn diff_sets(old: &[Package], new: &[Package]) -> DiffReport {
    diff_sets_in(old, new, &[])
}

/// [`diff_sets`], with `context`: packages that a type reference resolves
/// against without being compared. The `ridl` CLI passes the built-in
/// `ridl.std` here, so a struct field appended with a `ridl.std` type is judged
/// by that type's declaration (driftsys/ridl#598).
pub fn diff_sets_in(old: &[Package], new: &[Package], context: &[Package]) -> DiffReport {
    use std::collections::BTreeMap;

    let scope: Vec<&Package> = new.iter().chain(context).collect();

    let old_by: BTreeMap<&str, &Package> = old.iter().map(|pkg| (pkg.name.as_str(), pkg)).collect();
    let new_by: BTreeMap<&str, &Package> = new.iter().map(|pkg| (pkg.name.as_str(), pkg)).collect();

    // Each matched pair is walked and classified against its own two snapshots,
    // because the classifier resolves a change's path back into the packages it
    // came from.
    let mut changes = Vec::new();
    for (name, old_pkg) in &old_by {
        match new_by.get(name) {
            Some(new_pkg) => {
                let mut pair = Vec::new();
                walk::walk_packages(old_pkg, new_pkg, &mut pair);
                classify_all(&mut pair, old_pkg, new_pkg, &scope);
                changes.append(&mut pair);
            }
            // A package present on one side only: the change classifies on its
            // category alone, so the one snapshot stands for both.
            None => {
                let mut pair = Vec::new();
                emit(
                    &mut pair,
                    (*name).to_string(),
                    Category::DeclRemoved,
                    Some(format!("package {name}")),
                    None,
                );
                classify_all(&mut pair, old_pkg, old_pkg, &[]);
                changes.append(&mut pair);
            }
        }
    }
    for (name, new_pkg) in &new_by {
        if !old_by.contains_key(name) {
            let mut pair = Vec::new();
            emit(
                &mut pair,
                (*name).to_string(),
                Category::DeclAdded,
                None,
                Some(format!("package {name}")),
            );
            classify_all(&mut pair, new_pkg, new_pkg, &[]);
            changes.append(&mut pair);
        }
    }
    report(changes)
}

/// Compares two workspaces at the system (rsdl reference §14): the packages by
/// the ridl categories, exactly as [`diff_sets`] does, and — when both sides
/// carry a lowered system — the system's placement and composition changes,
/// which carry no verdict. A system on one side only is not compared: there is
/// nothing to compare it against.
///
/// `context` is passed to [`diff_sets_in`].
pub fn diff_workspaces(
    old: &[Package],
    old_system: Option<&System>,
    new: &[Package],
    new_system: Option<&System>,
    context: &[Package],
) -> DiffReport {
    let mut report = diff_sets_in(old, new, context);
    if let (Some(old_system), Some(new_system)) = (old_system, new_system) {
        report.system = diff_systems(old_system, new_system);
    }
    report
}

/// Loads an `.ir.json` snapshot written by `ridl build --emit ir-json` —
/// canonical protobuf JSON, read through the one reader every surface shares
/// (ADR-0014 decision 1).
pub fn load_ir_json(path: &Path) -> Result<Package, LoadError> {
    let text = std::fs::read_to_string(path).map_err(LoadError::Io)?;
    ridl_ir::v2::from_json(&text).map_err(|err| LoadError::Parse(err.to_string()))
}

/// The stable lowercase word for a verdict — used by both the text and JSON
/// renderers so the two stay in lockstep.
pub(crate) fn verdict_word(verdict: Verdict) -> &'static str {
    match verdict {
        Verdict::Identical => "identical",
        Verdict::Compatible => "compatible",
        Verdict::Breaking => "breaking",
    }
}

/// The stable snake_case word for a category — the single source of truth for
/// both renderers and for `ridl diff --explain`, which takes a category exactly
/// as the report prints it.
// A new variant must be given a real arm here, not swept into a
// catch-all: rustc forces *an* arm, and the arm its `help:` text
// proposes is `_ =>`, which classifies the new variant silently. The
// two lints below reject a wildcard over `Category` — the first when
// it covers several variants, the second when it covers exactly one,
// which is the case one added variant creates.
#[deny(
    clippy::wildcard_enum_match_arm,
    clippy::match_wildcard_for_single_variants
)]
pub fn category_word(category: Category) -> &'static str {
    match category {
        Category::DeclAdded => "decl_added",
        Category::DeclRemoved => "decl_removed",
        Category::InterfaceRenamed => "interface_renamed",
        Category::InterfaceRetired => "interface_retired",
        Category::MemberReordered => "member_reordered",
        Category::InteractionAppended => "interaction_appended",
        Category::InteractionInserted => "interaction_inserted",
        Category::InteractionReordered => "interaction_reordered",
        Category::InteractionRemoved => "interaction_removed",
        Category::InteractionRetired => "interaction_retired",
        Category::KindChanged => "kind_changed",
        Category::PayloadChanged => "payload_changed",
        Category::ReturnChanged => "return_changed",
        Category::ParamsChanged => "params_changed",
        Category::TimingChanged => "timing_changed",
        Category::RpcBoundChanged => "rpc_bound_changed",
        Category::ContractChanged => "contract_changed",
        Category::WidthChanged => "width_changed",
        Category::ConstraintChanged => "constraint_changed",
        Category::InitChanged => "init_changed",
        Category::ReservedNameRedeclared => "reserved_name_redeclared",
        Category::ServiceChanged => "service_changed",
        Category::ServiceInterfaceAdded => "service_interface_added",
        Category::ServiceInterfaceRemoved => "service_interface_removed",
        Category::DocOnly => "doc_only",
        Category::VisibilityChanged => "visibility_changed",
    }
}

/// The heading a category's changes are grouped under in the text report, or
/// `None` for a category listed plainly. One heading exists: "compatible on
/// the wire, visible in source", for a change that exits 0 but that a
/// consumer sees in its source — an interface renamed on its number changes
/// the generated identity-table names in both wire backends, and an interface
/// leaving a service's set stops the `service.member` addresses of that
/// interface resolving under the service. Each such category's `--explain`
/// text states its own consequence; the JSON report carries the category word
/// and no heading field.
///
/// Wildcard arms are denied for the reason `category_word` gives.
#[deny(
    clippy::wildcard_enum_match_arm,
    clippy::match_wildcard_for_single_variants
)]
pub fn heading(category: Category) -> Option<&'static str> {
    match category {
        Category::InterfaceRenamed | Category::ServiceInterfaceRemoved => {
            Some("compatible on the wire, visible in source")
        }
        Category::DeclAdded
        | Category::DeclRemoved
        | Category::InterfaceRetired
        | Category::MemberReordered
        | Category::InteractionAppended
        | Category::InteractionInserted
        | Category::InteractionReordered
        | Category::InteractionRemoved
        | Category::InteractionRetired
        | Category::KindChanged
        | Category::PayloadChanged
        | Category::ReturnChanged
        | Category::ParamsChanged
        | Category::TimingChanged
        | Category::RpcBoundChanged
        | Category::ContractChanged
        | Category::WidthChanged
        | Category::ConstraintChanged
        | Category::InitChanged
        | Category::ReservedNameRedeclared
        | Category::ServiceChanged
        | Category::ServiceInterfaceAdded
        | Category::DocOnly
        | Category::VisibilityChanged => None,
    }
}

impl serde::Serialize for Verdict {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(verdict_word(*self))
    }
}

impl serde::Serialize for Category {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(category_word(*self))
    }
}

impl serde::Serialize for Change {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct as _;
        let mut state = serializer.serialize_struct("Change", 5)?;
        state.serialize_field("path", &self.path)?;
        state.serialize_field("category", &self.category)?;
        state.serialize_field("verdict", &self.verdict)?;
        state.serialize_field("before", &self.before)?;
        state.serialize_field("after", &self.after)?;
        state.end()
    }
}

/// Renders a report as a human-readable summary: the report verdict on the
/// first line, then one indented line per change. A change whose category has
/// no [`heading`] is listed first, in report order; then each heading is
/// printed once, as its own line ending in a colon, followed by the changes
/// under it, in report order. Headings come in [`CATEGORIES`] order.
///
/// After the contract changes come the system headings (rsdl reference §14):
/// each heading that has a change on its own line, then one indented line per
/// change under it, in the `path: before -> after` form and with no verdict.
pub fn render_text(report: &DiffReport) -> String {
    let mut out = String::new();
    out.push_str(verdict_word(report.verdict));
    out.push('\n');
    for change in &report.changes {
        if heading(change.category).is_none() {
            push_change_line(&mut out, change);
        }
    }
    let mut printed: Vec<&'static str> = Vec::new();
    for category in CATEGORIES {
        let Some(title) = heading(category) else {
            continue;
        };
        if printed.contains(&title) {
            continue;
        }
        printed.push(title);
        let mut under = report
            .changes
            .iter()
            .filter(|change| heading(change.category) == Some(title))
            .peekable();
        if under.peek().is_none() {
            continue;
        }
        out.push_str(title);
        out.push_str(":\n");
        for change in under {
            push_change_line(&mut out, change);
        }
    }
    for heading in [
        SystemHeading::PlacementChanged,
        SystemHeading::CompositionChanged,
    ] {
        let mut listed = report
            .system
            .iter()
            .filter(|change| change.heading == heading)
            .peekable();
        if listed.peek().is_none() {
            continue;
        }
        out.push_str(system::heading_text(heading));
        out.push('\n');
        for change in listed {
            out.push_str("  ");
            out.push_str(&change.path);
            push_values(&mut out, change.before.as_ref(), change.after.as_ref());
            out.push('\n');
        }
    }
    out
}

/// One change of the text report: `  [verdict] category path`, then
/// `: before -> after` where the sides apply.
fn push_change_line(out: &mut String, change: &Change) {
    out.push_str("  [");
    out.push_str(verdict_word(change.verdict));
    out.push_str("] ");
    out.push_str(category_word(change.category));
    out.push(' ');
    out.push_str(&change.path);
    push_values(out, change.before.as_ref(), change.after.as_ref());
    out.push('\n');
}

/// The rendered `before -> after` tail of one change line, shared by contract
/// changes and system changes.
fn push_values(out: &mut String, before: Option<&String>, after: Option<&String>) {
    match (before, after) {
        (Some(before), Some(after)) => {
            out.push_str(": ");
            out.push_str(before);
            out.push_str(" -> ");
            out.push_str(after);
        }
        (Some(before), None) => {
            out.push_str(": ");
            out.push_str(before);
            out.push_str(" -> (removed)");
        }
        (None, Some(after)) => {
            out.push_str(": (absent) -> ");
            out.push_str(after);
        }
        (None, None) => {}
    }
}

/// Renders a report as machine-readable JSON with the stable schema
/// `{"verdict", "changes": [{"path", "category", "verdict", "before",
/// "after"}]}`.
pub fn render_json(report: &DiffReport) -> String {
    #[derive(serde::Serialize)]
    struct JsonSystemChange<'a> {
        path: &'a str,
        before: Option<&'a str>,
        after: Option<&'a str>,
    }

    #[derive(serde::Serialize)]
    struct JsonReport<'a> {
        verdict: Verdict,
        changes: &'a [Change],
        #[serde(skip_serializing_if = "Vec::is_empty")]
        placement_changed: Vec<JsonSystemChange<'a>>,
        #[serde(skip_serializing_if = "Vec::is_empty")]
        composition_changed: Vec<JsonSystemChange<'a>>,
    }

    let under = |heading: SystemHeading| -> Vec<JsonSystemChange<'_>> {
        report
            .system
            .iter()
            .filter(|change| change.heading == heading)
            .map(|change| JsonSystemChange {
                path: &change.path,
                before: change.before.as_deref(),
                after: change.after.as_deref(),
            })
            .collect()
    };
    serde_json::to_string_pretty(&JsonReport {
        verdict: report.verdict,
        changes: &report.changes,
        placement_changed: under(SystemHeading::PlacementChanged),
        composition_changed: under(SystemHeading::CompositionChanged),
    })
    .expect("a diff report holds only string-representable values, so serialization cannot fail")
}