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                "file" => new.deployments[0].file = Some("production-v2".to_string()),
961                "depth" => {
962                    new.deployments[0].sizing = Some(v2::Sizing {
963                        depth: Some(4),
964                        slots: None,
965                        budget: None,
966                    })
967                }
968                "slots" => {
969                    new.deployments[0].placements[0].sizing = Some(v2::Sizing {
970                        depth: None,
971                        slots: Some(4),
972                        budget: None,
973                    })
974                }
975                "budget" => {
976                    new.deployments[0].sizing = Some(v2::Sizing {
977                        depth: None,
978                        slots: None,
979                        budget: Some(4096),
980                    })
981                }
982                "ns.key" => new.deployments[0].machines[0].attributes.push(backend(
983                    "linux",
984                    "cpuset",
985                    Some("(2)"),
986                )),
987                other => panic!("registry row `{other}` has no mutation in this test"),
988            }
989            let changes = diff_systems(&old, &new);
990            match row.diff {
991                Diff::Compared(_) => assert!(!changes.is_empty(), "`{key}` must be reported"),
992                Diff::NotReported(reason) => assert!(
993                    changes.is_empty(),
994                    "`{key}` is recorded as not reported ({reason:?}) but was: {changes:?}"
995                ),
996            }
997        }
998    }
999
1000    /// rsdl §14: `labels`, `deprecated`, `tier` and a backend key are listed
1001    /// under the heading of the declaration they are on, as a before-and-after
1002    /// line. Every site the registry names is exercised here: the system and
1003    /// its member lines, a component with its `offers` and `requires` lines, a
1004    /// distribution with its member lines, a deployment, a machine and a
1005    /// placement line.
1006    #[test]
1007    fn attribute_changes_are_listed_under_the_heading_of_their_site() {
1008        let old = with_distribution();
1009        let mut new = with_distribution();
1010        new.labels = vec!["QM".to_string()];
1011        new.components[0].deprecated = Some("use Cruise2".to_string());
1012        new.distributions[0].tier = v2::Tier::Platform as i32;
1013        new.members[0]
1014            .attributes
1015            .push(backend("deb", "section", Some("net")));
1016        new.components[0].requires[0]
1017            .attributes
1018            .push(backend("someip", "clientId", Some("17")));
1019        new.distributions[0].members[0]
1020            .attributes
1021            .push(backend("sign", "key", None));
1022        new.components[0].offers[0]
1023            .attributes
1024            .push(backend("someip", "serviceId", Some("4660")));
1025        new.deployments[0]
1026            .attributes
1027            .push(backend("rust", "crate", Some("\"s\"")));
1028        new.deployments[0].machines[0].labels = vec!["ASIL_B".to_string()];
1029        new.deployments[0].placements[0]
1030            .attributes
1031            .push(backend("linux", "cpuset", Some("(2)")));
1032        assert_eq!(
1033            lines(&diff_systems(&old, &new)),
1034            [
1035                "composition changed: veh.topology.Vehicle/labels: () -> (QM)",
1036                "composition changed: veh.topology.Vehicle/veh.topology.Cruise/attributes: \
1037                 [] -> [ deb.section = net ]",
1038                "composition changed: veh.topology.Cruise/deprecated: (absent) -> \"use Cruise2\"",
1039                "composition changed: veh.topology.Cruise/offers/veh.adas.cruise/attributes: \
1040                 [] -> [ someip.serviceId = 4660 ]",
1041                "composition changed: veh.topology.Cruise/requires/veh.adas.LaneAssist/attributes: \
1042                 [] -> [ someip.clientId = 17 ]",
1043                "composition changed: veh.topology.Adas/tier: (absent) -> PLATFORM",
1044                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1045                 [] -> [ sign.key ]",
1046                "placement changed: Production/attributes: [] -> [ rust.crate = \"s\" ]",
1047                "placement changed: Production/AdasHpc/labels: () -> (ASIL_B)",
1048                "placement changed: Production/veh.topology.Cruise.primary/attributes: \
1049                 [] -> [ linux.cpuset = (2) ]",
1050            ]
1051        );
1052    }
1053
1054    /// A value removed is reported, as the mirror of one added.
1055    #[test]
1056    fn an_attribute_removed_is_reported() {
1057        let mut old = with_distribution();
1058        old.components[0].deprecated = Some("use Cruise2".to_string());
1059        old.distributions[0].tier = v2::Tier::Platform as i32;
1060        let new = with_distribution();
1061        assert_eq!(
1062            lines(&diff_systems(&old, &new)),
1063            [
1064                "composition changed: veh.topology.Cruise/deprecated: \"use Cruise2\" -> (removed)",
1065                "composition changed: veh.topology.Adas/tier: PLATFORM -> (removed)",
1066            ]
1067        );
1068    }
1069
1070    /// rsdl §14: a component moved between two existing distributions is a
1071    /// composition change on each, and a member line's backend keys are
1072    /// compared with an empty side when the member is added or removed.
1073    #[test]
1074    fn a_member_moved_between_distributions_is_listed_under_composition_changed() {
1075        let member = |name: &str, attributes: Vec<v2::Attribute>| v2::MemberLine {
1076            component: format!("veh.topology.{name}"),
1077            attributes,
1078            ..Default::default()
1079        };
1080        let distribution = |name: &str, members: Vec<v2::MemberLine>| v2::Distribution {
1081            name: name.to_string(),
1082            package: "veh.topology".to_string(),
1083            members,
1084            ..Default::default()
1085        };
1086        let signed = || vec![backend("sign", "key", Some("release"))];
1087        let mut old = base();
1088        old.components
1089            .push(component("Cluster", &["Unit"], &[], &[]));
1090        old.components.push(component("Gauge", &["Unit"], &[], &[]));
1091        // Each component is in one distribution. `Gauge` stays in `Adas` and
1092        // `Cluster` stays in `Hmi` with its key unchanged, so a paired member
1093        // line is compared with its own earlier line and lists nothing.
1094        old.distributions = vec![
1095            distribution(
1096                "Adas",
1097                vec![member("Cruise", signed()), member("Gauge", Vec::new())],
1098            ),
1099            distribution("Body", vec![member("Panel", Vec::new())]),
1100            distribution("Hmi", vec![member("Cluster", signed())]),
1101        ];
1102        let mut new = old.clone();
1103        new.distributions[0].members = vec![member("Panel", signed()), member("Gauge", Vec::new())];
1104        new.distributions[1].members = vec![member("Cruise", Vec::new())];
1105        assert_eq!(
1106            lines(&diff_systems(&old, &new)),
1107            [
1108                "composition changed: veh.topology.Adas/veh.topology.Panel: (absent) -> member",
1109                "composition changed: veh.topology.Adas/veh.topology.Panel/attributes: \
1110                 [] -> [ sign.key = release ]",
1111                "composition changed: veh.topology.Adas/veh.topology.Cruise: member -> (removed)",
1112                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1113                 [ sign.key = release ] -> []",
1114                "composition changed: veh.topology.Body/veh.topology.Cruise: (absent) -> member",
1115                "composition changed: veh.topology.Body/veh.topology.Panel: member -> (removed)",
1116            ]
1117        );
1118        assert_eq!(
1119            lines(&diff_systems(&new, &old)),
1120            [
1121                "composition changed: veh.topology.Adas/veh.topology.Cruise: (absent) -> member",
1122                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1123                 [] -> [ sign.key = release ]",
1124                "composition changed: veh.topology.Adas/veh.topology.Panel: member -> (removed)",
1125                "composition changed: veh.topology.Adas/veh.topology.Panel/attributes: \
1126                 [ sign.key = release ] -> []",
1127                "composition changed: veh.topology.Body/veh.topology.Panel: (absent) -> member",
1128                "composition changed: veh.topology.Body/veh.topology.Cruise: member -> (removed)",
1129            ]
1130        );
1131
1132        // The members of an added or removed distribution are listed with it,
1133        // in the order of their lines, and a member line's keys are compared
1134        // with an empty side.
1135        let mut absent = old.clone();
1136        absent.distributions.remove(0);
1137        assert_eq!(
1138            lines(&diff_systems(&absent, &old)),
1139            [
1140                "composition changed: veh.topology.Adas: (absent) -> distribution",
1141                "composition changed: veh.topology.Adas/veh.topology.Cruise: (absent) -> member",
1142                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1143                 [] -> [ sign.key = release ]",
1144                "composition changed: veh.topology.Adas/veh.topology.Gauge: (absent) -> member",
1145            ]
1146        );
1147        assert_eq!(
1148            lines(&diff_systems(&old, &absent)),
1149            [
1150                "composition changed: veh.topology.Adas: distribution -> (removed)",
1151                "composition changed: veh.topology.Adas/veh.topology.Cruise: member -> (removed)",
1152                "composition changed: veh.topology.Adas/veh.topology.Cruise/attributes: \
1153                 [ sign.key = release ] -> []",
1154                "composition changed: veh.topology.Adas/veh.topology.Gauge: member -> (removed)",
1155            ]
1156        );
1157    }
1158
1159    /// rsdl §14: an `offers` or `requires` line on one component in both
1160    /// closures, added or removed, is listed with its backend keys compared
1161    /// with an empty side.
1162    #[test]
1163    fn an_offers_or_requires_line_added_or_removed_lists_its_keys() {
1164        let signed = || vec![backend("sign", "key", Some("release"))];
1165        let mut old = base();
1166        // The lines both sides have carry a key of their own, so that a
1167        // paired line is compared with its own earlier line and lists nothing.
1168        old.components[0].offers[0].attributes = vec![backend("sign", "key", Some("other"))];
1169        old.components[0].requires[0].attributes = vec![backend("sign", "key", Some("other"))];
1170        let mut new = old.clone();
1171        let cruise = &mut new.components[0];
1172        cruise.offers.push(v2::Offer {
1173            service: "veh.adas.brake".to_string(),
1174            attributes: signed(),
1175            ..Default::default()
1176        });
1177        cruise.requires.push(v2::Require {
1178            interface: Some(v2::InterfaceRef {
1179                catalog: "veh.adas".to_string(),
1180                name: "Brake".to_string(),
1181                inline: false,
1182            }),
1183            attributes: signed(),
1184            ..Default::default()
1185        });
1186        assert_eq!(
1187            lines(&diff_systems(&old, &new)),
1188            [
1189                "composition changed: veh.topology.Cruise/offers/veh.adas.brake: \
1190                 (absent) -> offers veh.adas.brake",
1191                "composition changed: veh.topology.Cruise/requires/veh.adas.Brake: \
1192                 (absent) -> requires veh.adas.Brake",
1193                "composition changed: veh.topology.Cruise/offers/veh.adas.brake/attributes: \
1194                 [] -> [ sign.key = release ]",
1195                "composition changed: veh.topology.Cruise/requires/veh.adas.Brake/attributes: \
1196                 [] -> [ sign.key = release ]",
1197            ]
1198        );
1199        assert_eq!(
1200            lines(&diff_systems(&new, &old)),
1201            [
1202                "composition changed: veh.topology.Cruise/offers/veh.adas.brake: \
1203                 offers veh.adas.brake -> (removed)",
1204                "composition changed: veh.topology.Cruise/requires/veh.adas.Brake: \
1205                 requires veh.adas.Brake -> (removed)",
1206                "composition changed: veh.topology.Cruise/offers/veh.adas.brake/attributes: \
1207                 [ sign.key = release ] -> []",
1208                "composition changed: veh.topology.Cruise/requires/veh.adas.Brake/attributes: \
1209                 [ sign.key = release ] -> []",
1210            ]
1211        );
1212
1213        // The lines of a component added to the closure are not listed one by
1214        // one: the component is listed, and its keys are not compared.
1215        let mut grown = old.clone();
1216        let mut gauge = component("Gauge", &["Unit"], &["veh.adas.gauge"], &["LaneAssist"]);
1217        gauge.offers[0].attributes = signed();
1218        gauge.requires[0].attributes = signed();
1219        grown.components.push(gauge);
1220        assert_eq!(
1221            lines(&diff_systems(&old, &grown)),
1222            ["composition changed: veh.topology.Gauge: (absent) -> in the closure"]
1223        );
1224        assert_eq!(
1225            lines(&diff_systems(&grown, &old)),
1226            ["composition changed: veh.topology.Gauge: in the closure -> (removed)"]
1227        );
1228    }
1229
1230    /// rsdl §14: a `system` member line added or removed lists its backend
1231    /// keys compared with an empty side, a line with no keys lists none, and
1232    /// a line on both sides is compared with its own earlier line.
1233    #[test]
1234    fn a_system_member_line_added_or_removed_lists_its_keys() {
1235        let member = |name: &str, attributes: Vec<v2::Attribute>| v2::MemberLine {
1236            component: format!("veh.topology.{name}"),
1237            attributes,
1238            ..Default::default()
1239        };
1240        let mut old = base();
1241        old.members = vec![member(
1242            "Cruise",
1243            vec![backend("sign", "key", Some("other"))],
1244        )];
1245        let mut new = old.clone();
1246        new.members = vec![
1247            member("Cruise", vec![backend("sign", "key", Some("other"))]),
1248            member("Panel", vec![backend("sign", "key", Some("release"))]),
1249            member("Gauge", Vec::new()),
1250        ];
1251        assert_eq!(
1252            lines(&diff_systems(&old, &new)),
1253            [
1254                "composition changed: veh.topology.Vehicle/veh.topology.Panel/attributes: \
1255              [] -> [ sign.key = release ]"
1256            ]
1257        );
1258        assert_eq!(
1259            lines(&diff_systems(&new, &old)),
1260            [
1261                "composition changed: veh.topology.Vehicle/veh.topology.Panel/attributes: \
1262              [ sign.key = release ] -> []"
1263            ]
1264        );
1265    }
1266
1267    /// A system whose components hold the given `(component, instance,
1268    /// number, provisional)` numbers; the component is a qualified name.
1269    fn numbered(entries: &[(&str, &str, i32, bool)]) -> System {
1270        let mut system = base();
1271        system.components.clear();
1272        for (qualified, instance, number, provisional) in entries {
1273            let (package, name) = qualified.rsplit_once('.').expect("a qualified name");
1274            let at = system
1275                .components
1276                .iter()
1277                .position(|c| c.qualified_name() == *qualified);
1278            let at = at.unwrap_or_else(|| {
1279                let mut made = component(name, &[], &[], &[]);
1280                made.package = package.to_string();
1281                system.components.push(made);
1282                system.components.len() - 1
1283            });
1284            system.components[at].numbers.push(v2::InstanceNumber {
1285                instance: instance.to_string(),
1286                number: *number,
1287                provisional: *provisional,
1288            });
1289        }
1290        system
1291    }
1292
1293    fn listed(changes: &[SystemChange]) -> Vec<&SystemChange> {
1294        changes
1295            .iter()
1296            .filter(|c| c.heading == SystemHeading::InstanceNumberChanged)
1297            .collect()
1298    }
1299
1300    #[test]
1301    fn a_changed_locked_number_is_listed() {
1302        let changes = diff_systems(
1303            &numbered(&[("veh.C", "a", 1, false)]),
1304            &numbered(&[("veh.C", "a", 2, false)]),
1305        );
1306        let listed = listed(&changes);
1307        assert_eq!(listed.len(), 1);
1308        assert_eq!(listed[0].path, "veh.C/a");
1309        assert_eq!(
1310            (listed[0].before.as_deref(), listed[0].after.as_deref()),
1311            (Some("1"), Some("2"))
1312        );
1313    }
1314
1315    #[test]
1316    fn a_number_given_to_another_instance_is_listed() {
1317        let changes = diff_systems(
1318            &numbered(&[("veh.C", "a", 1, false)]),
1319            &numbered(&[("veh.C", "a", 2, false), ("veh.C", "b", 1, false)]),
1320        );
1321        let listed = listed(&changes);
1322        assert_eq!(listed.len(), 2);
1323        assert!(
1324            listed
1325                .iter()
1326                .any(|c| c.path == "veh.C/b" && c.before.as_deref() == Some("1 (veh.C/a)"))
1327        );
1328    }
1329
1330    #[test]
1331    fn a_renamed_instance_that_keeps_its_number_is_not_listed() {
1332        let changes = diff_systems(
1333            &numbered(&[("veh.C", "a", 1, false)]),
1334            &numbered(&[("veh.C", "b", 1, false)]),
1335        );
1336        assert!(listed(&changes).is_empty());
1337    }
1338
1339    #[test]
1340    fn a_provisional_old_number_is_not_listed() {
1341        let changes = diff_systems(
1342            &numbered(&[("veh.C", "a", 1, true)]),
1343            &numbered(&[("veh.C", "a", 2, false)]),
1344        );
1345        assert!(listed(&changes).is_empty());
1346    }
1347
1348    /// A locked number that both sides hold for the same key is not a
1349    /// change: a lock-bearing diff with no renumbering lists nothing.
1350    #[test]
1351    fn an_unchanged_locked_number_is_not_listed() {
1352        let both = numbered(&[("veh.C", "a", 1, false), ("veh.C", "b", 2, false)]);
1353        assert!(listed(&diff_systems(&both, &both)).is_empty());
1354    }
1355
1356    /// A new key that takes a number its old holder held only provisionally
1357    /// is not listed, though the old holder is still present: the old number
1358    /// was never part of the lock.
1359    #[test]
1360    fn a_new_key_on_a_provisional_old_number_is_not_listed() {
1361        let changes = diff_systems(
1362            &numbered(&[("veh.C", "a", 1, true)]),
1363            &numbered(&[("veh.C", "a", 2, false), ("veh.C", "b", 1, false)]),
1364        );
1365        assert!(listed(&changes).is_empty());
1366    }
1367
1368    #[test]
1369    fn an_unchanged_system_has_no_system_change() {
1370        assert!(diff_systems(&base(), &base()).is_empty());
1371    }
1372
1373    /// The region map is not compared, so a change to a region's catalog hash
1374    /// lists no system change.
1375    #[test]
1376    fn a_region_hash_change_is_not_a_system_change() {
1377        let region = |hash: u8| v2::Region {
1378            catalog: "veh.adas".to_string(),
1379            interfaces: Vec::new(),
1380            hash: vec![hash; 32],
1381        };
1382        let old = System {
1383            regions: vec![region(1)],
1384            ..base()
1385        };
1386        let new = System {
1387            regions: vec![region(2)],
1388            ..base()
1389        };
1390        assert!(diff_systems(&old, &new).is_empty());
1391    }
1392
1393    /// A doc edit is neither a placement nor a composition change, so the
1394    /// doc fields of every system message are ignored (ADR-0026).
1395    #[test]
1396    fn system_doc_changes_are_not_reported() {
1397        let see = v2::DocLink {
1398            text: "Other".to_string(),
1399            target: "veh.topology.Other".to_string(),
1400            ..Default::default()
1401        };
1402        macro_rules! document {
1403            ($carrier:expr) => {{
1404                let carrier = &mut $carrier;
1405                carrier.doc = "documented".to_string();
1406                carrier.links.push(see.clone());
1407                carrier.see.push(see.clone());
1408                carrier.since.push("1.2".to_string());
1409            }};
1410        }
1411        let mut old = base();
1412        old.members.push(v2::MemberLine {
1413            component: "veh.topology.Cruise".to_string(),
1414            ..Default::default()
1415        });
1416        old.distributions.push(v2::Distribution {
1417            name: "Adas".to_string(),
1418            package: "veh.topology".to_string(),
1419            members: old.members.clone(),
1420            ..Default::default()
1421        });
1422        let mut new = old.clone();
1423        document!(new);
1424        document!(new.members[0]);
1425        document!(new.components[0]);
1426        document!(new.components[0].offers[0]);
1427        document!(new.components[0].requires[0]);
1428        document!(new.distributions[0]);
1429        document!(new.distributions[0].members[0]);
1430        let deployment = &mut new.deployments[0];
1431        deployment.doc = "documented".to_string();
1432        deployment.doc_links.push(see.clone());
1433        deployment.see.push(see.clone());
1434        deployment.since.push("1.2".to_string());
1435        document!(new.deployments[0].machines[0]);
1436        assert_ne!(old, new);
1437        assert!(diff_systems(&old, &new).is_empty());
1438    }
1439
1440    /// A changed sizing value, on the deployment or on a placement, is
1441    /// neither a placement nor a composition change (rsdl §14).
1442    #[test]
1443    fn system_sizing_changes_are_not_reported() {
1444        let sized = |depth: u32, slots: u32, budget: u64| v2::Sizing {
1445            depth: Some(depth),
1446            slots: Some(slots),
1447            budget: Some(budget),
1448        };
1449        let mut old = base();
1450        old.deployments[0].sizing = Some(sized(3, 16, 4096));
1451        old.deployments[0].placements[0].sizing = Some(sized(3, 16, 4096));
1452        let mut new = old.clone();
1453        new.deployments[0].sizing = Some(sized(300, 64, 65536));
1454        new.deployments[0].placements[0].sizing = Some(sized(300, 64, 65536));
1455        assert_ne!(old, new);
1456        assert!(diff_systems(&old, &new).is_empty());
1457
1458        // Declaring a value where none was, and removing one, are not
1459        // reported either.
1460        assert!(diff_systems(&base(), &new).is_empty());
1461        assert!(diff_systems(&new, &base()).is_empty());
1462    }
1463
1464    /// A system change is rendered under its heading, after the contract
1465    /// changes and with no verdict, and leaves the report verdict alone; a
1466    /// system on one side only is not compared (rsdl §14).
1467    #[test]
1468    fn system_changes_render_under_their_headings_with_no_verdict() {
1469        let old = base();
1470        let mut new = base();
1471        new.deployments[0].placements[1].machine = "AdasHpc".to_string();
1472        new.components[1].external = true;
1473
1474        let report = crate::diff_workspaces(&[], Some(&old), &[], Some(&new), &[]);
1475        assert_eq!(report.verdict, crate::Verdict::Identical);
1476        assert_eq!(
1477            crate::render_text(&report),
1478            "identical\n\
1479             placement changed\n\
1480             \x20 Production/veh.topology.Cruise.backup: Cockpit -> AdasHpc\n\
1481             composition changed\n\
1482             \x20 veh.topology.Panel/external: false -> true\n"
1483        );
1484        let json: serde_json::Value =
1485            serde_json::from_str(&crate::render_json(&report)).expect("the report is JSON");
1486        assert_eq!(
1487            json["placement_changed"],
1488            serde_json::json!([{
1489                "path": "Production/veh.topology.Cruise.backup",
1490                "before": "Cockpit",
1491                "after": "AdasHpc"
1492            }])
1493        );
1494        assert_eq!(json["composition_changed"][0]["after"], "true");
1495
1496        let one_side = crate::diff_workspaces(&[], None, &[], Some(&new), &[]);
1497        assert!(one_side.system.is_empty());
1498        let json: serde_json::Value =
1499            serde_json::from_str(&crate::render_json(&one_side)).expect("the report is JSON");
1500        assert_eq!(
1501            json,
1502            serde_json::json!({ "verdict": "identical", "changes": [] })
1503        );
1504    }
1505
1506    /// rsdl §14: an instance moved to another machine, a machine added,
1507    /// removed or made `external`, and a deployment added or removed are
1508    /// placement changes.
1509    #[test]
1510    fn a_deployment_change_is_listed_under_placement_changed() {
1511        let old = base();
1512        let mut new = base();
1513        new.deployments[0].placements[1].machine = "AdasHpc".to_string();
1514        new.deployments[0].machines[1].external = true;
1515        new.deployments[0].machines.push(machine("Cloud", true));
1516        new.deployments.push(Deployment {
1517            name: "Bench".to_string(),
1518            ..Deployment::default()
1519        });
1520        assert_eq!(
1521            lines(&diff_systems(&old, &new)),
1522            [
1523                "placement changed: Production/Cockpit/external: false -> true",
1524                "placement changed: Production/Cloud: (absent) -> machine",
1525                "placement changed: Production/veh.topology.Cruise.backup: Cockpit -> AdasHpc",
1526                "placement changed: Bench: (absent) -> deployment",
1527            ]
1528        );
1529        assert_eq!(
1530            lines(&diff_systems(&new, &old)),
1531            [
1532                "placement changed: Production/Cockpit/external: true -> false",
1533                "placement changed: Production/Cloud: machine -> (removed)",
1534                "placement changed: Production/veh.topology.Cruise.backup: AdasHpc -> Cockpit",
1535                "placement changed: Bench: deployment -> (removed)",
1536            ]
1537        );
1538    }
1539
1540    /// rsdl §14: a component added to or removed from the system, an `offers`
1541    /// or `requires` line added or removed, `instances` changed, and a
1542    /// component made `external` are composition changes.
1543    #[test]
1544    fn a_closure_or_line_change_is_listed_under_composition_changed() {
1545        let old = base();
1546        let mut new = base();
1547        new.components[0].instances = vec!["Unit".to_string()];
1548        new.components[0].requires.clear();
1549        new.components[1].external = true;
1550        new.components[1].offers.push(v2::Offer {
1551            service: "veh.hmi.panel".to_string(),
1552            attributes: Vec::new(),
1553            doc: String::new(),
1554            links: Vec::new(),
1555            see: Vec::new(),
1556            since: Vec::new(),
1557        });
1558        new.components
1559            .push(component("Lane", &["Unit"], &["veh.adas.lane"], &[]));
1560        assert_eq!(
1561            lines(&diff_systems(&old, &new)),
1562            [
1563                "composition changed: veh.topology.Cruise/requires/veh.adas.LaneAssist: \
1564                 requires veh.adas.LaneAssist -> (removed)",
1565                "composition changed: veh.topology.Cruise/instances: (primary, backup) -> (Unit)",
1566                "composition changed: veh.topology.Panel/offers/veh.hmi.panel: \
1567                 (absent) -> offers veh.hmi.panel",
1568                "composition changed: veh.topology.Panel/external: false -> true",
1569                "composition changed: veh.topology.Lane: (absent) -> in the closure",
1570            ]
1571        );
1572        assert_eq!(
1573            lines(&diff_systems(&new, &old)).last().map(String::as_str),
1574            Some("composition changed: veh.topology.Lane: in the closure -> (removed)")
1575        );
1576    }
1577}