Skip to main content

ridl_diff/
system.rs

1//! `ridl diff` at the system (rsdl reference §14): the changes to a lowered
2//! system that are not contract changes.
3//!
4//! The contracts of a workspace are compared by the ridl categories, through
5//! [`crate::diff_sets`]. What rsdl adds is structure — which components exist,
6//! their lines, and where each instance runs — and a change to it changes the
7//! derived links and never the contract. Such a change is listed under one of
8//! two headings and carries no verdict: neither compatible nor breaking. Which
9//! of them are breaking, and for whom, is the stability policy's. A third
10//! heading, instance number changed, is the exception and is breaking.
11//!
12//! - **Placement changed** — a change in a deployment: a deployment added or
13//!   removed, a machine added, removed or made `external`, an instance moved to
14//!   another machine, or a `labels`, `deprecated` or backend key of the
15//!   deployment, of a machine or of a placement line changed.
16//! - **Composition changed** — a change to the closure or to a component's
17//!   lines: a component added to or removed from the system, an `offers` or
18//!   `requires` line added or removed, `instances` changed, a component made
19//!   `external`, a distribution added or removed, a member line added to or
20//!   removed from a distribution, or a `labels`, `deprecated`, `tier` or
21//!   backend key of the system, of a component, of a distribution or of one
22//!   of their lines changed.
23//!
24//! - **Instance number changed** — a locked instance number differs between
25//!   the two sides, or a number moved to another instance whose old holder is
26//!   still present. A provisional old number and a rename are not listed.
27//!
28//! All read the lowered `System` of each side and nothing else.
29
30use ridl_ir::v2::{self, Component, Deployment, InterfaceRef, System};
31
32/// The heading a system change is listed under (rsdl reference §14).
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum SystemHeading {
35    /// A change in a deployment.
36    PlacementChanged,
37    /// A change to the closure or to a component's lines.
38    CompositionChanged,
39    /// A locked instance number changed. The only system heading that carries
40    /// a verdict: breaking.
41    InstanceNumberChanged,
42}
43
44/// One change to the system, listed under its heading. Only a change under
45/// [`SystemHeading::InstanceNumberChanged`] carries a verdict: breaking.
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct SystemChange {
48    pub heading: SystemHeading,
49    /// A slash-separated path naming the affected system, component,
50    /// distribution, deployment, machine, instance, member or attribute.
51    pub path: String,
52    /// The rendered old value, absent when the change is an addition.
53    pub before: Option<String>,
54    /// The rendered new value, absent when the change is a removal.
55    pub after: Option<String>,
56}
57
58/// The heading as the text report prints it: `placement changed`.
59pub fn heading_text(heading: SystemHeading) -> &'static str {
60    match heading {
61        SystemHeading::PlacementChanged => "placement changed",
62        SystemHeading::CompositionChanged => "composition changed",
63        SystemHeading::InstanceNumberChanged => "instance number changed",
64    }
65}
66
67/// Compares two lowered systems: the composition changes first, in the new
68/// closure's order and then the removed components, then the placement
69/// changes, deployment by deployment in the new system's order and then the
70/// removed deployments, and then the instance number changes. The doc fields
71/// (`doc`, the doc links, `see`, `since`) are never read: a doc edit is
72/// neither a placement nor a composition change, and a placement or
73/// composition change has no verdict (ADR-0026). The
74/// sizing fields (`Deployment.sizing`, `Placement.sizing`) are never read: the
75/// registry records them as not reported, reason sizing
76/// (`ridl_core::attributes`).
77pub fn diff_systems(old: &System, new: &System) -> Vec<SystemChange> {
78    let mut changes = Vec::new();
79    let system_path = format!("{}.{}", new.package, new.name);
80    declaration_attrs(
81        &mut changes,
82        SystemHeading::CompositionChanged,
83        &system_path,
84        (&old.labels, old.deprecated.as_ref(), &old.attributes),
85        (&new.labels, new.deprecated.as_ref(), &new.attributes),
86    );
87    // A member line on one side only is compared with an empty side, so that
88    // its backend keys are listed with it.
89    for line in &new.members {
90        let before = old
91            .members
92            .iter()
93            .find(|before| before.component == line.component);
94        line_attrs(
95            &mut changes,
96            SystemHeading::CompositionChanged,
97            &format!("{system_path}/{}", line.component),
98            before.map_or(&[], |before| &before.attributes),
99            &line.attributes,
100        );
101    }
102    for line in &old.members {
103        if !new
104            .members
105            .iter()
106            .any(|after| after.component == line.component)
107        {
108            line_attrs(
109                &mut changes,
110                SystemHeading::CompositionChanged,
111                &format!("{system_path}/{}", line.component),
112                &line.attributes,
113                &[],
114            );
115        }
116    }
117    for component in &new.components {
118        let name = component.qualified_name();
119        match old
120            .components
121            .iter()
122            .find(|before| before.qualified_name() == name)
123        {
124            Some(before) => compare_components(before, component, &mut changes),
125            None => composition(&mut changes, name, None, Some("in the closure")),
126        }
127    }
128    for component in &old.components {
129        let name = component.qualified_name();
130        if !new
131            .components
132            .iter()
133            .any(|after| after.qualified_name() == name)
134        {
135            composition(&mut changes, name, Some("in the closure"), None);
136        }
137    }
138    let empty_distribution = v2::Distribution::default();
139    for distribution in &new.distributions {
140        let name = distribution.qualified_name();
141        let before = old
142            .distributions
143            .iter()
144            .find(|before| before.qualified_name() == name);
145        if before.is_none() {
146            composition(&mut changes, name.clone(), None, Some("distribution"));
147        }
148        compare_distribution(
149            before.unwrap_or(&empty_distribution),
150            distribution,
151            &name,
152            &mut changes,
153        );
154    }
155    for distribution in &old.distributions {
156        let name = distribution.qualified_name();
157        if !new
158            .distributions
159            .iter()
160            .any(|after| after.qualified_name() == name)
161        {
162            composition(&mut changes, name.clone(), Some("distribution"), None);
163            compare_distribution(distribution, &empty_distribution, &name, &mut changes);
164        }
165    }
166    for deployment in &new.deployments {
167        match old
168            .deployments
169            .iter()
170            .find(|before| before.name == deployment.name)
171        {
172            Some(before) => compare_deployments(before, deployment, &mut changes),
173            None => placement(
174                &mut changes,
175                deployment.name.clone(),
176                None,
177                Some("deployment"),
178            ),
179        }
180    }
181    for deployment in &old.deployments {
182        if !new
183            .deployments
184            .iter()
185            .any(|after| after.name == deployment.name)
186        {
187            placement(
188                &mut changes,
189                deployment.name.clone(),
190                Some("deployment"),
191                None,
192            );
193        }
194    }
195    instance_numbers(old, new, &mut changes);
196    changes
197}
198
199/// The `component/instance` key and the number of every instance of a system,
200/// in closure order, with whether the number is provisional.
201fn numbered_instances(system: &System) -> Vec<(String, i32, bool)> {
202    let mut numbered = Vec::new();
203    for component in &system.components {
204        let name = component.qualified_name();
205        for entry in &component.numbers {
206            numbered.push((
207                format!("{name}/{}", entry.instance),
208                entry.number,
209                entry.provisional,
210            ));
211        }
212    }
213    numbered
214}
215
216/// The instance numbers that changed. A key whose old number is locked and
217/// whose new number differs is listed. So is a new key that holds a locked
218/// number of the old side that another key held, while that other key is
219/// still present on the new side. When the old holder is absent, the change is
220/// a rename, which `ridl lock --rename` carries with the number, and it is not
221/// listed. A provisional old number is never listed, and a key on one side
222/// only is not listed for its own number.
223fn instance_numbers(old: &System, new: &System, changes: &mut Vec<SystemChange>) {
224    let old = numbered_instances(old);
225    let new = numbered_instances(new);
226    for (key, number, _) in &new {
227        if let Some((_, before, provisional)) = old.iter().find(|(old_key, ..)| old_key == key)
228            && !provisional
229            && before != number
230        {
231            changes.push(SystemChange {
232                heading: SystemHeading::InstanceNumberChanged,
233                path: key.clone(),
234                before: Some(before.to_string()),
235                after: Some(number.to_string()),
236            });
237        }
238    }
239    for (key, number, _) in &new {
240        if old.iter().any(|(old_key, ..)| old_key == key) {
241            continue;
242        }
243        let holder = old
244            .iter()
245            .find(|(old_key, held, provisional)| held == number && !provisional && old_key != key);
246        if let Some((holder, ..)) = holder
247            && new.iter().any(|(new_key, ..)| new_key == holder)
248        {
249            changes.push(SystemChange {
250                heading: SystemHeading::InstanceNumberChanged,
251                path: key.clone(),
252                before: Some(format!("{number} ({holder})")),
253                after: Some(number.to_string()),
254            });
255        }
256    }
257}
258
259/// A component in both closures: its `offers` and `requires` lines, its
260/// instances and its `external` flag.
261fn compare_components(old: &Component, new: &Component, changes: &mut Vec<SystemChange>) {
262    let name = new.qualified_name();
263    let old_offers: Vec<&str> = old
264        .offers
265        .iter()
266        .map(|offer| offer.service.as_str())
267        .collect();
268    let new_offers: Vec<&str> = new
269        .offers
270        .iter()
271        .map(|offer| offer.service.as_str())
272        .collect();
273    lines(changes, &name, "offers", &old_offers, &new_offers);
274    let old_requires: Vec<String> = old
275        .requires
276        .iter()
277        .map(|require| interface_text(require.interface.as_ref()))
278        .collect();
279    let new_requires: Vec<String> = new
280        .requires
281        .iter()
282        .map(|require| interface_text(require.interface.as_ref()))
283        .collect();
284    let old_requires: Vec<&str> = old_requires.iter().map(String::as_str).collect();
285    let new_requires: Vec<&str> = new_requires.iter().map(String::as_str).collect();
286    lines(changes, &name, "requires", &old_requires, &new_requires);
287    if old.instances != new.instances {
288        changes.push(SystemChange {
289            heading: SystemHeading::CompositionChanged,
290            path: format!("{name}/instances"),
291            before: Some(instance_list(&old.instances)),
292            after: Some(instance_list(&new.instances)),
293        });
294    }
295    if old.external != new.external {
296        changes.push(SystemChange {
297            heading: SystemHeading::CompositionChanged,
298            path: format!("{name}/external"),
299            before: Some(old.external.to_string()),
300            after: Some(new.external.to_string()),
301        });
302    }
303    declaration_attrs(
304        changes,
305        SystemHeading::CompositionChanged,
306        &name,
307        (&old.labels, old.deprecated.as_ref(), &old.attributes),
308        (&new.labels, new.deprecated.as_ref(), &new.attributes),
309    );
310    // An `offers` or `requires` line on one side only is compared with an
311    // empty side, so that its backend keys are listed with it.
312    for offer in &new.offers {
313        let before = old
314            .offers
315            .iter()
316            .find(|before| before.service == offer.service);
317        line_attrs(
318            changes,
319            SystemHeading::CompositionChanged,
320            &format!("{name}/offers/{}", offer.service),
321            before.map_or(&[], |before| &before.attributes),
322            &offer.attributes,
323        );
324    }
325    for offer in &old.offers {
326        if !new
327            .offers
328            .iter()
329            .any(|after| after.service == offer.service)
330        {
331            line_attrs(
332                changes,
333                SystemHeading::CompositionChanged,
334                &format!("{name}/offers/{}", offer.service),
335                &offer.attributes,
336                &[],
337            );
338        }
339    }
340    for require in &new.requires {
341        let interface = interface_text(require.interface.as_ref());
342        let before = old
343            .requires
344            .iter()
345            .find(|before| interface_text(before.interface.as_ref()) == interface);
346        line_attrs(
347            changes,
348            SystemHeading::CompositionChanged,
349            &format!("{name}/requires/{interface}"),
350            before.map_or(&[], |before| &before.attributes),
351            &require.attributes,
352        );
353    }
354    for require in &old.requires {
355        let interface = interface_text(require.interface.as_ref());
356        if !new
357            .requires
358            .iter()
359            .any(|after| interface_text(after.interface.as_ref()) == interface)
360        {
361            line_attrs(
362                changes,
363                SystemHeading::CompositionChanged,
364                &format!("{name}/requires/{interface}"),
365                &require.attributes,
366                &[],
367            );
368        }
369    }
370}
371
372/// The lines of one keyword that one side has and the other does not.
373fn lines(
374    changes: &mut Vec<SystemChange>,
375    component: &str,
376    keyword: &str,
377    old: &[&str],
378    new: &[&str],
379) {
380    for added in new.iter().filter(|line| !old.contains(line)) {
381        composition(
382            changes,
383            format!("{component}/{keyword}/{added}"),
384            None,
385            Some(&format!("{keyword} {added}")),
386        );
387    }
388    for removed in old.iter().filter(|line| !new.contains(line)) {
389        composition(
390            changes,
391            format!("{component}/{keyword}/{removed}"),
392            Some(&format!("{keyword} {removed}")),
393            None,
394        );
395    }
396}
397
398/// A deployment in both systems: its machines, their `external` flags, and
399/// the machine of every instance placed on both sides.
400fn compare_deployments(old: &Deployment, new: &Deployment, changes: &mut Vec<SystemChange>) {
401    declaration_attrs(
402        changes,
403        SystemHeading::PlacementChanged,
404        &new.name,
405        (&old.labels, old.deprecated.as_ref(), &old.attributes),
406        (&new.labels, new.deprecated.as_ref(), &new.attributes),
407    );
408    for machine in &new.machines {
409        let path = format!("{}/{}", new.name, machine.name);
410        match old
411            .machines
412            .iter()
413            .find(|before| before.name == machine.name)
414        {
415            Some(before) if before.external != machine.external => changes.push(SystemChange {
416                heading: SystemHeading::PlacementChanged,
417                path: format!("{path}/external"),
418                before: Some(before.external.to_string()),
419                after: Some(machine.external.to_string()),
420            }),
421            Some(_) => {}
422            None => placement(changes, path, None, Some("machine")),
423        }
424        if let Some(before) = old
425            .machines
426            .iter()
427            .find(|before| before.name == machine.name)
428        {
429            declaration_attrs(
430                changes,
431                SystemHeading::PlacementChanged,
432                &format!("{}/{}", new.name, machine.name),
433                (
434                    &before.labels,
435                    before.deprecated.as_ref(),
436                    &before.attributes,
437                ),
438                (
439                    &machine.labels,
440                    machine.deprecated.as_ref(),
441                    &machine.attributes,
442                ),
443            );
444        }
445    }
446    for machine in &old.machines {
447        if !new.machines.iter().any(|after| after.name == machine.name) {
448            placement(
449                changes,
450                format!("{}/{}", new.name, machine.name),
451                Some("machine"),
452                None,
453            );
454        }
455    }
456    for placed in &new.placements {
457        let paired = old.placements.iter().find(|before| {
458            before.component == placed.component && before.instance == placed.instance
459        });
460        let Some(before) = paired else {
461            continue;
462        };
463        if before.machine != placed.machine {
464            changes.push(SystemChange {
465                heading: SystemHeading::PlacementChanged,
466                path: format!("{}/{}.{}", new.name, placed.component, placed.instance),
467                before: Some(before.machine.clone()),
468                after: Some(placed.machine.clone()),
469            });
470        }
471        line_attrs(
472            changes,
473            SystemHeading::PlacementChanged,
474            &format!("{}/{}.{}", new.name, placed.component, placed.instance),
475            &before.attributes,
476            &placed.attributes,
477        );
478    }
479}
480
481fn compare_distribution(
482    before: &v2::Distribution,
483    after: &v2::Distribution,
484    name: &str,
485    changes: &mut Vec<SystemChange>,
486) {
487    value_change(
488        changes,
489        SystemHeading::CompositionChanged,
490        format!("{name}/tier"),
491        tier_text(before.tier),
492        tier_text(after.tier),
493    );
494    declaration_attrs(
495        changes,
496        SystemHeading::CompositionChanged,
497        name,
498        (
499            &before.labels,
500            before.deprecated.as_ref(),
501            &before.attributes,
502        ),
503        (&after.labels, after.deprecated.as_ref(), &after.attributes),
504    );
505    // A member line on one side only is compared with an empty side, so that
506    // its backend keys are listed with it.
507    for line in &after.members {
508        let path = format!("{name}/{}", line.component);
509        let earlier = before
510            .members
511            .iter()
512            .find(|earlier| earlier.component == line.component);
513        if earlier.is_none() {
514            composition(changes, path.clone(), None, Some("member"));
515        }
516        line_attrs(
517            changes,
518            SystemHeading::CompositionChanged,
519            &path,
520            earlier.map_or(&[], |earlier| &earlier.attributes),
521            &line.attributes,
522        );
523    }
524    for line in &before.members {
525        if !after
526            .members
527            .iter()
528            .any(|later| later.component == line.component)
529        {
530            let path = format!("{name}/{}", line.component);
531            composition(changes, path.clone(), Some("member"), None);
532            line_attrs(
533                changes,
534                SystemHeading::CompositionChanged,
535                &path,
536                &line.attributes,
537                &[],
538            );
539        }
540    }
541}
542
543fn composition(
544    changes: &mut Vec<SystemChange>,
545    path: String,
546    before: Option<&str>,
547    after: Option<&str>,
548) {
549    changes.push(SystemChange {
550        heading: SystemHeading::CompositionChanged,
551        path,
552        before: before.map(str::to_string),
553        after: after.map(str::to_string),
554    });
555}
556
557fn placement(
558    changes: &mut Vec<SystemChange>,
559    path: String,
560    before: Option<&str>,
561    after: Option<&str>,
562) {
563    changes.push(SystemChange {
564        heading: SystemHeading::PlacementChanged,
565        path,
566        before: before.map(str::to_string),
567        after: after.map(str::to_string),
568    });
569}
570
571/// `(A, B)` as `labels` is written; `()` when empty.
572fn label_list(labels: &[String]) -> String {
573    format!("({})", labels.join(", "))
574}
575
576/// `[ ns.key = value, ns.flag ]` as a backend key block is written; `[]`
577/// when empty.
578fn attribute_list(attributes: &[v2::Attribute]) -> String {
579    if attributes.is_empty() {
580        return "[]".to_string();
581    }
582    let items: Vec<String> = attributes
583        .iter()
584        .map(|attribute| match &attribute.value {
585            Some(value) => format!(
586                "{}.{} = {}",
587                attribute.namespace,
588                attribute.key,
589                value_text(value)
590            ),
591            None => format!("{}.{}", attribute.namespace, attribute.key),
592        })
593        .collect();
594    format!("[ {} ]", items.join(", "))
595}
596
597/// An attribute value as written: a scalar as its text, a list as `(a, b)`.
598fn value_text(value: &v2::AttributeValue) -> String {
599    match &value.kind {
600        Some(v2::attribute_value::Kind::Scalar(text)) => text.clone(),
601        Some(v2::attribute_value::Kind::List(list)) => {
602            let items: Vec<String> = list.items.iter().map(value_text).collect();
603            format!("({})", items.join(", "))
604        }
605        None => String::new(),
606    }
607}
608
609/// `PLATFORM` or `APPLICATION`, or `None` when the distribution has no tier.
610/// A value this build does not know renders as `tier(<n>)`, so that a
611/// snapshot written by a later toolchain does not read as "no tier".
612fn tier_text(tier: i32) -> Option<String> {
613    match v2::Tier::try_from(tier) {
614        Ok(v2::Tier::Platform) => Some("PLATFORM".to_string()),
615        Ok(v2::Tier::Application) => Some("APPLICATION".to_string()),
616        Ok(v2::Tier::Unspecified) => None,
617        Err(_) => Some(format!("tier({tier})")),
618    }
619}
620
621/// One before-and-after line when the two values differ.
622fn value_change(
623    changes: &mut Vec<SystemChange>,
624    heading: SystemHeading,
625    path: String,
626    before: Option<String>,
627    after: Option<String>,
628) {
629    if before != after {
630        changes.push(SystemChange {
631            heading,
632            path,
633            before,
634            after,
635        });
636    }
637}
638
639/// The `labels`, `deprecated` and backend keys of a declaration, under
640/// `heading` at `path`.
641fn declaration_attrs(
642    changes: &mut Vec<SystemChange>,
643    heading: SystemHeading,
644    path: &str,
645    old: (&[String], Option<&String>, &[v2::Attribute]),
646    new: (&[String], Option<&String>, &[v2::Attribute]),
647) {
648    value_change(
649        changes,
650        heading,
651        format!("{path}/labels"),
652        Some(label_list(old.0)),
653        Some(label_list(new.0)),
654    );
655    value_change(
656        changes,
657        heading,
658        format!("{path}/deprecated"),
659        old.1.map(|reason| format!("{reason:?}")),
660        new.1.map(|reason| format!("{reason:?}")),
661    );
662    line_attrs(changes, heading, path, old.2, new.2);
663}
664
665/// The backend keys of a line, under `heading` at `path`.
666fn line_attrs(
667    changes: &mut Vec<SystemChange>,
668    heading: SystemHeading,
669    path: &str,
670    old: &[v2::Attribute],
671    new: &[v2::Attribute],
672) {
673    value_change(
674        changes,
675        heading,
676        format!("{path}/attributes"),
677        Some(attribute_list(old)),
678        Some(attribute_list(new)),
679    );
680}
681
682/// `catalog.Name` for a declared interface, the service's dotted name for an
683/// inline shape.
684fn interface_text(interface: Option<&InterfaceRef>) -> String {
685    match interface {
686        Some(interface) if interface.inline => interface.name.clone(),
687        Some(interface) => format!("{}.{}", interface.catalog, interface.name),
688        None => String::new(),
689    }
690}
691
692/// `(primary, backup)`, as `instances` is written.
693fn instance_list(instances: &[String]) -> String {
694    format!("({})", instances.join(", "))
695}
696
697#[cfg(test)]
698mod tests {
699    use ridl_ir::v2;
700
701    use super::*;
702
703    fn component(name: &str, instances: &[&str], offers: &[&str], requires: &[&str]) -> Component {
704        Component {
705            name: name.to_string(),
706            package: "veh.topology".to_string(),
707            implicit: false,
708            external: false,
709            instances: instances
710                .iter()
711                .map(|instance| instance.to_string())
712                .collect(),
713            numbers: Vec::new(),
714            offers: offers
715                .iter()
716                .map(|service| v2::Offer {
717                    service: service.to_string(),
718                    attributes: Vec::new(),
719                    doc: String::new(),
720                    links: Vec::new(),
721                    see: Vec::new(),
722                    since: Vec::new(),
723                })
724                .collect(),
725            requires: requires
726                .iter()
727                .map(|interface| v2::Require {
728                    interface: Some(v2::InterfaceRef {
729                        catalog: "veh.adas".to_string(),
730                        name: interface.to_string(),
731                        inline: false,
732                    }),
733                    service: String::new(),
734                    producer: String::new(),
735                    attributes: Vec::new(),
736                    doc: String::new(),
737                    links: Vec::new(),
738                    see: Vec::new(),
739                    since: Vec::new(),
740                })
741                .collect(),
742            labels: Vec::new(),
743            attributes: Vec::new(),
744            doc: String::new(),
745            links: Vec::new(),
746            see: Vec::new(),
747            since: Vec::new(),
748            deprecated: None,
749        }
750    }
751
752    fn machine(name: &str, external: bool) -> v2::Machine {
753        v2::Machine {
754            name: name.to_string(),
755            external,
756            labels: Vec::new(),
757            attributes: Vec::new(),
758            doc: String::new(),
759            links: Vec::new(),
760            see: Vec::new(),
761            since: Vec::new(),
762            deprecated: None,
763        }
764    }
765
766    fn placed(component: &str, instance: &str, machine: &str) -> v2::Placement {
767        v2::Placement {
768            component: format!("veh.topology.{component}"),
769            instance: instance.to_string(),
770            machine: machine.to_string(),
771            attributes: Vec::new(),
772            sizing: None,
773        }
774    }
775
776    /// Appendix A reduced to `Cruise` and `Panel` in `Production`.
777    fn base() -> System {
778        System {
779            name: "Vehicle".to_string(),
780            package: "veh.topology".to_string(),
781            components: vec![
782                component(
783                    "Cruise",
784                    &["primary", "backup"],
785                    &["veh.adas.cruise"],
786                    &["LaneAssist"],
787                ),
788                component("Panel", &["Unit"], &[], &["CruiseControl"]),
789            ],
790            deployments: vec![Deployment {
791                name: "Production".to_string(),
792                package: "veh.topology".to_string(),
793                machines: vec![machine("AdasHpc", false), machine("Cockpit", false)],
794                placements: vec![
795                    placed("Cruise", "primary", "AdasHpc"),
796                    placed("Cruise", "backup", "Cockpit"),
797                    placed("Panel", "Unit", "Cockpit"),
798                ],
799                ..Deployment::default()
800            }],
801            ..System::default()
802        }
803    }
804
805    /// Each change as one line, `<heading>: <path>: <before> -> <after>`.
806    fn lines(changes: &[SystemChange]) -> Vec<String> {
807        changes
808            .iter()
809            .map(|change| {
810                let mut line = format!("{}: {}", heading_text(change.heading), change.path);
811                crate::push_values(&mut line, change.before.as_ref(), change.after.as_ref());
812                line
813            })
814            .collect()
815    }
816
817    fn backend(namespace: &str, key: &str, value: Option<&str>) -> v2::Attribute {
818        v2::Attribute {
819            namespace: namespace.to_string(),
820            key: key.to_string(),
821            value: value.map(|text| v2::AttributeValue {
822                kind: Some(v2::attribute_value::Kind::Scalar(text.to_string())),
823            }),
824        }
825    }
826
827    /// `base()` plus one distribution and the system's own member lines, so
828    /// that every rsdl site is present.
829    fn with_distribution() -> System {
830        let mut system = base();
831        system.members = vec![
832            v2::MemberLine {
833                component: "veh.topology.Cruise".to_string(),
834                ..Default::default()
835            },
836            v2::MemberLine {
837                component: "veh.topology.Panel".to_string(),
838                ..Default::default()
839            },
840        ];
841        system.distributions.push(v2::Distribution {
842            name: "Adas".to_string(),
843            package: "veh.topology".to_string(),
844            members: vec![v2::MemberLine {
845                component: "veh.topology.Cruise".to_string(),
846                ..Default::default()
847            }],
848            ..Default::default()
849        });
850        system
851    }
852
853    #[test]
854    fn bare_distributions_are_reported_in_both_directions() {
855        let present = with_distribution();
856        let mut absent = present.clone();
857        absent.distributions.clear();
858        // The bare member line is listed with its distribution and has no
859        // backend key to compare.
860        assert_eq!(
861            lines(&diff_systems(&absent, &present)),
862            [
863                "composition changed: veh.topology.Adas: (absent) -> distribution",
864                "composition changed: veh.topology.Adas/veh.topology.Cruise: (absent) -> member",
865            ]
866        );
867        assert_eq!(
868            lines(&diff_systems(&present, &absent)),
869            [
870                "composition changed: veh.topology.Adas: distribution -> (removed)",
871                "composition changed: veh.topology.Adas/veh.topology.Cruise: member -> (removed)",
872            ]
873        );
874    }
875
876    #[test]
877    fn added_and_removed_distributions_include_their_attributes() {
878        let mut old = with_distribution();
879        // An unchanged distribution with the same short name must not hide
880        // the changed distribution from a different package.
881        old.distributions.push(v2::Distribution {
882            name: "Adas".to_string(),
883            package: "veh.other".to_string(),
884            ..Default::default()
885        });
886        let mut new = old.clone();
887        let distribution = &mut new.distributions[0];
888        distribution.tier = v2::Tier::Platform as i32;
889        distribution.labels = vec!["QM".to_string()];
890        distribution.deprecated = Some("use Next".to_string());
891        distribution.attributes = vec![backend("sign", "key", Some("release"))];
892        let mut absent = old.clone();
893        absent
894            .distributions
895            .retain(|distribution| distribution.package != "veh.topology");
896        let added = diff_systems(&absent, &new);
897        let expected = [
898            ("veh.topology.Adas", None, Some("distribution")),
899            ("veh.topology.Adas/tier", None, Some("PLATFORM")),
900            ("veh.topology.Adas/labels", Some("()"), Some("(QM)")),
901            ("veh.topology.Adas/deprecated", None, Some("\"use Next\"")),
902            (
903                "veh.topology.Adas/attributes",
904                Some("[]"),
905                Some("[ sign.key = release ]"),
906            ),
907            (
908                "veh.topology.Adas/veh.topology.Cruise",
909                None,
910                Some("member"),
911            ),
912        ];
913        assert_eq!(added.len(), expected.len(), "{added:?}");
914        for (change, (path, before, after)) in added.iter().zip(expected) {
915            assert_eq!(change.heading, SystemHeading::CompositionChanged);
916            assert_eq!(change.path, path);
917            assert_eq!(change.before.as_deref(), before);
918            assert_eq!(change.after.as_deref(), after);
919        }
920        // The paired distribution keeps its member, so neither the
921        // distribution row nor the member row is listed.
922        assert_eq!(diff_systems(&old, &new), added[1..added.len() - 1]);
923        let removed = diff_systems(&new, &absent);
924        assert_eq!(removed.len(), added.len());
925        for (removed, added) in removed.iter().zip(&added) {
926            assert_eq!(removed.heading, added.heading);
927            assert_eq!(removed.path, added.path);
928            assert_eq!(removed.before, added.after);
929            assert_eq!(removed.after, added.before);
930        }
931    }
932
933    /// Every `Compared` row of the registry with an rsdl site is reported by
934    /// `diff_systems`, and every `NotReported` row is not. The mutation per
935    /// row is written here, so a row added to the registry without diff
936    /// support fails this test on the `panic!` arm.
937    #[test]
938    fn the_registry_rows_are_reported_as_recorded() {
939        use ridl_core::attributes::{ATTRIBUTES, AttrName, Diff, Site};
940        for row in ATTRIBUTES {
941            if !row
942                .sites
943                .iter()
944                .any(|site| !matches!(site, Site::Command | Site::Query))
945            {
946                continue;
947            }
948            let old = with_distribution();
949            let mut new = with_distribution();
950            let key = match row.name {
951                AttrName::Key(key) => key,
952                AttrName::Namespaced => "ns.key",
953            };
954            match key {
955                "instances" => new.components[0].instances = vec!["Unit".to_string()],
956                "external" => new.components[0].external = true,
957                "tier" => new.distributions[0].tier = v2::Tier::Application as i32,
958                "labels" => new.distributions[0].labels = vec!["QM".to_string()],
959                "deprecated" => new.deployments[0].deprecated = Some("use v2".to_string()),
960                "depth" => {
961                    new.deployments[0].sizing = Some(v2::Sizing {
962                        depth: Some(4),
963                        slots: None,
964                        budget: None,
965                    })
966                }
967                "slots" => {
968                    new.deployments[0].placements[0].sizing = Some(v2::Sizing {
969                        depth: None,
970                        slots: Some(4),
971                        budget: None,
972                    })
973                }
974                "budget" => {
975                    new.deployments[0].sizing = Some(v2::Sizing {
976                        depth: None,
977                        slots: None,
978                        budget: Some(4096),
979                    })
980                }
981                "ns.key" => new.deployments[0].machines[0].attributes.push(backend(
982                    "linux",
983                    "cpuset",
984                    Some("(2)"),
985                )),
986                other => panic!("registry row `{other}` has no mutation in this test"),
987            }
988            let changes = diff_systems(&old, &new);
989            match row.diff {
990                Diff::Compared(_) => assert!(!changes.is_empty(), "`{key}` must be reported"),
991                Diff::NotReported(reason) => assert!(
992                    changes.is_empty(),
993                    "`{key}` is recorded as not reported ({reason:?}) but was: {changes:?}"
994                ),
995            }
996        }
997    }
998
999    /// rsdl §14: `labels`, `deprecated`, `tier` and a backend key are listed
1000    /// under the heading of the declaration they are on, as a before-and-after
1001    /// line. Every site the registry names is exercised here: the system and
1002    /// its member lines, a component with its `offers` and `requires` lines, a
1003    /// distribution with its member lines, a deployment, a machine and a
1004    /// placement line.
1005    #[test]
1006    fn attribute_changes_are_listed_under_the_heading_of_their_site() {
1007        let old = with_distribution();
1008        let mut new = with_distribution();
1009        new.labels = vec!["QM".to_string()];
1010        new.components[0].deprecated = Some("use Cruise2".to_string());
1011        new.distributions[0].tier = v2::Tier::Platform as i32;
1012        new.members[0]
1013            .attributes
1014            .push(backend("deb", "section", Some("net")));
1015        new.components[0].requires[0]
1016            .attributes
1017            .push(backend("someip", "clientId", Some("17")));
1018        new.distributions[0].members[0]
1019            .attributes
1020            .push(backend("sign", "key", None));
1021        new.components[0].offers[0]
1022            .attributes
1023            .push(backend("someip", "serviceId", Some("4660")));
1024        new.deployments[0]
1025            .attributes
1026            .push(backend("rust", "crate", Some("\"s\"")));
1027        new.deployments[0].machines[0].labels = vec!["ASIL_B".to_string()];
1028        new.deployments[0].placements[0]
1029            .attributes
1030            .push(backend("linux", "cpuset", Some("(2)")));
1031        assert_eq!(
1032            lines(&diff_systems(&old, &new)),
1033            [
1034                "composition changed: veh.topology.Vehicle/labels: () -> (QM)",
1035                "composition changed: veh.topology.Vehicle/veh.topology.Cruise/attributes: \
1036                 [] -> [ deb.section = net ]",
1037                "composition changed: veh.topology.Cruise/deprecated: (absent) -> \"use Cruise2\"",
1038                "composition changed: veh.topology.Cruise/offers/veh.adas.cruise/attributes: \
1039                 [] -> [ someip.serviceId = 4660 ]",
1040                "composition changed: veh.topology.Cruise/requires/veh.adas.LaneAssist/attributes: \
1041                 [] -> [ someip.clientId = 17 ]",
1042                "composition changed: veh.topology.Adas/tier: (absent) -> PLATFORM",
1043                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1044                 [] -> [ sign.key ]",
1045                "placement changed: Production/attributes: [] -> [ rust.crate = \"s\" ]",
1046                "placement changed: Production/AdasHpc/labels: () -> (ASIL_B)",
1047                "placement changed: Production/veh.topology.Cruise.primary/attributes: \
1048                 [] -> [ linux.cpuset = (2) ]",
1049            ]
1050        );
1051    }
1052
1053    /// A value removed is reported, as the mirror of one added.
1054    #[test]
1055    fn an_attribute_removed_is_reported() {
1056        let mut old = with_distribution();
1057        old.components[0].deprecated = Some("use Cruise2".to_string());
1058        old.distributions[0].tier = v2::Tier::Platform as i32;
1059        let new = with_distribution();
1060        assert_eq!(
1061            lines(&diff_systems(&old, &new)),
1062            [
1063                "composition changed: veh.topology.Cruise/deprecated: \"use Cruise2\" -> (removed)",
1064                "composition changed: veh.topology.Adas/tier: PLATFORM -> (removed)",
1065            ]
1066        );
1067    }
1068
1069    /// rsdl §14: a component moved between two existing distributions is a
1070    /// composition change on each, and a member line's backend keys are
1071    /// compared with an empty side when the member is added or removed.
1072    #[test]
1073    fn a_member_moved_between_distributions_is_listed_under_composition_changed() {
1074        let member = |name: &str, attributes: Vec<v2::Attribute>| v2::MemberLine {
1075            component: format!("veh.topology.{name}"),
1076            attributes,
1077            ..Default::default()
1078        };
1079        let distribution = |name: &str, members: Vec<v2::MemberLine>| v2::Distribution {
1080            name: name.to_string(),
1081            package: "veh.topology".to_string(),
1082            members,
1083            ..Default::default()
1084        };
1085        let signed = || vec![backend("sign", "key", Some("release"))];
1086        let mut old = base();
1087        old.components
1088            .push(component("Cluster", &["Unit"], &[], &[]));
1089        old.components.push(component("Gauge", &["Unit"], &[], &[]));
1090        // Each component is in one distribution. `Gauge` stays in `Adas` and
1091        // `Cluster` stays in `Hmi` with its key unchanged, so a paired member
1092        // line is compared with its own earlier line and lists nothing.
1093        old.distributions = vec![
1094            distribution(
1095                "Adas",
1096                vec![member("Cruise", signed()), member("Gauge", Vec::new())],
1097            ),
1098            distribution("Body", vec![member("Panel", Vec::new())]),
1099            distribution("Hmi", vec![member("Cluster", signed())]),
1100        ];
1101        let mut new = old.clone();
1102        new.distributions[0].members = vec![member("Panel", signed()), member("Gauge", Vec::new())];
1103        new.distributions[1].members = vec![member("Cruise", Vec::new())];
1104        assert_eq!(
1105            lines(&diff_systems(&old, &new)),
1106            [
1107                "composition changed: veh.topology.Adas/veh.topology.Panel: (absent) -> member",
1108                "composition changed: veh.topology.Adas/veh.topology.Panel/attributes: \
1109                 [] -> [ sign.key = release ]",
1110                "composition changed: veh.topology.Adas/veh.topology.Cruise: member -> (removed)",
1111                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1112                 [ sign.key = release ] -> []",
1113                "composition changed: veh.topology.Body/veh.topology.Cruise: (absent) -> member",
1114                "composition changed: veh.topology.Body/veh.topology.Panel: member -> (removed)",
1115            ]
1116        );
1117        assert_eq!(
1118            lines(&diff_systems(&new, &old)),
1119            [
1120                "composition changed: veh.topology.Adas/veh.topology.Cruise: (absent) -> member",
1121                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1122                 [] -> [ sign.key = release ]",
1123                "composition changed: veh.topology.Adas/veh.topology.Panel: member -> (removed)",
1124                "composition changed: veh.topology.Adas/veh.topology.Panel/attributes: \
1125                 [ sign.key = release ] -> []",
1126                "composition changed: veh.topology.Body/veh.topology.Panel: (absent) -> member",
1127                "composition changed: veh.topology.Body/veh.topology.Cruise: member -> (removed)",
1128            ]
1129        );
1130
1131        // The members of an added or removed distribution are listed with it,
1132        // in the order of their lines, and a member line's keys are compared
1133        // with an empty side.
1134        let mut absent = old.clone();
1135        absent.distributions.remove(0);
1136        assert_eq!(
1137            lines(&diff_systems(&absent, &old)),
1138            [
1139                "composition changed: veh.topology.Adas: (absent) -> distribution",
1140                "composition changed: veh.topology.Adas/veh.topology.Cruise: (absent) -> member",
1141                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1142                 [] -> [ sign.key = release ]",
1143                "composition changed: veh.topology.Adas/veh.topology.Gauge: (absent) -> member",
1144            ]
1145        );
1146        assert_eq!(
1147            lines(&diff_systems(&old, &absent)),
1148            [
1149                "composition changed: veh.topology.Adas: distribution -> (removed)",
1150                "composition changed: veh.topology.Adas/veh.topology.Cruise: member -> (removed)",
1151                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1152                 [ sign.key = release ] -> []",
1153                "composition changed: veh.topology.Adas/veh.topology.Gauge: member -> (removed)",
1154            ]
1155        );
1156    }
1157
1158    /// rsdl §14: an `offers` or `requires` line on one component in both
1159    /// closures, added or removed, is listed with its backend keys compared
1160    /// with an empty side.
1161    #[test]
1162    fn an_offers_or_requires_line_added_or_removed_lists_its_keys() {
1163        let signed = || vec![backend("sign", "key", Some("release"))];
1164        let mut old = base();
1165        // The lines both sides have carry a key of their own, so that a
1166        // paired line is compared with its own earlier line and lists nothing.
1167        old.components[0].offers[0].attributes = vec![backend("sign", "key", Some("other"))];
1168        old.components[0].requires[0].attributes = vec![backend("sign", "key", Some("other"))];
1169        let mut new = old.clone();
1170        let cruise = &mut new.components[0];
1171        cruise.offers.push(v2::Offer {
1172            service: "veh.adas.brake".to_string(),
1173            attributes: signed(),
1174            ..Default::default()
1175        });
1176        cruise.requires.push(v2::Require {
1177            interface: Some(v2::InterfaceRef {
1178                catalog: "veh.adas".to_string(),
1179                name: "Brake".to_string(),
1180                inline: false,
1181            }),
1182            attributes: signed(),
1183            ..Default::default()
1184        });
1185        assert_eq!(
1186            lines(&diff_systems(&old, &new)),
1187            [
1188                "composition changed: veh.topology.Cruise/offers/veh.adas.brake: \
1189                 (absent) -> offers veh.adas.brake",
1190                "composition changed: veh.topology.Cruise/requires/veh.adas.Brake: \
1191                 (absent) -> requires veh.adas.Brake",
1192                "composition changed: veh.topology.Cruise/offers/veh.adas.brake/attributes: \
1193                 [] -> [ sign.key = release ]",
1194                "composition changed: veh.topology.Cruise/requires/veh.adas.Brake/attributes: \
1195                 [] -> [ sign.key = release ]",
1196            ]
1197        );
1198        assert_eq!(
1199            lines(&diff_systems(&new, &old)),
1200            [
1201                "composition changed: veh.topology.Cruise/offers/veh.adas.brake: \
1202                 offers veh.adas.brake -> (removed)",
1203                "composition changed: veh.topology.Cruise/requires/veh.adas.Brake: \
1204                 requires veh.adas.Brake -> (removed)",
1205                "composition changed: veh.topology.Cruise/offers/veh.adas.brake/attributes: \
1206                 [ sign.key = release ] -> []",
1207                "composition changed: veh.topology.Cruise/requires/veh.adas.Brake/attributes: \
1208                 [ sign.key = release ] -> []",
1209            ]
1210        );
1211
1212        // The lines of a component added to the closure are not listed one by
1213        // one: the component is listed, and its keys are not compared.
1214        let mut grown = old.clone();
1215        let mut gauge = component("Gauge", &["Unit"], &["veh.adas.gauge"], &["LaneAssist"]);
1216        gauge.offers[0].attributes = signed();
1217        gauge.requires[0].attributes = signed();
1218        grown.components.push(gauge);
1219        assert_eq!(
1220            lines(&diff_systems(&old, &grown)),
1221            ["composition changed: veh.topology.Gauge: (absent) -> in the closure"]
1222        );
1223        assert_eq!(
1224            lines(&diff_systems(&grown, &old)),
1225            ["composition changed: veh.topology.Gauge: in the closure -> (removed)"]
1226        );
1227    }
1228
1229    /// rsdl §14: a `system` member line added or removed lists its backend
1230    /// keys compared with an empty side, a line with no keys lists none, and
1231    /// a line on both sides is compared with its own earlier line.
1232    #[test]
1233    fn a_system_member_line_added_or_removed_lists_its_keys() {
1234        let member = |name: &str, attributes: Vec<v2::Attribute>| v2::MemberLine {
1235            component: format!("veh.topology.{name}"),
1236            attributes,
1237            ..Default::default()
1238        };
1239        let mut old = base();
1240        old.members = vec![member(
1241            "Cruise",
1242            vec![backend("sign", "key", Some("other"))],
1243        )];
1244        let mut new = old.clone();
1245        new.members = vec![
1246            member("Cruise", vec![backend("sign", "key", Some("other"))]),
1247            member("Panel", vec![backend("sign", "key", Some("release"))]),
1248            member("Gauge", Vec::new()),
1249        ];
1250        assert_eq!(
1251            lines(&diff_systems(&old, &new)),
1252            [
1253                "composition changed: veh.topology.Vehicle/veh.topology.Panel/attributes: \
1254              [] -> [ sign.key = release ]"
1255            ]
1256        );
1257        assert_eq!(
1258            lines(&diff_systems(&new, &old)),
1259            [
1260                "composition changed: veh.topology.Vehicle/veh.topology.Panel/attributes: \
1261              [ sign.key = release ] -> []"
1262            ]
1263        );
1264    }
1265
1266    /// A system whose components hold the given `(component, instance,
1267    /// number, provisional)` numbers; the component is a qualified name.
1268    fn numbered(entries: &[(&str, &str, i32, bool)]) -> System {
1269        let mut system = base();
1270        system.components.clear();
1271        for (qualified, instance, number, provisional) in entries {
1272            let (package, name) = qualified.rsplit_once('.').expect("a qualified name");
1273            let at = system
1274                .components
1275                .iter()
1276                .position(|c| c.qualified_name() == *qualified);
1277            let at = at.unwrap_or_else(|| {
1278                let mut made = component(name, &[], &[], &[]);
1279                made.package = package.to_string();
1280                system.components.push(made);
1281                system.components.len() - 1
1282            });
1283            system.components[at].numbers.push(v2::InstanceNumber {
1284                instance: instance.to_string(),
1285                number: *number,
1286                provisional: *provisional,
1287            });
1288        }
1289        system
1290    }
1291
1292    fn listed(changes: &[SystemChange]) -> Vec<&SystemChange> {
1293        changes
1294            .iter()
1295            .filter(|c| c.heading == SystemHeading::InstanceNumberChanged)
1296            .collect()
1297    }
1298
1299    #[test]
1300    fn a_changed_locked_number_is_listed() {
1301        let changes = diff_systems(
1302            &numbered(&[("veh.C", "a", 1, false)]),
1303            &numbered(&[("veh.C", "a", 2, false)]),
1304        );
1305        let listed = listed(&changes);
1306        assert_eq!(listed.len(), 1);
1307        assert_eq!(listed[0].path, "veh.C/a");
1308        assert_eq!(
1309            (listed[0].before.as_deref(), listed[0].after.as_deref()),
1310            (Some("1"), Some("2"))
1311        );
1312    }
1313
1314    #[test]
1315    fn a_number_given_to_another_instance_is_listed() {
1316        let changes = diff_systems(
1317            &numbered(&[("veh.C", "a", 1, false)]),
1318            &numbered(&[("veh.C", "a", 2, false), ("veh.C", "b", 1, false)]),
1319        );
1320        let listed = listed(&changes);
1321        assert_eq!(listed.len(), 2);
1322        assert!(
1323            listed
1324                .iter()
1325                .any(|c| c.path == "veh.C/b" && c.before.as_deref() == Some("1 (veh.C/a)"))
1326        );
1327    }
1328
1329    #[test]
1330    fn a_renamed_instance_that_keeps_its_number_is_not_listed() {
1331        let changes = diff_systems(
1332            &numbered(&[("veh.C", "a", 1, false)]),
1333            &numbered(&[("veh.C", "b", 1, false)]),
1334        );
1335        assert!(listed(&changes).is_empty());
1336    }
1337
1338    #[test]
1339    fn a_provisional_old_number_is_not_listed() {
1340        let changes = diff_systems(
1341            &numbered(&[("veh.C", "a", 1, true)]),
1342            &numbered(&[("veh.C", "a", 2, false)]),
1343        );
1344        assert!(listed(&changes).is_empty());
1345    }
1346
1347    /// A locked number that both sides hold for the same key is not a
1348    /// change: a lock-bearing diff with no renumbering lists nothing.
1349    #[test]
1350    fn an_unchanged_locked_number_is_not_listed() {
1351        let both = numbered(&[("veh.C", "a", 1, false), ("veh.C", "b", 2, false)]);
1352        assert!(listed(&diff_systems(&both, &both)).is_empty());
1353    }
1354
1355    /// A new key that takes a number its old holder held only provisionally
1356    /// is not listed, though the old holder is still present: the old number
1357    /// was never part of the lock.
1358    #[test]
1359    fn a_new_key_on_a_provisional_old_number_is_not_listed() {
1360        let changes = diff_systems(
1361            &numbered(&[("veh.C", "a", 1, true)]),
1362            &numbered(&[("veh.C", "a", 2, false), ("veh.C", "b", 1, false)]),
1363        );
1364        assert!(listed(&changes).is_empty());
1365    }
1366
1367    #[test]
1368    fn an_unchanged_system_has_no_system_change() {
1369        assert!(diff_systems(&base(), &base()).is_empty());
1370    }
1371
1372    /// The region map is not compared, so a change to a region's catalog hash
1373    /// lists no system change.
1374    #[test]
1375    fn a_region_hash_change_is_not_a_system_change() {
1376        let region = |hash: u8| v2::Region {
1377            catalog: "veh.adas".to_string(),
1378            interfaces: Vec::new(),
1379            hash: vec![hash; 32],
1380        };
1381        let old = System {
1382            regions: vec![region(1)],
1383            ..base()
1384        };
1385        let new = System {
1386            regions: vec![region(2)],
1387            ..base()
1388        };
1389        assert!(diff_systems(&old, &new).is_empty());
1390    }
1391
1392    /// A doc edit is neither a placement nor a composition change, so the
1393    /// doc fields of every system message are ignored (ADR-0026).
1394    #[test]
1395    fn system_doc_changes_are_not_reported() {
1396        let see = v2::DocLink {
1397            text: "Other".to_string(),
1398            target: "veh.topology.Other".to_string(),
1399            ..Default::default()
1400        };
1401        macro_rules! document {
1402            ($carrier:expr) => {{
1403                let carrier = &mut $carrier;
1404                carrier.doc = "documented".to_string();
1405                carrier.links.push(see.clone());
1406                carrier.see.push(see.clone());
1407                carrier.since.push("1.2".to_string());
1408            }};
1409        }
1410        let mut old = base();
1411        old.members.push(v2::MemberLine {
1412            component: "veh.topology.Cruise".to_string(),
1413            ..Default::default()
1414        });
1415        old.distributions.push(v2::Distribution {
1416            name: "Adas".to_string(),
1417            package: "veh.topology".to_string(),
1418            members: old.members.clone(),
1419            ..Default::default()
1420        });
1421        let mut new = old.clone();
1422        document!(new);
1423        document!(new.members[0]);
1424        document!(new.components[0]);
1425        document!(new.components[0].offers[0]);
1426        document!(new.components[0].requires[0]);
1427        document!(new.distributions[0]);
1428        document!(new.distributions[0].members[0]);
1429        let deployment = &mut new.deployments[0];
1430        deployment.doc = "documented".to_string();
1431        deployment.doc_links.push(see.clone());
1432        deployment.see.push(see.clone());
1433        deployment.since.push("1.2".to_string());
1434        document!(new.deployments[0].machines[0]);
1435        assert_ne!(old, new);
1436        assert!(diff_systems(&old, &new).is_empty());
1437    }
1438
1439    /// A changed sizing value, on the deployment or on a placement, is
1440    /// neither a placement nor a composition change (rsdl §14).
1441    #[test]
1442    fn system_sizing_changes_are_not_reported() {
1443        let sized = |depth: u32, slots: u32, budget: u64| v2::Sizing {
1444            depth: Some(depth),
1445            slots: Some(slots),
1446            budget: Some(budget),
1447        };
1448        let mut old = base();
1449        old.deployments[0].sizing = Some(sized(3, 16, 4096));
1450        old.deployments[0].placements[0].sizing = Some(sized(3, 16, 4096));
1451        let mut new = old.clone();
1452        new.deployments[0].sizing = Some(sized(300, 64, 65536));
1453        new.deployments[0].placements[0].sizing = Some(sized(300, 64, 65536));
1454        assert_ne!(old, new);
1455        assert!(diff_systems(&old, &new).is_empty());
1456
1457        // Declaring a value where none was, and removing one, are not
1458        // reported either.
1459        assert!(diff_systems(&base(), &new).is_empty());
1460        assert!(diff_systems(&new, &base()).is_empty());
1461    }
1462
1463    /// A system change is rendered under its heading, after the contract
1464    /// changes and with no verdict, and leaves the report verdict alone; a
1465    /// system on one side only is not compared (rsdl §14).
1466    #[test]
1467    fn system_changes_render_under_their_headings_with_no_verdict() {
1468        let old = base();
1469        let mut new = base();
1470        new.deployments[0].placements[1].machine = "AdasHpc".to_string();
1471        new.components[1].external = true;
1472
1473        let report = crate::diff_workspaces(&[], Some(&old), &[], Some(&new), &[]);
1474        assert_eq!(report.verdict, crate::Verdict::Identical);
1475        assert_eq!(
1476            crate::render_text(&report),
1477            "identical\n\
1478             placement changed\n\
1479             \x20 Production/veh.topology.Cruise.backup: Cockpit -> AdasHpc\n\
1480             composition changed\n\
1481             \x20 veh.topology.Panel/external: false -> true\n"
1482        );
1483        let json: serde_json::Value =
1484            serde_json::from_str(&crate::render_json(&report)).expect("the report is JSON");
1485        assert_eq!(
1486            json["placement_changed"],
1487            serde_json::json!([{
1488                "path": "Production/veh.topology.Cruise.backup",
1489                "before": "Cockpit",
1490                "after": "AdasHpc"
1491            }])
1492        );
1493        assert_eq!(json["composition_changed"][0]["after"], "true");
1494
1495        let one_side = crate::diff_workspaces(&[], None, &[], Some(&new), &[]);
1496        assert!(one_side.system.is_empty());
1497        let json: serde_json::Value =
1498            serde_json::from_str(&crate::render_json(&one_side)).expect("the report is JSON");
1499        assert_eq!(
1500            json,
1501            serde_json::json!({ "verdict": "identical", "changes": [] })
1502        );
1503    }
1504
1505    /// rsdl §14: an instance moved to another machine, a machine added,
1506    /// removed or made `external`, and a deployment added or removed are
1507    /// placement changes.
1508    #[test]
1509    fn a_deployment_change_is_listed_under_placement_changed() {
1510        let old = base();
1511        let mut new = base();
1512        new.deployments[0].placements[1].machine = "AdasHpc".to_string();
1513        new.deployments[0].machines[1].external = true;
1514        new.deployments[0].machines.push(machine("Cloud", true));
1515        new.deployments.push(Deployment {
1516            name: "Bench".to_string(),
1517            ..Deployment::default()
1518        });
1519        assert_eq!(
1520            lines(&diff_systems(&old, &new)),
1521            [
1522                "placement changed: Production/Cockpit/external: false -> true",
1523                "placement changed: Production/Cloud: (absent) -> machine",
1524                "placement changed: Production/veh.topology.Cruise.backup: Cockpit -> AdasHpc",
1525                "placement changed: Bench: (absent) -> deployment",
1526            ]
1527        );
1528        assert_eq!(
1529            lines(&diff_systems(&new, &old)),
1530            [
1531                "placement changed: Production/Cockpit/external: true -> false",
1532                "placement changed: Production/Cloud: machine -> (removed)",
1533                "placement changed: Production/veh.topology.Cruise.backup: AdasHpc -> Cockpit",
1534                "placement changed: Bench: deployment -> (removed)",
1535            ]
1536        );
1537    }
1538
1539    /// rsdl §14: a component added to or removed from the system, an `offers`
1540    /// or `requires` line added or removed, `instances` changed, and a
1541    /// component made `external` are composition changes.
1542    #[test]
1543    fn a_closure_or_line_change_is_listed_under_composition_changed() {
1544        let old = base();
1545        let mut new = base();
1546        new.components[0].instances = vec!["Unit".to_string()];
1547        new.components[0].requires.clear();
1548        new.components[1].external = true;
1549        new.components[1].offers.push(v2::Offer {
1550            service: "veh.hmi.panel".to_string(),
1551            attributes: Vec::new(),
1552            doc: String::new(),
1553            links: Vec::new(),
1554            see: Vec::new(),
1555            since: Vec::new(),
1556        });
1557        new.components
1558            .push(component("Lane", &["Unit"], &["veh.adas.lane"], &[]));
1559        assert_eq!(
1560            lines(&diff_systems(&old, &new)),
1561            [
1562                "composition changed: veh.topology.Cruise/requires/veh.adas.LaneAssist: \
1563                 requires veh.adas.LaneAssist -> (removed)",
1564                "composition changed: veh.topology.Cruise/instances: (primary, backup) -> (Unit)",
1565                "composition changed: veh.topology.Panel/offers/veh.hmi.panel: \
1566                 (absent) -> offers veh.hmi.panel",
1567                "composition changed: veh.topology.Panel/external: false -> true",
1568                "composition changed: veh.topology.Lane: (absent) -> in the closure",
1569            ]
1570        );
1571        assert_eq!(
1572            lines(&diff_systems(&new, &old)).last().map(String::as_str),
1573            Some("composition changed: veh.topology.Lane: in the closure -> (removed)")
1574        );
1575    }
1576}