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 artifact;
1160pub mod catalog_hash;
1161pub mod class;
1162pub mod codegen;
1163pub mod name;
1164pub mod projection;
1165pub mod rules;
1166pub mod step;
1167pub mod zero;
1168
1169#[cfg(test)]
1170mod v2_round_trip {
1171    use crate::v2;
1172
1173    /// Wraps an interaction kind in the shared `Decl` envelope. Visibility
1174    /// and `is_error` stay unset on interactions (ridl §14.1); the ordinal is
1175    /// the 1-based declaration order across all interactions of the
1176    /// enclosing interface (ridl §11).
1177    fn interaction(name: &str, ordinal: u32, kind: v2::decl::Kind) -> v2::Decl {
1178        v2::Decl {
1179            limit: None,
1180            name: name.to_string(),
1181            visibility: v2::Visibility::Unspecified as i32,
1182            is_error: false,
1183            doc: String::new(),
1184            labels: Vec::new(),
1185            deprecated: None,
1186            ordinal,
1187            kind: Some(kind),
1188            links: Vec::new(),
1189            see: Vec::new(),
1190            since: Vec::new(),
1191        }
1192    }
1193
1194    fn named_type(name: &str) -> v2::FieldType {
1195        v2::FieldType {
1196            optional: false,
1197            kind: Some(v2::field_type::Kind::Named(name.to_string())),
1198        }
1199    }
1200
1201    fn stream_of(element: v2::stream_type::Element) -> v2::FieldType {
1202        v2::FieldType {
1203            optional: false,
1204            kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
1205                element: Some(element),
1206            })),
1207        }
1208    }
1209
1210    /// A representative ridl package: one interface holding all five
1211    /// interaction kinds plus a reserved tombstone (ordinals 1–6, the
1212    /// tombstone counted, ridl §11), a strict-periodic and a defaulted
1213    /// range timing, a fallible query, and two services — a named
1214    /// reference and an inline shape holding a stream query.
1215    fn fixture() -> v2::Package {
1216        // signal speed : Speed @10ms — strict periodic stores the period
1217        // in both bounds (ADR-0008 decision 12).
1218        let speed = v2::SignalDef {
1219            payload: "Speed".to_string(),
1220            declared_init: None,
1221            init: Some(v2::InitValue {
1222                derivable: true,
1223                value: Some("0.0".to_string()),
1224            }),
1225            timing: Some(v2::Timing {
1226                mode: v2::TimingMode::StrictPeriodic as i32,
1227                min_us: Some("10000".to_string()),
1228                max_us: Some("10000".to_string()),
1229                default_applied: false,
1230            }),
1231            family: v2::Family::Dispatch as i32,
1232        };
1233
1234        // event doorOpened : DoorEvent — untimed in source, so the
1235        // configured default range is resolved at compile time (ridl §9.1).
1236        let door_opened = v2::EventDef {
1237            payload: "DoorEvent".to_string(),
1238            timing: Some(v2::Timing {
1239                mode: v2::TimingMode::Range as i32,
1240                min_us: Some("20000".to_string()),
1241                max_us: Some("500000".to_string()),
1242                default_applied: true,
1243            }),
1244            family: v2::Family::Dispatch as i32,
1245        };
1246
1247        // command setTarget(target : Speed) [ require target >= speed ]
1248        let set_target = v2::CommandDef {
1249            params: vec![v2::Param {
1250                name: "target".to_string(),
1251                r#type: Some(named_type("Speed")),
1252                doc: String::new(),
1253                links: Vec::new(),
1254                see: Vec::new(),
1255                since: Vec::new(),
1256            }],
1257            contracts: vec![v2::Contract {
1258                kind: v2::ContractKind::Require as i32,
1259                source: "target >= speed".to_string(),
1260                signal_refs: vec!["speed".to_string()],
1261                param_refs: vec!["target".to_string()],
1262                uses_result: false,
1263                observer_id: "VehicleStatus.setTarget.require[0]".to_string(),
1264            }],
1265            timing: None,
1266            family: v2::Family::Dispatch as i32,
1267            shape: v2::Shape::None as i32,
1268        };
1269
1270        // query fetchFaults(page : PageSpec) : FaultPage | DiagError
1271        //   [ ensure result.count <= page.limit ]
1272        let fetch_faults = v2::QueryDef {
1273            params: vec![v2::Param {
1274                name: "page".to_string(),
1275                r#type: Some(named_type("PageSpec")),
1276                doc: String::new(),
1277                links: Vec::new(),
1278                see: Vec::new(),
1279                since: Vec::new(),
1280            }],
1281            return_type: Some(v2::ReturnType {
1282                kind: Some(v2::return_type::Kind::Fallible(v2::FallibleType {
1283                    ok: "FaultPage".to_string(),
1284                    err: "DiagError".to_string(),
1285                })),
1286            }),
1287            contracts: vec![v2::Contract {
1288                kind: v2::ContractKind::Ensure as i32,
1289                source: "result.count <= page.limit".to_string(),
1290                signal_refs: Vec::new(),
1291                param_refs: vec!["page".to_string()],
1292                uses_result: true,
1293                observer_id: "VehicleStatus.fetchFaults.ensure[0]".to_string(),
1294            }],
1295            timing: None,
1296            family: v2::Family::Dispatch as i32,
1297        };
1298
1299        // fixed vin : Vin
1300        let vin = v2::FixedDef {
1301            payload: Some(named_type("Vin")),
1302        };
1303
1304        let vehicle_status = v2::Interface {
1305            name: "VehicleStatus".to_string(),
1306            visibility: v2::Visibility::Public as i32,
1307            doc: "Vehicle status contract".to_string(),
1308            labels: Vec::new(),
1309            deprecated: None,
1310            interactions: vec![
1311                interaction("speed", 1, v2::decl::Kind::SignalDef(speed)),
1312                interaction("doorOpened", 2, v2::decl::Kind::EventDef(door_opened)),
1313                // reserved legacyMode — the tombstone keeps ordinal 3
1314                // occupied in the one interaction sequence (ridl §11).
1315                v2::Decl {
1316                    ordinal: 3,
1317                    kind: Some(v2::decl::Kind::ReservedSlot(v2::Reserved {
1318                        ordinal: 3,
1319                        name: Some("legacyMode".to_string()),
1320                        value: None,
1321                    })),
1322                    ..interaction("", 3, v2::decl::Kind::ReservedSlot(v2::Reserved::default()))
1323                },
1324                interaction("setTarget", 4, v2::decl::Kind::CommandDef(set_target)),
1325                interaction("fetchFaults", 5, v2::decl::Kind::QueryDef(fetch_faults)),
1326                interaction("vin", 6, v2::decl::Kind::FixedDef(vin)),
1327            ],
1328            number: 0,
1329            provisional: false,
1330            links: Vec::new(),
1331            see: Vec::new(),
1332            since: Vec::new(),
1333        };
1334
1335        // query tailLogs(pattern : <string>) : <LogLine> — a stream param
1336        // and a stream return (ridl §12), inside the inline service shape.
1337        let tail_logs = v2::QueryDef {
1338            params: vec![v2::Param {
1339                name: "pattern".to_string(),
1340                r#type: Some(stream_of(v2::stream_type::Element::Primitive(
1341                    v2::PrimitiveType::String as i32,
1342                ))),
1343                doc: String::new(),
1344                links: Vec::new(),
1345                see: Vec::new(),
1346                since: Vec::new(),
1347            }],
1348            return_type: Some(v2::ReturnType {
1349                kind: Some(v2::return_type::Kind::Value(stream_of(
1350                    v2::stream_type::Element::Named("LogLine".to_string()),
1351                ))),
1352            }),
1353            contracts: Vec::new(),
1354            timing: None,
1355            family: v2::Family::Dispatch as i32,
1356        };
1357
1358        // service veh.adas.status : VehicleStatus — one named reference in
1359        // the service's set (ADR-0015 decision 12).
1360        let status_service = v2::Service {
1361            name: "veh.adas.status".to_string(),
1362            visibility: v2::Visibility::Public as i32,
1363            doc: String::new(),
1364            labels: Vec::new(),
1365            deprecated: None,
1366            shapes: vec![v2::ServiceShape {
1367                kind: Some(v2::service_shape::Kind::InterfaceRef(
1368                    "VehicleStatus".to_string(),
1369                )),
1370            }],
1371            links: Vec::new(),
1372            see: Vec::new(),
1373            since: Vec::new(),
1374        };
1375        // service veh.adas.logs { … } — the inline shape as the one entry,
1376        // Interface.name == "" (ridl §14.5).
1377        let logs_service = v2::Service {
1378            name: "veh.adas.logs".to_string(),
1379            visibility: v2::Visibility::Public as i32,
1380            doc: String::new(),
1381            labels: Vec::new(),
1382            deprecated: None,
1383            shapes: vec![v2::ServiceShape {
1384                kind: Some(v2::service_shape::Kind::Inline(v2::Interface {
1385                    name: String::new(),
1386                    visibility: v2::Visibility::Unspecified as i32,
1387                    doc: String::new(),
1388                    labels: Vec::new(),
1389                    deprecated: None,
1390                    interactions: vec![interaction(
1391                        "tailLogs",
1392                        1,
1393                        v2::decl::Kind::QueryDef(tail_logs),
1394                    )],
1395                    number: 0,
1396                    provisional: false,
1397                    links: Vec::new(),
1398                    see: Vec::new(),
1399                    since: Vec::new(),
1400                })),
1401            }],
1402            links: Vec::new(),
1403            see: Vec::new(),
1404            since: Vec::new(),
1405        };
1406
1407        v2::Package {
1408            name: "veh.adas".to_string(),
1409            // One typl declaration proves the verbatim v1 surface rides
1410            // along unchanged in v2; package-level declarations carry
1411            // ordinal 0.
1412            decls: vec![v2::Decl {
1413                limit: None,
1414                name: "Speed".to_string(),
1415                visibility: v2::Visibility::Public as i32,
1416                is_error: false,
1417                doc: String::new(),
1418                labels: Vec::new(),
1419                deprecated: None,
1420                ordinal: 0,
1421                kind: Some(v2::decl::Kind::TypeDef(v2::TypeDef {
1422                    backing: Some(v2::Backing {
1423                        kind: Some(v2::backing::Kind::Unit("km/h".to_string())),
1424                    }),
1425                    constraint: None,
1426                    declared_init: None,
1427                    init: None,
1428                    width: Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F32 as i32)),
1429                })),
1430                links: Vec::new(),
1431                see: Vec::new(),
1432                since: Vec::new(),
1433            }],
1434            interfaces: vec![vehicle_status],
1435            services: vec![status_service, logs_service],
1436            retired: Vec::new(),
1437            unit: "veh.adas".to_string(),
1438        }
1439    }
1440
1441    /// The typl vocabulary surface the interaction fixture does not reach:
1442    /// the boxed `inlineScalar` oneof member, genuine 64-bit integer fields
1443    /// (array and map bounds, length bounds, `Reserved.value`,
1444    /// `EnumValue.value`), a tuple, a map, a union, an enum set, a constant,
1445    /// and a set `deprecated`. A second fixture, so each stays readable; the
1446    /// same round-trip tests drive both.
1447    fn vocabulary_fixture() -> v2::Package {
1448        fn decl(name: &str, kind: v2::decl::Kind) -> v2::Decl {
1449            v2::Decl {
1450                limit: None,
1451                name: name.to_string(),
1452                visibility: v2::Visibility::Public as i32,
1453                is_error: false,
1454                doc: String::new(),
1455                labels: Vec::new(),
1456                deprecated: None,
1457                ordinal: 0,
1458                kind: Some(kind),
1459                links: Vec::new(),
1460                see: Vec::new(),
1461                since: Vec::new(),
1462            }
1463        }
1464
1465        fn field(name: &str, ordinal: u32, field_type: v2::FieldType) -> v2::Field {
1466            v2::Field {
1467                name: name.to_string(),
1468                ordinal,
1469                r#type: Some(field_type),
1470                declared_init: None,
1471                init: None,
1472                doc: String::new(),
1473                labels: Vec::new(),
1474                deprecated: None,
1475                links: Vec::new(),
1476                see: Vec::new(),
1477                since: Vec::new(),
1478            }
1479        }
1480
1481        // const MAX_RETRY : integer = 24
1482        let max_retry = v2::ConstDef {
1483            type_ref: Some("integer".to_string()),
1484            value: "24".to_string(),
1485            regex: None,
1486        };
1487
1488        // enum Gear { PARK = 1  DRIVE = 2  reserved 7 } — the tombstone
1489        // retires the integer value, a genuine int64 field.
1490        let gear = v2::EnumDef {
1491            values: vec![
1492                v2::EnumValue {
1493                    name: "PARK".to_string(),
1494                    value: 1,
1495                    doc: String::new(),
1496                    links: Vec::new(),
1497                    see: Vec::new(),
1498                    since: Vec::new(),
1499                },
1500                v2::EnumValue {
1501                    name: "DRIVE".to_string(),
1502                    value: 2,
1503                    doc: String::new(),
1504                    links: Vec::new(),
1505                    see: Vec::new(),
1506                    since: Vec::new(),
1507                },
1508            ],
1509            reserved: vec![v2::Reserved {
1510                ordinal: 0,
1511                name: None,
1512                value: Some(7),
1513            }],
1514            open: false,
1515        };
1516
1517        // enumset Warnings { LOW_FUEL = 0  ICE_RISK = 33 } — the standalone
1518        // form; bit 33 forces the u64 width and is a genuine int64 value.
1519        let warnings = v2::EnumSetDef {
1520            backing_enum: None,
1521            bits: vec![
1522                v2::EnumValue {
1523                    name: "LOW_FUEL".to_string(),
1524                    value: 0,
1525                    doc: String::new(),
1526                    links: Vec::new(),
1527                    see: Vec::new(),
1528                    since: Vec::new(),
1529                },
1530                v2::EnumValue {
1531                    name: "ICE_RISK".to_string(),
1532                    value: 33,
1533                    doc: String::new(),
1534                    links: Vec::new(),
1535                    see: Vec::new(),
1536                    since: Vec::new(),
1537                },
1538            ],
1539            width: v2::IntWidth::U64 as i32,
1540            open: false,
1541        };
1542
1543        // type PlateText : string [1..86] — character length bounds, two
1544        // genuine uint64 fields behind proto3 `optional`.
1545        let plate_text = v2::TypeDef {
1546            backing: Some(v2::Backing {
1547                kind: Some(v2::backing::Kind::Primitive(
1548                    v2::PrimitiveType::String as i32,
1549                )),
1550            }),
1551            constraint: Some(v2::Constraint {
1552                min: None,
1553                max: None,
1554                step: None,
1555                len_min: Some(1),
1556                len_max: Some(86),
1557                pattern: None,
1558                pattern_const: None,
1559            }),
1560            declared_init: None,
1561            init: None,
1562            width: None,
1563        };
1564
1565        // union Sample { speed : Speed  gear : Gear }
1566        let sample = v2::UnionDef {
1567            arms: vec![
1568                v2::UnionArm {
1569                    name: "speed".to_string(),
1570                    ordinal: 1,
1571                    type_ref: "Speed".to_string(),
1572                    doc: String::new(),
1573                    links: Vec::new(),
1574                    see: Vec::new(),
1575                    since: Vec::new(),
1576                },
1577                v2::UnionArm {
1578                    name: "gear".to_string(),
1579                    ordinal: 2,
1580                    type_ref: "Gear".to_string(),
1581                    doc: String::new(),
1582                    links: Vec::new(),
1583                    see: Vec::new(),
1584                    since: Vec::new(),
1585                },
1586            ],
1587            is_result: false,
1588            reserved: Vec::new(),
1589        };
1590
1591        // retries : integer [0..24] = 3 — the boxed `inlineScalar` oneof
1592        // member: the committed regression guard for ADR-0014 Open item 2,
1593        // which established that the Rust-side `Box` is invisible to the
1594        // reflection path. The enclosing field carries the init; the nested
1595        // TypeDef's stays unset.
1596        let retries = v2::Field {
1597            declared_init: Some("3".to_string()),
1598            init: Some(v2::InitValue {
1599                derivable: true,
1600                value: Some("3".to_string()),
1601            }),
1602            ..field(
1603                "retries",
1604                1,
1605                v2::FieldType {
1606                    optional: false,
1607                    kind: Some(v2::field_type::Kind::InlineScalar(Box::new(v2::TypeDef {
1608                        backing: Some(v2::Backing {
1609                            kind: Some(v2::backing::Kind::Primitive(
1610                                v2::PrimitiveType::Integer as i32,
1611                            )),
1612                        }),
1613                        constraint: Some(v2::Constraint {
1614                            min: Some("0".to_string()),
1615                            max: Some("24".to_string()),
1616                            step: None,
1617                            len_min: None,
1618                            len_max: None,
1619                            pattern: None,
1620                            pattern_const: None,
1621                        }),
1622                        declared_init: None,
1623                        init: None,
1624                        width: Some(v2::type_def::Width::IntWidth(v2::IntWidth::U8 as i32)),
1625                    }))),
1626                },
1627            )
1628        };
1629
1630        // position : (x : Speed, y : Speed) — an anonymous named-field
1631        // composite (typl §11).
1632        let position = field(
1633            "position",
1634            2,
1635            v2::FieldType {
1636                optional: false,
1637                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
1638                    fields: vec![
1639                        v2::TupleField {
1640                            name: "x".to_string(),
1641                            r#type: Some(named_type("Speed")),
1642                        },
1643                        v2::TupleField {
1644                            name: "y".to_string(),
1645                            r#type: Some(named_type("Speed")),
1646                        },
1647                    ],
1648                })),
1649            },
1650        );
1651
1652        // gears : [Gear; 1..4096] — array bounds are genuine uint64 fields.
1653        let gears = field(
1654            "gears",
1655            3,
1656            v2::FieldType {
1657                optional: false,
1658                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1659                    element: Some(Box::new(named_type("Gear"))),
1660                    min: 1,
1661                    max: 4096,
1662                }))),
1663            },
1664        );
1665
1666        // plates : { PlateText -> Gear } [0..53] — map bounds are genuine
1667        // uint64 fields. The field is deprecated, covering the optional
1668        // string on the Field envelope.
1669        let plates = v2::Field {
1670            deprecated: Some("superseded by gears".to_string()),
1671            ..field(
1672                "plates",
1673                4,
1674                v2::FieldType {
1675                    optional: false,
1676                    kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
1677                        key: Some(Box::new(named_type("PlateText"))),
1678                        value: Some(Box::new(named_type("Gear"))),
1679                        min: 0,
1680                        max: 53,
1681                    }))),
1682                },
1683            )
1684        };
1685
1686        let snapshot = v2::StructDef {
1687            members: [retries, position, gears, plates]
1688                .into_iter()
1689                .map(|field| v2::StructMember {
1690                    member: Some(v2::struct_member::Member::Field(Box::new(field))),
1691                })
1692                .collect(),
1693            fixed_layout: false,
1694        };
1695
1696        v2::Package {
1697            name: "veh.vocab".to_string(),
1698            decls: vec![
1699                decl("MAX_RETRY", v2::decl::Kind::ConstDef(max_retry)),
1700                decl("Gear", v2::decl::Kind::EnumDef(gear)),
1701                decl("Warnings", v2::decl::Kind::EnumSetDef(warnings)),
1702                decl("PlateText", v2::decl::Kind::TypeDef(plate_text)),
1703                // The union is deprecated — the optional string on the Decl
1704                // envelope.
1705                v2::Decl {
1706                    deprecated: Some("use Snapshot".to_string()),
1707                    ..decl("Sample", v2::decl::Kind::UnionDef(sample))
1708                },
1709                decl("Snapshot", v2::decl::Kind::StructDef(snapshot)),
1710            ],
1711            interfaces: Vec::new(),
1712            services: Vec::new(),
1713            retired: Vec::new(),
1714            unit: String::new(),
1715        }
1716    }
1717
1718    #[test]
1719    fn protobuf_round_trip_preserves_package() {
1720        let package = fixture();
1721
1722        let buf = v2::to_binary(&package);
1723        let decoded = v2::from_binary(buf.as_slice()).expect("decode must succeed");
1724
1725        assert_eq!(package, decoded);
1726
1727        // The vocabulary fixture rides the same round trip.
1728        let vocabulary = vocabulary_fixture();
1729        let decoded_vocabulary =
1730            v2::from_binary(v2::to_binary(&vocabulary).as_slice()).expect("decode must succeed");
1731        assert_eq!(vocabulary, decoded_vocabulary);
1732
1733        let interface = &decoded.interfaces[0];
1734        let ordinals: Vec<u32> = interface.interactions.iter().map(|d| d.ordinal).collect();
1735        assert_eq!(
1736            ordinals,
1737            [1, 2, 3, 4, 5, 6],
1738            "one ordinal sequence, tombstone counted (ridl §11)"
1739        );
1740        let Some(v2::decl::Kind::ReservedSlot(tombstone)) = &interface.interactions[2].kind else {
1741            panic!("ordinal 3 must decode as a reserved tombstone");
1742        };
1743        assert_eq!(tombstone.name.as_deref(), Some("legacyMode"));
1744        let Some(v2::service_shape::Kind::Inline(inline)) = decoded.services[1]
1745            .shapes
1746            .first()
1747            .and_then(|slot| slot.kind.as_ref())
1748        else {
1749            panic!("veh.adas.logs must decode as an inline shape");
1750        };
1751        assert_eq!(inline.name, "", "an inline shape carries no name");
1752        let references: Vec<&str> = decoded.services[0]
1753            .shapes
1754            .iter()
1755            .filter_map(|slot| match &slot.kind {
1756                Some(v2::service_shape::Kind::InterfaceRef(reference)) => Some(reference.as_str()),
1757                _ => None,
1758            })
1759            .collect();
1760        assert_eq!(
1761            references,
1762            ["VehicleStatus"],
1763            "a service's set carries its references and nothing else"
1764        );
1765    }
1766
1767    /// A package with one interface `I` holding one command `c` of the given
1768    /// family and shape.
1769    fn package_with_command(family: v2::Family, shape: v2::Shape) -> v2::Package {
1770        v2::Package {
1771            name: "app".to_string(),
1772            interfaces: vec![v2::Interface {
1773                name: "I".to_string(),
1774                visibility: v2::Visibility::Public as i32,
1775                interactions: vec![v2::Decl {
1776                    name: "c".to_string(),
1777                    visibility: v2::Visibility::Public as i32,
1778                    ordinal: 1,
1779                    kind: Some(v2::decl::Kind::CommandDef(v2::CommandDef {
1780                        family: family as i32,
1781                        shape: shape as i32,
1782                        ..Default::default()
1783                    })),
1784                    ..Default::default()
1785                }],
1786                ..Default::default()
1787            }],
1788            ..Default::default()
1789        }
1790    }
1791
1792    /// `(command, intent, none)` is refused where the IR is read, by both
1793    /// readers: ADR-0012 decision 5 admits no generic intent command.
1794    #[test]
1795    fn the_readers_reject_an_invalid_interaction_class() {
1796        let package = package_with_command(v2::Family::Intent, v2::Shape::None);
1797        let json = v2::render_json(&package).expect("the raw writer renders it");
1798        let err = v2::from_json(&json).expect_err("the JSON reader must refuse it");
1799        assert!(
1800            err.to_string().contains("invalid interaction class"),
1801            "{err}"
1802        );
1803        let bytes = prost::Message::encode_to_vec(&package);
1804        let err = v2::from_binary(&bytes).expect_err("the binary reader must refuse it");
1805        assert!(
1806            err.to_string().contains("invalid interaction class"),
1807            "{err}"
1808        );
1809    }
1810
1811    #[test]
1812    fn the_json_writer_refuses_an_invalid_interaction_class() {
1813        let package = package_with_command(v2::Family::Intent, v2::Shape::None);
1814        let err = v2::to_json_pretty(&package).expect_err("the writer must refuse it");
1815        assert!(matches!(err, v2::SerializeError::Class(_)), "{err}");
1816    }
1817
1818    #[test]
1819    fn a_valid_class_round_trips_through_both_readers() {
1820        let package = package_with_command(v2::Family::Intent, v2::Shape::Toggle);
1821        let json = v2::to_json_pretty(&package).expect("the writer renders it");
1822        assert_eq!(v2::from_json(&json).expect("the JSON parses"), package);
1823        assert_eq!(
1824            v2::from_binary(&v2::to_binary(&package)).expect("the binary decodes"),
1825            package
1826        );
1827    }
1828
1829    /// An IR written before `family` existed has no such key and reads as
1830    /// dispatch.
1831    #[test]
1832    fn a_snapshot_without_family_reads_as_dispatch() {
1833        let package = package_with_command(v2::Family::Dispatch, v2::Shape::None);
1834        let json = v2::to_json_pretty(&package).expect("the writer renders it");
1835        let mut value: serde_json::Value =
1836            serde_json::from_str(&json).expect("the rendering is JSON");
1837        let command = value["interfaces"][0]["interactions"][0]["commandDef"]
1838            .as_object_mut()
1839            .expect("the command object");
1840        assert!(command.remove("family").is_some(), "`family` was rendered");
1841        assert!(command.remove("shape").is_some(), "`shape` was rendered");
1842        let stripped = serde_json::to_string(&value).expect("the stripped value renders");
1843        let read = v2::from_json(&stripped).expect("a 0.9 snapshot reads");
1844        assert_eq!(read, package);
1845    }
1846
1847    #[test]
1848    fn json_round_trip_preserves_package() {
1849        for package in [fixture(), vocabulary_fixture()] {
1850            let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
1851            let decoded = v2::from_json(&json).expect("json deserialization must succeed");
1852
1853            assert_eq!(package, decoded);
1854        }
1855    }
1856
1857    /// The interface identity fields the lock design §9 adds — `number` and
1858    /// `provisional` on every `Interface`, an inline shape included, and the
1859    /// package's `retired` list — ride all three encodings unchanged, and the
1860    /// JSON writes them under their canonical names even when they hold their
1861    /// defaults (ADR-0014 decision 2), so a reader can tell `number` 0 from an
1862    /// absent field only by the schema, never by the text.
1863    #[test]
1864    fn number_provisional_and_retired_round_trip_through_json_text_and_binary() {
1865        let mut package = fixture();
1866        package.interfaces[0].number = 4;
1867        package.interfaces[0].provisional = true;
1868        let Some(v2::service_shape::Kind::Inline(inline)) =
1869            package.services[1].shapes[0].kind.as_mut()
1870        else {
1871            panic!("veh.adas.logs holds an inline shape in slot 1");
1872        };
1873        inline.number = 5;
1874        package.retired = vec![
1875            v2::RetiredInterface {
1876                name: "LaneAssist".to_string(),
1877                number: 2,
1878            },
1879            v2::RetiredInterface {
1880                name: "service:veh.hvac.cabin".to_string(),
1881                number: 3,
1882            },
1883        ];
1884
1885        let json = v2::to_json_pretty(&package).expect("the package serializes as IR JSON");
1886        assert_eq!(v2::from_json(&json).expect("the JSON parses back"), package);
1887        let text = v2::to_text_format(&package).expect("the package serializes as prototext");
1888        assert_eq!(
1889            v2::from_text_format(&text).expect("the prototext parses back"),
1890            package
1891        );
1892        assert_eq!(
1893            v2::from_binary(v2::to_binary(&package).as_slice()).expect("the binary decodes"),
1894            package
1895        );
1896
1897        for needle in [
1898            r#""number": 4"#,
1899            r#""provisional": true"#,
1900            r#""number": 5"#,
1901            r#""name": "LaneAssist""#,
1902            r#""name": "service:veh.hvac.cabin""#,
1903        ] {
1904            assert!(
1905                json.contains(needle),
1906                "the JSON must carry {needle}, got: {json}"
1907            );
1908        }
1909
1910        // A default holds its place in the text (decision 2): an interface
1911        // that was never numbered writes `0` and `false`, and a package with
1912        // nothing retired writes an empty list.
1913        let unnumbered = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
1914        for needle in [
1915            r#""number": 0"#,
1916            r#""provisional": false"#,
1917            r#""retired": []"#,
1918        ] {
1919            assert!(
1920                unnumbered.contains(needle),
1921                "a default field must still be written, expected {needle} in: {unnumbered}"
1922            );
1923        }
1924    }
1925
1926    /// A baseline published before the lock existed carries no `number`, no
1927    /// `provisional` and no `retired` field. It still loads — a missing field
1928    /// reads as its default, which is the `number` 0 the lock design §7 names
1929    /// as the one transition case — while an unknown field is still rejected
1930    /// (`json_parse_rejects_an_unknown_field`).
1931    #[test]
1932    fn a_snapshot_lacking_the_number_fields_still_loads() {
1933        let package = v2::from_json(
1934            r#"{"name": "veh.x", "interfaces": [{"name": "LaneKeeping"}], "services": [{"name": "veh.x.s", "shapes": [{"inline": {"name": ""}}]}]}"#,
1935        )
1936        .expect("a pre-lock snapshot loads");
1937
1938        assert_eq!(package.interfaces[0].number, 0);
1939        assert!(!package.interfaces[0].provisional);
1940        let Some(v2::service_shape::Kind::Inline(inline)) =
1941            package.services[0].shapes[0].kind.as_ref()
1942        else {
1943            panic!("the service holds an inline shape");
1944        };
1945        assert_eq!(inline.number, 0);
1946        assert!(!inline.provisional);
1947        assert_eq!(package.retired, Vec::new());
1948    }
1949
1950    /// The prototext read path (ADR-0014 decision 7): both fixtures survive
1951    /// `to_text_format` then `from_text_format` unchanged. With the binary
1952    /// and JSON round trips above, this is what proves all three encodings
1953    /// carry the same IR.
1954    #[test]
1955    fn text_format_round_trip_preserves_package() {
1956        for package in [fixture(), vocabulary_fixture()] {
1957            let text = v2::to_text_format(&package).expect("the fixture serializes as prototext");
1958            let decoded = v2::from_text_format(&text).expect("prototext parsing must succeed");
1959
1960            assert_eq!(package, decoded);
1961        }
1962    }
1963
1964    /// The prototext options ADR-0014 decision 8 fixes — `pretty`,
1965    /// `skip_default_fields(false)`, `print_message_fields_in_index_order`.
1966    /// Any option set round-trips, which is why the round-trip test above
1967    /// cannot guard them.
1968    ///
1969    /// The first two are asserted through a visible consequence. The third is
1970    /// **not guarded here and cannot be on this schema**: every message in
1971    /// `ir.proto` declares its fields in ascending field-number order, and
1972    /// field-number order is also `prost-reflect`'s default, so index order
1973    /// and default order coincide everywhere and dropping the option would
1974    /// change no output. It is set because the schema's ordering is a
1975    /// property of the schema rather than a guarantee, and a message whose
1976    /// declaration order departs from its numbering would otherwise reorder
1977    /// every artifact it appears in.
1978    #[test]
1979    fn text_format_is_pretty_with_defaults_in_index_order() {
1980        let text = v2::to_text_format(&fixture()).expect("the fixture serializes as prototext");
1981
1982        // pretty: nested messages are indented, one field per line.
1983        assert!(
1984            text.contains("\n  "),
1985            "pretty printing must indent nested fields, got: {text}"
1986        );
1987        // skip_default_fields(false): a field holding its default is present
1988        // (decision 2 — `ordinal: 0` is read, not inferred from absence).
1989        assert!(
1990            text.contains("is_error: false"),
1991            "a field holding its default must be emitted, got: {text}"
1992        );
1993        // print_message_fields_in_index_order: `name` is field 1 of
1994        // `Package`, so it opens the output.
1995        assert!(
1996            text.starts_with("name:"),
1997            "fields must print in schema index order, got: {text}"
1998        );
1999    }
2000
2001    /// Parses emitted JSON the way ADR-0014 decision 11's conformance test
2002    /// requires: unknown fields rejected, trailing input rejected. Since
2003    /// decision 14 the strict parser is the pbjson-generated `Deserialize`
2004    /// impl, whose default already rejects unknown fields
2005    /// (`ignore_unknown_fields()` stays unset in `build.rs`), so the
2006    /// strictness needs no option to opt into.
2007    fn strict_parse(json: &str) -> v2::Package {
2008        let mut deserializer = serde_json::Deserializer::from_str(json);
2009        let package = <v2::Package as serde::Deserialize>::deserialize(&mut deserializer)
2010            .expect("a strict conformant parser must accept the emitted JSON");
2011        deserializer.end().expect("no trailing input");
2012        package
2013    }
2014
2015    /// The conformance claim of ADR-0014 decision 11: a conformant protobuf
2016    /// JSON parser configured to reject unknown fields accepts the emitted
2017    /// JSON. Re-reading tests that claim itself; asserting on the rendered
2018    /// text would only restate the serializer's behaviour back to itself.
2019    #[test]
2020    fn emitted_json_survives_a_strict_conformant_parse() {
2021        for package in [fixture(), vocabulary_fixture()] {
2022            let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
2023            assert_eq!(package, strict_parse(&json));
2024        }
2025    }
2026
2027    #[test]
2028    fn json_renders_timing_bounds_and_fallible_arms_exactly() {
2029        let json = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
2030
2031        // Exactness is visible: timing bounds are exact-decimal microsecond
2032        // strings, never floating-point numbers (ADR-0008 decision 12) —
2033        // under the canonical lowerCamelCase field name (ADR-0014 decision 1).
2034        assert!(
2035            json.contains(r#""minUs": "10000""#),
2036            "the timing bound must be a JSON string, got: {json}"
2037        );
2038        // Both arms of the inline T | E return are visible by name.
2039        assert!(
2040            json.contains(r#""ok": "FaultPage""#),
2041            "the ok arm must render, got: {json}"
2042        );
2043        assert!(
2044            json.contains(r#""err": "DiagError""#),
2045            "the err arm must render, got: {json}"
2046        );
2047    }
2048
2049    /// ADR-0014 decision 8's stringification, tested on genuine 64-bit
2050    /// fields. The timing assertion above proves nothing about it —
2051    /// `Timing.min_us` is `optional string` in the schema — so the claim
2052    /// needs fields whose wire type actually is `uint64` or `int64`.
2053    #[test]
2054    fn json_renders_64_bit_integer_fields_as_strings() {
2055        let json = v2::to_json_pretty(&vocabulary_fixture())
2056            .expect("the vocabulary fixture serializes as IR JSON");
2057
2058        // uint64: the array's upper bound.
2059        assert!(
2060            json.contains(r#""max": "4096""#),
2061            "an array bound must be a JSON string, got: {json}"
2062        );
2063        // uint64 behind proto3 `optional`: the character length bound.
2064        assert!(
2065            json.contains(r#""lenMax": "86""#),
2066            "a length bound must be a JSON string, got: {json}"
2067        );
2068        // int64: the retired enum value and the enum-set bit position.
2069        assert!(
2070            json.contains(r#""value": "7""#),
2071            "a retired enum value must be a JSON string, got: {json}"
2072        );
2073        assert!(
2074            json.contains(r#""value": "33""#),
2075            "an enum-set bit position must be a JSON string, got: {json}"
2076        );
2077    }
2078
2079    #[test]
2080    fn fallible_transport_identity_follows_the_derivation_rule() {
2081        // The ADR-0008 decision 4 rule: interface + interaction ordinal +
2082        // both arm references, in that order.
2083        let fallible = v2::FallibleType {
2084            ok: "FaultPage".to_string(),
2085            err: "DiagError".to_string(),
2086        };
2087        assert_eq!(
2088            v2::fallible_transport_identity("VehicleStatus", 9, &fallible),
2089            "VehicleStatus#9:FaultPage|DiagError"
2090        );
2091
2092        // Derived from the fixture: the fallible query sits at ordinal 5.
2093        let package = fixture();
2094        let interface = &package.interfaces[0];
2095        let query_decl = &interface.interactions[4];
2096        let Some(v2::decl::Kind::QueryDef(query)) = &query_decl.kind else {
2097            panic!("ordinal 5 must be the fallible query");
2098        };
2099        let Some(v2::return_type::Kind::Fallible(arms)) = &query.return_type.as_ref().unwrap().kind
2100        else {
2101            panic!("fetchFaults must return a fallible type");
2102        };
2103        assert_eq!(
2104            v2::fallible_transport_identity(&interface.name, query_decl.ordinal, arms),
2105            "VehicleStatus#5:FaultPage|DiagError"
2106        );
2107    }
2108
2109    /// `Package::shapes` yields the named interfaces first, then the inline
2110    /// shapes of the services — and each shape carries the name it is known by
2111    /// OUTSIDE the package. The fixture's inline shape has `Interface.name ==
2112    /// ""` by construction, so a walk that yielded the interface bare would
2113    /// hand every consumer the empty string; two of the six E2 defects were
2114    /// exactly that.
2115    #[test]
2116    fn shapes_walks_named_interfaces_and_inline_service_shapes() {
2117        let package = fixture();
2118        let walk: Vec<(&str, bool, usize)> = package
2119            .shapes()
2120            .map(|shape| {
2121                (
2122                    shape.name,
2123                    shape.is_inline(),
2124                    shape.interface.interactions.len(),
2125                )
2126            })
2127            .collect();
2128        assert_eq!(
2129            walk,
2130            [("VehicleStatus", false, 6), ("veh.adas.logs", true, 1)],
2131            "the named interface, then the inline shape under the service's \
2132             dotted name",
2133        );
2134
2135        // The fixture's third shape-bearing declaration is `service
2136        // veh.adas.status : VehicleStatus`, which names an interface already in
2137        // the walk. Yielding it too would visit `VehicleStatus` twice.
2138        assert_eq!(package.services.len(), 2, "one reference form, one inline");
2139        assert!(
2140            !package
2141                .shapes()
2142                .any(|shape| shape.name == "veh.adas.status"),
2143            "a service naming an interface contributes no shape of its own",
2144        );
2145    }
2146
2147    #[test]
2148    fn relative_name_strips_the_unit_prefix() {
2149        assert_eq!(v2::relative_name("u", "u", "Session"), "Session");
2150        assert_eq!(
2151            v2::relative_name("u", "u.cluster", "Speed"),
2152            "cluster.Speed"
2153        );
2154        assert_eq!(
2155            v2::relative_name("com.example.hmi", "com.example.hmi.cluster.front", "A"),
2156            "cluster.front.A"
2157        );
2158    }
2159
2160    /// A package that is not inside the unit keeps its full name: no slice
2161    /// past the unit's length, whatever the snapshot says.
2162    #[test]
2163    fn relative_name_keeps_the_full_name_of_a_package_outside_the_unit() {
2164        assert_eq!(
2165            v2::relative_name("u", "w.cluster", "Speed"),
2166            "w.cluster.Speed"
2167        );
2168        assert_eq!(v2::relative_name("u", "ux", "A"), "ux.A");
2169        assert_eq!(v2::relative_name("u.cluster", "u", "Session"), "u.Session");
2170    }
2171
2172    /// A package named twice in the slice contributes the retired entries
2173    /// of its first occurrence only: two distinct values with the same name
2174    /// are not merged, and the later one is not read.
2175    #[test]
2176    fn unit_retired_reads_a_package_named_twice_once() {
2177        let first = v2::Package {
2178            name: "u.cluster".to_string(),
2179            unit: "u".to_string(),
2180            retired: vec![v2::RetiredInterface {
2181                name: "cluster.Old".to_string(),
2182                number: 3,
2183            }],
2184            ..Default::default()
2185        };
2186        let second = v2::Package {
2187            retired: vec![v2::RetiredInterface {
2188                name: "cluster.Older".to_string(),
2189                number: 4,
2190            }],
2191            ..first.clone()
2192        };
2193        assert_eq!(
2194            v2::unit_retired("u", &[&first, &second]),
2195            first.retired,
2196            "the first package of a name is the one read"
2197        );
2198    }
2199
2200    #[test]
2201    fn an_inline_shape_keeps_its_global_name() {
2202        let mut package = fixture();
2203        package.name = "u.cluster".to_string();
2204        package.unit = "u".to_string();
2205        let inline = package
2206            .shapes()
2207            .find(|shape| shape.is_inline())
2208            .expect("the fixture has an inline shape");
2209        assert_eq!(package.catalog_name(&inline), "veh.adas.logs");
2210        let named = package
2211            .shapes()
2212            .find(|shape| !shape.is_inline())
2213            .expect("the fixture has a declared interface");
2214        assert_eq!(package.catalog_name(&named), "cluster.VehicleStatus");
2215    }
2216
2217    #[test]
2218    fn catalog_name_treats_an_empty_unit_as_the_package_name() {
2219        let mut package = fixture();
2220        package.unit = String::new();
2221        let named = package
2222            .shapes()
2223            .find(|shape| !shape.is_inline())
2224            .expect("the fixture has a declared interface");
2225        assert_eq!(package.catalog_name(&named), "VehicleStatus");
2226    }
2227
2228    #[test]
2229    fn unit_of_falls_back_to_the_name() {
2230        let bare = v2::Package {
2231            name: "p".to_string(),
2232            ..Default::default()
2233        };
2234        assert_eq!(v2::unit_of(&bare), "p");
2235        let member = v2::Package {
2236            name: "u.a".to_string(),
2237            unit: "u".to_string(),
2238            ..Default::default()
2239        };
2240        assert_eq!(v2::unit_of(&member), "u");
2241    }
2242
2243    #[test]
2244    fn packages_of_unit_selects_by_unit_of() {
2245        let package = |name: &str, unit: &str| v2::Package {
2246            name: name.to_string(),
2247            unit: unit.to_string(),
2248            ..Default::default()
2249        };
2250        let packages = [
2251            package("u", "u"),
2252            package("u.a", "u"),
2253            package("w", ""),
2254            package("other.b", "other"),
2255        ];
2256        let names: Vec<&str> = v2::packages_of_unit("u", &packages)
2257            .map(|p| p.name.as_str())
2258            .collect();
2259        assert_eq!(names, ["u", "u.a"]);
2260        let legacy: Vec<&str> = v2::packages_of_unit("w", &packages)
2261            .map(|p| p.name.as_str())
2262            .collect();
2263        assert_eq!(legacy, ["w"]);
2264    }
2265
2266    /// The owning service is carried because `Service.visibility` is the
2267    /// authoritative one: an inline shape's own field is
2268    /// `VISIBILITY_UNSPECIFIED` by construction, which is not "internal" and
2269    /// not "public".
2270    #[test]
2271    fn shape_visibility_reads_the_owning_service_for_an_inline_shape() {
2272        let package = fixture();
2273        let shapes: Vec<v2::InterfaceShape<'_>> = package.shapes().collect();
2274
2275        let named = shapes[0];
2276        assert!(named.service.is_none());
2277        assert_eq!(named.visibility(), v2::Visibility::Public as i32);
2278        assert_eq!(named.visibility(), named.interface.visibility);
2279
2280        let inline = shapes[1];
2281        assert_eq!(
2282            inline.interface.visibility,
2283            v2::Visibility::Unspecified as i32,
2284            "the trap: an inline shape's own visibility field is unset",
2285        );
2286        assert_eq!(
2287            inline.service.expect("an inline shape has an owner").name,
2288            "veh.adas.logs",
2289        );
2290        assert_eq!(
2291            inline.visibility(),
2292            v2::Visibility::Public as i32,
2293            "the accessor reads the owning service's, never the unset field",
2294        );
2295    }
2296
2297    /// A package with no service at all still walks its interfaces, and a
2298    /// package with neither yields nothing — the emptiness both backends test
2299    /// for before emitting any interaction vocabulary.
2300    #[test]
2301    fn shapes_is_empty_only_when_the_package_declares_no_shape() {
2302        let mut package = fixture();
2303        package.services.clear();
2304        assert_eq!(package.shapes().count(), 1);
2305
2306        package.interfaces.clear();
2307        assert_eq!(package.shapes().count(), 0);
2308    }
2309
2310    /// A dotted reference contributes its qualifier; a bare one contributes
2311    /// nothing. Every recursive path through `walk_field_type` — array
2312    /// element, tuple field, map key, map value, stream element — carries a
2313    /// distinct qualifier, so no path's absence can hide behind another
2314    /// path's presence: deleting any one arm's body changes the expected set
2315    /// this test compares against, rather than leaving it unchanged.
2316    #[test]
2317    fn referenced_packages_finds_qualifiers_at_depth() {
2318        fn named(reference: &str) -> v2::FieldType {
2319            v2::FieldType {
2320                kind: Some(v2::field_type::Kind::Named(reference.to_string())),
2321                ..Default::default()
2322            }
2323        }
2324
2325        fn fixed(payload: v2::FieldType) -> v2::decl::Kind {
2326            v2::decl::Kind::FixedDef(v2::FixedDef {
2327                payload: Some(payload),
2328            })
2329        }
2330
2331        let package = v2::Package {
2332            name: "veh.cluster".to_string(),
2333            decls: vec![
2334                v2::Decl {
2335                    name: "Local".to_string(),
2336                    kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
2337                        payload: "Speed".to_string(),
2338                        ..Default::default()
2339                    })),
2340                    ..Default::default()
2341                },
2342                v2::Decl {
2343                    name: "Stamped".to_string(),
2344                    kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
2345                        payload: "ridl.std.Timestamp".to_string(),
2346                        ..Default::default()
2347                    })),
2348                    ..Default::default()
2349                },
2350                v2::Decl {
2351                    name: "ArrLabels".to_string(),
2352                    kind: Some(fixed(v2::FieldType {
2353                        kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
2354                            element: Some(Box::new(named("veh.arr.Label"))),
2355                            min: 0,
2356                            max: 32,
2357                        }))),
2358                        ..Default::default()
2359                    })),
2360                    ..Default::default()
2361                },
2362                v2::Decl {
2363                    name: "TupThing".to_string(),
2364                    kind: Some(fixed(v2::FieldType {
2365                        kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
2366                            fields: vec![v2::TupleField {
2367                                name: "x".to_string(),
2368                                r#type: Some(named("veh.tup.X")),
2369                            }],
2370                        })),
2371                        ..Default::default()
2372                    })),
2373                    ..Default::default()
2374                },
2375                v2::Decl {
2376                    name: "MapThing".to_string(),
2377                    kind: Some(fixed(v2::FieldType {
2378                        kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
2379                            key: Some(Box::new(named("veh.key.X"))),
2380                            value: Some(Box::new(named("veh.val.X"))),
2381                            min: 0,
2382                            max: 8,
2383                        }))),
2384                        ..Default::default()
2385                    })),
2386                    ..Default::default()
2387                },
2388                v2::Decl {
2389                    name: "StreamThing".to_string(),
2390                    kind: Some(fixed(v2::FieldType {
2391                        kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
2392                            element: Some(v2::stream_type::Element::Named(
2393                                "veh.strm.X".to_string(),
2394                            )),
2395                        })),
2396                        ..Default::default()
2397                    })),
2398                    ..Default::default()
2399                },
2400            ],
2401            ..Default::default()
2402        };
2403
2404        let found = v2::referenced_packages(&package);
2405        let expected: std::collections::BTreeSet<String> = [
2406            "ridl.std", "veh.arr", "veh.tup", "veh.key", "veh.val", "veh.strm",
2407        ]
2408        .into_iter()
2409        .map(str::to_string)
2410        .collect();
2411        assert_eq!(
2412            found, expected,
2413            "each recursive path must contribute its own distinct qualifier"
2414        );
2415        assert!(
2416            !found.contains("Speed") && !found.contains("veh.cluster"),
2417            "a bare reference contributes no package: {found:?}",
2418        );
2419    }
2420
2421    /// An empty package references nothing — the negative case the emit rule in
2422    /// `ridlc` depends on.
2423    #[test]
2424    fn referenced_packages_is_empty_without_references() {
2425        let package = v2::Package {
2426            name: "veh.solo".to_string(),
2427            ..Default::default()
2428        };
2429        assert!(v2::referenced_packages(&package).is_empty());
2430    }
2431
2432    /// Below prost's recursion limit at two message levels per nesting level
2433    /// — the depth ADR-0014 decision 12 measured as round-tripping correctly.
2434    /// Since decision 14 these two constants bound the prototext transcode
2435    /// alone: JSON no longer transcodes and carries its own read-side
2436    /// ceiling, tested separately below.
2437    const NESTING_BELOW_LIMIT: usize = 45;
2438    /// Past the limit today. The tests assert the outcome — an error, never a
2439    /// panic — not the exact threshold, so a prost release that moves the
2440    /// limit moves these constants, not the assertions.
2441    const NESTING_PAST_LIMIT: usize = 60;
2442
2443    /// One declaration whose payload nests `depth` levels of inline arrays —
2444    /// each level costs two message levels on the wire (`FieldType` plus
2445    /// `ArrayType`), the arithmetic ADR-0014 decision 12 records against
2446    /// prost's recursion limit.
2447    fn nested_package(depth: usize) -> v2::Package {
2448        let mut payload = v2::FieldType {
2449            optional: false,
2450            kind: Some(v2::field_type::Kind::Primitive(
2451                v2::PrimitiveType::Integer as i32,
2452            )),
2453        };
2454        for _ in 0..depth {
2455            payload = v2::FieldType {
2456                optional: false,
2457                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
2458                    element: Some(Box::new(payload)),
2459                    min: 1,
2460                    max: 1,
2461                }))),
2462            };
2463        }
2464        v2::Package {
2465            name: "veh.deep".to_string(),
2466            decls: vec![v2::Decl {
2467                name: "deep".to_string(),
2468                kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
2469                    payload: Some(payload),
2470                })),
2471                ..Default::default()
2472            }],
2473            ..Default::default()
2474        }
2475    }
2476
2477    /// One package whose nesting sits exactly `levels` message levels below
2478    /// the `Package` root — the unit the derived binary encoding's bound is
2479    /// stated in (the IR specification, "The derived encodings").
2480    ///
2481    /// The chain under a `FixedDef` costs three levels before any nesting
2482    /// (`Decl`, `FixedDef`, the outermost `FieldType`) and two per array level
2483    /// (`ArrayType`, `FieldType`), so an array-only chain reaches the odd
2484    /// depths alone. One tuple level costs three (`FieldType`, `TupleType`,
2485    /// `TupleField`, then the `FieldType` the next level counts), which is what
2486    /// reaches the even depths. Both shapes are what the front end lowers, so
2487    /// neither is a construction the schema would not otherwise see.
2488    fn package_at_message_depth(levels: usize) -> v2::Package {
2489        assert!(levels >= 3, "the chain costs three levels before nesting");
2490        let (arrays, tuple) = if levels % 2 == 1 {
2491            ((levels - 3) / 2, false)
2492        } else {
2493            assert!(levels >= 6, "one tuple level costs three");
2494            ((levels - 6) / 2, true)
2495        };
2496
2497        let mut payload = v2::FieldType {
2498            optional: false,
2499            kind: Some(v2::field_type::Kind::Primitive(
2500                v2::PrimitiveType::Integer as i32,
2501            )),
2502        };
2503        for _ in 0..arrays {
2504            payload = v2::FieldType {
2505                optional: false,
2506                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
2507                    element: Some(Box::new(payload)),
2508                    min: 1,
2509                    max: 1,
2510                }))),
2511            };
2512        }
2513        if tuple {
2514            payload = v2::FieldType {
2515                optional: false,
2516                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
2517                    fields: vec![v2::TupleField {
2518                        name: "f0".to_string(),
2519                        r#type: Some(payload),
2520                    }],
2521                })),
2522            };
2523        }
2524        v2::Package {
2525            name: "veh.deep".to_string(),
2526            decls: vec![v2::Decl {
2527                name: "deep".to_string(),
2528                kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
2529                    payload: Some(payload),
2530                })),
2531                ..Default::default()
2532            }],
2533            ..Default::default()
2534        }
2535    }
2536
2537    /// The nesting of JSON objects in a canonical artifact, which in the
2538    /// protobuf JSON mapping is the nesting of messages: every message is an
2539    /// object, a repeated field is an array of them, and the schema declares no
2540    /// `map<>` field. The root `Package` object is included, so a caller
2541    /// counting levels *below* the root subtracts one. Brackets inside a string
2542    /// literal do not count.
2543    fn message_nesting(json: &str) -> usize {
2544        let (mut depth, mut max) = (0usize, 0usize);
2545        let (mut in_string, mut escaped) = (false, false);
2546        for byte in json.bytes() {
2547            if in_string {
2548                if escaped {
2549                    escaped = false;
2550                } else if byte == b'\\' {
2551                    escaped = true;
2552                } else if byte == b'"' {
2553                    in_string = false;
2554                }
2555                continue;
2556            }
2557            match byte {
2558                b'"' => in_string = true,
2559                b'{' => {
2560                    depth += 1;
2561                    max = max.max(depth);
2562                }
2563                b'}' => depth = depth.saturating_sub(1),
2564                _ => {}
2565            }
2566        }
2567        max
2568    }
2569
2570    /// [`package_at_message_depth`] builds what it claims, on both parities.
2571    /// Without this the two bound tests below would pin a depth nobody
2572    /// measured.
2573    #[test]
2574    fn package_at_message_depth_builds_the_depth_it_names() {
2575        with_sized_stack(|| {
2576            for levels in [3, 6, 7, 99, 100, 101] {
2577                let json = v2::to_json_pretty(&package_at_message_depth(levels))
2578                    .expect("the writer is unrestricted at these depths");
2579                assert_eq!(
2580                    message_nesting(&json) - 1,
2581                    levels,
2582                    "the chain must nest {levels} message levels below the root"
2583                );
2584            }
2585        });
2586    }
2587
2588    /// The derived binary encoding's bound, stated by the IR specification and
2589    /// pinned here: 100 message levels below the root round-trip.
2590    ///
2591    /// `to_binary` writes any depth; it is `from_binary` that stops, at prost's
2592    /// `RECURSION_LIMIT` of 100, decremented once per nested message on decode
2593    /// and not consulted on encode. The test asserts the outcome, not prost's
2594    /// constant: a prost release that moves the limit moves these two tests and
2595    /// the specification's paragraph together.
2596    #[test]
2597    fn binary_round_trip_at_100_message_levels_succeeds() {
2598        let package = package_at_message_depth(100);
2599        let bytes = v2::to_binary(&package);
2600        let decoded = v2::from_binary(&bytes).expect("100 message levels decode");
2601        assert_eq!(package, decoded);
2602    }
2603
2604    /// One level past that bound the binary reader refuses — an error, never a
2605    /// panic — while the canonical encoding carries the same package. This is
2606    /// the asymmetry the specification states as the reason binary is derived
2607    /// rather than canonical (driftsys/ridl#231).
2608    #[test]
2609    fn binary_decode_at_101_message_levels_returns_an_error() {
2610        let package = package_at_message_depth(101);
2611        let bytes = v2::to_binary(&package);
2612        let error = v2::from_binary(&bytes).expect_err("101 message levels must fail, not panic");
2613        assert!(
2614            error.to_string().contains("recursion limit reached"),
2615            "the error must name the limit, got: {error}"
2616        );
2617
2618        let json = v2::to_json_pretty(&package).expect("the canonical encoding has no such bound");
2619        assert_eq!(
2620            package,
2621            v2::from_json(&json).expect("the canonical encoding round-trips the same package")
2622        );
2623    }
2624
2625    /// The write side after ADR-0014 decision 14: the pbjson-generated
2626    /// writer recurses the typed message directly — no transcode, so no
2627    /// message-level recursion limit — and 400 levels of array nesting,
2628    /// roughly eight times the ceiling decision 12 recorded, serialize and
2629    /// round-trip. Run on an explicitly sized stack: the writer recurses on
2630    /// the caller's stack, and debug-build frames at this depth overflow the
2631    /// default test-thread stack (the reader sizes its own thread inside
2632    /// `from_json`).
2633    #[test]
2634    fn json_round_trip_at_400_nested_levels_succeeds() {
2635        with_sized_stack(|| {
2636            let package = nested_package(400);
2637            let json = v2::to_json_pretty(&package).expect("the writer has no message-level limit");
2638            let decoded = v2::from_json(&json).expect("the reader parses within its ceiling");
2639            assert_eq!(package, decoded);
2640        });
2641    }
2642
2643    /// The one error path on the JSON write side (ADR-0014 decision 14),
2644    /// and it is new with the generated impl, not a survivor of the
2645    /// transcode's: an `i32` enum field holding a discriminant outside the
2646    /// schema — data, not depth — which the retired reflection path
2647    /// serialized successfully as its bare number. The checker never
2648    /// produces one, so there is no CLI route to this failure; it is pinned
2649    /// here at the crate surface.
2650    #[test]
2651    fn json_serialization_of_an_out_of_schema_discriminant_returns_an_error() {
2652        let mut package = fixture();
2653        package.decls[0].visibility = 999;
2654        let err = v2::to_json_pretty(&package)
2655            .expect_err("an out-of-schema discriminant must fail, not panic");
2656        let message = err.to_string();
2657        assert!(
2658            message.contains("canonical protobuf JSON"),
2659            "the error must name the encoding that failed, got: {message}"
2660        );
2661        assert!(
2662            message.contains("discriminant outside the schema"),
2663            "the error must name the known cause, got: {message}"
2664        );
2665    }
2666
2667    /// The strictness ADR-0014 decision 11 relies on is the generated
2668    /// deserializer's default: `ignore_unknown_fields()` is the opt-out and
2669    /// stays unset, so a field the schema does not declare is an error,
2670    /// never silently dropped.
2671    #[test]
2672    fn json_parse_rejects_an_unknown_field() {
2673        let error = v2::from_json(r#"{"name": "veh.deep", "notAField": 1}"#)
2674            .expect_err("an unknown field must be rejected");
2675        assert!(
2676            error.to_string().contains("unknown field"),
2677            "the error must name the defect, got: {error}"
2678        );
2679    }
2680
2681    /// A reader narrowing ADR-0014 decision 14 records: the proto3 JSON
2682    /// mapping expects parsers to accept numeric enum values, and the
2683    /// generated deserializer does — within the schema's range. A
2684    /// discriminant outside it (`"visibility": 77`) is rejected, where the
2685    /// retired reflection reader accepted it — and the retired *writer*
2686    /// emitted exactly such a number for an out-of-schema discriminant.
2687    /// Pinned so the narrowing stays a decision rather than an accident: a
2688    /// future mechanism change must confront this test.
2689    #[test]
2690    fn json_parse_rejects_an_out_of_range_numeric_enum_value() {
2691        let with_visibility =
2692            |value: &str| format!(r#"{{"name": "veh.x", "decls": [{{"visibility": {value}}}]}}"#);
2693        v2::from_json(&with_visibility("1"))
2694            .expect("an in-range numeric enum value parses, as the mapping expects");
2695        let error = v2::from_json(&with_visibility("77"))
2696            .expect_err("an out-of-range numeric enum value must be rejected");
2697        assert!(
2698            error.to_string().contains("invalid value: integer `77`"),
2699            "the error must name the value, got: {error}"
2700        );
2701    }
2702
2703    /// A reader narrowing ADR-0014 decision 14 records: the mapping accepts
2704    /// float and exponent notation for integer fields (`"min": 1.0`), and
2705    /// the retired reflection reader did; the generated deserializer
2706    /// rejects both. Pinned for the same reason as the numeric-enum case
2707    /// above.
2708    #[test]
2709    fn json_parse_rejects_a_float_form_integer() {
2710        for spelling in ["1.0", "1e0"] {
2711            let error = v2::from_json(&format!(
2712                r#"{{"name": "veh.x", "decls": [{{"fixedDef": {{"payload": {{"array": {{"min": {spelling}}}}}}}}}]}}"#,
2713            ))
2714            .expect_err("a float-form integer must be rejected");
2715            assert!(
2716                error.to_string().contains("did not match any variant"),
2717                "the integer field's deserializer must be the one refusing `{spelling}`, \
2718                 got: {error}"
2719            );
2720        }
2721    }
2722
2723    /// A reader narrowing ADR-0014 decision 14 records: `null` for a
2724    /// repeated field (`"decls": null`), which the retired reflection
2725    /// reader read as empty, is rejected. `null` for an optional scalar or
2726    /// message field is still accepted — parity with the retired reader,
2727    /// asserted alongside so the narrowing's edge is pinned from both
2728    /// sides.
2729    #[test]
2730    fn json_parse_rejects_null_for_a_repeated_field() {
2731        let error = v2::from_json(r#"{"name": "veh.x", "decls": null}"#)
2732            .expect_err("null for a repeated field must be rejected");
2733        assert!(
2734            error.to_string().contains("invalid type: null"),
2735            "the error must name the null, got: {error}"
2736        );
2737        v2::from_json(r#"{"name": "veh.x", "decls": [{"deprecated": null}]}"#)
2738            .expect("null for an optional scalar field still parses");
2739    }
2740
2741    /// A reader narrowing ADR-0014 decision 14 records: a duplicate JSON
2742    /// key, which the retired reflection reader resolved last-wins, is
2743    /// rejected.
2744    #[test]
2745    fn json_parse_rejects_a_duplicate_key() {
2746        let error = v2::from_json(r#"{"name": "a", "name": "b"}"#)
2747            .expect_err("a duplicate key must be rejected");
2748        assert!(
2749            error.to_string().contains("duplicate field `name`"),
2750            "the error must name the duplicated field, got: {error}"
2751        );
2752    }
2753
2754    /// The read-side ceiling (ADR-0014 decision 14): nesting past 1,000
2755    /// bracket levels returns an error before the parse begins — a
2756    /// diagnostic, where unbounded recursion would eventually abort on a
2757    /// stack overflow no caller can catch. The input is real writer output:
2758    /// past the ceiling the asymmetry is deliberate — the writer is
2759    /// unrestricted, the reader is not.
2760    #[test]
2761    fn json_parse_past_the_nesting_ceiling_returns_an_error() {
2762        with_sized_stack(|| {
2763            let json = v2::to_json_pretty(&nested_package(500))
2764                .expect("the writer is unrestricted at this depth");
2765            let error = v2::from_json(&json).expect_err("the reader must refuse past its ceiling");
2766            assert!(
2767                error.to_string().contains("1000 JSON levels"),
2768                "the error must name the ceiling, got: {error}"
2769            );
2770        });
2771    }
2772
2773    /// The ceiling is exact: 1,000 open brackets pass the scan and reach the
2774    /// parser — which then rejects the input as not a package — and 1,001 do
2775    /// not. The scan runs before the parse, so the over-ceiling probe needs
2776    /// no valid JSON behind its brackets.
2777    #[test]
2778    fn json_nesting_ceiling_binds_exactly_at_1000() {
2779        let at = v2::from_json(&"[".repeat(1_000)).expect_err("an array is not a package");
2780        assert!(
2781            !at.to_string().contains("JSON levels"),
2782            "at the ceiling the parser, not the scan, must be the one refusing, got: {at}"
2783        );
2784
2785        let past = v2::from_json(&"[".repeat(1_001)).expect_err("past the ceiling, the scan");
2786        assert!(
2787            past.to_string().contains("1000 JSON levels"),
2788            "past the ceiling the error must name it, got: {past}"
2789        );
2790    }
2791
2792    /// The nesting scan behind the ceiling: brackets count only outside
2793    /// string literals, an escaped quote does not end a literal, an escaped
2794    /// backslash does not disarm the real closing quote after it, and a
2795    /// stray closer never underflows the running depth.
2796    #[test]
2797    fn nesting_scan_counts_brackets_outside_string_literals_only() {
2798        // Plain structural nesting counts every open bracket.
2799        assert_eq!(v2::max_json_nesting(r#"{"a": [{"b": []}]}"#), 4);
2800        // Brackets inside a string literal do not count.
2801        assert_eq!(v2::max_json_nesting(r#"{"doc": "{[[[{"}"#), 1);
2802        // An escaped quote does not end the literal, so the brackets after
2803        // it are still inside it.
2804        assert_eq!(v2::max_json_nesting(r#"{"doc": "a\"[[[", "x": []}"#), 2);
2805        // An escaped backslash does not escape the closing quote: the
2806        // literal ends, and the brackets after it count.
2807        assert_eq!(v2::max_json_nesting(r#"{"doc": "a\\", "x": [[]]}"#), 3);
2808        // A stray closer saturates at zero rather than underflowing.
2809        assert_eq!(v2::max_json_nesting("]]]{"), 1);
2810    }
2811
2812    /// The prototext form of [`nested_package`], built by hand for the same
2813    /// reason [`nested_json`] is: past the limit the serializer rejects the
2814    /// package, so its prototext cannot come from [`v2::to_text_format`].
2815    fn nested_text(depth: usize) -> String {
2816        let mut payload = "primitive: PRIMITIVE_TYPE_INTEGER".to_string();
2817        for _ in 0..depth {
2818            payload = format!("array {{ element {{ {payload} }} min: 1 max: 1 }}");
2819        }
2820        format!(
2821            r#"name: "veh.deep" decls {{ name: "deep" fixed_def {{ payload {{ {payload} }} }} }}"#
2822        )
2823    }
2824
2825    /// The prototext write path carries the same recursion-limit failure mode
2826    /// as JSON — both go through the one transcode (ADR-0014 decision 12) —
2827    /// and reports it as an error naming its own encoding, never a panic.
2828    #[test]
2829    fn text_serialization_past_the_nesting_limit_returns_an_error() {
2830        let err = v2::to_text_format(&nested_package(NESTING_PAST_LIMIT))
2831            .expect_err("serialization past the recursion limit must fail, not panic");
2832        let message = err.to_string();
2833        assert!(
2834            message.contains("recursion limit"),
2835            "the error must name the nesting limit as the known cause, got: {message}"
2836        );
2837        assert!(
2838            message.contains("prototext"),
2839            "the error must name the encoding that failed, got: {message}"
2840        );
2841    }
2842
2843    /// Runs `test` on a thread whose stack fits the recursion the test
2844    /// drives on its own thread. Two groups need one. The prototext parser
2845    /// recurses once per message level with debug-build frames large enough
2846    /// that the default 2 MiB test-thread stack overflows near 45 array
2847    /// levels — under prost's own recursion limit, so the depths
2848    /// [`NESTING_BELOW_LIMIT`] and [`NESTING_PAST_LIMIT`] pin are
2849    /// unreachable on that stack; the production paths are unaffected, since
2850    /// the toolchain writes prototext and never parses it (`ridl diff` and
2851    /// the baselines stay `.ir.json`, ADR-0014 decision 5). And the deep
2852    /// JSON tests drive the pbjson-generated writer, which recurses on the
2853    /// caller's stack (ADR-0014 decision 14 — only the reader sizes a
2854    /// thread of its own, inside `from_json`).
2855    fn with_sized_stack(test: impl FnOnce() + Send + 'static) {
2856        let outcome = std::thread::Builder::new()
2857            .stack_size(16 * 1024 * 1024)
2858            .spawn(test)
2859            .expect("spawn the large-stack test thread")
2860            .join();
2861        if let Err(payload) = outcome {
2862            std::panic::resume_unwind(payload);
2863        }
2864    }
2865
2866    /// The read direction: the text-format parser itself has no depth limit,
2867    /// so the failure is the transcode out of the dynamic message, mapped
2868    /// into the error return instead of expected on (ADR-0014 decision 12).
2869    #[test]
2870    fn text_parse_past_the_nesting_limit_returns_an_error() {
2871        with_sized_stack(|| {
2872            let error = v2::from_text_format(&nested_text(NESTING_PAST_LIMIT))
2873                .expect_err("parsing past the recursion limit must fail, not panic");
2874
2875            // Assert *which* stage failed: prost's transcoding decoder says
2876            // "recursion limit reached", and a parse-stage failure would
2877            // render through the `Parse` variant instead.
2878            let message = error.to_string();
2879            assert!(
2880                message.contains("recursion limit reached"),
2881                "the transcode out of the dynamic message must be the failing \
2882                 stage, got: {message}"
2883            );
2884        });
2885    }
2886
2887    /// The prototext bound must not tighten silently either: below the limit
2888    /// the package still serializes and round-trips.
2889    #[test]
2890    fn text_round_trip_below_the_nesting_limit_succeeds() {
2891        with_sized_stack(|| {
2892            let package = nested_package(NESTING_BELOW_LIMIT);
2893            let text = v2::to_text_format(&package)
2894                .expect("below the recursion limit, serialization succeeds");
2895            let decoded =
2896                v2::from_text_format(&text).expect("below the recursion limit, parsing succeeds");
2897            assert_eq!(package, decoded);
2898        });
2899    }
2900}
2901
2902#[cfg(test)]
2903mod vacuous_constraint {
2904    use crate::v2;
2905
2906    /// A constraint with every field absent. Each test sets only the field it
2907    /// is about, so no assertion can pass through a neighbouring field.
2908    fn constraint() -> v2::Constraint {
2909        v2::Constraint {
2910            min: None,
2911            max: None,
2912            step: None,
2913            len_min: None,
2914            len_max: None,
2915            pattern: None,
2916            pattern_const: None,
2917        }
2918    }
2919
2920    #[test]
2921    fn an_absent_or_empty_constraint_is_vacuous() {
2922        assert!(v2::constraint_is_vacuous(None));
2923        assert!(v2::constraint_is_vacuous(Some(&constraint())));
2924    }
2925
2926    #[test]
2927    fn a_step_constraint_is_non_vacuous() {
2928        let stepped = v2::Constraint {
2929            step: Some("0.5".to_string()),
2930            ..constraint()
2931        };
2932        assert!(!v2::constraint_is_vacuous(Some(&stepped)));
2933    }
2934
2935    /// Every constrained field on its own. A fixture setting a pair — `min`
2936    /// with `max`, or `len_min` with `len_max` — cannot tell a predicate that
2937    /// reads both from one that reads either, so each bound here is one-sided.
2938    /// The paired shapes are pinned separately by
2939    /// [`a_bound_pair_set_together_is_non_vacuous`], which a one-sided fixture
2940    /// cannot do.
2941    #[test]
2942    fn any_single_constrained_field_is_non_vacuous() {
2943        let cases = [
2944            (
2945                "min",
2946                v2::Constraint {
2947                    min: Some("0.0".to_string()),
2948                    ..constraint()
2949                },
2950            ),
2951            (
2952                "max",
2953                v2::Constraint {
2954                    max: Some("250.0".to_string()),
2955                    ..constraint()
2956                },
2957            ),
2958            (
2959                "len_min",
2960                v2::Constraint {
2961                    len_min: Some(1),
2962                    ..constraint()
2963                },
2964            ),
2965            (
2966                "len_max",
2967                v2::Constraint {
2968                    len_max: Some(256),
2969                    ..constraint()
2970                },
2971            ),
2972            (
2973                "pattern",
2974                v2::Constraint {
2975                    pattern: Some("^[a-z]+$".to_string()),
2976                    ..constraint()
2977                },
2978            ),
2979            (
2980                "pattern_const",
2981                v2::Constraint {
2982                    pattern_const: Some("NAME_PATTERN".to_string()),
2983                    ..constraint()
2984                },
2985            ),
2986        ];
2987        for (field, case) in cases {
2988            assert!(
2989                !v2::constraint_is_vacuous(Some(&case)),
2990                "`{field}` alone must be non-vacuous"
2991            );
2992        }
2993    }
2994
2995    /// The two shapes the checker actually emits: a declared range, and the
2996    /// typl §4.4 default `[0..256]` every string and bytes type carries.
2997    ///
2998    /// A one-sided fixture cannot pin these. A predicate reading each bound as
2999    /// a pair — `(c.min.is_none() == c.max.is_none())` and the same for the
3000    /// length bounds — passes every one-sided case and still reports both
3001    /// shapes below as vacuous, which would drop the range check from every
3002    /// bounded number and every string.
3003    #[test]
3004    fn a_bound_pair_set_together_is_non_vacuous() {
3005        let ranged = v2::Constraint {
3006            min: Some("0.0".to_string()),
3007            max: Some("250.0".to_string()),
3008            ..constraint()
3009        };
3010        assert!(!v2::constraint_is_vacuous(Some(&ranged)));
3011
3012        let default_length = v2::Constraint {
3013            len_min: Some(0),
3014            len_max: Some(256),
3015            ..constraint()
3016        };
3017        assert!(!v2::constraint_is_vacuous(Some(&default_length)));
3018    }
3019}
3020
3021#[cfg(test)]
3022mod system_round_trip {
3023    use crate::v2;
3024
3025    fn attribute(namespace: &str, key: &str, value: Option<v2::AttributeValue>) -> v2::Attribute {
3026        v2::Attribute {
3027            namespace: namespace.to_string(),
3028            key: key.to_string(),
3029            value,
3030        }
3031    }
3032
3033    fn scalar(text: &str) -> v2::AttributeValue {
3034        v2::AttributeValue {
3035            kind: Some(v2::attribute_value::Kind::Scalar(text.to_string())),
3036        }
3037    }
3038
3039    fn list(items: Vec<v2::AttributeValue>) -> v2::AttributeValue {
3040        v2::AttributeValue {
3041            kind: Some(v2::attribute_value::Kind::List(v2::AttributeList { items })),
3042        }
3043    }
3044
3045    fn interface(catalog: &str, name: &str, inline: bool) -> Option<v2::InterfaceRef> {
3046        Some(v2::InterfaceRef {
3047            catalog: catalog.to_string(),
3048            name: name.to_string(),
3049            inline,
3050        })
3051    }
3052
3053    fn endpoint(component: &str, instance: &str, machine: &str) -> v2::Endpoint {
3054        v2::Endpoint {
3055            component: component.to_string(),
3056            instance: instance.to_string(),
3057            machine: machine.to_string(),
3058        }
3059    }
3060
3061    /// A reduced rsdl reference Appendix A: `Cruise` with two instances
3062    /// offering `veh.adas.cruise` and requiring `LaneAssist`, the implicit
3063    /// component of `veh.diag.access`, one distribution and one deployment.
3064    /// Every message of `system.proto` appears at least once, with every
3065    /// scalar set to a value other than its default — a flag and a nested-list
3066    /// attribute value included — so a round trip that drops a field is
3067    /// caught.
3068    fn doc_link() -> v2::DocLink {
3069        v2::DocLink {
3070            text: "Cruise".to_string(),
3071            offset: 16,
3072            len: 6,
3073            target: "veh.topology.Cruise".to_string(),
3074        }
3075    }
3076
3077    fn fixture() -> v2::System {
3078        let link = v2::Link {
3079            interface: interface("veh.diag", "veh.diag.access", true),
3080            service: "veh.diag.access".to_string(),
3081            consumer: Some(endpoint("veh.topology.Backend", "Unit", "Cloud")),
3082            producer: Some(endpoint("veh.diag.access", "Unit", "AdasHpc")),
3083            crossing: v2::Crossing::OffBoard as i32,
3084        };
3085        v2::System {
3086            name: "Vehicle".to_string(),
3087            package: "veh.topology".to_string(),
3088            labels: vec!["ASIL_B".to_string()],
3089            attributes: vec![attribute("rust", "crate", Some(scalar("\"vehicle\"")))],
3090            members: vec![
3091                v2::MemberLine {
3092                    component: "veh.topology.Cruise".to_string(),
3093                    attributes: vec![attribute("linux", "pinned", None)],
3094                    doc: "Documented, see [Cruise].".to_string(),
3095                    links: vec![doc_link()],
3096                    see: vec![doc_link()],
3097                    since: vec!["1.2".to_string()],
3098                },
3099                v2::MemberLine {
3100                    component: "veh.diag.access".to_string(),
3101                    attributes: vec![],
3102                    doc: "Documented, see [Cruise].".to_string(),
3103                    links: vec![doc_link()],
3104                    see: vec![doc_link()],
3105                    since: vec!["1.2".to_string()],
3106                },
3107            ],
3108            components: vec![
3109                v2::Component {
3110                    name: "Cruise".to_string(),
3111                    package: "veh.topology".to_string(),
3112                    implicit: false,
3113                    external: true,
3114                    instances: vec!["primary".to_string(), "backup".to_string()],
3115                    numbers: vec![
3116                        v2::InstanceNumber {
3117                            instance: "primary".to_string(),
3118                            number: 1,
3119                            provisional: false,
3120                        },
3121                        v2::InstanceNumber {
3122                            instance: "backup".to_string(),
3123                            number: 2,
3124                            provisional: true,
3125                        },
3126                    ],
3127                    offers: vec![v2::Offer {
3128                        service: "veh.adas.cruise".to_string(),
3129                        attributes: vec![attribute("someip", "serviceId", Some(scalar("4097")))],
3130                        doc: "Documented, see [Cruise].".to_string(),
3131                        links: vec![doc_link()],
3132                        see: vec![doc_link()],
3133                        since: vec!["1.2".to_string()],
3134                    }],
3135                    requires: vec![v2::Require {
3136                        interface: interface("veh.adas", "LaneAssist", false),
3137                        service: "veh.adas.lane".to_string(),
3138                        producer: "veh.topology.Lane".to_string(),
3139                        attributes: vec![attribute(
3140                            "linux",
3141                            "cpuset",
3142                            Some(list(vec![scalar("2"), list(vec![scalar("3")])])),
3143                        )],
3144                        doc: "Documented, see [Cruise].".to_string(),
3145                        links: vec![doc_link()],
3146                        see: vec![doc_link()],
3147                        since: vec!["1.2".to_string()],
3148                    }],
3149                    labels: vec!["ASIL_B".to_string()],
3150                    attributes: vec![attribute("rust", "crate", None)],
3151                    doc: "Documented, see [Cruise].".to_string(),
3152                    links: vec![doc_link()],
3153                    see: vec![doc_link()],
3154                    since: vec!["1.2".to_string()],
3155                    deprecated: Some("superseded".to_string()),
3156                },
3157                v2::Component {
3158                    name: "veh.diag.access".to_string(),
3159                    package: String::new(),
3160                    implicit: true,
3161                    external: false,
3162                    instances: vec!["Unit".to_string()],
3163                    numbers: vec![v2::InstanceNumber {
3164                        instance: "Unit".to_string(),
3165                        number: 3,
3166                        provisional: false,
3167                    }],
3168                    offers: vec![v2::Offer {
3169                        service: "veh.diag.access".to_string(),
3170                        attributes: vec![],
3171                        doc: "Documented, see [Cruise].".to_string(),
3172                        links: vec![doc_link()],
3173                        see: vec![doc_link()],
3174                        since: vec!["1.2".to_string()],
3175                    }],
3176                    requires: vec![],
3177                    labels: vec![],
3178                    attributes: vec![],
3179                    doc: "Documented, see [Cruise].".to_string(),
3180                    links: vec![doc_link()],
3181                    see: vec![doc_link()],
3182                    since: vec!["1.2".to_string()],
3183                    deprecated: Some("superseded".to_string()),
3184                },
3185            ],
3186            producers: vec![v2::Producer {
3187                service: "veh.adas.cruise".to_string(),
3188                component: "veh.topology.Cruise".to_string(),
3189                instances: vec!["primary".to_string(), "backup".to_string()],
3190                not_yet_realizable: true,
3191            }],
3192            grants: vec![v2::Grant {
3193                component: "veh.topology.Backend".to_string(),
3194                external: true,
3195                regions: vec!["veh.adas".to_string(), "veh.diag".to_string()],
3196            }],
3197            regions: vec![v2::Region {
3198                catalog: "veh.diag".to_string(),
3199                hash: vec![0xab; 32],
3200                interfaces: vec![v2::RegionInterface {
3201                    name: "veh.diag.access".to_string(),
3202                    inline: true,
3203                    number: 2,
3204                    provisional: true,
3205                    service: "veh.diag.access".to_string(),
3206                }],
3207            }],
3208            distributions: vec![v2::Distribution {
3209                name: "Adas".to_string(),
3210                package: "veh.topology".to_string(),
3211                members: vec![v2::MemberLine {
3212                    component: "veh.topology.Cruise".to_string(),
3213                    attributes: vec![],
3214                    doc: "Documented, see [Cruise].".to_string(),
3215                    links: vec![doc_link()],
3216                    see: vec![doc_link()],
3217                    since: vec!["1.2".to_string()],
3218                }],
3219                depends_on: vec!["veh.topology.Base".to_string()],
3220                labels: vec!["PLATFORM_BUNDLE".to_string()],
3221                attributes: vec![attribute("deb", "section", Some(scalar("net")))],
3222                doc: "Documented, see [Cruise].".to_string(),
3223                links: vec![doc_link()],
3224                see: vec![doc_link()],
3225                since: vec!["1.2".to_string()],
3226                tier: v2::Tier::Platform as i32,
3227                deprecated: Some("superseded".to_string()),
3228            }],
3229            deployments: vec![v2::Deployment {
3230                name: "Production".to_string(),
3231                package: "veh.topology".to_string(),
3232                labels: vec!["FLEET".to_string()],
3233                attributes: vec![attribute("ota", "channel", Some(scalar("stable")))],
3234                machines: vec![v2::Machine {
3235                    name: "Cloud".to_string(),
3236                    external: true,
3237                    labels: vec!["OFF_BOARD".to_string()],
3238                    attributes: vec![attribute("net", "zone", Some(scalar("wan")))],
3239                    doc: "Documented, see [Cruise].".to_string(),
3240                    links: vec![doc_link()],
3241                    see: vec![doc_link()],
3242                    since: vec!["1.2".to_string()],
3243                    deprecated: Some("superseded".to_string()),
3244                }],
3245                placements: vec![v2::Placement {
3246                    component: "veh.topology.Cruise".to_string(),
3247                    instance: "backup".to_string(),
3248                    machine: "Cockpit".to_string(),
3249                    attributes: vec![attribute("linux", "cpuset", Some(list(vec![])))],
3250                    sizing: Some(v2::Sizing {
3251                        depth: Some(4_294_967_295),
3252                        slots: Some(65_536),
3253                        budget: Some(18_446_744_073_709_551_615),
3254                    }),
3255                }],
3256                links: vec![link.clone()],
3257                routes: vec![v2::Route {
3258                    catalog: "veh.adas".to_string(),
3259                    interface_number: 2,
3260                    member_ordinal: 1,
3261                    interface: "LaneAssist".to_string(),
3262                    member: "active".to_string(),
3263                    service: "veh.adas.lane".to_string(),
3264                    producers: vec![endpoint("veh.topology.Lane", "Unit", "AdasHpc")],
3265                }],
3266                surface: vec![v2::Surface {
3267                    link: Some(link),
3268                    direction: v2::SurfaceDirection::ExternalConsumes as i32,
3269                }],
3270                installations: vec![v2::Installation {
3271                    distribution: "veh.topology.Adas".to_string(),
3272                    machines: vec!["AdasHpc".to_string(), "Cockpit".to_string()],
3273                }],
3274                doc: "Documented, see [Cruise].".to_string(),
3275                doc_links: vec![doc_link()],
3276                see: vec![doc_link()],
3277                since: vec!["1.2".to_string()],
3278                sizing: Some(v2::Sizing {
3279                    depth: Some(3),
3280                    slots: Some(8),
3281                    budget: Some(4096),
3282                }),
3283                deprecated: Some("superseded".to_string()),
3284                file: Some("veh-production".to_string()),
3285            }],
3286            doc: "Documented, see [Cruise].".to_string(),
3287            see: vec![doc_link()],
3288            since: vec!["1.2".to_string()],
3289            links: vec![doc_link()],
3290            deprecated: Some("superseded".to_string()),
3291        }
3292    }
3293
3294    #[test]
3295    fn system_binary_round_trip_preserves_system() {
3296        let system = fixture();
3297        let decoded = v2::system_from_binary(v2::system_to_binary(&system).as_slice())
3298            .expect("decode must succeed");
3299        assert_eq!(system, decoded);
3300    }
3301
3302    /// The canonical JSON of the system artifact re-reads through the same
3303    /// strict pbjson-generated impl the package uses (ADR-0014 decisions 11
3304    /// and 14): unknown fields rejected, the catalog hash as base64, enums by
3305    /// name, the nested attribute list intact.
3306    #[test]
3307    fn system_json_round_trip_preserves_system() {
3308        let system = fixture();
3309        let json = v2::system_to_json_pretty(&system).expect("the fixture serializes as JSON");
3310        assert!(
3311            json.contains("\"hash\": \"q6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6s=\""),
3312            "bytes render as base64, got:\n{json}"
3313        );
3314        assert!(
3315            json.contains("\"crossing\": \"CROSSING_OFF_BOARD\""),
3316            "enums render by name, got:\n{json}"
3317        );
3318        assert!(
3319            json.contains("\"notYetRealizable\": true"),
3320            "fields render in lowerCamelCase, got:\n{json}"
3321        );
3322        assert!(
3323            json.contains("\"budget\": \"18446744073709551615\""),
3324            "a 64-bit value renders as a string, got:\n{json}"
3325        );
3326        assert_eq!(
3327            system,
3328            v2::system_from_json(&json).expect("the JSON parses")
3329        );
3330        assert!(
3331            v2::system_from_json(&json.replacen("\"name\"", "\"nam\"", 1)).is_err(),
3332            "an unknown field is rejected"
3333        );
3334    }
3335
3336    /// An absent `sizing` and an empty one are different on the wire: a plugin
3337    /// reads "nothing declared" and "declared nothing" apart, in the binary and
3338    /// the JSON encodings.
3339    #[test]
3340    fn an_absent_sizing_and_an_empty_one_stay_distinct_through_the_encodings() {
3341        let mut absent = fixture();
3342        absent.deployments[0].sizing = None;
3343        absent.deployments[0].placements[0].sizing = None;
3344        let mut empty = absent.clone();
3345        empty.deployments[0].sizing = Some(v2::Sizing::default());
3346        empty.deployments[0].placements[0].sizing = Some(v2::Sizing::default());
3347        for system in [&absent, &empty] {
3348            let binary = v2::system_from_binary(v2::system_to_binary(system).as_slice())
3349                .expect("decode must succeed");
3350            assert_eq!(system, &binary);
3351            let json = v2::system_to_json_pretty(system).expect("serializes as JSON");
3352            assert_eq!(
3353                system,
3354                &v2::system_from_json(&json).expect("the JSON parses")
3355            );
3356        }
3357        assert_ne!(
3358            v2::system_to_binary(&absent),
3359            v2::system_to_binary(&empty),
3360            "the binary encodings differ"
3361        );
3362    }
3363
3364    #[test]
3365    fn system_text_format_round_trip_preserves_system() {
3366        let system = fixture();
3367        let text = v2::system_to_text_format(&system).expect("the fixture serializes as prototext");
3368        assert!(
3369            text.starts_with("name:"),
3370            "fields print in schema index order, got: {text}"
3371        );
3372        assert_eq!(
3373            system,
3374            v2::system_from_text_format(&text).expect("prototext parsing must succeed")
3375        );
3376    }
3377
3378    /// `pkg.Name` for a declared name; the implicit component of a lone
3379    /// service, which no package declares, is its own qualified name.
3380    #[test]
3381    fn qualified_names_follow_the_one_derivation() {
3382        let system = fixture();
3383        assert_eq!(system.qualified_name(), "veh.topology.Vehicle");
3384        assert_eq!(system.components[0].qualified_name(), "veh.topology.Cruise");
3385        assert_eq!(system.components[1].qualified_name(), "veh.diag.access");
3386        assert_eq!(
3387            system.distributions[0].qualified_name(),
3388            "veh.topology.Adas"
3389        );
3390    }
3391}
3392
3393#[cfg(test)]
3394mod load_ir_json {
3395    use crate::v2::{self, LoadError, MAX_JSON_NESTING, load_ir_json};
3396
3397    /// A snapshot written by `to_json_pretty` loads back as the same package.
3398    #[test]
3399    fn a_snapshot_file_loads() {
3400        let dir = tempfile::tempdir().unwrap();
3401        let package = v2::Package {
3402            name: "veh.cabin".to_string(),
3403            ..v2::Package::default()
3404        };
3405        let path = dir.path().join("cabin.ir.json");
3406        std::fs::write(&path, v2::to_json_pretty(&package).unwrap()).unwrap();
3407        assert_eq!(load_ir_json(&path).unwrap(), package);
3408    }
3409
3410    /// A missing file is an `Io` error and a file that is not IR v2 JSON is a
3411    /// `Parse` error, each with the message `ridl diff` prints, inner error
3412    /// included.
3413    #[test]
3414    fn a_missing_file_is_io_and_bad_json_is_parse() {
3415        let dir = tempfile::tempdir().unwrap();
3416
3417        let missing = dir.path().join("missing.ir.json");
3418        let io = std::fs::read_to_string(&missing).unwrap_err();
3419        let error = load_ir_json(&missing).unwrap_err();
3420        assert!(matches!(error, LoadError::Io(_)), "{error:?}");
3421        assert_eq!(
3422            error.to_string(),
3423            format!("cannot read the IR snapshot: {io}")
3424        );
3425
3426        // The leading newline puts the error on line 2, so a loader that
3427        // trimmed the text first would report a different position.
3428        let bad = dir.path().join("bad.ir.json");
3429        std::fs::write(&bad, "\n{").unwrap();
3430        let parse = v2::from_json("\n{").unwrap_err();
3431        let error = load_ir_json(&bad).unwrap_err();
3432        assert!(matches!(error, LoadError::Parse(_)), "{error:?}");
3433        assert_eq!(
3434            error.to_string(),
3435            format!("the IR snapshot is not valid IR v2 JSON: {parse}")
3436        );
3437    }
3438
3439    /// The loader reads through `from_json`: input nested past its cap draws
3440    /// the cap's own message, which a plain `serde_json` parse would not.
3441    #[test]
3442    fn input_past_the_nesting_cap_draws_from_json_s_refusal() {
3443        let dir = tempfile::tempdir().unwrap();
3444        let deep = format!(
3445            "{}{}",
3446            "[".repeat(MAX_JSON_NESTING + 1),
3447            "]".repeat(MAX_JSON_NESTING + 1)
3448        );
3449        let path = dir.path().join("deep.ir.json");
3450        std::fs::write(&path, &deep).unwrap();
3451        let refusal = v2::from_json(&deep).unwrap_err().to_string();
3452        assert!(
3453            refusal.contains("the ceiling this reader enforces"),
3454            "{refusal}"
3455        );
3456        let error = load_ir_json(&path).unwrap_err();
3457        assert!(matches!(error, LoadError::Parse(_)), "{error:?}");
3458        assert_eq!(
3459            error.to_string(),
3460            format!("the IR snapshot is not valid IR v2 JSON: {refusal}")
3461        );
3462    }
3463}