Skip to main content

ridl_ir/
lib.rs

1//! RIDL intermediate representation.
2//!
3//! The v2 schema (`proto/ridl/ir/v2/ir.proto`) is compiled from its protobuf
4//! source by `build.rs` (protox + prost-build, ADR-0006 decision 3) and
5//! exposed as [`v2`]. v2 is the typl surface plus the ridl interaction layer
6//! (ridl language reference §3–§14) with exact decimal values — every numeric
7//! value is a canonical decimal string, never a floating-point field (ADR-0007
8//! decision 9, ADR-0008 decision 12). The v1 schema was removed when its last
9//! consumer moved to v2 (task 6 of the E2 plan), mirroring the E1 v0→v1
10//! retirement.
11
12pub mod v2 {
13    //! IR v2 — the typl surface plus the ridl interaction layer (ridl
14    //! language reference §3–§14) with exact decimal values (ADR-0007
15    //! decision 9, ADR-0008 decision 12).
16
17    include!(concat!(env!("OUT_DIR"), "/ridl.ir.v2.rs"));
18    // The canonical protobuf JSON serde impls, generated by pbjson-build in
19    // `build.rs` from the same schema compilation as the types above
20    // (ADR-0014 decision 14).
21    //
22    // The file holds only trait impls, so it sits in a private module to scope
23    // one lint allowance to generated code: pbjson-build 0.9.0 writes
24    // `write!(formatter, "…", &FIELDS)`, which clippy 1.98 reports as
25    // `useless_borrows_in_formatting`. The build script writes the file into
26    // `OUT_DIR`, so an edit to it does not last and the lint cannot be repaired
27    // in source. A lint attribute on the `include!` itself is ignored by rustc.
28    // `expect` rather than `allow`: when the lint no longer fires here, clippy
29    // reports the expectation as unfulfilled. Then remove this module and
30    // include the file directly in `v2` again.
31    #[expect(clippy::useless_borrows_in_formatting)]
32    mod serde_impls {
33        use super::*;
34
35        include!(concat!(env!("OUT_DIR"), "/ridl.ir.v2.serde.rs"));
36    }
37
38    /// The descriptor pool over the compiled IR schema — the reflection data
39    /// the prototext encoding needs (ADR-0014 decision 7; since decision 14
40    /// JSON goes through the pbjson-generated impls and no longer uses the
41    /// pool). Binary needs none of it.
42    /// `build.rs` writes the `FileDescriptorSet` to `OUT_DIR` from the same
43    /// `protox` compilation that generates the types above, so the pool and
44    /// the types cannot disagree; every `expect` on this path leans on that.
45    static DESCRIPTOR_POOL: std::sync::LazyLock<prost_reflect::DescriptorPool> =
46        std::sync::LazyLock::new(|| {
47            prost_reflect::DescriptorPool::decode(
48                include_bytes!(concat!(env!("OUT_DIR"), "/ir_descriptor.binpb")).as_slice(),
49            )
50            .expect("the embedded descriptor set decodes: build.rs wrote it from the schema compilation that generated these types")
51        });
52
53    /// The descriptor of one root message of the compiled schema, by its
54    /// full name.
55    fn descriptor(name: &str) -> prost_reflect::MessageDescriptor {
56        DESCRIPTOR_POOL
57            .get_message_by_name(name)
58            .unwrap_or_else(|| panic!("{name} is declared by the compiled schema"))
59    }
60
61    /// The `Package` message descriptor — the entry point of the prototext
62    /// encoder and decoder, the one reflection path left in this module.
63    pub(crate) fn package_descriptor() -> prost_reflect::MessageDescriptor {
64        descriptor("ridl.ir.v2.Package")
65    }
66
67    /// The `System` message descriptor (`system.proto`), the prototext entry
68    /// point of the rsdl system layer.
69    pub(crate) fn system_descriptor() -> prost_reflect::MessageDescriptor {
70        descriptor("ridl.ir.v2.System")
71    }
72
73    /// The `ridl.codegen.v1.CodegenRequest` message descriptor — the entry
74    /// point of the request reader that ignores unknown keys.
75    pub(crate) fn codegen_request_descriptor() -> prost_reflect::MessageDescriptor {
76        descriptor("ridl.codegen.v1.CodegenRequest")
77    }
78
79    /// The `ridl.codegen.v1.Model` message descriptor — the prototext entry
80    /// point of the lowered codegen model, from the same pool, because
81    /// `build.rs` compiles both schemas in one `protox` call.
82    pub(crate) fn codegen_model_descriptor() -> prost_reflect::MessageDescriptor {
83        descriptor("ridl.codegen.v1.Model")
84    }
85
86    /// Rebuilds a message as a `DynamicMessage` over its descriptor — the
87    /// step `prost-reflect` needs before rendering a text encoding.
88    /// Transcoding goes through the wire encoding, whose decoder enforces
89    /// prost's fixed recursion limit, so a package whose composite nesting
90    /// crosses that limit fails here — an input-dependent failure, not
91    /// schema drift (ADR-0014 decision 12).
92    fn transcode<M: prost::Message>(
93        descriptor: prost_reflect::MessageDescriptor,
94        message: &M,
95    ) -> Result<prost_reflect::DynamicMessage, prost::DecodeError> {
96        let mut dynamic = prost_reflect::DynamicMessage::new(descriptor);
97        dynamic.transcode_from(message)?;
98        Ok(dynamic)
99    }
100
101    /// Derives the synthesized transport identity of an inline `T | E`
102    /// result union (ADR-0008 decision 4): the enclosing interface name plus
103    /// the interaction ordinal plus the ordered arm references. The single
104    /// derivation every consumer — backends and the diff classifier — calls,
105    /// so the identity stays stable under compatible evolution.
106    pub fn fallible_transport_identity(
107        interface: &str,
108        ordinal: u32,
109        fallible: &FallibleType,
110    ) -> String {
111        format!(
112            "{interface}#{ordinal}:{ok}|{err}",
113            ok = fallible.ok,
114            err = fallible.err
115        )
116    }
117
118    /// The error [`to_json_pretty`] and [`to_text_format`] return. The
119    /// serialization surface is fallible on purpose (ADR-0014 decisions 12
120    /// and 14), and the two encodings now fail for different causes, so each
121    /// carries its own variant — its `Display` names the encoding, so a
122    /// build requesting several IR emits attributes each failure to its own
123    /// artifact.
124    #[derive(Debug)]
125    pub enum SerializeError {
126        /// Canonical protobuf JSON (ADR-0014 decision 14): the
127        /// pbjson-generated `Serialize` impl writes the typed message
128        /// directly — no transcode, so no message-level recursion limit —
129        /// and its one error path is an `i32` enum field holding a
130        /// discriminant outside the schema.
131        Json(serde_json::Error),
132        /// Prototext (ADR-0014 decision 12): the transcode into the dynamic
133        /// message goes through the wire encoding, whose decoder enforces
134        /// prost's fixed recursion limit, and legal source can nest
135        /// composites past it.
136        Text(prost::DecodeError),
137        /// An interaction holds a (kind, family, shape) combination the IR
138        /// does not admit (`ridl_ir::class`).
139        Class(crate::class::InteractionClassError),
140    }
141
142    impl std::fmt::Display for SerializeError {
143        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144            match self {
145                Self::Json(source) => write!(
146                    f,
147                    "cannot render the package as canonical protobuf JSON: {source}; the known \
148                     cause is an enum field holding a discriminant outside the schema"
149                ),
150                Self::Text(source) => write!(
151                    f,
152                    "cannot render the package as prototext: {source}; the known cause \
153                     is composite nesting deeper than the transcoding decoder's recursion limit"
154                ),
155                Self::Class(source) => write!(f, "{source}"),
156            }
157        }
158    }
159
160    impl std::error::Error for SerializeError {
161        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
162            match self {
163                Self::Json(source) => Some(source),
164                Self::Text(source) => Some(source),
165                Self::Class(source) => Some(source),
166            }
167        }
168    }
169
170    /// Renders a package as pretty-printed canonical protobuf JSON — the one
171    /// dialect every IR surface carries: the `--emit ir-json` artifact, the
172    /// baselines, and the goldens (ADR-0014 decision 1) — through the
173    /// pbjson-generated `Serialize` impl (decision 14), byte-identical to
174    /// what the retired reflection path rendered.
175    ///
176    /// A field holding its default is emitted rather than skipped (decision
177    /// 2, `emit_fields()` in `build.rs`); an unset proto3 `optional` field
178    /// is omitted entirely, never rendered as `null` (the answer to that
179    /// decision's open item). 64-bit fields render as strings, the canonical
180    /// mapping JavaScript consumers need (decision 8).
181    ///
182    /// Still fallible (ADR-0014 decision 14, amending decision 12), but the
183    /// error path changed rather than survived: the generated impl writes
184    /// the typed message directly, so the transcode's depth error is gone,
185    /// and the one error path it has is new — an `i32` enum field holding a
186    /// discriminant outside the schema, which the retired reflection path
187    /// serialized successfully as its bare number. The checker never
188    /// produces one, but the value is data, not schema, so the failure is
189    /// returned rather than panicked on.
190    pub fn to_json_pretty(package: &Package) -> Result<String, SerializeError> {
191        crate::class::check_package(package).map_err(SerializeError::Class)?;
192        render_json(package)
193    }
194
195    /// Renders a lowered system (`system.proto`, rsdl reference §13) as
196    /// pretty-printed canonical protobuf JSON — the `<pkg.Name>.system.json`
197    /// artifact, under the rules of [`to_json_pretty`].
198    pub fn system_to_json_pretty(system: &System) -> Result<String, SerializeError> {
199        render_json(system)
200    }
201
202    /// The one JSON writer behind [`to_json_pretty`] and
203    /// [`system_to_json_pretty`]: the pbjson-generated `Serialize` impl of
204    /// the message, pretty-printed.
205    pub(crate) fn render_json<M: serde::Serialize>(message: &M) -> Result<String, SerializeError> {
206        let mut buf = Vec::new();
207        let mut serializer = serde_json::Serializer::pretty(&mut buf);
208        serde::Serialize::serialize(message, &mut serializer).map_err(SerializeError::Json)?;
209        Ok(String::from_utf8(buf).expect("serde_json emits UTF-8"))
210    }
211
212    /// The nesting ceiling `from_json` enforces, in JSON bracket levels.
213    ///
214    /// It cannot bind on IR this toolchain produces, and the bound is a
215    /// measurement rather than a guess. The parser refuses type nesting past
216    /// 128 levels (FORM-102, `MAX_TYPE_DEPTH` in `ridl-syntax`), and the
217    /// deepest package that limit admits emits JSON **516 brackets** deep —
218    /// so 1,000 leaves a factor of 1.9 over anything `ridlc` can write, and
219    /// the deepest nesting in the corpus is single digits. The figure this
220    /// comment carried until 2026-09-22, 262 brackets and a factor of 3.8,
221    /// was the array shape; the tuple shape costs four brackets per source
222    /// level rather than two and is the one that binds (the IR
223    /// specification, "The nesting bound").
224    ///
225    /// It exists for input this toolchain did not write: a hand-edited
226    /// baseline, or a snapshot from elsewhere. Past the stack ceiling the
227    /// failure mode is a stack-overflow abort, which no caller can catch, so
228    /// the cap turns an abort into a diagnostic (ADR-0014 decisions 12
229    /// and 14).
230    pub(crate) const MAX_JSON_NESTING: usize = 1_000;
231
232    /// The stack `from_json` parses on, in bytes. An explicit size makes the
233    /// depth that fits a constant of this crate rather than of the ambient
234    /// stack, which differs between debug and release builds and between
235    /// platforms — the same input parses everywhere or nowhere.
236    const JSON_PARSE_STACK: usize = 16 * 1024 * 1024;
237
238    /// The maximum bracket nesting of `text`: the largest number of `{` and
239    /// `[` open at once, with string literals skipped — a bracket inside a
240    /// string must not count, an escaped quote (`\"`) must not end the
241    /// string, and an escaped backslash (`\\`) must not disarm the real
242    /// closing quote after it. Runs before the parse in [`from_json`], so it
243    /// tolerates input that is not valid JSON; a stray closer never
244    /// underflows the running depth.
245    pub(crate) fn max_json_nesting(text: &str) -> usize {
246        let mut depth = 0usize;
247        let mut deepest = 0usize;
248        let mut in_string = false;
249        let mut escaped = false;
250        for byte in text.bytes() {
251            if in_string {
252                if escaped {
253                    escaped = false;
254                } else if byte == b'\\' {
255                    escaped = true;
256                } else if byte == b'"' {
257                    in_string = false;
258                }
259            } else {
260                match byte {
261                    b'"' => in_string = true,
262                    b'{' | b'[' => {
263                        depth += 1;
264                        deepest = deepest.max(depth);
265                    }
266                    b'}' | b']' => depth = depth.saturating_sub(1),
267                    _ => {}
268                }
269            }
270        }
271        deepest
272    }
273
274    /// Reads a package from canonical protobuf JSON — the inverse of
275    /// [`to_json_pretty`], through the pbjson-generated `Deserialize` impl
276    /// (ADR-0014 decision 14). Unknown fields are rejected (the generated
277    /// deserializer's default; `ignore_unknown_fields()` stays unset in
278    /// `build.rs`), so a snapshot written against a different schema fails
279    /// loudly rather than dropping fields silently.
280    ///
281    /// The generated impl recurses per JSON level, so `serde_json`'s own
282    /// recursion limit of 128 levels is disabled — it would bind far below
283    /// this crate's documented ceiling — and two guards replace it
284    /// (ADR-0014 decision 14):
285    ///
286    /// - input nesting is measured first and refused past
287    ///   `MAX_JSON_NESTING`, returning a diagnostic where unbounded
288    ///   recursion would eventually abort on a stack overflow no caller can
289    ///   catch;
290    /// - the parse runs on a thread of `JSON_PARSE_STACK` bytes, so the
291    ///   ceiling behaves identically across build profiles and platforms
292    ///   instead of tracking the ambient stack. On the wasm family there is
293    ///   no such thread — see the branch below — and the cap alone guards
294    ///   the parse.
295    ///
296    /// After the parse, every interaction's (kind, family, shape) is checked
297    /// against [`crate::class`]; an invalid combination is an error of this
298    /// reader.
299    pub fn from_json(text: &str) -> Result<Package, serde_json::Error> {
300        let package: Package = read_json(text)?;
301        crate::class::check_package(&package).map_err(serde::de::Error::custom)?;
302        Ok(package)
303    }
304
305    /// An error loading an `.ir.json` snapshot with [`load_ir_json`].
306    #[derive(Debug)]
307    pub enum LoadError {
308        /// The file could not be read.
309        Io(std::io::Error),
310        /// The file was not valid IR v2 JSON.
311        Parse(String),
312    }
313
314    impl std::fmt::Display for LoadError {
315        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316            match self {
317                LoadError::Io(err) => write!(f, "cannot read the IR snapshot: {err}"),
318                LoadError::Parse(err) => {
319                    write!(f, "the IR snapshot is not valid IR v2 JSON: {err}")
320                }
321            }
322        }
323    }
324
325    impl std::error::Error for LoadError {}
326
327    /// Loads an `.ir.json` snapshot written by `ridl build --emit ir-json` —
328    /// canonical protobuf JSON, read through [`from_json`], the one reader
329    /// every surface shares (ADR-0014 decision 1).
330    pub fn load_ir_json(path: &std::path::Path) -> Result<Package, LoadError> {
331        let text = std::fs::read_to_string(path).map_err(LoadError::Io)?;
332        from_json(&text).map_err(|err| LoadError::Parse(err.to_string()))
333    }
334
335    /// Reads a lowered system from canonical protobuf JSON — the inverse of
336    /// [`system_to_json_pretty`], under the rules and guards of
337    /// [`from_json`].
338    pub fn system_from_json(text: &str) -> Result<System, serde_json::Error> {
339        read_json(text)
340    }
341
342    /// The one JSON reader behind [`from_json`] and [`system_from_json`]:
343    /// the nesting cap, then the parse on its own stack.
344    pub(crate) fn read_json<M>(text: &str) -> Result<M, serde_json::Error>
345    where
346        M: serde::de::DeserializeOwned + Send,
347    {
348        check_nesting(text)?;
349        on_parse_stack(|| parse_json(text))
350    }
351
352    /// Reads a request-shaped message the way [`read_json`] does, except that
353    /// an object key the schema does not declare is ignored at every nesting
354    /// level. The same nesting cap and parse stack apply.
355    ///
356    /// The text is read once into a `serde_json::Value` that keeps only the
357    /// keys `descriptor` declares at each point (by JSON name or proto name),
358    /// including inside repeated and map message values, and the value is
359    /// then read by the generated deserializer of `M`. That reader still
360    /// rejects what it rejects for the strict path: a value of the wrong
361    /// type, an unknown enum name, and a field written twice. Only an unknown
362    /// key is dropped; an unknown enum name is an error, because it changes
363    /// the meaning of a known field. A value of a `google.protobuf` message
364    /// is left untouched.
365    ///
366    /// An error from the second phase, the generated deserializer reading the
367    /// filtered value, carries no line and column, because the value no longer
368    /// has a position in the text.
369    pub(crate) fn read_json_ignoring_unknown<M>(
370        descriptor: prost_reflect::MessageDescriptor,
371        text: &str,
372    ) -> Result<M, serde_json::Error>
373    where
374        M: serde::de::DeserializeOwned + Send,
375    {
376        use serde::de::DeserializeSeed as _;
377        check_nesting(text)?;
378        on_parse_stack(|| {
379            let mut deserializer = serde_json::Deserializer::from_str(text);
380            deserializer.disable_recursion_limit();
381            let known = JsonShape::Message(descriptor).deserialize(&mut deserializer)?;
382            deserializer.end()?;
383            serde::Deserialize::deserialize(known)
384        })
385    }
386
387    /// What a JSON value is expected to be, as far as dropping unknown keys
388    /// needs to know.
389    #[derive(Clone)]
390    enum JsonShape {
391        /// A message: an object whose unknown keys are dropped.
392        Message(prost_reflect::MessageDescriptor),
393        /// A repeated field: an array of the inner shape.
394        List(Box<JsonShape>),
395        /// A map field: an object whose values have the inner shape.
396        Map(Box<JsonShape>),
397        /// Anything else: kept as read.
398        Opaque,
399    }
400
401    impl JsonShape {
402        /// The shape of the value of one field.
403        fn of(field: &prost_reflect::FieldDescriptor) -> JsonShape {
404            use prost_reflect::Kind;
405            if field.is_map() {
406                let Kind::Message(entry) = field.kind() else {
407                    return JsonShape::Opaque;
408                };
409                return JsonShape::Map(Box::new(JsonShape::of_kind(
410                    &entry.map_entry_value_field().kind(),
411                )));
412            }
413            let item = JsonShape::of_kind(&field.kind());
414            if field.is_list() {
415                JsonShape::List(Box::new(item))
416            } else {
417                item
418            }
419        }
420
421        fn of_kind(kind: &prost_reflect::Kind) -> JsonShape {
422            match kind {
423                prost_reflect::Kind::Message(message)
424                    if !message.full_name().starts_with("google.protobuf.") =>
425                {
426                    JsonShape::Message(message.clone())
427                }
428                _ => JsonShape::Opaque,
429            }
430        }
431    }
432
433    impl<'de> serde::de::DeserializeSeed<'de> for JsonShape {
434        type Value = serde_json::Value;
435
436        fn deserialize<D: serde::Deserializer<'de>>(
437            self,
438            deserializer: D,
439        ) -> Result<Self::Value, D::Error> {
440            match self {
441                JsonShape::Opaque => serde::Deserialize::deserialize(deserializer),
442                shape => deserializer.deserialize_any(ShapeVisitor(shape)),
443            }
444        }
445    }
446
447    struct ShapeVisitor(JsonShape);
448
449    impl<'de> serde::de::Visitor<'de> for ShapeVisitor {
450        type Value = serde_json::Value;
451
452        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453            formatter.write_str(match self.0 {
454                JsonShape::List(_) => "an array",
455                _ => "an object",
456            })
457        }
458
459        // `null` is passed on: the generated reader decides what it means.
460        fn visit_unit<E>(self) -> Result<Self::Value, E> {
461            Ok(serde_json::Value::Null)
462        }
463
464        fn visit_seq<A: serde::de::SeqAccess<'de>>(
465            self,
466            mut seq: A,
467        ) -> Result<Self::Value, A::Error> {
468            let JsonShape::List(item) = self.0 else {
469                return Err(serde::de::Error::invalid_type(
470                    serde::de::Unexpected::Seq,
471                    &self,
472                ));
473            };
474            let mut items = Vec::new();
475            while let Some(value) = seq.next_element_seed((*item).clone())? {
476                items.push(value);
477            }
478            Ok(serde_json::Value::Array(items))
479        }
480
481        fn visit_map<A: serde::de::MapAccess<'de>>(
482            self,
483            mut map: A,
484        ) -> Result<Self::Value, A::Error> {
485            use serde::de::Error as _;
486            let mut out = serde_json::Map::new();
487            match &self.0 {
488                JsonShape::Message(descriptor) => {
489                    let mut seen = std::collections::HashSet::new();
490                    while let Some(key) = map.next_key::<String>()? {
491                        let field = descriptor
492                            .get_field_by_json_name(&key)
493                            .or_else(|| descriptor.get_field_by_name(&key));
494                        match field {
495                            Some(field) => {
496                                if !seen.insert(field.number()) {
497                                    return Err(A::Error::custom(format!(
498                                        "duplicate field `{key}`"
499                                    )));
500                                }
501                                let value = map.next_value_seed(JsonShape::of(&field))?;
502                                out.insert(key, value);
503                            }
504                            None => {
505                                map.next_value::<serde::de::IgnoredAny>()?;
506                            }
507                        }
508                    }
509                }
510                JsonShape::Map(value_shape) => {
511                    while let Some(key) = map.next_key::<String>()? {
512                        let value = map.next_value_seed((**value_shape).clone())?;
513                        if out.insert(key.clone(), value).is_some() {
514                            return Err(A::Error::custom(format!("duplicate key `{key}`")));
515                        }
516                    }
517                }
518                JsonShape::List(_) | JsonShape::Opaque => {
519                    return Err(A::Error::invalid_type(serde::de::Unexpected::Map, &self));
520                }
521            }
522            Ok(serde_json::Value::Object(out))
523        }
524    }
525
526    /// Refuses input that nests past `MAX_JSON_NESTING`.
527    fn check_nesting(text: &str) -> Result<(), serde_json::Error> {
528        if max_json_nesting(text) > MAX_JSON_NESTING {
529            return Err(<serde_json::Error as serde::de::Error>::custom(format!(
530                "the input nests deeper than {MAX_JSON_NESTING} JSON levels, the ceiling this \
531                 reader enforces (ADR-0014 decision 14); real IR nests orders of magnitude \
532                 shallower"
533            )));
534        }
535        Ok(())
536    }
537
538    /// Runs a parse on its own stack of `JSON_PARSE_STACK` bytes, or in line
539    /// on the wasm family.
540    fn on_parse_stack<R: Send>(parse: impl FnOnce() -> R + Send) -> R {
541        if cfg!(target_family = "wasm") {
542            // The wasm family has no spawnable threads: `spawn_scoped`
543            // returns `Err(Unsupported)` at run time on
544            // `wasm32-unknown-unknown`, the `just wasm-check` target, so a
545            // spawn here would turn every call into a panic. The parse runs
546            // in line instead, on the caller's stack. What this path loses
547            // is the deterministic stack — the ceiling is the ambient stack
548            // — and the `MAX_JSON_NESTING` cap is the guard that matters: it
549            // is what turns an abort into an error.
550            parse()
551        } else {
552            std::thread::scope(|scope| {
553                let handle = std::thread::Builder::new()
554                    .stack_size(JSON_PARSE_STACK)
555                    .spawn_scoped(scope, parse)
556                    .expect("the JSON parse thread spawns");
557                match handle.join() {
558                    Ok(result) => result,
559                    Err(payload) => std::panic::resume_unwind(payload),
560                }
561            })
562        }
563    }
564
565    /// The parse both branches of [`from_json`] share; only the stack that
566    /// carries it differs. `serde_json`'s own recursion limit is disabled
567    /// here, so the caller must have applied the `MAX_JSON_NESTING` cap
568    /// first.
569    fn parse_json<M: serde::de::DeserializeOwned>(text: &str) -> Result<M, serde_json::Error> {
570        let mut deserializer = serde_json::Deserializer::from_str(text);
571        deserializer.disable_recursion_limit();
572        let message: M = serde::Deserialize::deserialize(&mut deserializer)?;
573        deserializer.end()?;
574        Ok(message)
575    }
576
577    /// Renders a package in the protobuf text format — the inspection
578    /// encoding (ADR-0014 decision 9): emittable, but not a recommended
579    /// interchange form. Rendered `pretty`, with a field holding its default
580    /// emitted rather than skipped (decision 2) and message fields printed
581    /// in schema index order, so the output ordering is deterministic rather
582    /// than incidental (decision 8).
583    ///
584    /// Fallible on purpose (ADR-0014 decision 12): the transcode into the
585    /// dynamic message goes through the wire encoding, and a package whose
586    /// composite nesting crosses prost's recursion limit fails there. That
587    /// input is legal source, so the failure is returned rather than
588    /// panicked on. JSON lost this failure mode when it moved off the
589    /// transcode (decision 14); prototext keeps it.
590    pub fn to_text_format(package: &Package) -> Result<String, SerializeError> {
591        crate::class::check_package(package).map_err(SerializeError::Class)?;
592        render_text_for(package_descriptor(), package)
593    }
594
595    /// Renders a lowered system in the protobuf text format — the
596    /// `<pkg.Name>.system.txtpb` artifact, under the rules of
597    /// [`to_text_format`].
598    pub fn system_to_text_format(system: &System) -> Result<String, SerializeError> {
599        render_text_for(system_descriptor(), system)
600    }
601
602    /// The one prototext writer behind [`to_text_format`] and
603    /// [`system_to_text_format`].
604    pub(crate) fn render_text_for<M: prost::Message>(
605        descriptor: prost_reflect::MessageDescriptor,
606        message: &M,
607    ) -> Result<String, SerializeError> {
608        let dynamic = transcode(descriptor, message).map_err(SerializeError::Text)?;
609        Ok(dynamic.to_text_format_with_options(
610            &prost_reflect::text_format::FormatOptions::new()
611                .pretty(true)
612                .skip_default_fields(false)
613                .print_message_fields_in_index_order(true),
614        ))
615    }
616
617    /// The error [`from_text_format`] returns: the input does not parse as
618    /// prototext, or the parsed message does not transcode into the
619    /// generated types. The transcode failure is the read direction of the
620    /// recursion-limit failure mode (ADR-0014 decision 12) — input-dependent,
621    /// so it is mapped into this return rather than expected on.
622    #[cfg(test)]
623    #[derive(Debug)]
624    pub(crate) enum TextFormatError {
625        /// The input is not valid prototext for the `Package` schema.
626        Parse(prost_reflect::text_format::ParseError),
627        /// The parsed message cannot be rebuilt as a typed `Package`.
628        Transcode(prost::DecodeError),
629    }
630
631    #[cfg(test)]
632    impl std::fmt::Display for TextFormatError {
633        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
634            match self {
635                Self::Parse(source) => {
636                    write!(f, "cannot parse the text as an IR package: {source}")
637                }
638                Self::Transcode(source) => write!(
639                    f,
640                    "cannot rebuild the parsed prototext as a package: {source}; the known cause \
641                     is composite nesting deeper than the transcoding decoder's recursion limit"
642                ),
643            }
644        }
645    }
646
647    #[cfg(test)]
648    impl std::error::Error for TextFormatError {
649        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
650            match self {
651                Self::Parse(source) => Some(source),
652                Self::Transcode(source) => Some(source),
653            }
654        }
655    }
656
657    /// Reads a package from the protobuf text format — the inverse of
658    /// [`to_text_format`], kept because without it the prototext emit has no
659    /// round-trip test, and a write path with no read path is untested by
660    /// construction (ADR-0014 decision 7).
661    ///
662    /// **Deliberately not public.** `prost-reflect`'s text parser recurses per
663    /// message level with frames large enough that a debug build exhausts a
664    /// 2 MiB stack at roughly 45 levels of nesting — *below* prost's recursion
665    /// limit of 100, so on that path the error return below is unreachable and
666    /// the process aborts instead. A stack overflow cannot be caught, so the
667    /// hazard is contained by reach rather than handled: nothing in the
668    /// toolchain reads prototext, `ridl diff` and `ridl check --baseline`
669    /// refuse the encoding by name (ADR-0014 decision 5), and this function is
670    /// compiled only for this crate's tests. The tests that exercise it run on an
671    /// explicitly sized stack (see `with_sized_stack`). Making it public again
672    /// means giving it a stack strategy first — driftsys/ridl#218.
673    ///
674    /// A package whose nesting crosses prost's limit *before* the stack runs
675    /// out fails in the transcode out of the dynamic message; that failure is
676    /// mapped into the error return, not expected on (ADR-0014 decision 12).
677    #[cfg(test)]
678    pub(crate) fn from_text_format(text: &str) -> Result<Package, TextFormatError> {
679        parse_text(package_descriptor(), text)
680    }
681
682    /// Reads a lowered system from the protobuf text format — the inverse of
683    /// [`system_to_text_format`], test-only for the reason
684    /// [`from_text_format`] states.
685    #[cfg(test)]
686    pub(crate) fn system_from_text_format(text: &str) -> Result<System, TextFormatError> {
687        parse_text(system_descriptor(), text)
688    }
689
690    #[cfg(test)]
691    fn parse_text<M: prost::Message + Default>(
692        descriptor: prost_reflect::MessageDescriptor,
693        text: &str,
694    ) -> Result<M, TextFormatError> {
695        let dynamic = prost_reflect::DynamicMessage::parse_text_format(descriptor, text)
696            .map_err(TextFormatError::Parse)?;
697        dynamic.transcode_to().map_err(TextFormatError::Transcode)
698    }
699
700    /// Encodes a package in the protobuf binary wire format — a derived
701    /// encoding since ADR-0014 decision 9's 2026-09-22 amendment, whose
702    /// reader stops 100 message levels below the root where the canonical
703    /// encoding has no such bound (the IR specification, "The derived
704    /// encodings"). Binary needs no descriptors: prost's generated encoding
705    /// is schema-faithful by construction.
706    pub fn to_binary(package: &Package) -> Vec<u8> {
707        prost::Message::encode_to_vec(package)
708    }
709
710    /// Decodes a package from the protobuf binary wire format — the inverse
711    /// of [`to_binary`].
712    pub fn from_binary(bytes: &[u8]) -> Result<Package, prost::DecodeError> {
713        let package: Package = prost::Message::decode(bytes)?;
714        crate::class::check_package(&package).map_err(|err| {
715            // `DecodeError::new` is the only way to build one: prost exposes
716            // no other constructor, and this reader's error type is prost's.
717            #[allow(deprecated)]
718            prost::DecodeError::new(err.to_string())
719        })?;
720        Ok(package)
721    }
722
723    /// Encodes a lowered system in the protobuf binary wire format — the
724    /// `<pkg.Name>.system.binpb` artifact (ADR-0014 decision 9).
725    pub fn system_to_binary(system: &System) -> Vec<u8> {
726        prost::Message::encode_to_vec(system)
727    }
728
729    /// Decodes a lowered system from the protobuf binary wire format — the
730    /// inverse of [`system_to_binary`].
731    pub fn system_from_binary(bytes: &[u8]) -> Result<System, prost::DecodeError> {
732        prost::Message::decode(bytes)
733    }
734
735    /// `pkg.Name` — how a system, a component or a distribution is referred
736    /// to across the system layer (`system.proto`); a name with no package,
737    /// the implicit component of a lone service (rsdl §6), is its own
738    /// qualified name.
739    fn qualified(package: &str, name: &str) -> String {
740        if package.is_empty() {
741            name.to_string()
742        } else {
743            format!("{package}.{name}")
744        }
745    }
746
747    impl System {
748        /// The system's qualified name, `pkg.Name` — the base name of its
749        /// artifacts.
750        pub fn qualified_name(&self) -> String {
751            qualified(&self.package, &self.name)
752        }
753    }
754
755    impl Component {
756        /// The name every reference to this component uses: `pkg.Name` for a
757        /// declared component, the service's dotted name for an implicit one.
758        pub fn qualified_name(&self) -> String {
759            qualified(&self.package, &self.name)
760        }
761    }
762
763    impl Distribution {
764        /// The name `Distribution.depends_on` and `Installation.distribution`
765        /// use.
766        pub fn qualified_name(&self) -> String {
767            qualified(&self.package, &self.name)
768        }
769    }
770
771    /// One interface shape of a package (ridl §14.0): a declared `interface`,
772    /// or the inline shape of a `service` (§14.5).
773    ///
774    /// **[`Package::interfaces`] is not the complete set.** A `service`
775    /// declared with an inline body carries a full [`Interface`] inside its
776    /// shape list (the single `INLINE` slot, ADR-0015 decision 14), which
777    /// lives outside `interfaces`; a consumer that walks `interfaces` alone
778    /// silently misses it. Six defects of exactly that shape were found
779    /// independently across E2 — observer-stub lowering, both backends'
780    /// transport identity, `ridl test`'s report, the Rust backend's collision
781    /// check, and the desk check's span index.
782    /// [`Package::shapes`] is the one walk that sees both, the way
783    /// [`fallible_transport_identity`] is the one transport-identity
784    /// derivation.
785    ///
786    /// This view is deliberately not a bare `&Interface`, because two of an
787    /// inline shape's own fields are empty by construction and reading them
788    /// is what produced two of those six defects:
789    ///
790    /// - [`Interface::name`] is `""` for an inline shape, so [`Self::name`]
791    ///   carries the **identity** name instead — the interface's own name, or
792    ///   the owning service's dotted global name. That is the name the diff
793    ///   paths, the observer-stub scoping, and both backends' identity fields
794    ///   already use.
795    /// - [`Interface::visibility`] is `VISIBILITY_UNSPECIFIED` for an inline
796    ///   shape; the owning [`Service`] carries the authoritative one, which
797    ///   [`Self::visibility`] reads.
798    ///
799    /// The generated *type* name is not derived here on purpose: mangling is
800    /// language-specific and stays with each backend.
801    #[derive(Debug, Clone, Copy, PartialEq)]
802    pub struct InterfaceShape<'a> {
803        /// The name this shape is known by outside the package: an
804        /// `interface` declaration's own name, or the owning service's dotted
805        /// global name. Never `Interface::name` for an inline shape.
806        pub name: &'a str,
807        /// The interface body — its interactions and its doc envelope.
808        pub interface: &'a Interface,
809        /// The owning service, for an inline shape; `None` for a declared
810        /// `interface`.
811        pub service: Option<&'a Service>,
812    }
813
814    impl InterfaceShape<'_> {
815        /// The authoritative visibility of this shape: the owning service's
816        /// for an inline shape (an inline shape's own field is
817        /// `VISIBILITY_UNSPECIFIED` by construction), the interface's own
818        /// otherwise.
819        pub fn visibility(&self) -> i32 {
820            match self.service {
821                Some(service) => service.visibility,
822                None => self.interface.visibility,
823            }
824        }
825
826        /// `true` when this shape is the inline body of a `service`.
827        pub fn is_inline(&self) -> bool {
828            self.service.is_some()
829        }
830    }
831
832    impl Package {
833        /// Every interface shape the package carries — the declared
834        /// interfaces and the inline shapes of its services. See
835        /// [`InterfaceShape`] for why walking [`Package::interfaces`] alone is
836        /// a defect.
837        ///
838        /// The order is the one every consumer already walked: the declared
839        /// interfaces in source order, then the services in source order. A
840        /// shape-list entry that names an interface yields nothing — its
841        /// target is a declared interface and is already in the sequence, so
842        /// yielding it again would visit one shape twice; a service composing
843        /// several interfaces (ADR-0015 decision 12) therefore contributes
844        /// nothing at all. A tombstone slot names no shape. Only the `INLINE`
845        /// slot of an inline-form service carries an interface of its own,
846        /// and that is what this walk yields.
847        pub fn shapes(&self) -> impl Iterator<Item = InterfaceShape<'_>> {
848            let named = self.interfaces.iter().map(|interface| InterfaceShape {
849                name: &interface.name,
850                interface,
851                service: None,
852            });
853            let inline = self.services.iter().flat_map(|service| {
854                service
855                    .shapes
856                    .iter()
857                    .filter_map(move |slot| match slot.kind.as_ref()? {
858                        service_shape::Kind::Inline(interface) => Some(InterfaceShape {
859                            name: &service.name,
860                            interface,
861                            service: Some(service),
862                        }),
863                        service_shape::Kind::InterfaceRef(_) => None,
864                    })
865            });
866            named.chain(inline)
867        }
868    }
869
870    /// The unit of `package`: its `unit` field when set, else its `name`.
871    ///
872    /// A snapshot written before the field existed carries an empty `unit`;
873    /// for such a package the package name is the unit.
874    pub fn unit_of(package: &Package) -> &str {
875        if package.unit.is_empty() {
876            &package.name
877        } else {
878            &package.unit
879        }
880    }
881
882    /// The packages of `packages` that belong to `unit`, in their order.
883    pub fn packages_of_unit<'a>(
884        unit: &str,
885        packages: &'a [Package],
886    ) -> impl Iterator<Item = &'a Package> {
887        select_unit(unit, packages.iter())
888    }
889
890    /// [`packages_of_unit`] over borrowed packages, the form the catalog
891    /// hash and the codegen lowering hold.
892    pub fn members_of_unit<'a>(
893        unit: &str,
894        packages: &[&'a Package],
895    ) -> impl Iterator<Item = &'a Package> {
896        select_unit(unit, packages.iter().copied())
897    }
898
899    /// The one selection behind [`packages_of_unit`] and
900    /// [`members_of_unit`]: by [`unit_of`], never by a name prefix.
901    fn select_unit<'a>(
902        unit: &str,
903        packages: impl Iterator<Item = &'a Package>,
904    ) -> impl Iterator<Item = &'a Package> {
905        let unit = unit.to_owned();
906        packages.filter(move |p| unit_of(p) == unit)
907    }
908
909    /// The name of a declaration relative to its unit: `name` for a package
910    /// that is the unit itself, else the package's path below the unit
911    /// followed by `name`, joined with `.`.
912    pub fn relative_name(unit: &str, package: &str, name: &str) -> String {
913        if package == unit {
914            return name.to_owned();
915        }
916        // A package outside the unit — a corrupt or hand-edited snapshot
917        // read by `ridl diff` — keeps its full name, so no name is wrong and
918        // nothing panics in a release build.
919        match package
920            .strip_prefix(unit)
921            .and_then(|rest| rest.strip_prefix('.'))
922        {
923            Some(below) => format!("{below}.{name}"),
924            None => format!("{package}.{name}"),
925        }
926    }
927
928    impl Package {
929        /// The name `shape` carries in the catalog of its unit: the global
930        /// name for an inline shape, else the declared name relative to the
931        /// unit (see [`relative_name`]).
932        pub fn catalog_name(&self, shape: &InterfaceShape<'_>) -> String {
933            if shape.is_inline() {
934                shape.name.to_owned()
935            } else {
936                relative_name(unit_of(self), &self.name, shape.name)
937            }
938        }
939    }
940
941    /// The retired entries of the catalog of `unit`: every `retired` entry
942    /// of every package of the unit (a package named twice is read once),
943    /// as spelled, in number order. The checker spells each entry as its
944    /// lock key, which is its catalog name (`cluster.Old`, `Old` for the
945    /// root, `service:veh.x`), on the package the key names or on the
946    /// unit's anchor package, so no entry is qualified here.
947    pub fn unit_retired(unit: &str, packages: &[&Package]) -> Vec<RetiredInterface> {
948        let mut seen: Vec<&str> = Vec::new();
949        let mut retired: Vec<RetiredInterface> = members_of_unit(unit, packages)
950            .filter(|package| {
951                let first = !seen.contains(&package.name.as_str());
952                if first {
953                    seen.push(&package.name);
954                }
955                first
956            })
957            .flat_map(|package| package.retired.iter().cloned())
958            .collect();
959        retired.sort_by_key(|entry| entry.number);
960        retired
961    }
962
963    /// Every package named by a type reference in `package`.
964    ///
965    /// A resolved type-reference string is the fully qualified `pkg.Name` for
966    /// a cross-package reference and the bare `Name` for a same-package one,
967    /// never an import alias — the canonical form stated in
968    /// `proto/ridl/ir/v2/ir.proto`, which also enumerates the fields carrying
969    /// one. **That enumeration and this walk are edited together.** A
970    /// reference-bearing field added there and not read here makes the package
971    /// it names invisible to every caller asking what a package depends on.
972    ///
973    /// Every `oneof` below is matched exhaustively with no wildcard arm, so a
974    /// variant added later fails to compile here rather than going unread.
975    pub fn referenced_packages(package: &Package) -> std::collections::BTreeSet<String> {
976        let mut found = std::collections::BTreeSet::new();
977        for decl in &package.decls {
978            walk_decl(decl, &mut found);
979        }
980        for interface in &package.interfaces {
981            for interaction in &interface.interactions {
982                walk_decl(interaction, &mut found);
983            }
984        }
985        for service in &package.services {
986            for slot in &service.shapes {
987                match &slot.kind {
988                    Some(service_shape::Kind::InterfaceRef(reference)) => {
989                        qualifier(reference, &mut found);
990                    }
991                    Some(service_shape::Kind::Inline(interface)) => {
992                        for interaction in &interface.interactions {
993                            walk_decl(interaction, &mut found);
994                        }
995                    }
996                    None => {}
997                }
998            }
999        }
1000        found
1001    }
1002
1003    /// Records the package qualifier of a dotted reference. A bare reference
1004    /// is same-package and contributes nothing.
1005    fn qualifier(reference: &str, found: &mut std::collections::BTreeSet<String>) {
1006        if let Some((package, _)) = reference.rsplit_once('.') {
1007            found.insert(package.to_string());
1008        }
1009    }
1010
1011    /// Records every reference in one declaration — a package-level one or an
1012    /// interaction inside an interface, which share the `Decl` envelope.
1013    fn walk_decl(decl: &Decl, found: &mut std::collections::BTreeSet<String>) {
1014        match &decl.kind {
1015            Some(decl::Kind::TypeDef(type_def)) => walk_type_def(type_def, found),
1016            Some(decl::Kind::ConstDef(const_def)) => {
1017                if let Some(reference) = &const_def.type_ref {
1018                    qualifier(reference, found);
1019                }
1020            }
1021            Some(decl::Kind::StructDef(struct_def)) => {
1022                for member in &struct_def.members {
1023                    match &member.member {
1024                        Some(struct_member::Member::Field(field)) => {
1025                            if let Some(field_type) = &field.r#type {
1026                                walk_field_type(field_type, found);
1027                            }
1028                        }
1029                        // A tombstone occupies an ordinal and names no type.
1030                        Some(struct_member::Member::Reserved(_)) | None => {}
1031                    }
1032                }
1033            }
1034            // An enum's variants are integers; it names no type.
1035            Some(decl::Kind::EnumDef(_)) => {}
1036            Some(decl::Kind::EnumSetDef(enum_set)) => {
1037                if let Some(reference) = &enum_set.backing_enum {
1038                    qualifier(reference, found);
1039                }
1040            }
1041            Some(decl::Kind::UnionDef(union_def)) => {
1042                for arm in &union_def.arms {
1043                    qualifier(&arm.type_ref, found);
1044                }
1045            }
1046            Some(decl::Kind::SignalDef(signal)) => qualifier(&signal.payload, found),
1047            Some(decl::Kind::EventDef(event)) => qualifier(&event.payload, found),
1048            Some(decl::Kind::CommandDef(command)) => {
1049                for param in &command.params {
1050                    if let Some(field_type) = &param.r#type {
1051                        walk_field_type(field_type, found);
1052                    }
1053                }
1054            }
1055            Some(decl::Kind::QueryDef(query)) => {
1056                for param in &query.params {
1057                    if let Some(field_type) = &param.r#type {
1058                        walk_field_type(field_type, found);
1059                    }
1060                }
1061                if let Some(return_type) = &query.return_type {
1062                    walk_return_type(return_type, found);
1063                }
1064            }
1065            Some(decl::Kind::FixedDef(fixed)) => {
1066                if let Some(field_type) = &fixed.payload {
1067                    walk_field_type(field_type, found);
1068                }
1069            }
1070            // A tombstone occupies an ordinal and names no type.
1071            Some(decl::Kind::ReservedSlot(_)) | None => {}
1072        }
1073    }
1074
1075    /// The recursive half: a reference is reachable at arbitrary depth through
1076    /// tuples, arrays, maps, inline scalars, and streams.
1077    fn walk_field_type(field_type: &FieldType, found: &mut std::collections::BTreeSet<String>) {
1078        match &field_type.kind {
1079            Some(field_type::Kind::Named(reference)) => qualifier(reference, found),
1080            // A primitive names no package.
1081            Some(field_type::Kind::Primitive(_)) => {}
1082            Some(field_type::Kind::InlineScalar(type_def)) => walk_type_def(type_def, found),
1083            Some(field_type::Kind::Tuple(tuple)) => {
1084                for field in &tuple.fields {
1085                    if let Some(inner) = &field.r#type {
1086                        walk_field_type(inner, found);
1087                    }
1088                }
1089            }
1090            Some(field_type::Kind::Array(array)) => {
1091                if let Some(element) = &array.element {
1092                    walk_field_type(element, found);
1093                }
1094            }
1095            Some(field_type::Kind::Map(map)) => {
1096                if let Some(key) = &map.key {
1097                    walk_field_type(key, found);
1098                }
1099                if let Some(value) = &map.value {
1100                    walk_field_type(value, found);
1101                }
1102            }
1103            Some(field_type::Kind::Stream(stream)) => match &stream.element {
1104                Some(stream_type::Element::Named(reference)) => qualifier(reference, found),
1105                // STRING or BYTES only; names no package.
1106                Some(stream_type::Element::Primitive(_)) | None => {}
1107            },
1108            None => {}
1109        }
1110    }
1111
1112    /// A `TypeDef`'s only reference is the constant a `match` bound names.
1113    fn walk_type_def(type_def: &TypeDef, found: &mut std::collections::BTreeSet<String>) {
1114        if let Some(constraint) = &type_def.constraint
1115            && let Some(reference) = &constraint.pattern_const
1116        {
1117            qualifier(reference, found);
1118        }
1119    }
1120
1121    fn walk_return_type(return_type: &ReturnType, found: &mut std::collections::BTreeSet<String>) {
1122        match &return_type.kind {
1123            Some(return_type::Kind::Value(field_type)) => walk_field_type(field_type, found),
1124            Some(return_type::Kind::Fallible(fallible)) => {
1125                qualifier(&fallible.ok, found);
1126                qualifier(&fallible.err, found);
1127            }
1128            None => {}
1129        }
1130    }
1131
1132    /// Whether a constraint leaves a generated constructor nothing to check.
1133    ///
1134    /// True when no bound, step or pattern is present. A step is an enforced
1135    /// quantization constraint, including when its origin defaults to zero.
1136    ///
1137    /// A pattern given by name counts as a pattern: `pattern_const` is read as
1138    /// well as `pattern`, because a pattern constant that did not resolve leaves
1139    /// `pattern` absent while the type still carries a match constraint.
1140    /// `ridl-sem` treats the two fields the same way in its derived-init rule
1141    /// (`init.rs`).
1142    ///
1143    /// Because the checker materializes the typl §4.4 default `[0..256]` into
1144    /// `len_min`/`len_max`, every string and bytes type is non-vacuous. In
1145    /// practice this reduces to `boolean`, and `integer`/`float` with no declared
1146    /// range.
1147    pub fn constraint_is_vacuous(constraint: Option<&Constraint>) -> bool {
1148        let Some(c) = constraint else { return true };
1149        c.min.is_none()
1150            && c.max.is_none()
1151            && c.step.is_none()
1152            && c.len_min.is_none()
1153            && c.len_max.is_none()
1154            && c.pattern.is_none()
1155            && c.pattern_const.is_none()
1156    }
1157}
1158
1159pub mod catalog_hash;
1160pub mod class;
1161pub mod codegen;
1162pub mod name;
1163pub mod projection;
1164pub mod rules;
1165pub mod step;
1166pub mod zero;
1167
1168#[cfg(test)]
1169mod v2_round_trip {
1170    use crate::v2;
1171
1172    /// Wraps an interaction kind in the shared `Decl` envelope. Visibility
1173    /// and `is_error` stay unset on interactions (ridl §14.1); the ordinal is
1174    /// the 1-based declaration order across all interactions of the
1175    /// enclosing interface (ridl §11).
1176    fn interaction(name: &str, ordinal: u32, kind: v2::decl::Kind) -> v2::Decl {
1177        v2::Decl {
1178            limit: None,
1179            name: name.to_string(),
1180            visibility: v2::Visibility::Unspecified as i32,
1181            is_error: false,
1182            doc: String::new(),
1183            labels: Vec::new(),
1184            deprecated: None,
1185            ordinal,
1186            kind: Some(kind),
1187            links: Vec::new(),
1188            see: Vec::new(),
1189            since: Vec::new(),
1190        }
1191    }
1192
1193    fn named_type(name: &str) -> v2::FieldType {
1194        v2::FieldType {
1195            optional: false,
1196            kind: Some(v2::field_type::Kind::Named(name.to_string())),
1197        }
1198    }
1199
1200    fn stream_of(element: v2::stream_type::Element) -> v2::FieldType {
1201        v2::FieldType {
1202            optional: false,
1203            kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
1204                element: Some(element),
1205            })),
1206        }
1207    }
1208
1209    /// A representative ridl package: one interface holding all five
1210    /// interaction kinds plus a reserved tombstone (ordinals 1–6, the
1211    /// tombstone counted, ridl §11), a strict-periodic and a defaulted
1212    /// range timing, a fallible query, and two services — a named
1213    /// reference and an inline shape holding a stream query.
1214    fn fixture() -> v2::Package {
1215        // signal speed : Speed @10ms — strict periodic stores the period
1216        // in both bounds (ADR-0008 decision 12).
1217        let speed = v2::SignalDef {
1218            payload: "Speed".to_string(),
1219            declared_init: None,
1220            init: Some(v2::InitValue {
1221                derivable: true,
1222                value: Some("0.0".to_string()),
1223            }),
1224            timing: Some(v2::Timing {
1225                mode: v2::TimingMode::StrictPeriodic as i32,
1226                min_us: Some("10000".to_string()),
1227                max_us: Some("10000".to_string()),
1228                default_applied: false,
1229            }),
1230            family: v2::Family::Dispatch as i32,
1231        };
1232
1233        // event doorOpened : DoorEvent — untimed in source, so the
1234        // configured default range is resolved at compile time (ridl §9.1).
1235        let door_opened = v2::EventDef {
1236            payload: "DoorEvent".to_string(),
1237            timing: Some(v2::Timing {
1238                mode: v2::TimingMode::Range as i32,
1239                min_us: Some("20000".to_string()),
1240                max_us: Some("500000".to_string()),
1241                default_applied: true,
1242            }),
1243            family: v2::Family::Dispatch as i32,
1244        };
1245
1246        // command setTarget(target : Speed) [ require target >= speed ]
1247        let set_target = v2::CommandDef {
1248            params: vec![v2::Param {
1249                name: "target".to_string(),
1250                r#type: Some(named_type("Speed")),
1251                doc: String::new(),
1252                links: Vec::new(),
1253                see: Vec::new(),
1254                since: Vec::new(),
1255            }],
1256            contracts: vec![v2::Contract {
1257                kind: v2::ContractKind::Require as i32,
1258                source: "target >= speed".to_string(),
1259                signal_refs: vec!["speed".to_string()],
1260                param_refs: vec!["target".to_string()],
1261                uses_result: false,
1262                observer_id: "VehicleStatus.setTarget.require[0]".to_string(),
1263            }],
1264            timing: None,
1265            family: v2::Family::Dispatch as i32,
1266            shape: v2::Shape::None as i32,
1267        };
1268
1269        // query fetchFaults(page : PageSpec) : FaultPage | DiagError
1270        //   [ ensure result.count <= page.limit ]
1271        let fetch_faults = v2::QueryDef {
1272            params: vec![v2::Param {
1273                name: "page".to_string(),
1274                r#type: Some(named_type("PageSpec")),
1275                doc: String::new(),
1276                links: Vec::new(),
1277                see: Vec::new(),
1278                since: Vec::new(),
1279            }],
1280            return_type: Some(v2::ReturnType {
1281                kind: Some(v2::return_type::Kind::Fallible(v2::FallibleType {
1282                    ok: "FaultPage".to_string(),
1283                    err: "DiagError".to_string(),
1284                })),
1285            }),
1286            contracts: vec![v2::Contract {
1287                kind: v2::ContractKind::Ensure as i32,
1288                source: "result.count <= page.limit".to_string(),
1289                signal_refs: Vec::new(),
1290                param_refs: vec!["page".to_string()],
1291                uses_result: true,
1292                observer_id: "VehicleStatus.fetchFaults.ensure[0]".to_string(),
1293            }],
1294            timing: None,
1295            family: v2::Family::Dispatch as i32,
1296        };
1297
1298        // fixed vin : Vin
1299        let vin = v2::FixedDef {
1300            payload: Some(named_type("Vin")),
1301        };
1302
1303        let vehicle_status = v2::Interface {
1304            name: "VehicleStatus".to_string(),
1305            visibility: v2::Visibility::Public as i32,
1306            doc: "Vehicle status contract".to_string(),
1307            labels: Vec::new(),
1308            deprecated: None,
1309            interactions: vec![
1310                interaction("speed", 1, v2::decl::Kind::SignalDef(speed)),
1311                interaction("doorOpened", 2, v2::decl::Kind::EventDef(door_opened)),
1312                // reserved legacyMode — the tombstone keeps ordinal 3
1313                // occupied in the one interaction sequence (ridl §11).
1314                v2::Decl {
1315                    ordinal: 3,
1316                    kind: Some(v2::decl::Kind::ReservedSlot(v2::Reserved {
1317                        ordinal: 3,
1318                        name: Some("legacyMode".to_string()),
1319                        value: None,
1320                    })),
1321                    ..interaction("", 3, v2::decl::Kind::ReservedSlot(v2::Reserved::default()))
1322                },
1323                interaction("setTarget", 4, v2::decl::Kind::CommandDef(set_target)),
1324                interaction("fetchFaults", 5, v2::decl::Kind::QueryDef(fetch_faults)),
1325                interaction("vin", 6, v2::decl::Kind::FixedDef(vin)),
1326            ],
1327            number: 0,
1328            provisional: false,
1329            links: Vec::new(),
1330            see: Vec::new(),
1331            since: Vec::new(),
1332        };
1333
1334        // query tailLogs(pattern : <string>) : <LogLine> — a stream param
1335        // and a stream return (ridl §12), inside the inline service shape.
1336        let tail_logs = v2::QueryDef {
1337            params: vec![v2::Param {
1338                name: "pattern".to_string(),
1339                r#type: Some(stream_of(v2::stream_type::Element::Primitive(
1340                    v2::PrimitiveType::String as i32,
1341                ))),
1342                doc: String::new(),
1343                links: Vec::new(),
1344                see: Vec::new(),
1345                since: Vec::new(),
1346            }],
1347            return_type: Some(v2::ReturnType {
1348                kind: Some(v2::return_type::Kind::Value(stream_of(
1349                    v2::stream_type::Element::Named("LogLine".to_string()),
1350                ))),
1351            }),
1352            contracts: Vec::new(),
1353            timing: None,
1354            family: v2::Family::Dispatch as i32,
1355        };
1356
1357        // service veh.adas.status : VehicleStatus — one named reference in
1358        // the service's set (ADR-0015 decision 12).
1359        let status_service = v2::Service {
1360            name: "veh.adas.status".to_string(),
1361            visibility: v2::Visibility::Public as i32,
1362            doc: String::new(),
1363            labels: Vec::new(),
1364            deprecated: None,
1365            shapes: vec![v2::ServiceShape {
1366                kind: Some(v2::service_shape::Kind::InterfaceRef(
1367                    "VehicleStatus".to_string(),
1368                )),
1369            }],
1370            links: Vec::new(),
1371            see: Vec::new(),
1372            since: Vec::new(),
1373        };
1374        // service veh.adas.logs { … } — the inline shape as the one entry,
1375        // Interface.name == "" (ridl §14.5).
1376        let logs_service = v2::Service {
1377            name: "veh.adas.logs".to_string(),
1378            visibility: v2::Visibility::Public as i32,
1379            doc: String::new(),
1380            labels: Vec::new(),
1381            deprecated: None,
1382            shapes: vec![v2::ServiceShape {
1383                kind: Some(v2::service_shape::Kind::Inline(v2::Interface {
1384                    name: String::new(),
1385                    visibility: v2::Visibility::Unspecified as i32,
1386                    doc: String::new(),
1387                    labels: Vec::new(),
1388                    deprecated: None,
1389                    interactions: vec![interaction(
1390                        "tailLogs",
1391                        1,
1392                        v2::decl::Kind::QueryDef(tail_logs),
1393                    )],
1394                    number: 0,
1395                    provisional: false,
1396                    links: Vec::new(),
1397                    see: Vec::new(),
1398                    since: Vec::new(),
1399                })),
1400            }],
1401            links: Vec::new(),
1402            see: Vec::new(),
1403            since: Vec::new(),
1404        };
1405
1406        v2::Package {
1407            name: "veh.adas".to_string(),
1408            // One typl declaration proves the verbatim v1 surface rides
1409            // along unchanged in v2; package-level declarations carry
1410            // ordinal 0.
1411            decls: vec![v2::Decl {
1412                limit: None,
1413                name: "Speed".to_string(),
1414                visibility: v2::Visibility::Public as i32,
1415                is_error: false,
1416                doc: String::new(),
1417                labels: Vec::new(),
1418                deprecated: None,
1419                ordinal: 0,
1420                kind: Some(v2::decl::Kind::TypeDef(v2::TypeDef {
1421                    backing: Some(v2::Backing {
1422                        kind: Some(v2::backing::Kind::Unit("km/h".to_string())),
1423                    }),
1424                    constraint: None,
1425                    declared_init: None,
1426                    init: None,
1427                    width: Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F32 as i32)),
1428                })),
1429                links: Vec::new(),
1430                see: Vec::new(),
1431                since: Vec::new(),
1432            }],
1433            interfaces: vec![vehicle_status],
1434            services: vec![status_service, logs_service],
1435            retired: Vec::new(),
1436            unit: "veh.adas".to_string(),
1437        }
1438    }
1439
1440    /// The typl vocabulary surface the interaction fixture does not reach:
1441    /// the boxed `inlineScalar` oneof member, genuine 64-bit integer fields
1442    /// (array and map bounds, length bounds, `Reserved.value`,
1443    /// `EnumValue.value`), a tuple, a map, a union, an enum set, a constant,
1444    /// and a set `deprecated`. A second fixture, so each stays readable; the
1445    /// same round-trip tests drive both.
1446    fn vocabulary_fixture() -> v2::Package {
1447        fn decl(name: &str, kind: v2::decl::Kind) -> v2::Decl {
1448            v2::Decl {
1449                limit: None,
1450                name: name.to_string(),
1451                visibility: v2::Visibility::Public as i32,
1452                is_error: false,
1453                doc: String::new(),
1454                labels: Vec::new(),
1455                deprecated: None,
1456                ordinal: 0,
1457                kind: Some(kind),
1458                links: Vec::new(),
1459                see: Vec::new(),
1460                since: Vec::new(),
1461            }
1462        }
1463
1464        fn field(name: &str, ordinal: u32, field_type: v2::FieldType) -> v2::Field {
1465            v2::Field {
1466                name: name.to_string(),
1467                ordinal,
1468                r#type: Some(field_type),
1469                declared_init: None,
1470                init: None,
1471                doc: String::new(),
1472                labels: Vec::new(),
1473                deprecated: None,
1474                links: Vec::new(),
1475                see: Vec::new(),
1476                since: Vec::new(),
1477            }
1478        }
1479
1480        // const MAX_RETRY : integer = 24
1481        let max_retry = v2::ConstDef {
1482            type_ref: Some("integer".to_string()),
1483            value: "24".to_string(),
1484            regex: None,
1485        };
1486
1487        // enum Gear { PARK = 1  DRIVE = 2  reserved 7 } — the tombstone
1488        // retires the integer value, a genuine int64 field.
1489        let gear = v2::EnumDef {
1490            values: vec![
1491                v2::EnumValue {
1492                    name: "PARK".to_string(),
1493                    value: 1,
1494                    doc: String::new(),
1495                    links: Vec::new(),
1496                    see: Vec::new(),
1497                    since: Vec::new(),
1498                },
1499                v2::EnumValue {
1500                    name: "DRIVE".to_string(),
1501                    value: 2,
1502                    doc: String::new(),
1503                    links: Vec::new(),
1504                    see: Vec::new(),
1505                    since: Vec::new(),
1506                },
1507            ],
1508            reserved: vec![v2::Reserved {
1509                ordinal: 0,
1510                name: None,
1511                value: Some(7),
1512            }],
1513            open: false,
1514        };
1515
1516        // enumset Warnings { LOW_FUEL = 0  ICE_RISK = 33 } — the standalone
1517        // form; bit 33 forces the u64 width and is a genuine int64 value.
1518        let warnings = v2::EnumSetDef {
1519            backing_enum: None,
1520            bits: vec![
1521                v2::EnumValue {
1522                    name: "LOW_FUEL".to_string(),
1523                    value: 0,
1524                    doc: String::new(),
1525                    links: Vec::new(),
1526                    see: Vec::new(),
1527                    since: Vec::new(),
1528                },
1529                v2::EnumValue {
1530                    name: "ICE_RISK".to_string(),
1531                    value: 33,
1532                    doc: String::new(),
1533                    links: Vec::new(),
1534                    see: Vec::new(),
1535                    since: Vec::new(),
1536                },
1537            ],
1538            width: v2::IntWidth::U64 as i32,
1539            open: false,
1540        };
1541
1542        // type PlateText : string [1..86] — character length bounds, two
1543        // genuine uint64 fields behind proto3 `optional`.
1544        let plate_text = v2::TypeDef {
1545            backing: Some(v2::Backing {
1546                kind: Some(v2::backing::Kind::Primitive(
1547                    v2::PrimitiveType::String as i32,
1548                )),
1549            }),
1550            constraint: Some(v2::Constraint {
1551                min: None,
1552                max: None,
1553                step: None,
1554                len_min: Some(1),
1555                len_max: Some(86),
1556                pattern: None,
1557                pattern_const: None,
1558            }),
1559            declared_init: None,
1560            init: None,
1561            width: None,
1562        };
1563
1564        // union Sample { speed : Speed  gear : Gear }
1565        let sample = v2::UnionDef {
1566            arms: vec![
1567                v2::UnionArm {
1568                    name: "speed".to_string(),
1569                    ordinal: 1,
1570                    type_ref: "Speed".to_string(),
1571                    doc: String::new(),
1572                    links: Vec::new(),
1573                    see: Vec::new(),
1574                    since: Vec::new(),
1575                },
1576                v2::UnionArm {
1577                    name: "gear".to_string(),
1578                    ordinal: 2,
1579                    type_ref: "Gear".to_string(),
1580                    doc: String::new(),
1581                    links: Vec::new(),
1582                    see: Vec::new(),
1583                    since: Vec::new(),
1584                },
1585            ],
1586            is_result: false,
1587            reserved: Vec::new(),
1588        };
1589
1590        // retries : integer [0..24] = 3 — the boxed `inlineScalar` oneof
1591        // member: the committed regression guard for ADR-0014 Open item 2,
1592        // which established that the Rust-side `Box` is invisible to the
1593        // reflection path. The enclosing field carries the init; the nested
1594        // TypeDef's stays unset.
1595        let retries = v2::Field {
1596            declared_init: Some("3".to_string()),
1597            init: Some(v2::InitValue {
1598                derivable: true,
1599                value: Some("3".to_string()),
1600            }),
1601            ..field(
1602                "retries",
1603                1,
1604                v2::FieldType {
1605                    optional: false,
1606                    kind: Some(v2::field_type::Kind::InlineScalar(Box::new(v2::TypeDef {
1607                        backing: Some(v2::Backing {
1608                            kind: Some(v2::backing::Kind::Primitive(
1609                                v2::PrimitiveType::Integer as i32,
1610                            )),
1611                        }),
1612                        constraint: Some(v2::Constraint {
1613                            min: Some("0".to_string()),
1614                            max: Some("24".to_string()),
1615                            step: None,
1616                            len_min: None,
1617                            len_max: None,
1618                            pattern: None,
1619                            pattern_const: None,
1620                        }),
1621                        declared_init: None,
1622                        init: None,
1623                        width: Some(v2::type_def::Width::IntWidth(v2::IntWidth::U8 as i32)),
1624                    }))),
1625                },
1626            )
1627        };
1628
1629        // position : (x : Speed, y : Speed) — an anonymous named-field
1630        // composite (typl §11).
1631        let position = field(
1632            "position",
1633            2,
1634            v2::FieldType {
1635                optional: false,
1636                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
1637                    fields: vec![
1638                        v2::TupleField {
1639                            name: "x".to_string(),
1640                            r#type: Some(named_type("Speed")),
1641                        },
1642                        v2::TupleField {
1643                            name: "y".to_string(),
1644                            r#type: Some(named_type("Speed")),
1645                        },
1646                    ],
1647                })),
1648            },
1649        );
1650
1651        // gears : [Gear; 1..4096] — array bounds are genuine uint64 fields.
1652        let gears = field(
1653            "gears",
1654            3,
1655            v2::FieldType {
1656                optional: false,
1657                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1658                    element: Some(Box::new(named_type("Gear"))),
1659                    min: 1,
1660                    max: 4096,
1661                }))),
1662            },
1663        );
1664
1665        // plates : { PlateText -> Gear } [0..53] — map bounds are genuine
1666        // uint64 fields. The field is deprecated, covering the optional
1667        // string on the Field envelope.
1668        let plates = v2::Field {
1669            deprecated: Some("superseded by gears".to_string()),
1670            ..field(
1671                "plates",
1672                4,
1673                v2::FieldType {
1674                    optional: false,
1675                    kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
1676                        key: Some(Box::new(named_type("PlateText"))),
1677                        value: Some(Box::new(named_type("Gear"))),
1678                        min: 0,
1679                        max: 53,
1680                    }))),
1681                },
1682            )
1683        };
1684
1685        let snapshot = v2::StructDef {
1686            members: [retries, position, gears, plates]
1687                .into_iter()
1688                .map(|field| v2::StructMember {
1689                    member: Some(v2::struct_member::Member::Field(Box::new(field))),
1690                })
1691                .collect(),
1692            fixed_layout: false,
1693        };
1694
1695        v2::Package {
1696            name: "veh.vocab".to_string(),
1697            decls: vec![
1698                decl("MAX_RETRY", v2::decl::Kind::ConstDef(max_retry)),
1699                decl("Gear", v2::decl::Kind::EnumDef(gear)),
1700                decl("Warnings", v2::decl::Kind::EnumSetDef(warnings)),
1701                decl("PlateText", v2::decl::Kind::TypeDef(plate_text)),
1702                // The union is deprecated — the optional string on the Decl
1703                // envelope.
1704                v2::Decl {
1705                    deprecated: Some("use Snapshot".to_string()),
1706                    ..decl("Sample", v2::decl::Kind::UnionDef(sample))
1707                },
1708                decl("Snapshot", v2::decl::Kind::StructDef(snapshot)),
1709            ],
1710            interfaces: Vec::new(),
1711            services: Vec::new(),
1712            retired: Vec::new(),
1713            unit: String::new(),
1714        }
1715    }
1716
1717    #[test]
1718    fn protobuf_round_trip_preserves_package() {
1719        let package = fixture();
1720
1721        let buf = v2::to_binary(&package);
1722        let decoded = v2::from_binary(buf.as_slice()).expect("decode must succeed");
1723
1724        assert_eq!(package, decoded);
1725
1726        // The vocabulary fixture rides the same round trip.
1727        let vocabulary = vocabulary_fixture();
1728        let decoded_vocabulary =
1729            v2::from_binary(v2::to_binary(&vocabulary).as_slice()).expect("decode must succeed");
1730        assert_eq!(vocabulary, decoded_vocabulary);
1731
1732        let interface = &decoded.interfaces[0];
1733        let ordinals: Vec<u32> = interface.interactions.iter().map(|d| d.ordinal).collect();
1734        assert_eq!(
1735            ordinals,
1736            [1, 2, 3, 4, 5, 6],
1737            "one ordinal sequence, tombstone counted (ridl §11)"
1738        );
1739        let Some(v2::decl::Kind::ReservedSlot(tombstone)) = &interface.interactions[2].kind else {
1740            panic!("ordinal 3 must decode as a reserved tombstone");
1741        };
1742        assert_eq!(tombstone.name.as_deref(), Some("legacyMode"));
1743        let Some(v2::service_shape::Kind::Inline(inline)) = decoded.services[1]
1744            .shapes
1745            .first()
1746            .and_then(|slot| slot.kind.as_ref())
1747        else {
1748            panic!("veh.adas.logs must decode as an inline shape");
1749        };
1750        assert_eq!(inline.name, "", "an inline shape carries no name");
1751        let references: Vec<&str> = decoded.services[0]
1752            .shapes
1753            .iter()
1754            .filter_map(|slot| match &slot.kind {
1755                Some(v2::service_shape::Kind::InterfaceRef(reference)) => Some(reference.as_str()),
1756                _ => None,
1757            })
1758            .collect();
1759        assert_eq!(
1760            references,
1761            ["VehicleStatus"],
1762            "a service's set carries its references and nothing else"
1763        );
1764    }
1765
1766    /// A package with one interface `I` holding one command `c` of the given
1767    /// family and shape.
1768    fn package_with_command(family: v2::Family, shape: v2::Shape) -> v2::Package {
1769        v2::Package {
1770            name: "app".to_string(),
1771            interfaces: vec![v2::Interface {
1772                name: "I".to_string(),
1773                visibility: v2::Visibility::Public as i32,
1774                interactions: vec![v2::Decl {
1775                    name: "c".to_string(),
1776                    visibility: v2::Visibility::Public as i32,
1777                    ordinal: 1,
1778                    kind: Some(v2::decl::Kind::CommandDef(v2::CommandDef {
1779                        family: family as i32,
1780                        shape: shape as i32,
1781                        ..Default::default()
1782                    })),
1783                    ..Default::default()
1784                }],
1785                ..Default::default()
1786            }],
1787            ..Default::default()
1788        }
1789    }
1790
1791    /// `(command, intent, none)` is refused where the IR is read, by both
1792    /// readers: ADR-0012 decision 5 admits no generic intent command.
1793    #[test]
1794    fn the_readers_reject_an_invalid_interaction_class() {
1795        let package = package_with_command(v2::Family::Intent, v2::Shape::None);
1796        let json = v2::render_json(&package).expect("the raw writer renders it");
1797        let err = v2::from_json(&json).expect_err("the JSON reader must refuse it");
1798        assert!(
1799            err.to_string().contains("invalid interaction class"),
1800            "{err}"
1801        );
1802        let bytes = prost::Message::encode_to_vec(&package);
1803        let err = v2::from_binary(&bytes).expect_err("the binary reader must refuse it");
1804        assert!(
1805            err.to_string().contains("invalid interaction class"),
1806            "{err}"
1807        );
1808    }
1809
1810    #[test]
1811    fn the_json_writer_refuses_an_invalid_interaction_class() {
1812        let package = package_with_command(v2::Family::Intent, v2::Shape::None);
1813        let err = v2::to_json_pretty(&package).expect_err("the writer must refuse it");
1814        assert!(matches!(err, v2::SerializeError::Class(_)), "{err}");
1815    }
1816
1817    #[test]
1818    fn a_valid_class_round_trips_through_both_readers() {
1819        let package = package_with_command(v2::Family::Intent, v2::Shape::Toggle);
1820        let json = v2::to_json_pretty(&package).expect("the writer renders it");
1821        assert_eq!(v2::from_json(&json).expect("the JSON parses"), package);
1822        assert_eq!(
1823            v2::from_binary(&v2::to_binary(&package)).expect("the binary decodes"),
1824            package
1825        );
1826    }
1827
1828    /// An IR written before `family` existed has no such key and reads as
1829    /// dispatch.
1830    #[test]
1831    fn a_snapshot_without_family_reads_as_dispatch() {
1832        let package = package_with_command(v2::Family::Dispatch, v2::Shape::None);
1833        let json = v2::to_json_pretty(&package).expect("the writer renders it");
1834        let mut value: serde_json::Value =
1835            serde_json::from_str(&json).expect("the rendering is JSON");
1836        let command = value["interfaces"][0]["interactions"][0]["commandDef"]
1837            .as_object_mut()
1838            .expect("the command object");
1839        assert!(command.remove("family").is_some(), "`family` was rendered");
1840        assert!(command.remove("shape").is_some(), "`shape` was rendered");
1841        let stripped = serde_json::to_string(&value).expect("the stripped value renders");
1842        let read = v2::from_json(&stripped).expect("a 0.9 snapshot reads");
1843        assert_eq!(read, package);
1844    }
1845
1846    #[test]
1847    fn json_round_trip_preserves_package() {
1848        for package in [fixture(), vocabulary_fixture()] {
1849            let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
1850            let decoded = v2::from_json(&json).expect("json deserialization must succeed");
1851
1852            assert_eq!(package, decoded);
1853        }
1854    }
1855
1856    /// The interface identity fields the lock design §9 adds — `number` and
1857    /// `provisional` on every `Interface`, an inline shape included, and the
1858    /// package's `retired` list — ride all three encodings unchanged, and the
1859    /// JSON writes them under their canonical names even when they hold their
1860    /// defaults (ADR-0014 decision 2), so a reader can tell `number` 0 from an
1861    /// absent field only by the schema, never by the text.
1862    #[test]
1863    fn number_provisional_and_retired_round_trip_through_json_text_and_binary() {
1864        let mut package = fixture();
1865        package.interfaces[0].number = 4;
1866        package.interfaces[0].provisional = true;
1867        let Some(v2::service_shape::Kind::Inline(inline)) =
1868            package.services[1].shapes[0].kind.as_mut()
1869        else {
1870            panic!("veh.adas.logs holds an inline shape in slot 1");
1871        };
1872        inline.number = 5;
1873        package.retired = vec![
1874            v2::RetiredInterface {
1875                name: "LaneAssist".to_string(),
1876                number: 2,
1877            },
1878            v2::RetiredInterface {
1879                name: "service:veh.hvac.cabin".to_string(),
1880                number: 3,
1881            },
1882        ];
1883
1884        let json = v2::to_json_pretty(&package).expect("the package serializes as IR JSON");
1885        assert_eq!(v2::from_json(&json).expect("the JSON parses back"), package);
1886        let text = v2::to_text_format(&package).expect("the package serializes as prototext");
1887        assert_eq!(
1888            v2::from_text_format(&text).expect("the prototext parses back"),
1889            package
1890        );
1891        assert_eq!(
1892            v2::from_binary(v2::to_binary(&package).as_slice()).expect("the binary decodes"),
1893            package
1894        );
1895
1896        for needle in [
1897            r#""number": 4"#,
1898            r#""provisional": true"#,
1899            r#""number": 5"#,
1900            r#""name": "LaneAssist""#,
1901            r#""name": "service:veh.hvac.cabin""#,
1902        ] {
1903            assert!(
1904                json.contains(needle),
1905                "the JSON must carry {needle}, got: {json}"
1906            );
1907        }
1908
1909        // A default holds its place in the text (decision 2): an interface
1910        // that was never numbered writes `0` and `false`, and a package with
1911        // nothing retired writes an empty list.
1912        let unnumbered = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
1913        for needle in [
1914            r#""number": 0"#,
1915            r#""provisional": false"#,
1916            r#""retired": []"#,
1917        ] {
1918            assert!(
1919                unnumbered.contains(needle),
1920                "a default field must still be written, expected {needle} in: {unnumbered}"
1921            );
1922        }
1923    }
1924
1925    /// A baseline published before the lock existed carries no `number`, no
1926    /// `provisional` and no `retired` field. It still loads — a missing field
1927    /// reads as its default, which is the `number` 0 the lock design §7 names
1928    /// as the one transition case — while an unknown field is still rejected
1929    /// (`json_parse_rejects_an_unknown_field`).
1930    #[test]
1931    fn a_snapshot_lacking_the_number_fields_still_loads() {
1932        let package = v2::from_json(
1933            r#"{"name": "veh.x", "interfaces": [{"name": "LaneKeeping"}], "services": [{"name": "veh.x.s", "shapes": [{"inline": {"name": ""}}]}]}"#,
1934        )
1935        .expect("a pre-lock snapshot loads");
1936
1937        assert_eq!(package.interfaces[0].number, 0);
1938        assert!(!package.interfaces[0].provisional);
1939        let Some(v2::service_shape::Kind::Inline(inline)) =
1940            package.services[0].shapes[0].kind.as_ref()
1941        else {
1942            panic!("the service holds an inline shape");
1943        };
1944        assert_eq!(inline.number, 0);
1945        assert!(!inline.provisional);
1946        assert_eq!(package.retired, Vec::new());
1947    }
1948
1949    /// The prototext read path (ADR-0014 decision 7): both fixtures survive
1950    /// `to_text_format` then `from_text_format` unchanged. With the binary
1951    /// and JSON round trips above, this is what proves all three encodings
1952    /// carry the same IR.
1953    #[test]
1954    fn text_format_round_trip_preserves_package() {
1955        for package in [fixture(), vocabulary_fixture()] {
1956            let text = v2::to_text_format(&package).expect("the fixture serializes as prototext");
1957            let decoded = v2::from_text_format(&text).expect("prototext parsing must succeed");
1958
1959            assert_eq!(package, decoded);
1960        }
1961    }
1962
1963    /// The prototext options ADR-0014 decision 8 fixes — `pretty`,
1964    /// `skip_default_fields(false)`, `print_message_fields_in_index_order`.
1965    /// Any option set round-trips, which is why the round-trip test above
1966    /// cannot guard them.
1967    ///
1968    /// The first two are asserted through a visible consequence. The third is
1969    /// **not guarded here and cannot be on this schema**: every message in
1970    /// `ir.proto` declares its fields in ascending field-number order, and
1971    /// field-number order is also `prost-reflect`'s default, so index order
1972    /// and default order coincide everywhere and dropping the option would
1973    /// change no output. It is set because the schema's ordering is a
1974    /// property of the schema rather than a guarantee, and a message whose
1975    /// declaration order departs from its numbering would otherwise reorder
1976    /// every artifact it appears in.
1977    #[test]
1978    fn text_format_is_pretty_with_defaults_in_index_order() {
1979        let text = v2::to_text_format(&fixture()).expect("the fixture serializes as prototext");
1980
1981        // pretty: nested messages are indented, one field per line.
1982        assert!(
1983            text.contains("\n  "),
1984            "pretty printing must indent nested fields, got: {text}"
1985        );
1986        // skip_default_fields(false): a field holding its default is present
1987        // (decision 2 — `ordinal: 0` is read, not inferred from absence).
1988        assert!(
1989            text.contains("is_error: false"),
1990            "a field holding its default must be emitted, got: {text}"
1991        );
1992        // print_message_fields_in_index_order: `name` is field 1 of
1993        // `Package`, so it opens the output.
1994        assert!(
1995            text.starts_with("name:"),
1996            "fields must print in schema index order, got: {text}"
1997        );
1998    }
1999
2000    /// Parses emitted JSON the way ADR-0014 decision 11's conformance test
2001    /// requires: unknown fields rejected, trailing input rejected. Since
2002    /// decision 14 the strict parser is the pbjson-generated `Deserialize`
2003    /// impl, whose default already rejects unknown fields
2004    /// (`ignore_unknown_fields()` stays unset in `build.rs`), so the
2005    /// strictness needs no option to opt into.
2006    fn strict_parse(json: &str) -> v2::Package {
2007        let mut deserializer = serde_json::Deserializer::from_str(json);
2008        let package = <v2::Package as serde::Deserialize>::deserialize(&mut deserializer)
2009            .expect("a strict conformant parser must accept the emitted JSON");
2010        deserializer.end().expect("no trailing input");
2011        package
2012    }
2013
2014    /// The conformance claim of ADR-0014 decision 11: a conformant protobuf
2015    /// JSON parser configured to reject unknown fields accepts the emitted
2016    /// JSON. Re-reading tests that claim itself; asserting on the rendered
2017    /// text would only restate the serializer's behaviour back to itself.
2018    #[test]
2019    fn emitted_json_survives_a_strict_conformant_parse() {
2020        for package in [fixture(), vocabulary_fixture()] {
2021            let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
2022            assert_eq!(package, strict_parse(&json));
2023        }
2024    }
2025
2026    #[test]
2027    fn json_renders_timing_bounds_and_fallible_arms_exactly() {
2028        let json = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
2029
2030        // Exactness is visible: timing bounds are exact-decimal microsecond
2031        // strings, never floating-point numbers (ADR-0008 decision 12) —
2032        // under the canonical lowerCamelCase field name (ADR-0014 decision 1).
2033        assert!(
2034            json.contains(r#""minUs": "10000""#),
2035            "the timing bound must be a JSON string, got: {json}"
2036        );
2037        // Both arms of the inline T | E return are visible by name.
2038        assert!(
2039            json.contains(r#""ok": "FaultPage""#),
2040            "the ok arm must render, got: {json}"
2041        );
2042        assert!(
2043            json.contains(r#""err": "DiagError""#),
2044            "the err arm must render, got: {json}"
2045        );
2046    }
2047
2048    /// ADR-0014 decision 8's stringification, tested on genuine 64-bit
2049    /// fields. The timing assertion above proves nothing about it —
2050    /// `Timing.min_us` is `optional string` in the schema — so the claim
2051    /// needs fields whose wire type actually is `uint64` or `int64`.
2052    #[test]
2053    fn json_renders_64_bit_integer_fields_as_strings() {
2054        let json = v2::to_json_pretty(&vocabulary_fixture())
2055            .expect("the vocabulary fixture serializes as IR JSON");
2056
2057        // uint64: the array's upper bound.
2058        assert!(
2059            json.contains(r#""max": "4096""#),
2060            "an array bound must be a JSON string, got: {json}"
2061        );
2062        // uint64 behind proto3 `optional`: the character length bound.
2063        assert!(
2064            json.contains(r#""lenMax": "86""#),
2065            "a length bound must be a JSON string, got: {json}"
2066        );
2067        // int64: the retired enum value and the enum-set bit position.
2068        assert!(
2069            json.contains(r#""value": "7""#),
2070            "a retired enum value must be a JSON string, got: {json}"
2071        );
2072        assert!(
2073            json.contains(r#""value": "33""#),
2074            "an enum-set bit position must be a JSON string, got: {json}"
2075        );
2076    }
2077
2078    #[test]
2079    fn fallible_transport_identity_follows_the_derivation_rule() {
2080        // The ADR-0008 decision 4 rule: interface + interaction ordinal +
2081        // both arm references, in that order.
2082        let fallible = v2::FallibleType {
2083            ok: "FaultPage".to_string(),
2084            err: "DiagError".to_string(),
2085        };
2086        assert_eq!(
2087            v2::fallible_transport_identity("VehicleStatus", 9, &fallible),
2088            "VehicleStatus#9:FaultPage|DiagError"
2089        );
2090
2091        // Derived from the fixture: the fallible query sits at ordinal 5.
2092        let package = fixture();
2093        let interface = &package.interfaces[0];
2094        let query_decl = &interface.interactions[4];
2095        let Some(v2::decl::Kind::QueryDef(query)) = &query_decl.kind else {
2096            panic!("ordinal 5 must be the fallible query");
2097        };
2098        let Some(v2::return_type::Kind::Fallible(arms)) = &query.return_type.as_ref().unwrap().kind
2099        else {
2100            panic!("fetchFaults must return a fallible type");
2101        };
2102        assert_eq!(
2103            v2::fallible_transport_identity(&interface.name, query_decl.ordinal, arms),
2104            "VehicleStatus#5:FaultPage|DiagError"
2105        );
2106    }
2107
2108    /// `Package::shapes` yields the named interfaces first, then the inline
2109    /// shapes of the services — and each shape carries the name it is known by
2110    /// OUTSIDE the package. The fixture's inline shape has `Interface.name ==
2111    /// ""` by construction, so a walk that yielded the interface bare would
2112    /// hand every consumer the empty string; two of the six E2 defects were
2113    /// exactly that.
2114    #[test]
2115    fn shapes_walks_named_interfaces_and_inline_service_shapes() {
2116        let package = fixture();
2117        let walk: Vec<(&str, bool, usize)> = package
2118            .shapes()
2119            .map(|shape| {
2120                (
2121                    shape.name,
2122                    shape.is_inline(),
2123                    shape.interface.interactions.len(),
2124                )
2125            })
2126            .collect();
2127        assert_eq!(
2128            walk,
2129            [("VehicleStatus", false, 6), ("veh.adas.logs", true, 1)],
2130            "the named interface, then the inline shape under the service's \
2131             dotted name",
2132        );
2133
2134        // The fixture's third shape-bearing declaration is `service
2135        // veh.adas.status : VehicleStatus`, which names an interface already in
2136        // the walk. Yielding it too would visit `VehicleStatus` twice.
2137        assert_eq!(package.services.len(), 2, "one reference form, one inline");
2138        assert!(
2139            !package
2140                .shapes()
2141                .any(|shape| shape.name == "veh.adas.status"),
2142            "a service naming an interface contributes no shape of its own",
2143        );
2144    }
2145
2146    #[test]
2147    fn relative_name_strips_the_unit_prefix() {
2148        assert_eq!(v2::relative_name("u", "u", "Session"), "Session");
2149        assert_eq!(
2150            v2::relative_name("u", "u.cluster", "Speed"),
2151            "cluster.Speed"
2152        );
2153        assert_eq!(
2154            v2::relative_name("com.example.hmi", "com.example.hmi.cluster.front", "A"),
2155            "cluster.front.A"
2156        );
2157    }
2158
2159    /// A package that is not inside the unit keeps its full name: no slice
2160    /// past the unit's length, whatever the snapshot says.
2161    #[test]
2162    fn relative_name_keeps_the_full_name_of_a_package_outside_the_unit() {
2163        assert_eq!(
2164            v2::relative_name("u", "w.cluster", "Speed"),
2165            "w.cluster.Speed"
2166        );
2167        assert_eq!(v2::relative_name("u", "ux", "A"), "ux.A");
2168        assert_eq!(v2::relative_name("u.cluster", "u", "Session"), "u.Session");
2169    }
2170
2171    /// A package named twice in the slice contributes the retired entries
2172    /// of its first occurrence only: two distinct values with the same name
2173    /// are not merged, and the later one is not read.
2174    #[test]
2175    fn unit_retired_reads_a_package_named_twice_once() {
2176        let first = v2::Package {
2177            name: "u.cluster".to_string(),
2178            unit: "u".to_string(),
2179            retired: vec![v2::RetiredInterface {
2180                name: "cluster.Old".to_string(),
2181                number: 3,
2182            }],
2183            ..Default::default()
2184        };
2185        let second = v2::Package {
2186            retired: vec![v2::RetiredInterface {
2187                name: "cluster.Older".to_string(),
2188                number: 4,
2189            }],
2190            ..first.clone()
2191        };
2192        assert_eq!(
2193            v2::unit_retired("u", &[&first, &second]),
2194            first.retired,
2195            "the first package of a name is the one read"
2196        );
2197    }
2198
2199    #[test]
2200    fn an_inline_shape_keeps_its_global_name() {
2201        let mut package = fixture();
2202        package.name = "u.cluster".to_string();
2203        package.unit = "u".to_string();
2204        let inline = package
2205            .shapes()
2206            .find(|shape| shape.is_inline())
2207            .expect("the fixture has an inline shape");
2208        assert_eq!(package.catalog_name(&inline), "veh.adas.logs");
2209        let named = package
2210            .shapes()
2211            .find(|shape| !shape.is_inline())
2212            .expect("the fixture has a declared interface");
2213        assert_eq!(package.catalog_name(&named), "cluster.VehicleStatus");
2214    }
2215
2216    #[test]
2217    fn catalog_name_treats_an_empty_unit_as_the_package_name() {
2218        let mut package = fixture();
2219        package.unit = String::new();
2220        let named = package
2221            .shapes()
2222            .find(|shape| !shape.is_inline())
2223            .expect("the fixture has a declared interface");
2224        assert_eq!(package.catalog_name(&named), "VehicleStatus");
2225    }
2226
2227    #[test]
2228    fn unit_of_falls_back_to_the_name() {
2229        let bare = v2::Package {
2230            name: "p".to_string(),
2231            ..Default::default()
2232        };
2233        assert_eq!(v2::unit_of(&bare), "p");
2234        let member = v2::Package {
2235            name: "u.a".to_string(),
2236            unit: "u".to_string(),
2237            ..Default::default()
2238        };
2239        assert_eq!(v2::unit_of(&member), "u");
2240    }
2241
2242    #[test]
2243    fn packages_of_unit_selects_by_unit_of() {
2244        let package = |name: &str, unit: &str| v2::Package {
2245            name: name.to_string(),
2246            unit: unit.to_string(),
2247            ..Default::default()
2248        };
2249        let packages = [
2250            package("u", "u"),
2251            package("u.a", "u"),
2252            package("w", ""),
2253            package("other.b", "other"),
2254        ];
2255        let names: Vec<&str> = v2::packages_of_unit("u", &packages)
2256            .map(|p| p.name.as_str())
2257            .collect();
2258        assert_eq!(names, ["u", "u.a"]);
2259        let legacy: Vec<&str> = v2::packages_of_unit("w", &packages)
2260            .map(|p| p.name.as_str())
2261            .collect();
2262        assert_eq!(legacy, ["w"]);
2263    }
2264
2265    /// The owning service is carried because `Service.visibility` is the
2266    /// authoritative one: an inline shape's own field is
2267    /// `VISIBILITY_UNSPECIFIED` by construction, which is not "internal" and
2268    /// not "public".
2269    #[test]
2270    fn shape_visibility_reads_the_owning_service_for_an_inline_shape() {
2271        let package = fixture();
2272        let shapes: Vec<v2::InterfaceShape<'_>> = package.shapes().collect();
2273
2274        let named = shapes[0];
2275        assert!(named.service.is_none());
2276        assert_eq!(named.visibility(), v2::Visibility::Public as i32);
2277        assert_eq!(named.visibility(), named.interface.visibility);
2278
2279        let inline = shapes[1];
2280        assert_eq!(
2281            inline.interface.visibility,
2282            v2::Visibility::Unspecified as i32,
2283            "the trap: an inline shape's own visibility field is unset",
2284        );
2285        assert_eq!(
2286            inline.service.expect("an inline shape has an owner").name,
2287            "veh.adas.logs",
2288        );
2289        assert_eq!(
2290            inline.visibility(),
2291            v2::Visibility::Public as i32,
2292            "the accessor reads the owning service's, never the unset field",
2293        );
2294    }
2295
2296    /// A package with no service at all still walks its interfaces, and a
2297    /// package with neither yields nothing — the emptiness both backends test
2298    /// for before emitting any interaction vocabulary.
2299    #[test]
2300    fn shapes_is_empty_only_when_the_package_declares_no_shape() {
2301        let mut package = fixture();
2302        package.services.clear();
2303        assert_eq!(package.shapes().count(), 1);
2304
2305        package.interfaces.clear();
2306        assert_eq!(package.shapes().count(), 0);
2307    }
2308
2309    /// A dotted reference contributes its qualifier; a bare one contributes
2310    /// nothing. Every recursive path through `walk_field_type` — array
2311    /// element, tuple field, map key, map value, stream element — carries a
2312    /// distinct qualifier, so no path's absence can hide behind another
2313    /// path's presence: deleting any one arm's body changes the expected set
2314    /// this test compares against, rather than leaving it unchanged.
2315    #[test]
2316    fn referenced_packages_finds_qualifiers_at_depth() {
2317        fn named(reference: &str) -> v2::FieldType {
2318            v2::FieldType {
2319                kind: Some(v2::field_type::Kind::Named(reference.to_string())),
2320                ..Default::default()
2321            }
2322        }
2323
2324        fn fixed(payload: v2::FieldType) -> v2::decl::Kind {
2325            v2::decl::Kind::FixedDef(v2::FixedDef {
2326                payload: Some(payload),
2327            })
2328        }
2329
2330        let package = v2::Package {
2331            name: "veh.cluster".to_string(),
2332            decls: vec![
2333                v2::Decl {
2334                    name: "Local".to_string(),
2335                    kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
2336                        payload: "Speed".to_string(),
2337                        ..Default::default()
2338                    })),
2339                    ..Default::default()
2340                },
2341                v2::Decl {
2342                    name: "Stamped".to_string(),
2343                    kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
2344                        payload: "ridl.std.Timestamp".to_string(),
2345                        ..Default::default()
2346                    })),
2347                    ..Default::default()
2348                },
2349                v2::Decl {
2350                    name: "ArrLabels".to_string(),
2351                    kind: Some(fixed(v2::FieldType {
2352                        kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
2353                            element: Some(Box::new(named("veh.arr.Label"))),
2354                            min: 0,
2355                            max: 32,
2356                        }))),
2357                        ..Default::default()
2358                    })),
2359                    ..Default::default()
2360                },
2361                v2::Decl {
2362                    name: "TupThing".to_string(),
2363                    kind: Some(fixed(v2::FieldType {
2364                        kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
2365                            fields: vec![v2::TupleField {
2366                                name: "x".to_string(),
2367                                r#type: Some(named("veh.tup.X")),
2368                            }],
2369                        })),
2370                        ..Default::default()
2371                    })),
2372                    ..Default::default()
2373                },
2374                v2::Decl {
2375                    name: "MapThing".to_string(),
2376                    kind: Some(fixed(v2::FieldType {
2377                        kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
2378                            key: Some(Box::new(named("veh.key.X"))),
2379                            value: Some(Box::new(named("veh.val.X"))),
2380                            min: 0,
2381                            max: 8,
2382                        }))),
2383                        ..Default::default()
2384                    })),
2385                    ..Default::default()
2386                },
2387                v2::Decl {
2388                    name: "StreamThing".to_string(),
2389                    kind: Some(fixed(v2::FieldType {
2390                        kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
2391                            element: Some(v2::stream_type::Element::Named(
2392                                "veh.strm.X".to_string(),
2393                            )),
2394                        })),
2395                        ..Default::default()
2396                    })),
2397                    ..Default::default()
2398                },
2399            ],
2400            ..Default::default()
2401        };
2402
2403        let found = v2::referenced_packages(&package);
2404        let expected: std::collections::BTreeSet<String> = [
2405            "ridl.std", "veh.arr", "veh.tup", "veh.key", "veh.val", "veh.strm",
2406        ]
2407        .into_iter()
2408        .map(str::to_string)
2409        .collect();
2410        assert_eq!(
2411            found, expected,
2412            "each recursive path must contribute its own distinct qualifier"
2413        );
2414        assert!(
2415            !found.contains("Speed") && !found.contains("veh.cluster"),
2416            "a bare reference contributes no package: {found:?}",
2417        );
2418    }
2419
2420    /// An empty package references nothing — the negative case the emit rule in
2421    /// `ridlc` depends on.
2422    #[test]
2423    fn referenced_packages_is_empty_without_references() {
2424        let package = v2::Package {
2425            name: "veh.solo".to_string(),
2426            ..Default::default()
2427        };
2428        assert!(v2::referenced_packages(&package).is_empty());
2429    }
2430
2431    /// Below prost's recursion limit at two message levels per nesting level
2432    /// — the depth ADR-0014 decision 12 measured as round-tripping correctly.
2433    /// Since decision 14 these two constants bound the prototext transcode
2434    /// alone: JSON no longer transcodes and carries its own read-side
2435    /// ceiling, tested separately below.
2436    const NESTING_BELOW_LIMIT: usize = 45;
2437    /// Past the limit today. The tests assert the outcome — an error, never a
2438    /// panic — not the exact threshold, so a prost release that moves the
2439    /// limit moves these constants, not the assertions.
2440    const NESTING_PAST_LIMIT: usize = 60;
2441
2442    /// One declaration whose payload nests `depth` levels of inline arrays —
2443    /// each level costs two message levels on the wire (`FieldType` plus
2444    /// `ArrayType`), the arithmetic ADR-0014 decision 12 records against
2445    /// prost's recursion limit.
2446    fn nested_package(depth: usize) -> v2::Package {
2447        let mut payload = v2::FieldType {
2448            optional: false,
2449            kind: Some(v2::field_type::Kind::Primitive(
2450                v2::PrimitiveType::Integer as i32,
2451            )),
2452        };
2453        for _ in 0..depth {
2454            payload = v2::FieldType {
2455                optional: false,
2456                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
2457                    element: Some(Box::new(payload)),
2458                    min: 1,
2459                    max: 1,
2460                }))),
2461            };
2462        }
2463        v2::Package {
2464            name: "veh.deep".to_string(),
2465            decls: vec![v2::Decl {
2466                name: "deep".to_string(),
2467                kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
2468                    payload: Some(payload),
2469                })),
2470                ..Default::default()
2471            }],
2472            ..Default::default()
2473        }
2474    }
2475
2476    /// One package whose nesting sits exactly `levels` message levels below
2477    /// the `Package` root — the unit the derived binary encoding's bound is
2478    /// stated in (the IR specification, "The derived encodings").
2479    ///
2480    /// The chain under a `FixedDef` costs three levels before any nesting
2481    /// (`Decl`, `FixedDef`, the outermost `FieldType`) and two per array level
2482    /// (`ArrayType`, `FieldType`), so an array-only chain reaches the odd
2483    /// depths alone. One tuple level costs three (`FieldType`, `TupleType`,
2484    /// `TupleField`, then the `FieldType` the next level counts), which is what
2485    /// reaches the even depths. Both shapes are what the front end lowers, so
2486    /// neither is a construction the schema would not otherwise see.
2487    fn package_at_message_depth(levels: usize) -> v2::Package {
2488        assert!(levels >= 3, "the chain costs three levels before nesting");
2489        let (arrays, tuple) = if levels % 2 == 1 {
2490            ((levels - 3) / 2, false)
2491        } else {
2492            assert!(levels >= 6, "one tuple level costs three");
2493            ((levels - 6) / 2, true)
2494        };
2495
2496        let mut payload = v2::FieldType {
2497            optional: false,
2498            kind: Some(v2::field_type::Kind::Primitive(
2499                v2::PrimitiveType::Integer as i32,
2500            )),
2501        };
2502        for _ in 0..arrays {
2503            payload = v2::FieldType {
2504                optional: false,
2505                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
2506                    element: Some(Box::new(payload)),
2507                    min: 1,
2508                    max: 1,
2509                }))),
2510            };
2511        }
2512        if tuple {
2513            payload = v2::FieldType {
2514                optional: false,
2515                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
2516                    fields: vec![v2::TupleField {
2517                        name: "f0".to_string(),
2518                        r#type: Some(payload),
2519                    }],
2520                })),
2521            };
2522        }
2523        v2::Package {
2524            name: "veh.deep".to_string(),
2525            decls: vec![v2::Decl {
2526                name: "deep".to_string(),
2527                kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
2528                    payload: Some(payload),
2529                })),
2530                ..Default::default()
2531            }],
2532            ..Default::default()
2533        }
2534    }
2535
2536    /// The nesting of JSON objects in a canonical artifact, which in the
2537    /// protobuf JSON mapping is the nesting of messages: every message is an
2538    /// object, a repeated field is an array of them, and the schema declares no
2539    /// `map<>` field. The root `Package` object is included, so a caller
2540    /// counting levels *below* the root subtracts one. Brackets inside a string
2541    /// literal do not count.
2542    fn message_nesting(json: &str) -> usize {
2543        let (mut depth, mut max) = (0usize, 0usize);
2544        let (mut in_string, mut escaped) = (false, false);
2545        for byte in json.bytes() {
2546            if in_string {
2547                if escaped {
2548                    escaped = false;
2549                } else if byte == b'\\' {
2550                    escaped = true;
2551                } else if byte == b'"' {
2552                    in_string = false;
2553                }
2554                continue;
2555            }
2556            match byte {
2557                b'"' => in_string = true,
2558                b'{' => {
2559                    depth += 1;
2560                    max = max.max(depth);
2561                }
2562                b'}' => depth = depth.saturating_sub(1),
2563                _ => {}
2564            }
2565        }
2566        max
2567    }
2568
2569    /// [`package_at_message_depth`] builds what it claims, on both parities.
2570    /// Without this the two bound tests below would pin a depth nobody
2571    /// measured.
2572    #[test]
2573    fn package_at_message_depth_builds_the_depth_it_names() {
2574        with_sized_stack(|| {
2575            for levels in [3, 6, 7, 99, 100, 101] {
2576                let json = v2::to_json_pretty(&package_at_message_depth(levels))
2577                    .expect("the writer is unrestricted at these depths");
2578                assert_eq!(
2579                    message_nesting(&json) - 1,
2580                    levels,
2581                    "the chain must nest {levels} message levels below the root"
2582                );
2583            }
2584        });
2585    }
2586
2587    /// The derived binary encoding's bound, stated by the IR specification and
2588    /// pinned here: 100 message levels below the root round-trip.
2589    ///
2590    /// `to_binary` writes any depth; it is `from_binary` that stops, at prost's
2591    /// `RECURSION_LIMIT` of 100, decremented once per nested message on decode
2592    /// and not consulted on encode. The test asserts the outcome, not prost's
2593    /// constant: a prost release that moves the limit moves these two tests and
2594    /// the specification's paragraph together.
2595    #[test]
2596    fn binary_round_trip_at_100_message_levels_succeeds() {
2597        let package = package_at_message_depth(100);
2598        let bytes = v2::to_binary(&package);
2599        let decoded = v2::from_binary(&bytes).expect("100 message levels decode");
2600        assert_eq!(package, decoded);
2601    }
2602
2603    /// One level past that bound the binary reader refuses — an error, never a
2604    /// panic — while the canonical encoding carries the same package. This is
2605    /// the asymmetry the specification states as the reason binary is derived
2606    /// rather than canonical (driftsys/ridl#231).
2607    #[test]
2608    fn binary_decode_at_101_message_levels_returns_an_error() {
2609        let package = package_at_message_depth(101);
2610        let bytes = v2::to_binary(&package);
2611        let error = v2::from_binary(&bytes).expect_err("101 message levels must fail, not panic");
2612        assert!(
2613            error.to_string().contains("recursion limit reached"),
2614            "the error must name the limit, got: {error}"
2615        );
2616
2617        let json = v2::to_json_pretty(&package).expect("the canonical encoding has no such bound");
2618        assert_eq!(
2619            package,
2620            v2::from_json(&json).expect("the canonical encoding round-trips the same package")
2621        );
2622    }
2623
2624    /// The write side after ADR-0014 decision 14: the pbjson-generated
2625    /// writer recurses the typed message directly — no transcode, so no
2626    /// message-level recursion limit — and 400 levels of array nesting,
2627    /// roughly eight times the ceiling decision 12 recorded, serialize and
2628    /// round-trip. Run on an explicitly sized stack: the writer recurses on
2629    /// the caller's stack, and debug-build frames at this depth overflow the
2630    /// default test-thread stack (the reader sizes its own thread inside
2631    /// `from_json`).
2632    #[test]
2633    fn json_round_trip_at_400_nested_levels_succeeds() {
2634        with_sized_stack(|| {
2635            let package = nested_package(400);
2636            let json = v2::to_json_pretty(&package).expect("the writer has no message-level limit");
2637            let decoded = v2::from_json(&json).expect("the reader parses within its ceiling");
2638            assert_eq!(package, decoded);
2639        });
2640    }
2641
2642    /// The one error path on the JSON write side (ADR-0014 decision 14),
2643    /// and it is new with the generated impl, not a survivor of the
2644    /// transcode's: an `i32` enum field holding a discriminant outside the
2645    /// schema — data, not depth — which the retired reflection path
2646    /// serialized successfully as its bare number. The checker never
2647    /// produces one, so there is no CLI route to this failure; it is pinned
2648    /// here at the crate surface.
2649    #[test]
2650    fn json_serialization_of_an_out_of_schema_discriminant_returns_an_error() {
2651        let mut package = fixture();
2652        package.decls[0].visibility = 999;
2653        let err = v2::to_json_pretty(&package)
2654            .expect_err("an out-of-schema discriminant must fail, not panic");
2655        let message = err.to_string();
2656        assert!(
2657            message.contains("canonical protobuf JSON"),
2658            "the error must name the encoding that failed, got: {message}"
2659        );
2660        assert!(
2661            message.contains("discriminant outside the schema"),
2662            "the error must name the known cause, got: {message}"
2663        );
2664    }
2665
2666    /// The strictness ADR-0014 decision 11 relies on is the generated
2667    /// deserializer's default: `ignore_unknown_fields()` is the opt-out and
2668    /// stays unset, so a field the schema does not declare is an error,
2669    /// never silently dropped.
2670    #[test]
2671    fn json_parse_rejects_an_unknown_field() {
2672        let error = v2::from_json(r#"{"name": "veh.deep", "notAField": 1}"#)
2673            .expect_err("an unknown field must be rejected");
2674        assert!(
2675            error.to_string().contains("unknown field"),
2676            "the error must name the defect, got: {error}"
2677        );
2678    }
2679
2680    /// A reader narrowing ADR-0014 decision 14 records: the proto3 JSON
2681    /// mapping expects parsers to accept numeric enum values, and the
2682    /// generated deserializer does — within the schema's range. A
2683    /// discriminant outside it (`"visibility": 77`) is rejected, where the
2684    /// retired reflection reader accepted it — and the retired *writer*
2685    /// emitted exactly such a number for an out-of-schema discriminant.
2686    /// Pinned so the narrowing stays a decision rather than an accident: a
2687    /// future mechanism change must confront this test.
2688    #[test]
2689    fn json_parse_rejects_an_out_of_range_numeric_enum_value() {
2690        let with_visibility =
2691            |value: &str| format!(r#"{{"name": "veh.x", "decls": [{{"visibility": {value}}}]}}"#);
2692        v2::from_json(&with_visibility("1"))
2693            .expect("an in-range numeric enum value parses, as the mapping expects");
2694        let error = v2::from_json(&with_visibility("77"))
2695            .expect_err("an out-of-range numeric enum value must be rejected");
2696        assert!(
2697            error.to_string().contains("invalid value: integer `77`"),
2698            "the error must name the value, got: {error}"
2699        );
2700    }
2701
2702    /// A reader narrowing ADR-0014 decision 14 records: the mapping accepts
2703    /// float and exponent notation for integer fields (`"min": 1.0`), and
2704    /// the retired reflection reader did; the generated deserializer
2705    /// rejects both. Pinned for the same reason as the numeric-enum case
2706    /// above.
2707    #[test]
2708    fn json_parse_rejects_a_float_form_integer() {
2709        for spelling in ["1.0", "1e0"] {
2710            let error = v2::from_json(&format!(
2711                r#"{{"name": "veh.x", "decls": [{{"fixedDef": {{"payload": {{"array": {{"min": {spelling}}}}}}}}}]}}"#,
2712            ))
2713            .expect_err("a float-form integer must be rejected");
2714            assert!(
2715                error.to_string().contains("did not match any variant"),
2716                "the integer field's deserializer must be the one refusing `{spelling}`, \
2717                 got: {error}"
2718            );
2719        }
2720    }
2721
2722    /// A reader narrowing ADR-0014 decision 14 records: `null` for a
2723    /// repeated field (`"decls": null`), which the retired reflection
2724    /// reader read as empty, is rejected. `null` for an optional scalar or
2725    /// message field is still accepted — parity with the retired reader,
2726    /// asserted alongside so the narrowing's edge is pinned from both
2727    /// sides.
2728    #[test]
2729    fn json_parse_rejects_null_for_a_repeated_field() {
2730        let error = v2::from_json(r#"{"name": "veh.x", "decls": null}"#)
2731            .expect_err("null for a repeated field must be rejected");
2732        assert!(
2733            error.to_string().contains("invalid type: null"),
2734            "the error must name the null, got: {error}"
2735        );
2736        v2::from_json(r#"{"name": "veh.x", "decls": [{"deprecated": null}]}"#)
2737            .expect("null for an optional scalar field still parses");
2738    }
2739
2740    /// A reader narrowing ADR-0014 decision 14 records: a duplicate JSON
2741    /// key, which the retired reflection reader resolved last-wins, is
2742    /// rejected.
2743    #[test]
2744    fn json_parse_rejects_a_duplicate_key() {
2745        let error = v2::from_json(r#"{"name": "a", "name": "b"}"#)
2746            .expect_err("a duplicate key must be rejected");
2747        assert!(
2748            error.to_string().contains("duplicate field `name`"),
2749            "the error must name the duplicated field, got: {error}"
2750        );
2751    }
2752
2753    /// The read-side ceiling (ADR-0014 decision 14): nesting past 1,000
2754    /// bracket levels returns an error before the parse begins — a
2755    /// diagnostic, where unbounded recursion would eventually abort on a
2756    /// stack overflow no caller can catch. The input is real writer output:
2757    /// past the ceiling the asymmetry is deliberate — the writer is
2758    /// unrestricted, the reader is not.
2759    #[test]
2760    fn json_parse_past_the_nesting_ceiling_returns_an_error() {
2761        with_sized_stack(|| {
2762            let json = v2::to_json_pretty(&nested_package(500))
2763                .expect("the writer is unrestricted at this depth");
2764            let error = v2::from_json(&json).expect_err("the reader must refuse past its ceiling");
2765            assert!(
2766                error.to_string().contains("1000 JSON levels"),
2767                "the error must name the ceiling, got: {error}"
2768            );
2769        });
2770    }
2771
2772    /// The ceiling is exact: 1,000 open brackets pass the scan and reach the
2773    /// parser — which then rejects the input as not a package — and 1,001 do
2774    /// not. The scan runs before the parse, so the over-ceiling probe needs
2775    /// no valid JSON behind its brackets.
2776    #[test]
2777    fn json_nesting_ceiling_binds_exactly_at_1000() {
2778        let at = v2::from_json(&"[".repeat(1_000)).expect_err("an array is not a package");
2779        assert!(
2780            !at.to_string().contains("JSON levels"),
2781            "at the ceiling the parser, not the scan, must be the one refusing, got: {at}"
2782        );
2783
2784        let past = v2::from_json(&"[".repeat(1_001)).expect_err("past the ceiling, the scan");
2785        assert!(
2786            past.to_string().contains("1000 JSON levels"),
2787            "past the ceiling the error must name it, got: {past}"
2788        );
2789    }
2790
2791    /// The nesting scan behind the ceiling: brackets count only outside
2792    /// string literals, an escaped quote does not end a literal, an escaped
2793    /// backslash does not disarm the real closing quote after it, and a
2794    /// stray closer never underflows the running depth.
2795    #[test]
2796    fn nesting_scan_counts_brackets_outside_string_literals_only() {
2797        // Plain structural nesting counts every open bracket.
2798        assert_eq!(v2::max_json_nesting(r#"{"a": [{"b": []}]}"#), 4);
2799        // Brackets inside a string literal do not count.
2800        assert_eq!(v2::max_json_nesting(r#"{"doc": "{[[[{"}"#), 1);
2801        // An escaped quote does not end the literal, so the brackets after
2802        // it are still inside it.
2803        assert_eq!(v2::max_json_nesting(r#"{"doc": "a\"[[[", "x": []}"#), 2);
2804        // An escaped backslash does not escape the closing quote: the
2805        // literal ends, and the brackets after it count.
2806        assert_eq!(v2::max_json_nesting(r#"{"doc": "a\\", "x": [[]]}"#), 3);
2807        // A stray closer saturates at zero rather than underflowing.
2808        assert_eq!(v2::max_json_nesting("]]]{"), 1);
2809    }
2810
2811    /// The prototext form of [`nested_package`], built by hand for the same
2812    /// reason [`nested_json`] is: past the limit the serializer rejects the
2813    /// package, so its prototext cannot come from [`v2::to_text_format`].
2814    fn nested_text(depth: usize) -> String {
2815        let mut payload = "primitive: PRIMITIVE_TYPE_INTEGER".to_string();
2816        for _ in 0..depth {
2817            payload = format!("array {{ element {{ {payload} }} min: 1 max: 1 }}");
2818        }
2819        format!(
2820            r#"name: "veh.deep" decls {{ name: "deep" fixed_def {{ payload {{ {payload} }} }} }}"#
2821        )
2822    }
2823
2824    /// The prototext write path carries the same recursion-limit failure mode
2825    /// as JSON — both go through the one transcode (ADR-0014 decision 12) —
2826    /// and reports it as an error naming its own encoding, never a panic.
2827    #[test]
2828    fn text_serialization_past_the_nesting_limit_returns_an_error() {
2829        let err = v2::to_text_format(&nested_package(NESTING_PAST_LIMIT))
2830            .expect_err("serialization past the recursion limit must fail, not panic");
2831        let message = err.to_string();
2832        assert!(
2833            message.contains("recursion limit"),
2834            "the error must name the nesting limit as the known cause, got: {message}"
2835        );
2836        assert!(
2837            message.contains("prototext"),
2838            "the error must name the encoding that failed, got: {message}"
2839        );
2840    }
2841
2842    /// Runs `test` on a thread whose stack fits the recursion the test
2843    /// drives on its own thread. Two groups need one. The prototext parser
2844    /// recurses once per message level with debug-build frames large enough
2845    /// that the default 2 MiB test-thread stack overflows near 45 array
2846    /// levels — under prost's own recursion limit, so the depths
2847    /// [`NESTING_BELOW_LIMIT`] and [`NESTING_PAST_LIMIT`] pin are
2848    /// unreachable on that stack; the production paths are unaffected, since
2849    /// the toolchain writes prototext and never parses it (`ridl diff` and
2850    /// the baselines stay `.ir.json`, ADR-0014 decision 5). And the deep
2851    /// JSON tests drive the pbjson-generated writer, which recurses on the
2852    /// caller's stack (ADR-0014 decision 14 — only the reader sizes a
2853    /// thread of its own, inside `from_json`).
2854    fn with_sized_stack(test: impl FnOnce() + Send + 'static) {
2855        let outcome = std::thread::Builder::new()
2856            .stack_size(16 * 1024 * 1024)
2857            .spawn(test)
2858            .expect("spawn the large-stack test thread")
2859            .join();
2860        if let Err(payload) = outcome {
2861            std::panic::resume_unwind(payload);
2862        }
2863    }
2864
2865    /// The read direction: the text-format parser itself has no depth limit,
2866    /// so the failure is the transcode out of the dynamic message, mapped
2867    /// into the error return instead of expected on (ADR-0014 decision 12).
2868    #[test]
2869    fn text_parse_past_the_nesting_limit_returns_an_error() {
2870        with_sized_stack(|| {
2871            let error = v2::from_text_format(&nested_text(NESTING_PAST_LIMIT))
2872                .expect_err("parsing past the recursion limit must fail, not panic");
2873
2874            // Assert *which* stage failed: prost's transcoding decoder says
2875            // "recursion limit reached", and a parse-stage failure would
2876            // render through the `Parse` variant instead.
2877            let message = error.to_string();
2878            assert!(
2879                message.contains("recursion limit reached"),
2880                "the transcode out of the dynamic message must be the failing \
2881                 stage, got: {message}"
2882            );
2883        });
2884    }
2885
2886    /// The prototext bound must not tighten silently either: below the limit
2887    /// the package still serializes and round-trips.
2888    #[test]
2889    fn text_round_trip_below_the_nesting_limit_succeeds() {
2890        with_sized_stack(|| {
2891            let package = nested_package(NESTING_BELOW_LIMIT);
2892            let text = v2::to_text_format(&package)
2893                .expect("below the recursion limit, serialization succeeds");
2894            let decoded =
2895                v2::from_text_format(&text).expect("below the recursion limit, parsing succeeds");
2896            assert_eq!(package, decoded);
2897        });
2898    }
2899}
2900
2901#[cfg(test)]
2902mod vacuous_constraint {
2903    use crate::v2;
2904
2905    /// A constraint with every field absent. Each test sets only the field it
2906    /// is about, so no assertion can pass through a neighbouring field.
2907    fn constraint() -> v2::Constraint {
2908        v2::Constraint {
2909            min: None,
2910            max: None,
2911            step: None,
2912            len_min: None,
2913            len_max: None,
2914            pattern: None,
2915            pattern_const: None,
2916        }
2917    }
2918
2919    #[test]
2920    fn an_absent_or_empty_constraint_is_vacuous() {
2921        assert!(v2::constraint_is_vacuous(None));
2922        assert!(v2::constraint_is_vacuous(Some(&constraint())));
2923    }
2924
2925    #[test]
2926    fn a_step_constraint_is_non_vacuous() {
2927        let stepped = v2::Constraint {
2928            step: Some("0.5".to_string()),
2929            ..constraint()
2930        };
2931        assert!(!v2::constraint_is_vacuous(Some(&stepped)));
2932    }
2933
2934    /// Every constrained field on its own. A fixture setting a pair — `min`
2935    /// with `max`, or `len_min` with `len_max` — cannot tell a predicate that
2936    /// reads both from one that reads either, so each bound here is one-sided.
2937    /// The paired shapes are pinned separately by
2938    /// [`a_bound_pair_set_together_is_non_vacuous`], which a one-sided fixture
2939    /// cannot do.
2940    #[test]
2941    fn any_single_constrained_field_is_non_vacuous() {
2942        let cases = [
2943            (
2944                "min",
2945                v2::Constraint {
2946                    min: Some("0.0".to_string()),
2947                    ..constraint()
2948                },
2949            ),
2950            (
2951                "max",
2952                v2::Constraint {
2953                    max: Some("250.0".to_string()),
2954                    ..constraint()
2955                },
2956            ),
2957            (
2958                "len_min",
2959                v2::Constraint {
2960                    len_min: Some(1),
2961                    ..constraint()
2962                },
2963            ),
2964            (
2965                "len_max",
2966                v2::Constraint {
2967                    len_max: Some(256),
2968                    ..constraint()
2969                },
2970            ),
2971            (
2972                "pattern",
2973                v2::Constraint {
2974                    pattern: Some("^[a-z]+$".to_string()),
2975                    ..constraint()
2976                },
2977            ),
2978            (
2979                "pattern_const",
2980                v2::Constraint {
2981                    pattern_const: Some("NAME_PATTERN".to_string()),
2982                    ..constraint()
2983                },
2984            ),
2985        ];
2986        for (field, case) in cases {
2987            assert!(
2988                !v2::constraint_is_vacuous(Some(&case)),
2989                "`{field}` alone must be non-vacuous"
2990            );
2991        }
2992    }
2993
2994    /// The two shapes the checker actually emits: a declared range, and the
2995    /// typl §4.4 default `[0..256]` every string and bytes type carries.
2996    ///
2997    /// A one-sided fixture cannot pin these. A predicate reading each bound as
2998    /// a pair — `(c.min.is_none() == c.max.is_none())` and the same for the
2999    /// length bounds — passes every one-sided case and still reports both
3000    /// shapes below as vacuous, which would drop the range check from every
3001    /// bounded number and every string.
3002    #[test]
3003    fn a_bound_pair_set_together_is_non_vacuous() {
3004        let ranged = v2::Constraint {
3005            min: Some("0.0".to_string()),
3006            max: Some("250.0".to_string()),
3007            ..constraint()
3008        };
3009        assert!(!v2::constraint_is_vacuous(Some(&ranged)));
3010
3011        let default_length = v2::Constraint {
3012            len_min: Some(0),
3013            len_max: Some(256),
3014            ..constraint()
3015        };
3016        assert!(!v2::constraint_is_vacuous(Some(&default_length)));
3017    }
3018}
3019
3020#[cfg(test)]
3021mod system_round_trip {
3022    use crate::v2;
3023
3024    fn attribute(namespace: &str, key: &str, value: Option<v2::AttributeValue>) -> v2::Attribute {
3025        v2::Attribute {
3026            namespace: namespace.to_string(),
3027            key: key.to_string(),
3028            value,
3029        }
3030    }
3031
3032    fn scalar(text: &str) -> v2::AttributeValue {
3033        v2::AttributeValue {
3034            kind: Some(v2::attribute_value::Kind::Scalar(text.to_string())),
3035        }
3036    }
3037
3038    fn list(items: Vec<v2::AttributeValue>) -> v2::AttributeValue {
3039        v2::AttributeValue {
3040            kind: Some(v2::attribute_value::Kind::List(v2::AttributeList { items })),
3041        }
3042    }
3043
3044    fn interface(catalog: &str, name: &str, inline: bool) -> Option<v2::InterfaceRef> {
3045        Some(v2::InterfaceRef {
3046            catalog: catalog.to_string(),
3047            name: name.to_string(),
3048            inline,
3049        })
3050    }
3051
3052    fn endpoint(component: &str, instance: &str, machine: &str) -> v2::Endpoint {
3053        v2::Endpoint {
3054            component: component.to_string(),
3055            instance: instance.to_string(),
3056            machine: machine.to_string(),
3057        }
3058    }
3059
3060    /// A reduced rsdl reference Appendix A: `Cruise` with two instances
3061    /// offering `veh.adas.cruise` and requiring `LaneAssist`, the implicit
3062    /// component of `veh.diag.access`, one distribution and one deployment.
3063    /// Every message of `system.proto` appears at least once, with every
3064    /// scalar set to a value other than its default — a flag and a nested-list
3065    /// attribute value included — so a round trip that drops a field is
3066    /// caught.
3067    fn doc_link() -> v2::DocLink {
3068        v2::DocLink {
3069            text: "Cruise".to_string(),
3070            offset: 16,
3071            len: 6,
3072            target: "veh.topology.Cruise".to_string(),
3073        }
3074    }
3075
3076    fn fixture() -> v2::System {
3077        let link = v2::Link {
3078            interface: interface("veh.diag", "veh.diag.access", true),
3079            service: "veh.diag.access".to_string(),
3080            consumer: Some(endpoint("veh.topology.Backend", "Unit", "Cloud")),
3081            producer: Some(endpoint("veh.diag.access", "Unit", "AdasHpc")),
3082            crossing: v2::Crossing::OffBoard as i32,
3083        };
3084        v2::System {
3085            name: "Vehicle".to_string(),
3086            package: "veh.topology".to_string(),
3087            labels: vec!["ASIL_B".to_string()],
3088            attributes: vec![attribute("rust", "crate", Some(scalar("\"vehicle\"")))],
3089            members: vec![
3090                v2::MemberLine {
3091                    component: "veh.topology.Cruise".to_string(),
3092                    attributes: vec![attribute("linux", "pinned", None)],
3093                    doc: "Documented, see [Cruise].".to_string(),
3094                    links: vec![doc_link()],
3095                    see: vec![doc_link()],
3096                    since: vec!["1.2".to_string()],
3097                },
3098                v2::MemberLine {
3099                    component: "veh.diag.access".to_string(),
3100                    attributes: vec![],
3101                    doc: "Documented, see [Cruise].".to_string(),
3102                    links: vec![doc_link()],
3103                    see: vec![doc_link()],
3104                    since: vec!["1.2".to_string()],
3105                },
3106            ],
3107            components: vec![
3108                v2::Component {
3109                    name: "Cruise".to_string(),
3110                    package: "veh.topology".to_string(),
3111                    implicit: false,
3112                    external: true,
3113                    instances: vec!["primary".to_string(), "backup".to_string()],
3114                    numbers: vec![
3115                        v2::InstanceNumber {
3116                            instance: "primary".to_string(),
3117                            number: 1,
3118                            provisional: false,
3119                        },
3120                        v2::InstanceNumber {
3121                            instance: "backup".to_string(),
3122                            number: 2,
3123                            provisional: true,
3124                        },
3125                    ],
3126                    offers: vec![v2::Offer {
3127                        service: "veh.adas.cruise".to_string(),
3128                        attributes: vec![attribute("someip", "serviceId", Some(scalar("4097")))],
3129                        doc: "Documented, see [Cruise].".to_string(),
3130                        links: vec![doc_link()],
3131                        see: vec![doc_link()],
3132                        since: vec!["1.2".to_string()],
3133                    }],
3134                    requires: vec![v2::Require {
3135                        interface: interface("veh.adas", "LaneAssist", false),
3136                        service: "veh.adas.lane".to_string(),
3137                        producer: "veh.topology.Lane".to_string(),
3138                        attributes: vec![attribute(
3139                            "linux",
3140                            "cpuset",
3141                            Some(list(vec![scalar("2"), list(vec![scalar("3")])])),
3142                        )],
3143                        doc: "Documented, see [Cruise].".to_string(),
3144                        links: vec![doc_link()],
3145                        see: vec![doc_link()],
3146                        since: vec!["1.2".to_string()],
3147                    }],
3148                    labels: vec!["ASIL_B".to_string()],
3149                    attributes: vec![attribute("rust", "crate", None)],
3150                    doc: "Documented, see [Cruise].".to_string(),
3151                    links: vec![doc_link()],
3152                    see: vec![doc_link()],
3153                    since: vec!["1.2".to_string()],
3154                    deprecated: Some("superseded".to_string()),
3155                },
3156                v2::Component {
3157                    name: "veh.diag.access".to_string(),
3158                    package: String::new(),
3159                    implicit: true,
3160                    external: false,
3161                    instances: vec!["Unit".to_string()],
3162                    numbers: vec![v2::InstanceNumber {
3163                        instance: "Unit".to_string(),
3164                        number: 3,
3165                        provisional: false,
3166                    }],
3167                    offers: vec![v2::Offer {
3168                        service: "veh.diag.access".to_string(),
3169                        attributes: vec![],
3170                        doc: "Documented, see [Cruise].".to_string(),
3171                        links: vec![doc_link()],
3172                        see: vec![doc_link()],
3173                        since: vec!["1.2".to_string()],
3174                    }],
3175                    requires: vec![],
3176                    labels: vec![],
3177                    attributes: vec![],
3178                    doc: "Documented, see [Cruise].".to_string(),
3179                    links: vec![doc_link()],
3180                    see: vec![doc_link()],
3181                    since: vec!["1.2".to_string()],
3182                    deprecated: Some("superseded".to_string()),
3183                },
3184            ],
3185            producers: vec![v2::Producer {
3186                service: "veh.adas.cruise".to_string(),
3187                component: "veh.topology.Cruise".to_string(),
3188                instances: vec!["primary".to_string(), "backup".to_string()],
3189                not_yet_realizable: true,
3190            }],
3191            grants: vec![v2::Grant {
3192                component: "veh.topology.Backend".to_string(),
3193                external: true,
3194                regions: vec!["veh.adas".to_string(), "veh.diag".to_string()],
3195            }],
3196            regions: vec![v2::Region {
3197                catalog: "veh.diag".to_string(),
3198                hash: vec![0xab; 32],
3199                interfaces: vec![v2::RegionInterface {
3200                    name: "veh.diag.access".to_string(),
3201                    inline: true,
3202                    number: 2,
3203                    provisional: true,
3204                    service: "veh.diag.access".to_string(),
3205                }],
3206            }],
3207            distributions: vec![v2::Distribution {
3208                name: "Adas".to_string(),
3209                package: "veh.topology".to_string(),
3210                members: vec![v2::MemberLine {
3211                    component: "veh.topology.Cruise".to_string(),
3212                    attributes: vec![],
3213                    doc: "Documented, see [Cruise].".to_string(),
3214                    links: vec![doc_link()],
3215                    see: vec![doc_link()],
3216                    since: vec!["1.2".to_string()],
3217                }],
3218                depends_on: vec!["veh.topology.Base".to_string()],
3219                labels: vec!["PLATFORM_BUNDLE".to_string()],
3220                attributes: vec![attribute("deb", "section", Some(scalar("net")))],
3221                doc: "Documented, see [Cruise].".to_string(),
3222                links: vec![doc_link()],
3223                see: vec![doc_link()],
3224                since: vec!["1.2".to_string()],
3225                tier: v2::Tier::Platform as i32,
3226                deprecated: Some("superseded".to_string()),
3227            }],
3228            deployments: vec![v2::Deployment {
3229                name: "Production".to_string(),
3230                package: "veh.topology".to_string(),
3231                labels: vec!["FLEET".to_string()],
3232                attributes: vec![attribute("ota", "channel", Some(scalar("stable")))],
3233                machines: vec![v2::Machine {
3234                    name: "Cloud".to_string(),
3235                    external: true,
3236                    labels: vec!["OFF_BOARD".to_string()],
3237                    attributes: vec![attribute("net", "zone", Some(scalar("wan")))],
3238                    doc: "Documented, see [Cruise].".to_string(),
3239                    links: vec![doc_link()],
3240                    see: vec![doc_link()],
3241                    since: vec!["1.2".to_string()],
3242                    deprecated: Some("superseded".to_string()),
3243                }],
3244                placements: vec![v2::Placement {
3245                    component: "veh.topology.Cruise".to_string(),
3246                    instance: "backup".to_string(),
3247                    machine: "Cockpit".to_string(),
3248                    attributes: vec![attribute("linux", "cpuset", Some(list(vec![])))],
3249                    sizing: Some(v2::Sizing {
3250                        depth: Some(4_294_967_295),
3251                        slots: Some(65_536),
3252                        budget: Some(18_446_744_073_709_551_615),
3253                    }),
3254                }],
3255                links: vec![link.clone()],
3256                routes: vec![v2::Route {
3257                    catalog: "veh.adas".to_string(),
3258                    interface_number: 2,
3259                    member_ordinal: 1,
3260                    interface: "LaneAssist".to_string(),
3261                    member: "active".to_string(),
3262                    service: "veh.adas.lane".to_string(),
3263                    producers: vec![endpoint("veh.topology.Lane", "Unit", "AdasHpc")],
3264                }],
3265                surface: vec![v2::Surface {
3266                    link: Some(link),
3267                    direction: v2::SurfaceDirection::ExternalConsumes as i32,
3268                }],
3269                installations: vec![v2::Installation {
3270                    distribution: "veh.topology.Adas".to_string(),
3271                    machines: vec!["AdasHpc".to_string(), "Cockpit".to_string()],
3272                }],
3273                doc: "Documented, see [Cruise].".to_string(),
3274                doc_links: vec![doc_link()],
3275                see: vec![doc_link()],
3276                since: vec!["1.2".to_string()],
3277                sizing: Some(v2::Sizing {
3278                    depth: Some(3),
3279                    slots: Some(8),
3280                    budget: Some(4096),
3281                }),
3282                deprecated: Some("superseded".to_string()),
3283            }],
3284            doc: "Documented, see [Cruise].".to_string(),
3285            see: vec![doc_link()],
3286            since: vec!["1.2".to_string()],
3287            links: vec![doc_link()],
3288            deprecated: Some("superseded".to_string()),
3289        }
3290    }
3291
3292    #[test]
3293    fn system_binary_round_trip_preserves_system() {
3294        let system = fixture();
3295        let decoded = v2::system_from_binary(v2::system_to_binary(&system).as_slice())
3296            .expect("decode must succeed");
3297        assert_eq!(system, decoded);
3298    }
3299
3300    /// The canonical JSON of the system artifact re-reads through the same
3301    /// strict pbjson-generated impl the package uses (ADR-0014 decisions 11
3302    /// and 14): unknown fields rejected, the catalog hash as base64, enums by
3303    /// name, the nested attribute list intact.
3304    #[test]
3305    fn system_json_round_trip_preserves_system() {
3306        let system = fixture();
3307        let json = v2::system_to_json_pretty(&system).expect("the fixture serializes as JSON");
3308        assert!(
3309            json.contains("\"hash\": \"q6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6s=\""),
3310            "bytes render as base64, got:\n{json}"
3311        );
3312        assert!(
3313            json.contains("\"crossing\": \"CROSSING_OFF_BOARD\""),
3314            "enums render by name, got:\n{json}"
3315        );
3316        assert!(
3317            json.contains("\"notYetRealizable\": true"),
3318            "fields render in lowerCamelCase, got:\n{json}"
3319        );
3320        assert!(
3321            json.contains("\"budget\": \"18446744073709551615\""),
3322            "a 64-bit value renders as a string, got:\n{json}"
3323        );
3324        assert_eq!(
3325            system,
3326            v2::system_from_json(&json).expect("the JSON parses")
3327        );
3328        assert!(
3329            v2::system_from_json(&json.replacen("\"name\"", "\"nam\"", 1)).is_err(),
3330            "an unknown field is rejected"
3331        );
3332    }
3333
3334    /// An absent `sizing` and an empty one are different on the wire: a plugin
3335    /// reads "nothing declared" and "declared nothing" apart, in the binary and
3336    /// the JSON encodings.
3337    #[test]
3338    fn an_absent_sizing_and_an_empty_one_stay_distinct_through_the_encodings() {
3339        let mut absent = fixture();
3340        absent.deployments[0].sizing = None;
3341        absent.deployments[0].placements[0].sizing = None;
3342        let mut empty = absent.clone();
3343        empty.deployments[0].sizing = Some(v2::Sizing::default());
3344        empty.deployments[0].placements[0].sizing = Some(v2::Sizing::default());
3345        for system in [&absent, &empty] {
3346            let binary = v2::system_from_binary(v2::system_to_binary(system).as_slice())
3347                .expect("decode must succeed");
3348            assert_eq!(system, &binary);
3349            let json = v2::system_to_json_pretty(system).expect("serializes as JSON");
3350            assert_eq!(
3351                system,
3352                &v2::system_from_json(&json).expect("the JSON parses")
3353            );
3354        }
3355        assert_ne!(
3356            v2::system_to_binary(&absent),
3357            v2::system_to_binary(&empty),
3358            "the binary encodings differ"
3359        );
3360    }
3361
3362    #[test]
3363    fn system_text_format_round_trip_preserves_system() {
3364        let system = fixture();
3365        let text = v2::system_to_text_format(&system).expect("the fixture serializes as prototext");
3366        assert!(
3367            text.starts_with("name:"),
3368            "fields print in schema index order, got: {text}"
3369        );
3370        assert_eq!(
3371            system,
3372            v2::system_from_text_format(&text).expect("prototext parsing must succeed")
3373        );
3374    }
3375
3376    /// `pkg.Name` for a declared name; the implicit component of a lone
3377    /// service, which no package declares, is its own qualified name.
3378    #[test]
3379    fn qualified_names_follow_the_one_derivation() {
3380        let system = fixture();
3381        assert_eq!(system.qualified_name(), "veh.topology.Vehicle");
3382        assert_eq!(system.components[0].qualified_name(), "veh.topology.Cruise");
3383        assert_eq!(system.components[1].qualified_name(), "veh.diag.access");
3384        assert_eq!(
3385            system.distributions[0].qualified_name(),
3386            "veh.topology.Adas"
3387        );
3388    }
3389}
3390
3391#[cfg(test)]
3392mod load_ir_json {
3393    use crate::v2::{self, LoadError, MAX_JSON_NESTING, load_ir_json};
3394
3395    /// A snapshot written by `to_json_pretty` loads back as the same package.
3396    #[test]
3397    fn a_snapshot_file_loads() {
3398        let dir = tempfile::tempdir().unwrap();
3399        let package = v2::Package {
3400            name: "veh.cabin".to_string(),
3401            ..v2::Package::default()
3402        };
3403        let path = dir.path().join("cabin.ir.json");
3404        std::fs::write(&path, v2::to_json_pretty(&package).unwrap()).unwrap();
3405        assert_eq!(load_ir_json(&path).unwrap(), package);
3406    }
3407
3408    /// A missing file is an `Io` error and a file that is not IR v2 JSON is a
3409    /// `Parse` error, each with the message `ridl diff` prints, inner error
3410    /// included.
3411    #[test]
3412    fn a_missing_file_is_io_and_bad_json_is_parse() {
3413        let dir = tempfile::tempdir().unwrap();
3414
3415        let missing = dir.path().join("missing.ir.json");
3416        let io = std::fs::read_to_string(&missing).unwrap_err();
3417        let error = load_ir_json(&missing).unwrap_err();
3418        assert!(matches!(error, LoadError::Io(_)), "{error:?}");
3419        assert_eq!(
3420            error.to_string(),
3421            format!("cannot read the IR snapshot: {io}")
3422        );
3423
3424        // The leading newline puts the error on line 2, so a loader that
3425        // trimmed the text first would report a different position.
3426        let bad = dir.path().join("bad.ir.json");
3427        std::fs::write(&bad, "\n{").unwrap();
3428        let parse = v2::from_json("\n{").unwrap_err();
3429        let error = load_ir_json(&bad).unwrap_err();
3430        assert!(matches!(error, LoadError::Parse(_)), "{error:?}");
3431        assert_eq!(
3432            error.to_string(),
3433            format!("the IR snapshot is not valid IR v2 JSON: {parse}")
3434        );
3435    }
3436
3437    /// The loader reads through `from_json`: input nested past its cap draws
3438    /// the cap's own message, which a plain `serde_json` parse would not.
3439    #[test]
3440    fn input_past_the_nesting_cap_draws_from_json_s_refusal() {
3441        let dir = tempfile::tempdir().unwrap();
3442        let deep = format!(
3443            "{}{}",
3444            "[".repeat(MAX_JSON_NESTING + 1),
3445            "]".repeat(MAX_JSON_NESTING + 1)
3446        );
3447        let path = dir.path().join("deep.ir.json");
3448        std::fs::write(&path, &deep).unwrap();
3449        let refusal = v2::from_json(&deep).unwrap_err().to_string();
3450        assert!(
3451            refusal.contains("the ceiling this reader enforces"),
3452            "{refusal}"
3453        );
3454        let error = load_ir_json(&path).unwrap_err();
3455        assert!(matches!(error, LoadError::Parse(_)), "{error:?}");
3456        assert_eq!(
3457            error.to_string(),
3458            format!("the IR snapshot is not valid IR v2 JSON: {refusal}")
3459        );
3460    }
3461}