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 name-paired interaction's family or operation shape changed
222 /// (ADR-0012 decision 6).
223 InteractionClassChanged,
224 /// A derived wire width or scalar backing changed.
225 WidthChanged,
226 /// A scalar constraint (range, step, length, pattern) changed, or a
227 /// composite member changed in place.
228 ConstraintChanged,
229 /// A resolved or declared init value changed.
230 InitChanged,
231 /// A name that was a `reserved` tombstone is live again — an
232 /// interaction inside an interface body.
233 ReservedNameRedeclared,
234 /// A service switched between the named list and an inline shape.
235 /// Narrowed to the form switch by ADR-0015 decision 19: a changed
236 /// list is read as a set by the two `ServiceInterface*` categories
237 /// below.
238 ServiceChanged,
239 /// An interface in a service's set that the old snapshot's set did not
240 /// hold (ADR-0015 decision 19 as amended on 2026-09-15: a service's
241 /// list is a set of interface references).
242 ServiceInterfaceAdded,
243 /// An interface the old snapshot's set held that the new one does not.
244 /// Compatible on the wire — the routing key does not contain the
245 /// service — and visible in source, so the text report lists it under
246 /// that heading ([`heading`]).
247 ServiceInterfaceRemoved,
248 /// Only doc comment, labels, or deprecation metadata changed.
249 DocOnly,
250 /// The visibility a declaration is published at changed. Separate from
251 /// [`Category::DocOnly`] because `internal` removes the declaration from
252 /// every out-of-package consumer (ADR-0002 §8), so the change has a
253 /// direction.
254 VisibilityChanged,
255 }
256}
257
258/// One difference between two snapshots, with an honest path into the IR and
259/// the rendered before/after values where they apply.
260#[derive(Clone, Debug, PartialEq, Eq)]
261pub struct Change {
262 /// A slash-separated path, e.g. `veh.cluster/VehicleStatus/doorOpened`.
263 pub path: String,
264 pub category: Category,
265 pub verdict: Verdict,
266 /// The rendered old value, absent when the change is an addition.
267 pub before: Option<String>,
268 /// The rendered new value, absent when the change is a removal.
269 pub after: Option<String>,
270}
271
272impl Change {
273 /// The dotted name of the package the change belongs to: the first
274 /// segment of [`path`](Change::path). The walk builds the path as
275 /// `<package>/<name>[/<member>...]`, and this accessor and
276 /// [`declaration`](Change::declaration) are the one place that reads that
277 /// layout back.
278 pub fn package(&self) -> &str {
279 self.path.split('/').next().unwrap_or_default()
280 }
281
282 /// The bare name of the package-level declaration, interface or service
283 /// the change belongs to: the second segment of [`path`](Change::path), or
284 /// `None` for a change to the package itself.
285 pub fn declaration(&self) -> Option<&str> {
286 self.path.split('/').nth(1)
287 }
288}
289
290/// The result of a comparison: every change and the report-level verdict (the
291/// maximum verdict over the changes; [`Verdict::Identical`] when there are
292/// none).
293#[derive(Clone, Debug, PartialEq, Eq)]
294pub struct DiffReport {
295 pub changes: Vec<Change>,
296 pub verdict: Verdict,
297 /// The changes to the lowered system, each under its heading and with no
298 /// verdict (rsdl reference §14). They never enter `verdict`. Empty unless
299 /// both sides carry a system ([`diff_workspaces`]).
300 pub system: Vec<SystemChange>,
301}
302
303/// Appends one change.
304///
305/// The verdict is stamped breaking here and settled by [`classify`] once the
306/// walk of the containing package pair is complete — the classifier needs both
307/// snapshots, which the walk does not carry down to every emission site.
308/// Breaking is the safe placeholder: a change that somehow escaped
309/// classification would gate rather than pass.
310pub(crate) fn emit(
311 changes: &mut Vec<Change>,
312 path: String,
313 category: Category,
314 before: Option<String>,
315 after: Option<String>,
316) {
317 changes.push(Change {
318 path,
319 category,
320 verdict: Verdict::Breaking,
321 before,
322 after,
323 });
324}
325
326/// Whether an interface carries an identity: a frozen, non-zero number from
327/// its unit's `interfaces.lock` (lock design §7). A provisional number is
328/// no identity, and `number` 0 — never allocated — marks a snapshot published
329/// before the lock existed. The walk matches by number only when both sides
330/// have one, and the classifier re-finds the old side the same way.
331pub(crate) fn frozen(interface: &ridl_ir::v2::Interface) -> bool {
332 interface.number != 0 && !interface.provisional
333}
334
335/// Settles the verdict of every change the walk of one package pair produced.
336/// `scope` is every package a reference to another package's declaration
337/// resolves against ([`classify::classify_in`]).
338///
339/// A change's new side is in `new`, except for an interface whose number
340/// moved to another package of the unit: the walk puts that package first in
341/// the change's path, and the classifier reads the new side from it, so the
342/// package is taken from `scope`, which holds every package of the new set.
343fn classify_all(changes: &mut [Change], old: &Package, new: &Package, scope: &[&Package]) {
344 for change in changes {
345 let held_by = change.path.split('/').next().unwrap_or_default();
346 let new = if held_by == new.name {
347 new
348 } else {
349 scope
350 .iter()
351 .copied()
352 .find(|package| package.name == held_by)
353 .unwrap_or(new)
354 };
355 change.verdict = classify::classify_in(change, old, new, scope);
356 }
357}
358
359/// Assembles a [`DiffReport`], deriving the report verdict as the maximum over
360/// its changes.
361pub(crate) fn report(changes: Vec<Change>) -> DiffReport {
362 let verdict = changes
363 .iter()
364 .map(|change| change.verdict)
365 .max()
366 .unwrap_or(Verdict::Identical);
367 DiffReport {
368 changes,
369 verdict,
370 system: Vec::new(),
371 }
372}
373
374/// Compares two resolved packages. Matched packages share a name; the new
375/// package's name is used as the path prefix.
376///
377/// Only the pair is in hand, so a type from another package does not resolve,
378/// and a type the diff cannot resolve is reported as breaking: a struct field
379/// appended with such a type classifies breaking (driftsys/ridl#598).
380/// [`diff_sets_in`] resolves it.
381pub fn diff_packages(old: &Package, new: &Package) -> DiffReport {
382 let matching = walk::Matching::new(&[old], &[new]);
383 let mut changes = Vec::new();
384 walk::walk_packages(old, new, &matching, &mut changes);
385 classify_all(&mut changes, old, new, &[]);
386 report(changes)
387}
388
389/// Compares two sets of resolved packages, matching by package name, and
390/// interface numbers within each unit ([`walk::Matching`]). A package present
391/// only on the new side is a [`Category::DeclAdded`]; matched packages are
392/// walked pairwise. A package present only on the old side is a
393/// [`Category::DeclRemoved`] when its whole unit is gone from the new side,
394/// and is walked declaration by declaration when the unit is still there, so
395/// that an interface whose number moved to another package of the unit is
396/// [`Category::InterfaceRenamed`] and one the unit retired is
397/// [`Category::InterfaceRetired`].
398///
399/// [`diff_sets_in`] with no context: a type from a package outside `new`, such
400/// as `ridl.std`, which no snapshot carries, does not resolve, and a type the
401/// diff cannot resolve is reported as breaking.
402pub fn diff_sets(old: &[Package], new: &[Package]) -> DiffReport {
403 diff_sets_in(old, new, &[])
404}
405
406/// [`diff_sets`], with `context`: packages that a type reference resolves
407/// against without being compared. The `ridl` CLI passes the built-in
408/// `ridl.std` here, so a struct field appended with a `ridl.std` type is judged
409/// by that type's declaration (driftsys/ridl#598).
410pub fn diff_sets_in(old: &[Package], new: &[Package], context: &[Package]) -> DiffReport {
411 let old: Vec<&Package> = old.iter().collect();
412 let new: Vec<&Package> = new.iter().collect();
413 let context: Vec<&Package> = context.iter().collect();
414 diff_refs_in(&old, &new, &context)
415}
416
417/// [`diff_sets_in`] over borrowed packages, for a caller that holds the
418/// packages by reference and would otherwise clone them.
419pub fn diff_refs_in(old: &[&Package], new: &[&Package], context: &[&Package]) -> DiffReport {
420 use std::collections::BTreeMap;
421
422 use ridl_ir::v2::{members_of_unit, unit_of};
423
424 let scope: Vec<&Package> = new.iter().chain(context).copied().collect();
425 let matching = walk::Matching::new(old, new);
426
427 let old_by: BTreeMap<&str, &Package> =
428 old.iter().map(|pkg| (pkg.name.as_str(), *pkg)).collect();
429 let new_by: BTreeMap<&str, &Package> =
430 new.iter().map(|pkg| (pkg.name.as_str(), *pkg)).collect();
431
432 // Each matched pair is walked and classified against its own two snapshots,
433 // because the classifier resolves a change's path back into the packages it
434 // came from.
435 let mut changes = Vec::new();
436 for (name, old_pkg) in &old_by {
437 match new_by.get(name) {
438 Some(new_pkg) => {
439 let mut pair = Vec::new();
440 walk::walk_packages(old_pkg, new_pkg, &matching, &mut pair);
441 classify_all(&mut pair, old_pkg, new_pkg, &scope);
442 changes.append(&mut pair);
443 }
444 // A package gone while its unit stays: walked against a package
445 // with nothing in it, so that each shape is matched in the unit,
446 // retired by the unit, or removed, and each other declaration is
447 // removed on its own line.
448 None if members_of_unit(unit_of(old_pkg), new).next().is_some() => {
449 let gone = Package {
450 name: old_pkg.name.clone(),
451 unit: old_pkg.unit.clone(),
452 ..Default::default()
453 };
454 let mut pair = Vec::new();
455 walk::walk_packages(old_pkg, &gone, &matching, &mut pair);
456 classify_all(&mut pair, old_pkg, &gone, &scope);
457 changes.append(&mut pair);
458 }
459 // A package present on one side only: the change classifies on its
460 // category alone, so the one snapshot stands for both.
461 None => {
462 let mut pair = Vec::new();
463 emit(
464 &mut pair,
465 (*name).to_string(),
466 Category::DeclRemoved,
467 Some(format!("package {name}")),
468 None,
469 );
470 classify_all(&mut pair, old_pkg, old_pkg, &[]);
471 changes.append(&mut pair);
472 }
473 }
474 }
475 for (name, new_pkg) in &new_by {
476 if !old_by.contains_key(name) {
477 let mut pair = Vec::new();
478 emit(
479 &mut pair,
480 (*name).to_string(),
481 Category::DeclAdded,
482 None,
483 Some(format!("package {name}")),
484 );
485 classify_all(&mut pair, new_pkg, new_pkg, &[]);
486 changes.append(&mut pair);
487 }
488 }
489 report(changes)
490}
491
492/// Compares two workspaces at the system (rsdl reference §14): the packages by
493/// the ridl categories, exactly as [`diff_sets`] does, and — when both sides
494/// carry a lowered system — the system's placement and composition changes,
495/// which carry no verdict. A system on one side only is not compared: there is
496/// nothing to compare it against.
497///
498/// `context` is passed to [`diff_sets_in`].
499pub fn diff_workspaces(
500 old: &[Package],
501 old_system: Option<&System>,
502 new: &[Package],
503 new_system: Option<&System>,
504 context: &[Package],
505) -> DiffReport {
506 let mut report = diff_sets_in(old, new, context);
507 if let (Some(old_system), Some(new_system)) = (old_system, new_system) {
508 report.system = diff_systems(old_system, new_system);
509 }
510 report
511}
512
513/// The stable lowercase word for a verdict — used by both the text and JSON
514/// renderers so the two stay in lockstep.
515pub(crate) fn verdict_word(verdict: Verdict) -> &'static str {
516 match verdict {
517 Verdict::Identical => "identical",
518 Verdict::Compatible => "compatible",
519 Verdict::Breaking => "breaking",
520 }
521}
522
523/// The stable snake_case word for a category — the single source of truth for
524/// both renderers and for `ridl diff --explain`, which takes a category exactly
525/// as the report prints it.
526// A new variant must be given a real arm here, not swept into a
527// catch-all: rustc forces *an* arm, and the arm its `help:` text
528// proposes is `_ =>`, which classifies the new variant silently. The
529// two lints below reject a wildcard over `Category` — the first when
530// it covers several variants, the second when it covers exactly one,
531// which is the case one added variant creates.
532#[deny(
533 clippy::wildcard_enum_match_arm,
534 clippy::match_wildcard_for_single_variants
535)]
536pub fn category_word(category: Category) -> &'static str {
537 match category {
538 Category::DeclAdded => "decl_added",
539 Category::DeclRemoved => "decl_removed",
540 Category::InterfaceRenamed => "interface_renamed",
541 Category::InterfaceRetired => "interface_retired",
542 Category::InterfaceFrozen => "interface_frozen",
543 Category::InterfaceNumberChanged => "interface_number_changed",
544 Category::MemberReordered => "member_reordered",
545 Category::EnumReordered => "enum_reordered",
546 Category::InteractionAppended => "interaction_appended",
547 Category::InteractionInserted => "interaction_inserted",
548 Category::InteractionReordered => "interaction_reordered",
549 Category::InteractionRemoved => "interaction_removed",
550 Category::InteractionRetired => "interaction_retired",
551 Category::KindChanged => "kind_changed",
552 Category::PayloadChanged => "payload_changed",
553 Category::ReturnChanged => "return_changed",
554 Category::ParamsChanged => "params_changed",
555 Category::TimingChanged => "timing_changed",
556 Category::RpcBoundChanged => "rpc_bound_changed",
557 Category::ContractChanged => "contract_changed",
558 Category::InteractionClassChanged => "interaction_class_changed",
559 Category::WidthChanged => "width_changed",
560 Category::ConstraintChanged => "constraint_changed",
561 Category::InitChanged => "init_changed",
562 Category::ReservedNameRedeclared => "reserved_name_redeclared",
563 Category::ServiceChanged => "service_changed",
564 Category::ServiceInterfaceAdded => "service_interface_added",
565 Category::ServiceInterfaceRemoved => "service_interface_removed",
566 Category::DocOnly => "doc_only",
567 Category::VisibilityChanged => "visibility_changed",
568 }
569}
570
571/// The heading a category's changes are grouped under in the text report, or
572/// `None` for a category listed plainly. Two headings exist. "compatible on
573/// the wire, visible in source" is for a change that exits 0 but that a
574/// consumer sees in its source — an interface renamed on its number changes
575/// the generated identity-table names in both wire backends, and an interface
576/// leaving a service's set stops the `service.member` addresses of that
577/// interface resolving under the service. "compatible on the wire, may change
578/// the catalog hash" is for a change that exits 0 but can change the catalog
579/// hash, which a generated face compares with its peer's — a number `ridl
580/// lock` froze in place, which always changes it, and an enum or enum-set body
581/// reordered, which changes it when an interface reaches the enum or enum set
582/// (the hash covers only the declarations an interface reaches). Each such
583/// category's `--explain` text states its own consequence; the JSON report
584/// carries the category word and no heading field.
585///
586/// Wildcard arms are denied for the reason `category_word` gives.
587#[deny(
588 clippy::wildcard_enum_match_arm,
589 clippy::match_wildcard_for_single_variants
590)]
591pub fn heading(category: Category) -> Option<&'static str> {
592 match category {
593 Category::InterfaceRenamed | Category::ServiceInterfaceRemoved => {
594 Some("compatible on the wire, visible in source")
595 }
596 Category::InterfaceFrozen | Category::EnumReordered => {
597 Some("compatible on the wire, may change the catalog hash")
598 }
599 Category::DeclAdded
600 | Category::DeclRemoved
601 | Category::InterfaceRetired
602 | Category::InterfaceNumberChanged
603 | Category::MemberReordered
604 | Category::InteractionAppended
605 | Category::InteractionInserted
606 | Category::InteractionReordered
607 | Category::InteractionRemoved
608 | Category::InteractionRetired
609 | Category::KindChanged
610 | Category::PayloadChanged
611 | Category::ReturnChanged
612 | Category::ParamsChanged
613 | Category::TimingChanged
614 | Category::RpcBoundChanged
615 | Category::ContractChanged
616 | Category::InteractionClassChanged
617 | Category::WidthChanged
618 | Category::ConstraintChanged
619 | Category::InitChanged
620 | Category::ReservedNameRedeclared
621 | Category::ServiceChanged
622 | Category::ServiceInterfaceAdded
623 | Category::DocOnly
624 | Category::VisibilityChanged => None,
625 }
626}
627
628impl serde::Serialize for Verdict {
629 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
630 serializer.serialize_str(verdict_word(*self))
631 }
632}
633
634impl serde::Serialize for Category {
635 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
636 serializer.serialize_str(category_word(*self))
637 }
638}
639
640impl serde::Serialize for Change {
641 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
642 use serde::ser::SerializeStruct as _;
643 let mut state = serializer.serialize_struct("Change", 5)?;
644 state.serialize_field("path", &self.path)?;
645 state.serialize_field("category", &self.category)?;
646 state.serialize_field("verdict", &self.verdict)?;
647 state.serialize_field("before", &self.before)?;
648 state.serialize_field("after", &self.after)?;
649 state.end()
650 }
651}
652
653/// Renders a report as a human-readable summary: the report verdict on the
654/// first line, then one indented line per change. A change whose category has
655/// no [`heading`] is listed first, in report order; then each heading is
656/// printed once, as its own line ending in a colon, followed by the changes
657/// under it, in report order. Headings come in [`CATEGORIES`] order.
658///
659/// After the contract changes come the system headings (rsdl reference §14):
660/// each heading that has a change on its own line, then one indented line per
661/// change under it, in the `path: before -> after` form and with no verdict.
662pub fn render_text(report: &DiffReport) -> String {
663 let mut out = String::new();
664 out.push_str(verdict_word(report.verdict));
665 out.push('\n');
666 for change in &report.changes {
667 if heading(change.category).is_none() {
668 push_change_line(&mut out, change);
669 }
670 }
671 let mut printed: Vec<&'static str> = Vec::new();
672 for category in CATEGORIES {
673 let Some(title) = heading(category) else {
674 continue;
675 };
676 if printed.contains(&title) {
677 continue;
678 }
679 printed.push(title);
680 let mut under = report
681 .changes
682 .iter()
683 .filter(|change| heading(change.category) == Some(title))
684 .peekable();
685 if under.peek().is_none() {
686 continue;
687 }
688 out.push_str(title);
689 out.push_str(":\n");
690 for change in under {
691 push_change_line(&mut out, change);
692 }
693 }
694 for heading in [
695 SystemHeading::PlacementChanged,
696 SystemHeading::CompositionChanged,
697 ] {
698 let mut listed = report
699 .system
700 .iter()
701 .filter(|change| change.heading == heading)
702 .peekable();
703 if listed.peek().is_none() {
704 continue;
705 }
706 out.push_str(system::heading_text(heading));
707 out.push('\n');
708 for change in listed {
709 out.push_str(" ");
710 out.push_str(&change.path);
711 push_values(&mut out, change.before.as_ref(), change.after.as_ref());
712 out.push('\n');
713 }
714 }
715 out
716}
717
718/// One change of the text report: ` [verdict] category path`, then
719/// `: before -> after` where the sides apply.
720fn push_change_line(out: &mut String, change: &Change) {
721 out.push_str(" [");
722 out.push_str(verdict_word(change.verdict));
723 out.push_str("] ");
724 out.push_str(category_word(change.category));
725 out.push(' ');
726 out.push_str(&change.path);
727 push_values(out, change.before.as_ref(), change.after.as_ref());
728 out.push('\n');
729}
730
731/// The rendered `before -> after` tail of one change line, shared by contract
732/// changes and system changes.
733fn push_values(out: &mut String, before: Option<&String>, after: Option<&String>) {
734 match (before, after) {
735 (Some(before), Some(after)) => {
736 out.push_str(": ");
737 out.push_str(before);
738 out.push_str(" -> ");
739 out.push_str(after);
740 }
741 (Some(before), None) => {
742 out.push_str(": ");
743 out.push_str(before);
744 out.push_str(" -> (removed)");
745 }
746 (None, Some(after)) => {
747 out.push_str(": (absent) -> ");
748 out.push_str(after);
749 }
750 (None, None) => {}
751 }
752}
753
754/// Renders a report as machine-readable JSON with the stable schema
755/// `{"verdict", "changes": [{"path", "category", "verdict", "before",
756/// "after"}]}`.
757pub fn render_json(report: &DiffReport) -> String {
758 #[derive(serde::Serialize)]
759 struct JsonSystemChange<'a> {
760 path: &'a str,
761 before: Option<&'a str>,
762 after: Option<&'a str>,
763 }
764
765 #[derive(serde::Serialize)]
766 struct JsonReport<'a> {
767 verdict: Verdict,
768 changes: &'a [Change],
769 #[serde(skip_serializing_if = "Vec::is_empty")]
770 placement_changed: Vec<JsonSystemChange<'a>>,
771 #[serde(skip_serializing_if = "Vec::is_empty")]
772 composition_changed: Vec<JsonSystemChange<'a>>,
773 }
774
775 let under = |heading: SystemHeading| -> Vec<JsonSystemChange<'_>> {
776 report
777 .system
778 .iter()
779 .filter(|change| change.heading == heading)
780 .map(|change| JsonSystemChange {
781 path: &change.path,
782 before: change.before.as_deref(),
783 after: change.after.as_deref(),
784 })
785 .collect()
786 };
787 serde_json::to_string_pretty(&JsonReport {
788 verdict: report.verdict,
789 changes: &report.changes,
790 placement_changed: under(SystemHeading::PlacementChanged),
791 composition_changed: under(SystemHeading::CompositionChanged),
792 })
793 .expect("a diff report holds only string-representable values, so serialization cannot fail")
794}