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