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.Model` message descriptor — the prototext entry
74    /// point of the lowered codegen model, from the same pool, because
75    /// `build.rs` compiles both schemas in one `protox` call.
76    pub(crate) fn codegen_model_descriptor() -> prost_reflect::MessageDescriptor {
77        descriptor("ridl.codegen.v1.Model")
78    }
79
80    /// Rebuilds a message as a `DynamicMessage` over its descriptor — the
81    /// step `prost-reflect` needs before rendering a text encoding.
82    /// Transcoding goes through the wire encoding, whose decoder enforces
83    /// prost's fixed recursion limit, so a package whose composite nesting
84    /// crosses that limit fails here — an input-dependent failure, not
85    /// schema drift (ADR-0014 decision 12).
86    fn transcode<M: prost::Message>(
87        descriptor: prost_reflect::MessageDescriptor,
88        message: &M,
89    ) -> Result<prost_reflect::DynamicMessage, prost::DecodeError> {
90        let mut dynamic = prost_reflect::DynamicMessage::new(descriptor);
91        dynamic.transcode_from(message)?;
92        Ok(dynamic)
93    }
94
95    /// Derives the synthesized transport identity of an inline `T | E`
96    /// result union (ADR-0008 decision 4): the enclosing interface name plus
97    /// the interaction ordinal plus the ordered arm references. The single
98    /// derivation every consumer — backends and the diff classifier — calls,
99    /// so the identity stays stable under compatible evolution.
100    pub fn fallible_transport_identity(
101        interface: &str,
102        ordinal: u32,
103        fallible: &FallibleType,
104    ) -> String {
105        format!(
106            "{interface}#{ordinal}:{ok}|{err}",
107            ok = fallible.ok,
108            err = fallible.err
109        )
110    }
111
112    /// The error [`to_json_pretty`] and [`to_text_format`] return. The
113    /// serialization surface is fallible on purpose (ADR-0014 decisions 12
114    /// and 14), and the two encodings now fail for different causes, so each
115    /// carries its own variant — its `Display` names the encoding, so a
116    /// build requesting several IR emits attributes each failure to its own
117    /// artifact.
118    #[derive(Debug)]
119    pub enum SerializeError {
120        /// Canonical protobuf JSON (ADR-0014 decision 14): the
121        /// pbjson-generated `Serialize` impl writes the typed message
122        /// directly — no transcode, so no message-level recursion limit —
123        /// and its one error path is an `i32` enum field holding a
124        /// discriminant outside the schema.
125        Json(serde_json::Error),
126        /// Prototext (ADR-0014 decision 12): the transcode into the dynamic
127        /// message goes through the wire encoding, whose decoder enforces
128        /// prost's fixed recursion limit, and legal source can nest
129        /// composites past it.
130        Text(prost::DecodeError),
131    }
132
133    impl std::fmt::Display for SerializeError {
134        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135            match self {
136                Self::Json(source) => write!(
137                    f,
138                    "cannot render the package as canonical protobuf JSON: {source}; the known \
139                     cause is an enum field holding a discriminant outside the schema"
140                ),
141                Self::Text(source) => write!(
142                    f,
143                    "cannot render the package as prototext: {source}; the known cause \
144                     is composite nesting deeper than the transcoding decoder's recursion limit"
145                ),
146            }
147        }
148    }
149
150    impl std::error::Error for SerializeError {
151        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
152            match self {
153                Self::Json(source) => Some(source),
154                Self::Text(source) => Some(source),
155            }
156        }
157    }
158
159    /// Renders a package as pretty-printed canonical protobuf JSON — the one
160    /// dialect every IR surface carries: the `--emit ir-json` artifact, the
161    /// baselines, and the goldens (ADR-0014 decision 1) — through the
162    /// pbjson-generated `Serialize` impl (decision 14), byte-identical to
163    /// what the retired reflection path rendered.
164    ///
165    /// A field holding its default is emitted rather than skipped (decision
166    /// 2, `emit_fields()` in `build.rs`); an unset proto3 `optional` field
167    /// is omitted entirely, never rendered as `null` (the answer to that
168    /// decision's open item). 64-bit fields render as strings, the canonical
169    /// mapping JavaScript consumers need (decision 8).
170    ///
171    /// Still fallible (ADR-0014 decision 14, amending decision 12), but the
172    /// error path changed rather than survived: the generated impl writes
173    /// the typed message directly, so the transcode's depth error is gone,
174    /// and the one error path it has is new — an `i32` enum field holding a
175    /// discriminant outside the schema, which the retired reflection path
176    /// serialized successfully as its bare number. The checker never
177    /// produces one, but the value is data, not schema, so the failure is
178    /// returned rather than panicked on.
179    pub fn to_json_pretty(package: &Package) -> Result<String, SerializeError> {
180        render_json(package)
181    }
182
183    /// Renders a lowered system (`system.proto`, rsdl reference §13) as
184    /// pretty-printed canonical protobuf JSON — the `<pkg.Name>.system.json`
185    /// artifact, under the rules of [`to_json_pretty`].
186    pub fn system_to_json_pretty(system: &System) -> Result<String, SerializeError> {
187        render_json(system)
188    }
189
190    /// The one JSON writer behind [`to_json_pretty`] and
191    /// [`system_to_json_pretty`]: the pbjson-generated `Serialize` impl of
192    /// the message, pretty-printed.
193    pub(crate) fn render_json<M: serde::Serialize>(message: &M) -> Result<String, SerializeError> {
194        let mut buf = Vec::new();
195        let mut serializer = serde_json::Serializer::pretty(&mut buf);
196        serde::Serialize::serialize(message, &mut serializer).map_err(SerializeError::Json)?;
197        Ok(String::from_utf8(buf).expect("serde_json emits UTF-8"))
198    }
199
200    /// The nesting ceiling `from_json` enforces, in JSON bracket levels.
201    ///
202    /// It cannot bind on IR this toolchain produces, and the bound is a
203    /// measurement rather than a guess. The parser refuses type nesting past
204    /// 128 levels (FORM-102, `MAX_TYPE_DEPTH` in `ridl-syntax`), and the
205    /// deepest package that limit admits emits JSON **516 brackets** deep —
206    /// so 1,000 leaves a factor of 1.9 over anything `ridlc` can write, and
207    /// the deepest nesting in the corpus is single digits. The figure this
208    /// comment carried until 2026-09-22, 262 brackets and a factor of 3.8,
209    /// was the array shape; the tuple shape costs four brackets per source
210    /// level rather than two and is the one that binds (the IR
211    /// specification, "The nesting bound").
212    ///
213    /// It exists for input this toolchain did not write: a hand-edited
214    /// baseline, or a snapshot from elsewhere. Past the stack ceiling the
215    /// failure mode is a stack-overflow abort, which no caller can catch, so
216    /// the cap turns an abort into a diagnostic (ADR-0014 decisions 12
217    /// and 14).
218    pub(crate) const MAX_JSON_NESTING: usize = 1_000;
219
220    /// The stack `from_json` parses on, in bytes. An explicit size makes the
221    /// depth that fits a constant of this crate rather than of the ambient
222    /// stack, which differs between debug and release builds and between
223    /// platforms — the same input parses everywhere or nowhere.
224    const JSON_PARSE_STACK: usize = 16 * 1024 * 1024;
225
226    /// The maximum bracket nesting of `text`: the largest number of `{` and
227    /// `[` open at once, with string literals skipped — a bracket inside a
228    /// string must not count, an escaped quote (`\"`) must not end the
229    /// string, and an escaped backslash (`\\`) must not disarm the real
230    /// closing quote after it. Runs before the parse in [`from_json`], so it
231    /// tolerates input that is not valid JSON; a stray closer never
232    /// underflows the running depth.
233    pub(crate) fn max_json_nesting(text: &str) -> usize {
234        let mut depth = 0usize;
235        let mut deepest = 0usize;
236        let mut in_string = false;
237        let mut escaped = false;
238        for byte in text.bytes() {
239            if in_string {
240                if escaped {
241                    escaped = false;
242                } else if byte == b'\\' {
243                    escaped = true;
244                } else if byte == b'"' {
245                    in_string = false;
246                }
247            } else {
248                match byte {
249                    b'"' => in_string = true,
250                    b'{' | b'[' => {
251                        depth += 1;
252                        deepest = deepest.max(depth);
253                    }
254                    b'}' | b']' => depth = depth.saturating_sub(1),
255                    _ => {}
256                }
257            }
258        }
259        deepest
260    }
261
262    /// Reads a package from canonical protobuf JSON — the inverse of
263    /// [`to_json_pretty`], through the pbjson-generated `Deserialize` impl
264    /// (ADR-0014 decision 14). Unknown fields are rejected (the generated
265    /// deserializer's default; `ignore_unknown_fields()` stays unset in
266    /// `build.rs`), so a snapshot written against a different schema fails
267    /// loudly rather than dropping fields silently.
268    ///
269    /// The generated impl recurses per JSON level, so `serde_json`'s own
270    /// recursion limit of 128 levels is disabled — it would bind far below
271    /// this crate's documented ceiling — and two guards replace it
272    /// (ADR-0014 decision 14):
273    ///
274    /// - input nesting is measured first and refused past
275    ///   `MAX_JSON_NESTING`, returning a diagnostic where unbounded
276    ///   recursion would eventually abort on a stack overflow no caller can
277    ///   catch;
278    /// - the parse runs on a thread of `JSON_PARSE_STACK` bytes, so the
279    ///   ceiling behaves identically across build profiles and platforms
280    ///   instead of tracking the ambient stack. On the wasm family there is
281    ///   no such thread — see the branch below — and the cap alone guards
282    ///   the parse.
283    pub fn from_json(text: &str) -> Result<Package, serde_json::Error> {
284        read_json(text)
285    }
286
287    /// Reads a lowered system from canonical protobuf JSON — the inverse of
288    /// [`system_to_json_pretty`], under the rules and guards of
289    /// [`from_json`].
290    pub fn system_from_json(text: &str) -> Result<System, serde_json::Error> {
291        read_json(text)
292    }
293
294    /// The one JSON reader behind [`from_json`] and [`system_from_json`]:
295    /// the nesting cap, then the parse on its own stack.
296    pub(crate) fn read_json<M>(text: &str) -> Result<M, serde_json::Error>
297    where
298        M: serde::de::DeserializeOwned + Send,
299    {
300        if max_json_nesting(text) > MAX_JSON_NESTING {
301            return Err(<serde_json::Error as serde::de::Error>::custom(format!(
302                "the input nests deeper than {MAX_JSON_NESTING} JSON levels, the ceiling this \
303                 reader enforces (ADR-0014 decision 14); real IR nests orders of magnitude \
304                 shallower"
305            )));
306        }
307        if cfg!(target_family = "wasm") {
308            // The wasm family has no spawnable threads: `spawn_scoped`
309            // returns `Err(Unsupported)` at run time on
310            // `wasm32-unknown-unknown`, the `just wasm-check` target, so a
311            // spawn here would turn every call into a panic. The parse runs
312            // in line instead, on the caller's stack. What this path loses
313            // is the deterministic stack — the ceiling is the ambient stack
314            // — and the `MAX_JSON_NESTING` cap above is the guard that
315            // matters: it is what turns an abort into an error.
316            parse_json(text)
317        } else {
318            std::thread::scope(|scope| {
319                let handle = std::thread::Builder::new()
320                    .stack_size(JSON_PARSE_STACK)
321                    .spawn_scoped(scope, || parse_json(text))
322                    .expect("the JSON parse thread spawns");
323                match handle.join() {
324                    Ok(result) => result,
325                    Err(payload) => std::panic::resume_unwind(payload),
326                }
327            })
328        }
329    }
330
331    /// The parse both branches of [`from_json`] share; only the stack that
332    /// carries it differs. `serde_json`'s own recursion limit is disabled
333    /// here, so the caller must have applied the `MAX_JSON_NESTING` cap
334    /// first.
335    fn parse_json<M: serde::de::DeserializeOwned>(text: &str) -> Result<M, serde_json::Error> {
336        let mut deserializer = serde_json::Deserializer::from_str(text);
337        deserializer.disable_recursion_limit();
338        let message: M = serde::Deserialize::deserialize(&mut deserializer)?;
339        deserializer.end()?;
340        Ok(message)
341    }
342
343    /// Renders a package in the protobuf text format — the inspection
344    /// encoding (ADR-0014 decision 9): emittable, but not a recommended
345    /// interchange form. Rendered `pretty`, with a field holding its default
346    /// emitted rather than skipped (decision 2) and message fields printed
347    /// in schema index order, so the output ordering is deterministic rather
348    /// than incidental (decision 8).
349    ///
350    /// Fallible on purpose (ADR-0014 decision 12): the transcode into the
351    /// dynamic message goes through the wire encoding, and a package whose
352    /// composite nesting crosses prost's recursion limit fails there. That
353    /// input is legal source, so the failure is returned rather than
354    /// panicked on. JSON lost this failure mode when it moved off the
355    /// transcode (decision 14); prototext keeps it.
356    pub fn to_text_format(package: &Package) -> Result<String, SerializeError> {
357        render_text_for(package_descriptor(), package)
358    }
359
360    /// Renders a lowered system in the protobuf text format — the
361    /// `<pkg.Name>.system.txtpb` artifact, under the rules of
362    /// [`to_text_format`].
363    pub fn system_to_text_format(system: &System) -> Result<String, SerializeError> {
364        render_text_for(system_descriptor(), system)
365    }
366
367    /// The one prototext writer behind [`to_text_format`] and
368    /// [`system_to_text_format`].
369    pub(crate) fn render_text_for<M: prost::Message>(
370        descriptor: prost_reflect::MessageDescriptor,
371        message: &M,
372    ) -> Result<String, SerializeError> {
373        let dynamic = transcode(descriptor, message).map_err(SerializeError::Text)?;
374        Ok(dynamic.to_text_format_with_options(
375            &prost_reflect::text_format::FormatOptions::new()
376                .pretty(true)
377                .skip_default_fields(false)
378                .print_message_fields_in_index_order(true),
379        ))
380    }
381
382    /// The error [`from_text_format`] returns: the input does not parse as
383    /// prototext, or the parsed message does not transcode into the
384    /// generated types. The transcode failure is the read direction of the
385    /// recursion-limit failure mode (ADR-0014 decision 12) — input-dependent,
386    /// so it is mapped into this return rather than expected on.
387    #[cfg(test)]
388    #[derive(Debug)]
389    pub(crate) enum TextFormatError {
390        /// The input is not valid prototext for the `Package` schema.
391        Parse(prost_reflect::text_format::ParseError),
392        /// The parsed message cannot be rebuilt as a typed `Package`.
393        Transcode(prost::DecodeError),
394    }
395
396    #[cfg(test)]
397    impl std::fmt::Display for TextFormatError {
398        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
399            match self {
400                Self::Parse(source) => {
401                    write!(f, "cannot parse the text as an IR package: {source}")
402                }
403                Self::Transcode(source) => write!(
404                    f,
405                    "cannot rebuild the parsed prototext as a package: {source}; the known cause \
406                     is composite nesting deeper than the transcoding decoder's recursion limit"
407                ),
408            }
409        }
410    }
411
412    #[cfg(test)]
413    impl std::error::Error for TextFormatError {
414        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
415            match self {
416                Self::Parse(source) => Some(source),
417                Self::Transcode(source) => Some(source),
418            }
419        }
420    }
421
422    /// Reads a package from the protobuf text format — the inverse of
423    /// [`to_text_format`], kept because without it the prototext emit has no
424    /// round-trip test, and a write path with no read path is untested by
425    /// construction (ADR-0014 decision 7).
426    ///
427    /// **Deliberately not public.** `prost-reflect`'s text parser recurses per
428    /// message level with frames large enough that a debug build exhausts a
429    /// 2 MiB stack at roughly 45 levels of nesting — *below* prost's recursion
430    /// limit of 100, so on that path the error return below is unreachable and
431    /// the process aborts instead. A stack overflow cannot be caught, so the
432    /// hazard is contained by reach rather than handled: nothing in the
433    /// toolchain reads prototext, `ridl diff` and `ridl check --baseline`
434    /// refuse the encoding by name (ADR-0014 decision 5), and this function is
435    /// compiled only for this crate's tests. The tests that exercise it run on an
436    /// explicitly sized stack (see `with_sized_stack`). Making it public again
437    /// means giving it a stack strategy first — driftsys/ridl#218.
438    ///
439    /// A package whose nesting crosses prost's limit *before* the stack runs
440    /// out fails in the transcode out of the dynamic message; that failure is
441    /// mapped into the error return, not expected on (ADR-0014 decision 12).
442    #[cfg(test)]
443    pub(crate) fn from_text_format(text: &str) -> Result<Package, TextFormatError> {
444        parse_text(package_descriptor(), text)
445    }
446
447    /// Reads a lowered system from the protobuf text format — the inverse of
448    /// [`system_to_text_format`], test-only for the reason
449    /// [`from_text_format`] states.
450    #[cfg(test)]
451    pub(crate) fn system_from_text_format(text: &str) -> Result<System, TextFormatError> {
452        parse_text(system_descriptor(), text)
453    }
454
455    #[cfg(test)]
456    fn parse_text<M: prost::Message + Default>(
457        descriptor: prost_reflect::MessageDescriptor,
458        text: &str,
459    ) -> Result<M, TextFormatError> {
460        let dynamic = prost_reflect::DynamicMessage::parse_text_format(descriptor, text)
461            .map_err(TextFormatError::Parse)?;
462        dynamic.transcode_to().map_err(TextFormatError::Transcode)
463    }
464
465    /// Encodes a package in the protobuf binary wire format — a derived
466    /// encoding since ADR-0014 decision 9's 2026-09-22 amendment, whose
467    /// reader stops 100 message levels below the root where the canonical
468    /// encoding has no such bound (the IR specification, "The derived
469    /// encodings"). Binary needs no descriptors: prost's generated encoding
470    /// is schema-faithful by construction.
471    pub fn to_binary(package: &Package) -> Vec<u8> {
472        prost::Message::encode_to_vec(package)
473    }
474
475    /// Decodes a package from the protobuf binary wire format — the inverse
476    /// of [`to_binary`].
477    pub fn from_binary(bytes: &[u8]) -> Result<Package, prost::DecodeError> {
478        prost::Message::decode(bytes)
479    }
480
481    /// Encodes a lowered system in the protobuf binary wire format — the
482    /// `<pkg.Name>.system.binpb` artifact (ADR-0014 decision 9).
483    pub fn system_to_binary(system: &System) -> Vec<u8> {
484        prost::Message::encode_to_vec(system)
485    }
486
487    /// Decodes a lowered system from the protobuf binary wire format — the
488    /// inverse of [`system_to_binary`].
489    pub fn system_from_binary(bytes: &[u8]) -> Result<System, prost::DecodeError> {
490        prost::Message::decode(bytes)
491    }
492
493    /// `pkg.Name` — how a system, a component or a distribution is referred
494    /// to across the system layer (`system.proto`); a name with no package,
495    /// the implicit component of a lone service (rsdl §6), is its own
496    /// qualified name.
497    fn qualified(package: &str, name: &str) -> String {
498        if package.is_empty() {
499            name.to_string()
500        } else {
501            format!("{package}.{name}")
502        }
503    }
504
505    impl System {
506        /// The system's qualified name, `pkg.Name` — the base name of its
507        /// artifacts.
508        pub fn qualified_name(&self) -> String {
509            qualified(&self.package, &self.name)
510        }
511    }
512
513    impl Component {
514        /// The name every reference to this component uses: `pkg.Name` for a
515        /// declared component, the service's dotted name for an implicit one.
516        pub fn qualified_name(&self) -> String {
517            qualified(&self.package, &self.name)
518        }
519    }
520
521    impl Distribution {
522        /// The name `Distribution.depends_on` and `Installation.distribution`
523        /// use.
524        pub fn qualified_name(&self) -> String {
525            qualified(&self.package, &self.name)
526        }
527    }
528
529    /// One interface shape of a package (ridl §14.0): a declared `interface`,
530    /// or the inline shape of a `service` (§14.5).
531    ///
532    /// **[`Package::interfaces`] is not the complete set.** A `service`
533    /// declared with an inline body carries a full [`Interface`] inside its
534    /// shape list (the single `INLINE` slot, ADR-0015 decision 14), which
535    /// lives outside `interfaces`; a consumer that walks `interfaces` alone
536    /// silently misses it. Six defects of exactly that shape were found
537    /// independently across E2 — observer-stub lowering, both backends'
538    /// transport identity, `ridl test`'s report, the Rust backend's collision
539    /// check, and the desk check's span index.
540    /// [`Package::shapes`] is the one walk that sees both, the way
541    /// [`fallible_transport_identity`] is the one transport-identity
542    /// derivation.
543    ///
544    /// This view is deliberately not a bare `&Interface`, because two of an
545    /// inline shape's own fields are empty by construction and reading them
546    /// is what produced two of those six defects:
547    ///
548    /// - [`Interface::name`] is `""` for an inline shape, so [`Self::name`]
549    ///   carries the **identity** name instead — the interface's own name, or
550    ///   the owning service's dotted global name. That is the name the diff
551    ///   paths, the observer-stub scoping, and both backends' identity fields
552    ///   already use.
553    /// - [`Interface::visibility`] is `VISIBILITY_UNSPECIFIED` for an inline
554    ///   shape; the owning [`Service`] carries the authoritative one, which
555    ///   [`Self::visibility`] reads.
556    ///
557    /// The generated *type* name is not derived here on purpose: mangling is
558    /// language-specific and stays with each backend.
559    #[derive(Debug, Clone, Copy, PartialEq)]
560    pub struct InterfaceShape<'a> {
561        /// The name this shape is known by outside the package: an
562        /// `interface` declaration's own name, or the owning service's dotted
563        /// global name. Never `Interface::name` for an inline shape.
564        pub name: &'a str,
565        /// The interface body — its interactions and its doc envelope.
566        pub interface: &'a Interface,
567        /// The owning service, for an inline shape; `None` for a declared
568        /// `interface`.
569        pub service: Option<&'a Service>,
570    }
571
572    impl InterfaceShape<'_> {
573        /// The authoritative visibility of this shape: the owning service's
574        /// for an inline shape (an inline shape's own field is
575        /// `VISIBILITY_UNSPECIFIED` by construction), the interface's own
576        /// otherwise.
577        pub fn visibility(&self) -> i32 {
578            match self.service {
579                Some(service) => service.visibility,
580                None => self.interface.visibility,
581            }
582        }
583
584        /// `true` when this shape is the inline body of a `service`.
585        pub fn is_inline(&self) -> bool {
586            self.service.is_some()
587        }
588    }
589
590    impl Package {
591        /// Every interface shape the package carries — the declared
592        /// interfaces and the inline shapes of its services. See
593        /// [`InterfaceShape`] for why walking [`Package::interfaces`] alone is
594        /// a defect.
595        ///
596        /// The order is the one every consumer already walked: the declared
597        /// interfaces in source order, then the services in source order. A
598        /// shape-list entry that names an interface yields nothing — its
599        /// target is a declared interface and is already in the sequence, so
600        /// yielding it again would visit one shape twice; a service composing
601        /// several interfaces (ADR-0015 decision 12) therefore contributes
602        /// nothing at all. A tombstone slot names no shape. Only the `INLINE`
603        /// slot of an inline-form service carries an interface of its own,
604        /// and that is what this walk yields.
605        pub fn shapes(&self) -> impl Iterator<Item = InterfaceShape<'_>> {
606            let named = self.interfaces.iter().map(|interface| InterfaceShape {
607                name: &interface.name,
608                interface,
609                service: None,
610            });
611            let inline = self.services.iter().flat_map(|service| {
612                service
613                    .shapes
614                    .iter()
615                    .filter_map(move |slot| match slot.kind.as_ref()? {
616                        service_shape::Kind::Inline(interface) => Some(InterfaceShape {
617                            name: &service.name,
618                            interface,
619                            service: Some(service),
620                        }),
621                        service_shape::Kind::InterfaceRef(_) => None,
622                    })
623            });
624            named.chain(inline)
625        }
626    }
627
628    /// Every package named by a type reference in `package`.
629    ///
630    /// A resolved type-reference string is the fully qualified `pkg.Name` for
631    /// a cross-package reference and the bare `Name` for a same-package one,
632    /// never an import alias — the canonical form stated in
633    /// `proto/ridl/ir/v2/ir.proto`, which also enumerates the fields carrying
634    /// one. **That enumeration and this walk are edited together.** A
635    /// reference-bearing field added there and not read here makes the package
636    /// it names invisible to every caller asking what a package depends on.
637    ///
638    /// Every `oneof` below is matched exhaustively with no wildcard arm, so a
639    /// variant added later fails to compile here rather than going unread.
640    pub fn referenced_packages(package: &Package) -> std::collections::BTreeSet<String> {
641        let mut found = std::collections::BTreeSet::new();
642        for decl in &package.decls {
643            walk_decl(decl, &mut found);
644        }
645        for interface in &package.interfaces {
646            for interaction in &interface.interactions {
647                walk_decl(interaction, &mut found);
648            }
649        }
650        for service in &package.services {
651            for slot in &service.shapes {
652                match &slot.kind {
653                    Some(service_shape::Kind::InterfaceRef(reference)) => {
654                        qualifier(reference, &mut found);
655                    }
656                    Some(service_shape::Kind::Inline(interface)) => {
657                        for interaction in &interface.interactions {
658                            walk_decl(interaction, &mut found);
659                        }
660                    }
661                    None => {}
662                }
663            }
664        }
665        found
666    }
667
668    /// Records the package qualifier of a dotted reference. A bare reference
669    /// is same-package and contributes nothing.
670    fn qualifier(reference: &str, found: &mut std::collections::BTreeSet<String>) {
671        if let Some((package, _)) = reference.rsplit_once('.') {
672            found.insert(package.to_string());
673        }
674    }
675
676    /// Records every reference in one declaration — a package-level one or an
677    /// interaction inside an interface, which share the `Decl` envelope.
678    fn walk_decl(decl: &Decl, found: &mut std::collections::BTreeSet<String>) {
679        match &decl.kind {
680            Some(decl::Kind::TypeDef(type_def)) => walk_type_def(type_def, found),
681            Some(decl::Kind::ConstDef(const_def)) => {
682                if let Some(reference) = &const_def.type_ref {
683                    qualifier(reference, found);
684                }
685            }
686            Some(decl::Kind::StructDef(struct_def)) => {
687                for member in &struct_def.members {
688                    match &member.member {
689                        Some(struct_member::Member::Field(field)) => {
690                            if let Some(field_type) = &field.r#type {
691                                walk_field_type(field_type, found);
692                            }
693                        }
694                        // A tombstone occupies an ordinal and names no type.
695                        Some(struct_member::Member::Reserved(_)) | None => {}
696                    }
697                }
698            }
699            // An enum's variants are integers; it names no type.
700            Some(decl::Kind::EnumDef(_)) => {}
701            Some(decl::Kind::EnumSetDef(enum_set)) => {
702                if let Some(reference) = &enum_set.backing_enum {
703                    qualifier(reference, found);
704                }
705            }
706            Some(decl::Kind::UnionDef(union_def)) => {
707                for arm in &union_def.arms {
708                    qualifier(&arm.type_ref, found);
709                }
710            }
711            Some(decl::Kind::SignalDef(signal)) => qualifier(&signal.payload, found),
712            Some(decl::Kind::EventDef(event)) => qualifier(&event.payload, found),
713            Some(decl::Kind::CommandDef(command)) => {
714                for param in &command.params {
715                    if let Some(field_type) = &param.r#type {
716                        walk_field_type(field_type, found);
717                    }
718                }
719            }
720            Some(decl::Kind::QueryDef(query)) => {
721                for param in &query.params {
722                    if let Some(field_type) = &param.r#type {
723                        walk_field_type(field_type, found);
724                    }
725                }
726                if let Some(return_type) = &query.return_type {
727                    walk_return_type(return_type, found);
728                }
729            }
730            Some(decl::Kind::FixedDef(fixed)) => {
731                if let Some(field_type) = &fixed.payload {
732                    walk_field_type(field_type, found);
733                }
734            }
735            // A tombstone occupies an ordinal and names no type.
736            Some(decl::Kind::ReservedSlot(_)) | None => {}
737        }
738    }
739
740    /// The recursive half: a reference is reachable at arbitrary depth through
741    /// tuples, arrays, maps, inline scalars, and streams.
742    fn walk_field_type(field_type: &FieldType, found: &mut std::collections::BTreeSet<String>) {
743        match &field_type.kind {
744            Some(field_type::Kind::Named(reference)) => qualifier(reference, found),
745            // A primitive names no package.
746            Some(field_type::Kind::Primitive(_)) => {}
747            Some(field_type::Kind::InlineScalar(type_def)) => walk_type_def(type_def, found),
748            Some(field_type::Kind::Tuple(tuple)) => {
749                for field in &tuple.fields {
750                    if let Some(inner) = &field.r#type {
751                        walk_field_type(inner, found);
752                    }
753                }
754            }
755            Some(field_type::Kind::Array(array)) => {
756                if let Some(element) = &array.element {
757                    walk_field_type(element, found);
758                }
759            }
760            Some(field_type::Kind::Map(map)) => {
761                if let Some(key) = &map.key {
762                    walk_field_type(key, found);
763                }
764                if let Some(value) = &map.value {
765                    walk_field_type(value, found);
766                }
767            }
768            Some(field_type::Kind::Stream(stream)) => match &stream.element {
769                Some(stream_type::Element::Named(reference)) => qualifier(reference, found),
770                // STRING or BYTES only; names no package.
771                Some(stream_type::Element::Primitive(_)) | None => {}
772            },
773            None => {}
774        }
775    }
776
777    /// A `TypeDef`'s only reference is the constant a `match` bound names.
778    fn walk_type_def(type_def: &TypeDef, found: &mut std::collections::BTreeSet<String>) {
779        if let Some(constraint) = &type_def.constraint
780            && let Some(reference) = &constraint.pattern_const
781        {
782            qualifier(reference, found);
783        }
784    }
785
786    fn walk_return_type(return_type: &ReturnType, found: &mut std::collections::BTreeSet<String>) {
787        match &return_type.kind {
788            Some(return_type::Kind::Value(field_type)) => walk_field_type(field_type, found),
789            Some(return_type::Kind::Fallible(fallible)) => {
790                qualifier(&fallible.ok, found);
791                qualifier(&fallible.err, found);
792            }
793            None => {}
794        }
795    }
796
797    /// Whether a constraint leaves a generated constructor nothing to check.
798    ///
799    /// True when no bound, step or pattern is present. A step is an enforced
800    /// quantization constraint, including when its origin defaults to zero.
801    ///
802    /// A pattern given by name counts as a pattern: `pattern_const` is read as
803    /// well as `pattern`, because a pattern constant that did not resolve leaves
804    /// `pattern` absent while the type still carries a match constraint.
805    /// `ridl-sem` treats the two fields the same way in its derived-init rule
806    /// (`init.rs`).
807    ///
808    /// Because the checker materializes the typl §4.4 default `[0..256]` into
809    /// `len_min`/`len_max`, every string and bytes type is non-vacuous. In
810    /// practice this reduces to `boolean`, and `integer`/`float` with no declared
811    /// range.
812    pub fn constraint_is_vacuous(constraint: Option<&Constraint>) -> bool {
813        let Some(c) = constraint else { return true };
814        c.min.is_none()
815            && c.max.is_none()
816            && c.step.is_none()
817            && c.len_min.is_none()
818            && c.len_max.is_none()
819            && c.pattern.is_none()
820            && c.pattern_const.is_none()
821    }
822}
823
824pub mod codegen;
825pub mod name;
826pub mod projection;
827pub mod zero;
828
829#[cfg(test)]
830mod v2_round_trip {
831    use crate::v2;
832
833    /// Wraps an interaction kind in the shared `Decl` envelope. Visibility
834    /// and `is_error` stay unset on interactions (ridl §14.1); the ordinal is
835    /// the 1-based declaration order across all interactions of the
836    /// enclosing interface (ridl §11).
837    fn interaction(name: &str, ordinal: u32, kind: v2::decl::Kind) -> v2::Decl {
838        v2::Decl {
839            name: name.to_string(),
840            visibility: v2::Visibility::Unspecified as i32,
841            is_error: false,
842            doc: String::new(),
843            labels: Vec::new(),
844            deprecated: None,
845            ordinal,
846            kind: Some(kind),
847        }
848    }
849
850    fn named_type(name: &str) -> v2::FieldType {
851        v2::FieldType {
852            optional: false,
853            kind: Some(v2::field_type::Kind::Named(name.to_string())),
854        }
855    }
856
857    fn stream_of(element: v2::stream_type::Element) -> v2::FieldType {
858        v2::FieldType {
859            optional: false,
860            kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
861                element: Some(element),
862            })),
863        }
864    }
865
866    /// A representative ridl package: one interface holding all five
867    /// interaction kinds plus a reserved tombstone (ordinals 1–6, the
868    /// tombstone counted, ridl §11), a strict-periodic and a defaulted
869    /// range timing, a fallible query, and two services — a named
870    /// reference and an inline shape holding a stream query.
871    fn fixture() -> v2::Package {
872        // signal speed : Speed @10ms — strict periodic stores the period
873        // in both bounds (ADR-0008 decision 12).
874        let speed = v2::SignalDef {
875            payload: "Speed".to_string(),
876            declared_init: None,
877            init: Some(v2::InitValue {
878                derivable: true,
879                value: Some("0.0".to_string()),
880            }),
881            timing: Some(v2::Timing {
882                mode: v2::TimingMode::StrictPeriodic as i32,
883                min_us: Some("10000".to_string()),
884                max_us: Some("10000".to_string()),
885                default_applied: false,
886            }),
887        };
888
889        // event doorOpened : DoorEvent — untimed in source, so the
890        // configured default range is resolved at compile time (ridl §9.1).
891        let door_opened = v2::EventDef {
892            payload: "DoorEvent".to_string(),
893            timing: Some(v2::Timing {
894                mode: v2::TimingMode::Range as i32,
895                min_us: Some("20000".to_string()),
896                max_us: Some("500000".to_string()),
897                default_applied: true,
898            }),
899        };
900
901        // command setTarget(target : Speed) [ require target >= speed ]
902        let set_target = v2::CommandDef {
903            params: vec![v2::Param {
904                name: "target".to_string(),
905                r#type: Some(named_type("Speed")),
906            }],
907            contracts: vec![v2::Contract {
908                kind: v2::ContractKind::Require as i32,
909                source: "target >= speed".to_string(),
910                signal_refs: vec!["speed".to_string()],
911                param_refs: vec!["target".to_string()],
912                uses_result: false,
913                observer_id: "VehicleStatus.setTarget.require[0]".to_string(),
914            }],
915            timing: None,
916        };
917
918        // query fetchFaults(page : PageSpec) : FaultPage | DiagError
919        //   [ ensure result.count <= page.limit ]
920        let fetch_faults = v2::QueryDef {
921            params: vec![v2::Param {
922                name: "page".to_string(),
923                r#type: Some(named_type("PageSpec")),
924            }],
925            return_type: Some(v2::ReturnType {
926                kind: Some(v2::return_type::Kind::Fallible(v2::FallibleType {
927                    ok: "FaultPage".to_string(),
928                    err: "DiagError".to_string(),
929                })),
930            }),
931            contracts: vec![v2::Contract {
932                kind: v2::ContractKind::Ensure as i32,
933                source: "result.count <= page.limit".to_string(),
934                signal_refs: Vec::new(),
935                param_refs: vec!["page".to_string()],
936                uses_result: true,
937                observer_id: "VehicleStatus.fetchFaults.ensure[0]".to_string(),
938            }],
939            timing: None,
940        };
941
942        // fixed vin : Vin
943        let vin = v2::FixedDef {
944            payload: Some(named_type("Vin")),
945        };
946
947        let vehicle_status = v2::Interface {
948            name: "VehicleStatus".to_string(),
949            visibility: v2::Visibility::Public as i32,
950            doc: "Vehicle status contract".to_string(),
951            labels: Vec::new(),
952            deprecated: None,
953            interactions: vec![
954                interaction("speed", 1, v2::decl::Kind::SignalDef(speed)),
955                interaction("doorOpened", 2, v2::decl::Kind::EventDef(door_opened)),
956                // reserved legacyMode — the tombstone keeps ordinal 3
957                // occupied in the one interaction sequence (ridl §11).
958                v2::Decl {
959                    ordinal: 3,
960                    kind: Some(v2::decl::Kind::ReservedSlot(v2::Reserved {
961                        ordinal: 3,
962                        name: Some("legacyMode".to_string()),
963                        value: None,
964                    })),
965                    ..interaction("", 3, v2::decl::Kind::ReservedSlot(v2::Reserved::default()))
966                },
967                interaction("setTarget", 4, v2::decl::Kind::CommandDef(set_target)),
968                interaction("fetchFaults", 5, v2::decl::Kind::QueryDef(fetch_faults)),
969                interaction("vin", 6, v2::decl::Kind::FixedDef(vin)),
970            ],
971            number: 0,
972            provisional: false,
973        };
974
975        // query tailLogs(pattern : <string>) : <LogLine> — a stream param
976        // and a stream return (ridl §12), inside the inline service shape.
977        let tail_logs = v2::QueryDef {
978            params: vec![v2::Param {
979                name: "pattern".to_string(),
980                r#type: Some(stream_of(v2::stream_type::Element::Primitive(
981                    v2::PrimitiveType::String as i32,
982                ))),
983            }],
984            return_type: Some(v2::ReturnType {
985                kind: Some(v2::return_type::Kind::Value(stream_of(
986                    v2::stream_type::Element::Named("LogLine".to_string()),
987                ))),
988            }),
989            contracts: Vec::new(),
990            timing: None,
991        };
992
993        // service veh.adas.status : VehicleStatus — one named reference in
994        // the service's set (ADR-0015 decision 12).
995        let status_service = v2::Service {
996            name: "veh.adas.status".to_string(),
997            visibility: v2::Visibility::Public as i32,
998            doc: String::new(),
999            labels: Vec::new(),
1000            deprecated: None,
1001            shapes: vec![v2::ServiceShape {
1002                kind: Some(v2::service_shape::Kind::InterfaceRef(
1003                    "VehicleStatus".to_string(),
1004                )),
1005            }],
1006        };
1007        // service veh.adas.logs { … } — the inline shape as the one entry,
1008        // Interface.name == "" (ridl §14.5).
1009        let logs_service = v2::Service {
1010            name: "veh.adas.logs".to_string(),
1011            visibility: v2::Visibility::Public as i32,
1012            doc: String::new(),
1013            labels: Vec::new(),
1014            deprecated: None,
1015            shapes: vec![v2::ServiceShape {
1016                kind: Some(v2::service_shape::Kind::Inline(v2::Interface {
1017                    name: String::new(),
1018                    visibility: v2::Visibility::Unspecified as i32,
1019                    doc: String::new(),
1020                    labels: Vec::new(),
1021                    deprecated: None,
1022                    interactions: vec![interaction(
1023                        "tailLogs",
1024                        1,
1025                        v2::decl::Kind::QueryDef(tail_logs),
1026                    )],
1027                    number: 0,
1028                    provisional: false,
1029                })),
1030            }],
1031        };
1032
1033        v2::Package {
1034            name: "veh.adas".to_string(),
1035            // One typl declaration proves the verbatim v1 surface rides
1036            // along unchanged in v2; package-level declarations carry
1037            // ordinal 0.
1038            decls: vec![v2::Decl {
1039                name: "Speed".to_string(),
1040                visibility: v2::Visibility::Public as i32,
1041                is_error: false,
1042                doc: String::new(),
1043                labels: Vec::new(),
1044                deprecated: None,
1045                ordinal: 0,
1046                kind: Some(v2::decl::Kind::TypeDef(v2::TypeDef {
1047                    backing: Some(v2::Backing {
1048                        kind: Some(v2::backing::Kind::Unit("km/h".to_string())),
1049                    }),
1050                    constraint: None,
1051                    declared_init: None,
1052                    init: None,
1053                    width: Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F32 as i32)),
1054                })),
1055            }],
1056            interfaces: vec![vehicle_status],
1057            services: vec![status_service, logs_service],
1058            retired: Vec::new(),
1059        }
1060    }
1061
1062    /// The typl vocabulary surface the interaction fixture does not reach:
1063    /// the boxed `inlineScalar` oneof member, genuine 64-bit integer fields
1064    /// (array and map bounds, length bounds, `Reserved.value`,
1065    /// `EnumValue.value`), a tuple, a map, a union, an enum set, a constant,
1066    /// and a set `deprecated`. A second fixture, so each stays readable; the
1067    /// same round-trip tests drive both.
1068    fn vocabulary_fixture() -> v2::Package {
1069        fn decl(name: &str, kind: v2::decl::Kind) -> v2::Decl {
1070            v2::Decl {
1071                name: name.to_string(),
1072                visibility: v2::Visibility::Public as i32,
1073                is_error: false,
1074                doc: String::new(),
1075                labels: Vec::new(),
1076                deprecated: None,
1077                ordinal: 0,
1078                kind: Some(kind),
1079            }
1080        }
1081
1082        fn field(name: &str, ordinal: u32, field_type: v2::FieldType) -> v2::Field {
1083            v2::Field {
1084                name: name.to_string(),
1085                ordinal,
1086                r#type: Some(field_type),
1087                declared_init: None,
1088                init: None,
1089                doc: String::new(),
1090                labels: Vec::new(),
1091                deprecated: None,
1092            }
1093        }
1094
1095        // const MAX_RETRY : integer = 24
1096        let max_retry = v2::ConstDef {
1097            type_ref: Some("integer".to_string()),
1098            value: "24".to_string(),
1099            regex: None,
1100        };
1101
1102        // enum Gear { PARK = 1  DRIVE = 2  reserved 7 } — the tombstone
1103        // retires the integer value, a genuine int64 field.
1104        let gear = v2::EnumDef {
1105            values: vec![
1106                v2::EnumValue {
1107                    name: "PARK".to_string(),
1108                    value: 1,
1109                    doc: String::new(),
1110                },
1111                v2::EnumValue {
1112                    name: "DRIVE".to_string(),
1113                    value: 2,
1114                    doc: String::new(),
1115                },
1116            ],
1117            reserved: vec![v2::Reserved {
1118                ordinal: 0,
1119                name: None,
1120                value: Some(7),
1121            }],
1122        };
1123
1124        // enumset Warnings { LOW_FUEL = 0  ICE_RISK = 33 } — the standalone
1125        // form; bit 33 forces the u64 width and is a genuine int64 value.
1126        let warnings = v2::EnumSetDef {
1127            backing_enum: None,
1128            bits: vec![
1129                v2::EnumValue {
1130                    name: "LOW_FUEL".to_string(),
1131                    value: 0,
1132                    doc: String::new(),
1133                },
1134                v2::EnumValue {
1135                    name: "ICE_RISK".to_string(),
1136                    value: 33,
1137                    doc: String::new(),
1138                },
1139            ],
1140            width: v2::IntWidth::U64 as i32,
1141        };
1142
1143        // type PlateText : string [1..86] — character length bounds, two
1144        // genuine uint64 fields behind proto3 `optional`.
1145        let plate_text = v2::TypeDef {
1146            backing: Some(v2::Backing {
1147                kind: Some(v2::backing::Kind::Primitive(
1148                    v2::PrimitiveType::String as i32,
1149                )),
1150            }),
1151            constraint: Some(v2::Constraint {
1152                min: None,
1153                max: None,
1154                step: None,
1155                len_min: Some(1),
1156                len_max: Some(86),
1157                pattern: None,
1158                pattern_const: None,
1159            }),
1160            declared_init: None,
1161            init: None,
1162            width: None,
1163        };
1164
1165        // union Sample { speed : Speed  gear : Gear }
1166        let sample = v2::UnionDef {
1167            arms: vec![
1168                v2::UnionArm {
1169                    name: "speed".to_string(),
1170                    ordinal: 1,
1171                    type_ref: "Speed".to_string(),
1172                    doc: String::new(),
1173                },
1174                v2::UnionArm {
1175                    name: "gear".to_string(),
1176                    ordinal: 2,
1177                    type_ref: "Gear".to_string(),
1178                    doc: String::new(),
1179                },
1180            ],
1181            is_result: false,
1182            reserved: Vec::new(),
1183        };
1184
1185        // retries : integer [0..24] = 3 — the boxed `inlineScalar` oneof
1186        // member: the committed regression guard for ADR-0014 Open item 2,
1187        // which established that the Rust-side `Box` is invisible to the
1188        // reflection path. The enclosing field carries the init; the nested
1189        // TypeDef's stays unset.
1190        let retries = v2::Field {
1191            declared_init: Some("3".to_string()),
1192            init: Some(v2::InitValue {
1193                derivable: true,
1194                value: Some("3".to_string()),
1195            }),
1196            ..field(
1197                "retries",
1198                1,
1199                v2::FieldType {
1200                    optional: false,
1201                    kind: Some(v2::field_type::Kind::InlineScalar(Box::new(v2::TypeDef {
1202                        backing: Some(v2::Backing {
1203                            kind: Some(v2::backing::Kind::Primitive(
1204                                v2::PrimitiveType::Integer as i32,
1205                            )),
1206                        }),
1207                        constraint: Some(v2::Constraint {
1208                            min: Some("0".to_string()),
1209                            max: Some("24".to_string()),
1210                            step: None,
1211                            len_min: None,
1212                            len_max: None,
1213                            pattern: None,
1214                            pattern_const: None,
1215                        }),
1216                        declared_init: None,
1217                        init: None,
1218                        width: Some(v2::type_def::Width::IntWidth(v2::IntWidth::U8 as i32)),
1219                    }))),
1220                },
1221            )
1222        };
1223
1224        // position : (x : Speed, y : Speed) — an anonymous named-field
1225        // composite (typl §11).
1226        let position = field(
1227            "position",
1228            2,
1229            v2::FieldType {
1230                optional: false,
1231                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
1232                    fields: vec![
1233                        v2::TupleField {
1234                            name: "x".to_string(),
1235                            r#type: Some(named_type("Speed")),
1236                        },
1237                        v2::TupleField {
1238                            name: "y".to_string(),
1239                            r#type: Some(named_type("Speed")),
1240                        },
1241                    ],
1242                })),
1243            },
1244        );
1245
1246        // gears : [Gear; 1..4096] — array bounds are genuine uint64 fields.
1247        let gears = field(
1248            "gears",
1249            3,
1250            v2::FieldType {
1251                optional: false,
1252                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1253                    element: Some(Box::new(named_type("Gear"))),
1254                    min: 1,
1255                    max: 4096,
1256                }))),
1257            },
1258        );
1259
1260        // plates : { PlateText -> Gear } [0..53] — map bounds are genuine
1261        // uint64 fields. The field is deprecated, covering the optional
1262        // string on the Field envelope.
1263        let plates = v2::Field {
1264            deprecated: Some("superseded by gears".to_string()),
1265            ..field(
1266                "plates",
1267                4,
1268                v2::FieldType {
1269                    optional: false,
1270                    kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
1271                        key: Some(Box::new(named_type("PlateText"))),
1272                        value: Some(Box::new(named_type("Gear"))),
1273                        min: 0,
1274                        max: 53,
1275                    }))),
1276                },
1277            )
1278        };
1279
1280        let snapshot = v2::StructDef {
1281            members: [retries, position, gears, plates]
1282                .into_iter()
1283                .map(|field| v2::StructMember {
1284                    member: Some(v2::struct_member::Member::Field(field)),
1285                })
1286                .collect(),
1287            fixed_layout: false,
1288        };
1289
1290        v2::Package {
1291            name: "veh.vocab".to_string(),
1292            decls: vec![
1293                decl("MAX_RETRY", v2::decl::Kind::ConstDef(max_retry)),
1294                decl("Gear", v2::decl::Kind::EnumDef(gear)),
1295                decl("Warnings", v2::decl::Kind::EnumSetDef(warnings)),
1296                decl("PlateText", v2::decl::Kind::TypeDef(plate_text)),
1297                // The union is deprecated — the optional string on the Decl
1298                // envelope.
1299                v2::Decl {
1300                    deprecated: Some("use Snapshot".to_string()),
1301                    ..decl("Sample", v2::decl::Kind::UnionDef(sample))
1302                },
1303                decl("Snapshot", v2::decl::Kind::StructDef(snapshot)),
1304            ],
1305            interfaces: Vec::new(),
1306            services: Vec::new(),
1307            retired: Vec::new(),
1308        }
1309    }
1310
1311    #[test]
1312    fn protobuf_round_trip_preserves_package() {
1313        let package = fixture();
1314
1315        let buf = v2::to_binary(&package);
1316        let decoded = v2::from_binary(buf.as_slice()).expect("decode must succeed");
1317
1318        assert_eq!(package, decoded);
1319
1320        // The vocabulary fixture rides the same round trip.
1321        let vocabulary = vocabulary_fixture();
1322        let decoded_vocabulary =
1323            v2::from_binary(v2::to_binary(&vocabulary).as_slice()).expect("decode must succeed");
1324        assert_eq!(vocabulary, decoded_vocabulary);
1325
1326        let interface = &decoded.interfaces[0];
1327        let ordinals: Vec<u32> = interface.interactions.iter().map(|d| d.ordinal).collect();
1328        assert_eq!(
1329            ordinals,
1330            [1, 2, 3, 4, 5, 6],
1331            "one ordinal sequence, tombstone counted (ridl §11)"
1332        );
1333        let Some(v2::decl::Kind::ReservedSlot(tombstone)) = &interface.interactions[2].kind else {
1334            panic!("ordinal 3 must decode as a reserved tombstone");
1335        };
1336        assert_eq!(tombstone.name.as_deref(), Some("legacyMode"));
1337        let Some(v2::service_shape::Kind::Inline(inline)) = decoded.services[1]
1338            .shapes
1339            .first()
1340            .and_then(|slot| slot.kind.as_ref())
1341        else {
1342            panic!("veh.adas.logs must decode as an inline shape");
1343        };
1344        assert_eq!(inline.name, "", "an inline shape carries no name");
1345        let references: Vec<&str> = decoded.services[0]
1346            .shapes
1347            .iter()
1348            .filter_map(|slot| match &slot.kind {
1349                Some(v2::service_shape::Kind::InterfaceRef(reference)) => Some(reference.as_str()),
1350                _ => None,
1351            })
1352            .collect();
1353        assert_eq!(
1354            references,
1355            ["VehicleStatus"],
1356            "a service's set carries its references and nothing else"
1357        );
1358    }
1359
1360    #[test]
1361    fn json_round_trip_preserves_package() {
1362        for package in [fixture(), vocabulary_fixture()] {
1363            let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
1364            let decoded = v2::from_json(&json).expect("json deserialization must succeed");
1365
1366            assert_eq!(package, decoded);
1367        }
1368    }
1369
1370    /// The interface identity fields the lock design §9 adds — `number` and
1371    /// `provisional` on every `Interface`, an inline shape included, and the
1372    /// package's `retired` list — ride all three encodings unchanged, and the
1373    /// JSON writes them under their canonical names even when they hold their
1374    /// defaults (ADR-0014 decision 2), so a reader can tell `number` 0 from an
1375    /// absent field only by the schema, never by the text.
1376    #[test]
1377    fn number_provisional_and_retired_round_trip_through_json_text_and_binary() {
1378        let mut package = fixture();
1379        package.interfaces[0].number = 4;
1380        package.interfaces[0].provisional = true;
1381        let Some(v2::service_shape::Kind::Inline(inline)) =
1382            package.services[1].shapes[0].kind.as_mut()
1383        else {
1384            panic!("veh.adas.logs holds an inline shape in slot 1");
1385        };
1386        inline.number = 5;
1387        package.retired = vec![
1388            v2::RetiredInterface {
1389                name: "LaneAssist".to_string(),
1390                number: 2,
1391            },
1392            v2::RetiredInterface {
1393                name: "service:veh.hvac.cabin".to_string(),
1394                number: 3,
1395            },
1396        ];
1397
1398        let json = v2::to_json_pretty(&package).expect("the package serializes as IR JSON");
1399        assert_eq!(v2::from_json(&json).expect("the JSON parses back"), package);
1400        let text = v2::to_text_format(&package).expect("the package serializes as prototext");
1401        assert_eq!(
1402            v2::from_text_format(&text).expect("the prototext parses back"),
1403            package
1404        );
1405        assert_eq!(
1406            v2::from_binary(v2::to_binary(&package).as_slice()).expect("the binary decodes"),
1407            package
1408        );
1409
1410        for needle in [
1411            r#""number": 4"#,
1412            r#""provisional": true"#,
1413            r#""number": 5"#,
1414            r#""name": "LaneAssist""#,
1415            r#""name": "service:veh.hvac.cabin""#,
1416        ] {
1417            assert!(
1418                json.contains(needle),
1419                "the JSON must carry {needle}, got: {json}"
1420            );
1421        }
1422
1423        // A default holds its place in the text (decision 2): an interface
1424        // that was never numbered writes `0` and `false`, and a package with
1425        // nothing retired writes an empty list.
1426        let unnumbered = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
1427        for needle in [
1428            r#""number": 0"#,
1429            r#""provisional": false"#,
1430            r#""retired": []"#,
1431        ] {
1432            assert!(
1433                unnumbered.contains(needle),
1434                "a default field must still be written, expected {needle} in: {unnumbered}"
1435            );
1436        }
1437    }
1438
1439    /// A baseline published before the lock existed carries no `number`, no
1440    /// `provisional` and no `retired` field. It still loads — a missing field
1441    /// reads as its default, which is the `number` 0 the lock design §7 names
1442    /// as the one transition case — while an unknown field is still rejected
1443    /// (`json_parse_rejects_an_unknown_field`).
1444    #[test]
1445    fn a_snapshot_lacking_the_number_fields_still_loads() {
1446        let package = v2::from_json(
1447            r#"{"name": "veh.x", "interfaces": [{"name": "LaneKeeping"}], "services": [{"name": "veh.x.s", "shapes": [{"inline": {"name": ""}}]}]}"#,
1448        )
1449        .expect("a pre-lock snapshot loads");
1450
1451        assert_eq!(package.interfaces[0].number, 0);
1452        assert!(!package.interfaces[0].provisional);
1453        let Some(v2::service_shape::Kind::Inline(inline)) =
1454            package.services[0].shapes[0].kind.as_ref()
1455        else {
1456            panic!("the service holds an inline shape");
1457        };
1458        assert_eq!(inline.number, 0);
1459        assert!(!inline.provisional);
1460        assert_eq!(package.retired, Vec::new());
1461    }
1462
1463    /// The prototext read path (ADR-0014 decision 7): both fixtures survive
1464    /// `to_text_format` then `from_text_format` unchanged. With the binary
1465    /// and JSON round trips above, this is what proves all three encodings
1466    /// carry the same IR.
1467    #[test]
1468    fn text_format_round_trip_preserves_package() {
1469        for package in [fixture(), vocabulary_fixture()] {
1470            let text = v2::to_text_format(&package).expect("the fixture serializes as prototext");
1471            let decoded = v2::from_text_format(&text).expect("prototext parsing must succeed");
1472
1473            assert_eq!(package, decoded);
1474        }
1475    }
1476
1477    /// The prototext options ADR-0014 decision 8 fixes — `pretty`,
1478    /// `skip_default_fields(false)`, `print_message_fields_in_index_order`.
1479    /// Any option set round-trips, which is why the round-trip test above
1480    /// cannot guard them.
1481    ///
1482    /// The first two are asserted through a visible consequence. The third is
1483    /// **not guarded here and cannot be on this schema**: every message in
1484    /// `ir.proto` declares its fields in ascending field-number order, and
1485    /// field-number order is also `prost-reflect`'s default, so index order
1486    /// and default order coincide everywhere and dropping the option would
1487    /// change no output. It is set because the schema's ordering is a
1488    /// property of the schema rather than a guarantee, and a message whose
1489    /// declaration order departs from its numbering would otherwise reorder
1490    /// every artifact it appears in.
1491    #[test]
1492    fn text_format_is_pretty_with_defaults_in_index_order() {
1493        let text = v2::to_text_format(&fixture()).expect("the fixture serializes as prototext");
1494
1495        // pretty: nested messages are indented, one field per line.
1496        assert!(
1497            text.contains("\n  "),
1498            "pretty printing must indent nested fields, got: {text}"
1499        );
1500        // skip_default_fields(false): a field holding its default is present
1501        // (decision 2 — `ordinal: 0` is read, not inferred from absence).
1502        assert!(
1503            text.contains("is_error: false"),
1504            "a field holding its default must be emitted, got: {text}"
1505        );
1506        // print_message_fields_in_index_order: `name` is field 1 of
1507        // `Package`, so it opens the output.
1508        assert!(
1509            text.starts_with("name:"),
1510            "fields must print in schema index order, got: {text}"
1511        );
1512    }
1513
1514    /// Parses emitted JSON the way ADR-0014 decision 11's conformance test
1515    /// requires: unknown fields rejected, trailing input rejected. Since
1516    /// decision 14 the strict parser is the pbjson-generated `Deserialize`
1517    /// impl, whose default already rejects unknown fields
1518    /// (`ignore_unknown_fields()` stays unset in `build.rs`), so the
1519    /// strictness needs no option to opt into.
1520    fn strict_parse(json: &str) -> v2::Package {
1521        let mut deserializer = serde_json::Deserializer::from_str(json);
1522        let package = <v2::Package as serde::Deserialize>::deserialize(&mut deserializer)
1523            .expect("a strict conformant parser must accept the emitted JSON");
1524        deserializer.end().expect("no trailing input");
1525        package
1526    }
1527
1528    /// The conformance claim of ADR-0014 decision 11: a conformant protobuf
1529    /// JSON parser configured to reject unknown fields accepts the emitted
1530    /// JSON. Re-reading tests that claim itself; asserting on the rendered
1531    /// text would only restate the serializer's behaviour back to itself.
1532    #[test]
1533    fn emitted_json_survives_a_strict_conformant_parse() {
1534        for package in [fixture(), vocabulary_fixture()] {
1535            let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
1536            assert_eq!(package, strict_parse(&json));
1537        }
1538    }
1539
1540    #[test]
1541    fn json_renders_timing_bounds_and_fallible_arms_exactly() {
1542        let json = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
1543
1544        // Exactness is visible: timing bounds are exact-decimal microsecond
1545        // strings, never floating-point numbers (ADR-0008 decision 12) —
1546        // under the canonical lowerCamelCase field name (ADR-0014 decision 1).
1547        assert!(
1548            json.contains(r#""minUs": "10000""#),
1549            "the timing bound must be a JSON string, got: {json}"
1550        );
1551        // Both arms of the inline T | E return are visible by name.
1552        assert!(
1553            json.contains(r#""ok": "FaultPage""#),
1554            "the ok arm must render, got: {json}"
1555        );
1556        assert!(
1557            json.contains(r#""err": "DiagError""#),
1558            "the err arm must render, got: {json}"
1559        );
1560    }
1561
1562    /// ADR-0014 decision 8's stringification, tested on genuine 64-bit
1563    /// fields. The timing assertion above proves nothing about it —
1564    /// `Timing.min_us` is `optional string` in the schema — so the claim
1565    /// needs fields whose wire type actually is `uint64` or `int64`.
1566    #[test]
1567    fn json_renders_64_bit_integer_fields_as_strings() {
1568        let json = v2::to_json_pretty(&vocabulary_fixture())
1569            .expect("the vocabulary fixture serializes as IR JSON");
1570
1571        // uint64: the array's upper bound.
1572        assert!(
1573            json.contains(r#""max": "4096""#),
1574            "an array bound must be a JSON string, got: {json}"
1575        );
1576        // uint64 behind proto3 `optional`: the character length bound.
1577        assert!(
1578            json.contains(r#""lenMax": "86""#),
1579            "a length bound must be a JSON string, got: {json}"
1580        );
1581        // int64: the retired enum value and the enum-set bit position.
1582        assert!(
1583            json.contains(r#""value": "7""#),
1584            "a retired enum value must be a JSON string, got: {json}"
1585        );
1586        assert!(
1587            json.contains(r#""value": "33""#),
1588            "an enum-set bit position must be a JSON string, got: {json}"
1589        );
1590    }
1591
1592    #[test]
1593    fn fallible_transport_identity_follows_the_derivation_rule() {
1594        // The ADR-0008 decision 4 rule: interface + interaction ordinal +
1595        // both arm references, in that order.
1596        let fallible = v2::FallibleType {
1597            ok: "FaultPage".to_string(),
1598            err: "DiagError".to_string(),
1599        };
1600        assert_eq!(
1601            v2::fallible_transport_identity("VehicleStatus", 9, &fallible),
1602            "VehicleStatus#9:FaultPage|DiagError"
1603        );
1604
1605        // Derived from the fixture: the fallible query sits at ordinal 5.
1606        let package = fixture();
1607        let interface = &package.interfaces[0];
1608        let query_decl = &interface.interactions[4];
1609        let Some(v2::decl::Kind::QueryDef(query)) = &query_decl.kind else {
1610            panic!("ordinal 5 must be the fallible query");
1611        };
1612        let Some(v2::return_type::Kind::Fallible(arms)) = &query.return_type.as_ref().unwrap().kind
1613        else {
1614            panic!("fetchFaults must return a fallible type");
1615        };
1616        assert_eq!(
1617            v2::fallible_transport_identity(&interface.name, query_decl.ordinal, arms),
1618            "VehicleStatus#5:FaultPage|DiagError"
1619        );
1620    }
1621
1622    /// `Package::shapes` yields the named interfaces first, then the inline
1623    /// shapes of the services — and each shape carries the name it is known by
1624    /// OUTSIDE the package. The fixture's inline shape has `Interface.name ==
1625    /// ""` by construction, so a walk that yielded the interface bare would
1626    /// hand every consumer the empty string; two of the six E2 defects were
1627    /// exactly that.
1628    #[test]
1629    fn shapes_walks_named_interfaces_and_inline_service_shapes() {
1630        let package = fixture();
1631        let walk: Vec<(&str, bool, usize)> = package
1632            .shapes()
1633            .map(|shape| {
1634                (
1635                    shape.name,
1636                    shape.is_inline(),
1637                    shape.interface.interactions.len(),
1638                )
1639            })
1640            .collect();
1641        assert_eq!(
1642            walk,
1643            [("VehicleStatus", false, 6), ("veh.adas.logs", true, 1)],
1644            "the named interface, then the inline shape under the service's \
1645             dotted name",
1646        );
1647
1648        // The fixture's third shape-bearing declaration is `service
1649        // veh.adas.status : VehicleStatus`, which names an interface already in
1650        // the walk. Yielding it too would visit `VehicleStatus` twice.
1651        assert_eq!(package.services.len(), 2, "one reference form, one inline");
1652        assert!(
1653            !package
1654                .shapes()
1655                .any(|shape| shape.name == "veh.adas.status"),
1656            "a service naming an interface contributes no shape of its own",
1657        );
1658    }
1659
1660    /// The owning service is carried because `Service.visibility` is the
1661    /// authoritative one: an inline shape's own field is
1662    /// `VISIBILITY_UNSPECIFIED` by construction, which is not "internal" and
1663    /// not "public".
1664    #[test]
1665    fn shape_visibility_reads_the_owning_service_for_an_inline_shape() {
1666        let package = fixture();
1667        let shapes: Vec<v2::InterfaceShape<'_>> = package.shapes().collect();
1668
1669        let named = shapes[0];
1670        assert!(named.service.is_none());
1671        assert_eq!(named.visibility(), v2::Visibility::Public as i32);
1672        assert_eq!(named.visibility(), named.interface.visibility);
1673
1674        let inline = shapes[1];
1675        assert_eq!(
1676            inline.interface.visibility,
1677            v2::Visibility::Unspecified as i32,
1678            "the trap: an inline shape's own visibility field is unset",
1679        );
1680        assert_eq!(
1681            inline.service.expect("an inline shape has an owner").name,
1682            "veh.adas.logs",
1683        );
1684        assert_eq!(
1685            inline.visibility(),
1686            v2::Visibility::Public as i32,
1687            "the accessor reads the owning service's, never the unset field",
1688        );
1689    }
1690
1691    /// A package with no service at all still walks its interfaces, and a
1692    /// package with neither yields nothing — the emptiness both backends test
1693    /// for before emitting any interaction vocabulary.
1694    #[test]
1695    fn shapes_is_empty_only_when_the_package_declares_no_shape() {
1696        let mut package = fixture();
1697        package.services.clear();
1698        assert_eq!(package.shapes().count(), 1);
1699
1700        package.interfaces.clear();
1701        assert_eq!(package.shapes().count(), 0);
1702    }
1703
1704    /// A dotted reference contributes its qualifier; a bare one contributes
1705    /// nothing. Every recursive path through `walk_field_type` — array
1706    /// element, tuple field, map key, map value, stream element — carries a
1707    /// distinct qualifier, so no path's absence can hide behind another
1708    /// path's presence: deleting any one arm's body changes the expected set
1709    /// this test compares against, rather than leaving it unchanged.
1710    #[test]
1711    fn referenced_packages_finds_qualifiers_at_depth() {
1712        fn named(reference: &str) -> v2::FieldType {
1713            v2::FieldType {
1714                kind: Some(v2::field_type::Kind::Named(reference.to_string())),
1715                ..Default::default()
1716            }
1717        }
1718
1719        fn fixed(payload: v2::FieldType) -> v2::decl::Kind {
1720            v2::decl::Kind::FixedDef(v2::FixedDef {
1721                payload: Some(payload),
1722            })
1723        }
1724
1725        let package = v2::Package {
1726            name: "veh.cluster".to_string(),
1727            decls: vec![
1728                v2::Decl {
1729                    name: "Local".to_string(),
1730                    kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
1731                        payload: "Speed".to_string(),
1732                        ..Default::default()
1733                    })),
1734                    ..Default::default()
1735                },
1736                v2::Decl {
1737                    name: "Stamped".to_string(),
1738                    kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
1739                        payload: "ridl.std.Timestamp".to_string(),
1740                        ..Default::default()
1741                    })),
1742                    ..Default::default()
1743                },
1744                v2::Decl {
1745                    name: "ArrLabels".to_string(),
1746                    kind: Some(fixed(v2::FieldType {
1747                        kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1748                            element: Some(Box::new(named("veh.arr.Label"))),
1749                            min: 0,
1750                            max: 32,
1751                        }))),
1752                        ..Default::default()
1753                    })),
1754                    ..Default::default()
1755                },
1756                v2::Decl {
1757                    name: "TupThing".to_string(),
1758                    kind: Some(fixed(v2::FieldType {
1759                        kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
1760                            fields: vec![v2::TupleField {
1761                                name: "x".to_string(),
1762                                r#type: Some(named("veh.tup.X")),
1763                            }],
1764                        })),
1765                        ..Default::default()
1766                    })),
1767                    ..Default::default()
1768                },
1769                v2::Decl {
1770                    name: "MapThing".to_string(),
1771                    kind: Some(fixed(v2::FieldType {
1772                        kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
1773                            key: Some(Box::new(named("veh.key.X"))),
1774                            value: Some(Box::new(named("veh.val.X"))),
1775                            min: 0,
1776                            max: 8,
1777                        }))),
1778                        ..Default::default()
1779                    })),
1780                    ..Default::default()
1781                },
1782                v2::Decl {
1783                    name: "StreamThing".to_string(),
1784                    kind: Some(fixed(v2::FieldType {
1785                        kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
1786                            element: Some(v2::stream_type::Element::Named(
1787                                "veh.strm.X".to_string(),
1788                            )),
1789                        })),
1790                        ..Default::default()
1791                    })),
1792                    ..Default::default()
1793                },
1794            ],
1795            ..Default::default()
1796        };
1797
1798        let found = v2::referenced_packages(&package);
1799        let expected: std::collections::BTreeSet<String> = [
1800            "ridl.std", "veh.arr", "veh.tup", "veh.key", "veh.val", "veh.strm",
1801        ]
1802        .into_iter()
1803        .map(str::to_string)
1804        .collect();
1805        assert_eq!(
1806            found, expected,
1807            "each recursive path must contribute its own distinct qualifier"
1808        );
1809        assert!(
1810            !found.contains("Speed") && !found.contains("veh.cluster"),
1811            "a bare reference contributes no package: {found:?}",
1812        );
1813    }
1814
1815    /// An empty package references nothing — the negative case the emit rule in
1816    /// `ridlc` depends on.
1817    #[test]
1818    fn referenced_packages_is_empty_without_references() {
1819        let package = v2::Package {
1820            name: "veh.solo".to_string(),
1821            ..Default::default()
1822        };
1823        assert!(v2::referenced_packages(&package).is_empty());
1824    }
1825
1826    /// Below prost's recursion limit at two message levels per nesting level
1827    /// — the depth ADR-0014 decision 12 measured as round-tripping correctly.
1828    /// Since decision 14 these two constants bound the prototext transcode
1829    /// alone: JSON no longer transcodes and carries its own read-side
1830    /// ceiling, tested separately below.
1831    const NESTING_BELOW_LIMIT: usize = 45;
1832    /// Past the limit today. The tests assert the outcome — an error, never a
1833    /// panic — not the exact threshold, so a prost release that moves the
1834    /// limit moves these constants, not the assertions.
1835    const NESTING_PAST_LIMIT: usize = 60;
1836
1837    /// One declaration whose payload nests `depth` levels of inline arrays —
1838    /// each level costs two message levels on the wire (`FieldType` plus
1839    /// `ArrayType`), the arithmetic ADR-0014 decision 12 records against
1840    /// prost's recursion limit.
1841    fn nested_package(depth: usize) -> v2::Package {
1842        let mut payload = v2::FieldType {
1843            optional: false,
1844            kind: Some(v2::field_type::Kind::Primitive(
1845                v2::PrimitiveType::Integer as i32,
1846            )),
1847        };
1848        for _ in 0..depth {
1849            payload = v2::FieldType {
1850                optional: false,
1851                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1852                    element: Some(Box::new(payload)),
1853                    min: 1,
1854                    max: 1,
1855                }))),
1856            };
1857        }
1858        v2::Package {
1859            name: "veh.deep".to_string(),
1860            decls: vec![v2::Decl {
1861                name: "deep".to_string(),
1862                kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
1863                    payload: Some(payload),
1864                })),
1865                ..Default::default()
1866            }],
1867            ..Default::default()
1868        }
1869    }
1870
1871    /// One package whose nesting sits exactly `levels` message levels below
1872    /// the `Package` root — the unit the derived binary encoding's bound is
1873    /// stated in (the IR specification, "The derived encodings").
1874    ///
1875    /// The chain under a `FixedDef` costs three levels before any nesting
1876    /// (`Decl`, `FixedDef`, the outermost `FieldType`) and two per array level
1877    /// (`ArrayType`, `FieldType`), so an array-only chain reaches the odd
1878    /// depths alone. One tuple level costs three (`FieldType`, `TupleType`,
1879    /// `TupleField`, then the `FieldType` the next level counts), which is what
1880    /// reaches the even depths. Both shapes are what the front end lowers, so
1881    /// neither is a construction the schema would not otherwise see.
1882    fn package_at_message_depth(levels: usize) -> v2::Package {
1883        assert!(levels >= 3, "the chain costs three levels before nesting");
1884        let (arrays, tuple) = if levels % 2 == 1 {
1885            ((levels - 3) / 2, false)
1886        } else {
1887            assert!(levels >= 6, "one tuple level costs three");
1888            ((levels - 6) / 2, true)
1889        };
1890
1891        let mut payload = v2::FieldType {
1892            optional: false,
1893            kind: Some(v2::field_type::Kind::Primitive(
1894                v2::PrimitiveType::Integer as i32,
1895            )),
1896        };
1897        for _ in 0..arrays {
1898            payload = v2::FieldType {
1899                optional: false,
1900                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1901                    element: Some(Box::new(payload)),
1902                    min: 1,
1903                    max: 1,
1904                }))),
1905            };
1906        }
1907        if tuple {
1908            payload = v2::FieldType {
1909                optional: false,
1910                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
1911                    fields: vec![v2::TupleField {
1912                        name: "f0".to_string(),
1913                        r#type: Some(payload),
1914                    }],
1915                })),
1916            };
1917        }
1918        v2::Package {
1919            name: "veh.deep".to_string(),
1920            decls: vec![v2::Decl {
1921                name: "deep".to_string(),
1922                kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
1923                    payload: Some(payload),
1924                })),
1925                ..Default::default()
1926            }],
1927            ..Default::default()
1928        }
1929    }
1930
1931    /// The nesting of JSON objects in a canonical artifact, which in the
1932    /// protobuf JSON mapping is the nesting of messages: every message is an
1933    /// object, a repeated field is an array of them, and the schema declares no
1934    /// `map<>` field. The root `Package` object is included, so a caller
1935    /// counting levels *below* the root subtracts one. Brackets inside a string
1936    /// literal do not count.
1937    fn message_nesting(json: &str) -> usize {
1938        let (mut depth, mut max) = (0usize, 0usize);
1939        let (mut in_string, mut escaped) = (false, false);
1940        for byte in json.bytes() {
1941            if in_string {
1942                if escaped {
1943                    escaped = false;
1944                } else if byte == b'\\' {
1945                    escaped = true;
1946                } else if byte == b'"' {
1947                    in_string = false;
1948                }
1949                continue;
1950            }
1951            match byte {
1952                b'"' => in_string = true,
1953                b'{' => {
1954                    depth += 1;
1955                    max = max.max(depth);
1956                }
1957                b'}' => depth = depth.saturating_sub(1),
1958                _ => {}
1959            }
1960        }
1961        max
1962    }
1963
1964    /// [`package_at_message_depth`] builds what it claims, on both parities.
1965    /// Without this the two bound tests below would pin a depth nobody
1966    /// measured.
1967    #[test]
1968    fn package_at_message_depth_builds_the_depth_it_names() {
1969        with_sized_stack(|| {
1970            for levels in [3, 6, 7, 99, 100, 101] {
1971                let json = v2::to_json_pretty(&package_at_message_depth(levels))
1972                    .expect("the writer is unrestricted at these depths");
1973                assert_eq!(
1974                    message_nesting(&json) - 1,
1975                    levels,
1976                    "the chain must nest {levels} message levels below the root"
1977                );
1978            }
1979        });
1980    }
1981
1982    /// The derived binary encoding's bound, stated by the IR specification and
1983    /// pinned here: 100 message levels below the root round-trip.
1984    ///
1985    /// `to_binary` writes any depth; it is `from_binary` that stops, at prost's
1986    /// `RECURSION_LIMIT` of 100, decremented once per nested message on decode
1987    /// and not consulted on encode. The test asserts the outcome, not prost's
1988    /// constant: a prost release that moves the limit moves these two tests and
1989    /// the specification's paragraph together.
1990    #[test]
1991    fn binary_round_trip_at_100_message_levels_succeeds() {
1992        let package = package_at_message_depth(100);
1993        let bytes = v2::to_binary(&package);
1994        let decoded = v2::from_binary(&bytes).expect("100 message levels decode");
1995        assert_eq!(package, decoded);
1996    }
1997
1998    /// One level past that bound the binary reader refuses — an error, never a
1999    /// panic — while the canonical encoding carries the same package. This is
2000    /// the asymmetry the specification states as the reason binary is derived
2001    /// rather than canonical (driftsys/ridl#231).
2002    #[test]
2003    fn binary_decode_at_101_message_levels_returns_an_error() {
2004        let package = package_at_message_depth(101);
2005        let bytes = v2::to_binary(&package);
2006        let error = v2::from_binary(&bytes).expect_err("101 message levels must fail, not panic");
2007        assert!(
2008            error.to_string().contains("recursion limit reached"),
2009            "the error must name the limit, got: {error}"
2010        );
2011
2012        let json = v2::to_json_pretty(&package).expect("the canonical encoding has no such bound");
2013        assert_eq!(
2014            package,
2015            v2::from_json(&json).expect("the canonical encoding round-trips the same package")
2016        );
2017    }
2018
2019    /// The write side after ADR-0014 decision 14: the pbjson-generated
2020    /// writer recurses the typed message directly — no transcode, so no
2021    /// message-level recursion limit — and 400 levels of array nesting,
2022    /// roughly eight times the ceiling decision 12 recorded, serialize and
2023    /// round-trip. Run on an explicitly sized stack: the writer recurses on
2024    /// the caller's stack, and debug-build frames at this depth overflow the
2025    /// default test-thread stack (the reader sizes its own thread inside
2026    /// `from_json`).
2027    #[test]
2028    fn json_round_trip_at_400_nested_levels_succeeds() {
2029        with_sized_stack(|| {
2030            let package = nested_package(400);
2031            let json = v2::to_json_pretty(&package).expect("the writer has no message-level limit");
2032            let decoded = v2::from_json(&json).expect("the reader parses within its ceiling");
2033            assert_eq!(package, decoded);
2034        });
2035    }
2036
2037    /// The one error path on the JSON write side (ADR-0014 decision 14),
2038    /// and it is new with the generated impl, not a survivor of the
2039    /// transcode's: an `i32` enum field holding a discriminant outside the
2040    /// schema — data, not depth — which the retired reflection path
2041    /// serialized successfully as its bare number. The checker never
2042    /// produces one, so there is no CLI route to this failure; it is pinned
2043    /// here at the crate surface.
2044    #[test]
2045    fn json_serialization_of_an_out_of_schema_discriminant_returns_an_error() {
2046        let mut package = fixture();
2047        package.decls[0].visibility = 999;
2048        let err = v2::to_json_pretty(&package)
2049            .expect_err("an out-of-schema discriminant must fail, not panic");
2050        let message = err.to_string();
2051        assert!(
2052            message.contains("canonical protobuf JSON"),
2053            "the error must name the encoding that failed, got: {message}"
2054        );
2055        assert!(
2056            message.contains("discriminant outside the schema"),
2057            "the error must name the known cause, got: {message}"
2058        );
2059    }
2060
2061    /// The strictness ADR-0014 decision 11 relies on is the generated
2062    /// deserializer's default: `ignore_unknown_fields()` is the opt-out and
2063    /// stays unset, so a field the schema does not declare is an error,
2064    /// never silently dropped.
2065    #[test]
2066    fn json_parse_rejects_an_unknown_field() {
2067        let error = v2::from_json(r#"{"name": "veh.deep", "notAField": 1}"#)
2068            .expect_err("an unknown field must be rejected");
2069        assert!(
2070            error.to_string().contains("unknown field"),
2071            "the error must name the defect, got: {error}"
2072        );
2073    }
2074
2075    /// A reader narrowing ADR-0014 decision 14 records: the proto3 JSON
2076    /// mapping expects parsers to accept numeric enum values, and the
2077    /// generated deserializer does — within the schema's range. A
2078    /// discriminant outside it (`"visibility": 77`) is rejected, where the
2079    /// retired reflection reader accepted it — and the retired *writer*
2080    /// emitted exactly such a number for an out-of-schema discriminant.
2081    /// Pinned so the narrowing stays a decision rather than an accident: a
2082    /// future mechanism change must confront this test.
2083    #[test]
2084    fn json_parse_rejects_an_out_of_range_numeric_enum_value() {
2085        let with_visibility =
2086            |value: &str| format!(r#"{{"name": "veh.x", "decls": [{{"visibility": {value}}}]}}"#);
2087        v2::from_json(&with_visibility("1"))
2088            .expect("an in-range numeric enum value parses, as the mapping expects");
2089        let error = v2::from_json(&with_visibility("77"))
2090            .expect_err("an out-of-range numeric enum value must be rejected");
2091        assert!(
2092            error.to_string().contains("invalid value: integer `77`"),
2093            "the error must name the value, got: {error}"
2094        );
2095    }
2096
2097    /// A reader narrowing ADR-0014 decision 14 records: the mapping accepts
2098    /// float and exponent notation for integer fields (`"min": 1.0`), and
2099    /// the retired reflection reader did; the generated deserializer
2100    /// rejects both. Pinned for the same reason as the numeric-enum case
2101    /// above.
2102    #[test]
2103    fn json_parse_rejects_a_float_form_integer() {
2104        for spelling in ["1.0", "1e0"] {
2105            let error = v2::from_json(&format!(
2106                r#"{{"name": "veh.x", "decls": [{{"fixedDef": {{"payload": {{"array": {{"min": {spelling}}}}}}}}}]}}"#,
2107            ))
2108            .expect_err("a float-form integer must be rejected");
2109            assert!(
2110                error.to_string().contains("did not match any variant"),
2111                "the integer field's deserializer must be the one refusing `{spelling}`, \
2112                 got: {error}"
2113            );
2114        }
2115    }
2116
2117    /// A reader narrowing ADR-0014 decision 14 records: `null` for a
2118    /// repeated field (`"decls": null`), which the retired reflection
2119    /// reader read as empty, is rejected. `null` for an optional scalar or
2120    /// message field is still accepted — parity with the retired reader,
2121    /// asserted alongside so the narrowing's edge is pinned from both
2122    /// sides.
2123    #[test]
2124    fn json_parse_rejects_null_for_a_repeated_field() {
2125        let error = v2::from_json(r#"{"name": "veh.x", "decls": null}"#)
2126            .expect_err("null for a repeated field must be rejected");
2127        assert!(
2128            error.to_string().contains("invalid type: null"),
2129            "the error must name the null, got: {error}"
2130        );
2131        v2::from_json(r#"{"name": "veh.x", "decls": [{"deprecated": null}]}"#)
2132            .expect("null for an optional scalar field still parses");
2133    }
2134
2135    /// A reader narrowing ADR-0014 decision 14 records: a duplicate JSON
2136    /// key, which the retired reflection reader resolved last-wins, is
2137    /// rejected.
2138    #[test]
2139    fn json_parse_rejects_a_duplicate_key() {
2140        let error = v2::from_json(r#"{"name": "a", "name": "b"}"#)
2141            .expect_err("a duplicate key must be rejected");
2142        assert!(
2143            error.to_string().contains("duplicate field `name`"),
2144            "the error must name the duplicated field, got: {error}"
2145        );
2146    }
2147
2148    /// The read-side ceiling (ADR-0014 decision 14): nesting past 1,000
2149    /// bracket levels returns an error before the parse begins — a
2150    /// diagnostic, where unbounded recursion would eventually abort on a
2151    /// stack overflow no caller can catch. The input is real writer output:
2152    /// past the ceiling the asymmetry is deliberate — the writer is
2153    /// unrestricted, the reader is not.
2154    #[test]
2155    fn json_parse_past_the_nesting_ceiling_returns_an_error() {
2156        with_sized_stack(|| {
2157            let json = v2::to_json_pretty(&nested_package(500))
2158                .expect("the writer is unrestricted at this depth");
2159            let error = v2::from_json(&json).expect_err("the reader must refuse past its ceiling");
2160            assert!(
2161                error.to_string().contains("1000 JSON levels"),
2162                "the error must name the ceiling, got: {error}"
2163            );
2164        });
2165    }
2166
2167    /// The ceiling is exact: 1,000 open brackets pass the scan and reach the
2168    /// parser — which then rejects the input as not a package — and 1,001 do
2169    /// not. The scan runs before the parse, so the over-ceiling probe needs
2170    /// no valid JSON behind its brackets.
2171    #[test]
2172    fn json_nesting_ceiling_binds_exactly_at_1000() {
2173        let at = v2::from_json(&"[".repeat(1_000)).expect_err("an array is not a package");
2174        assert!(
2175            !at.to_string().contains("JSON levels"),
2176            "at the ceiling the parser, not the scan, must be the one refusing, got: {at}"
2177        );
2178
2179        let past = v2::from_json(&"[".repeat(1_001)).expect_err("past the ceiling, the scan");
2180        assert!(
2181            past.to_string().contains("1000 JSON levels"),
2182            "past the ceiling the error must name it, got: {past}"
2183        );
2184    }
2185
2186    /// The nesting scan behind the ceiling: brackets count only outside
2187    /// string literals, an escaped quote does not end a literal, an escaped
2188    /// backslash does not disarm the real closing quote after it, and a
2189    /// stray closer never underflows the running depth.
2190    #[test]
2191    fn nesting_scan_counts_brackets_outside_string_literals_only() {
2192        // Plain structural nesting counts every open bracket.
2193        assert_eq!(v2::max_json_nesting(r#"{"a": [{"b": []}]}"#), 4);
2194        // Brackets inside a string literal do not count.
2195        assert_eq!(v2::max_json_nesting(r#"{"doc": "{[[[{"}"#), 1);
2196        // An escaped quote does not end the literal, so the brackets after
2197        // it are still inside it.
2198        assert_eq!(v2::max_json_nesting(r#"{"doc": "a\"[[[", "x": []}"#), 2);
2199        // An escaped backslash does not escape the closing quote: the
2200        // literal ends, and the brackets after it count.
2201        assert_eq!(v2::max_json_nesting(r#"{"doc": "a\\", "x": [[]]}"#), 3);
2202        // A stray closer saturates at zero rather than underflowing.
2203        assert_eq!(v2::max_json_nesting("]]]{"), 1);
2204    }
2205
2206    /// The prototext form of [`nested_package`], built by hand for the same
2207    /// reason [`nested_json`] is: past the limit the serializer rejects the
2208    /// package, so its prototext cannot come from [`v2::to_text_format`].
2209    fn nested_text(depth: usize) -> String {
2210        let mut payload = "primitive: PRIMITIVE_TYPE_INTEGER".to_string();
2211        for _ in 0..depth {
2212            payload = format!("array {{ element {{ {payload} }} min: 1 max: 1 }}");
2213        }
2214        format!(
2215            r#"name: "veh.deep" decls {{ name: "deep" fixed_def {{ payload {{ {payload} }} }} }}"#
2216        )
2217    }
2218
2219    /// The prototext write path carries the same recursion-limit failure mode
2220    /// as JSON — both go through the one transcode (ADR-0014 decision 12) —
2221    /// and reports it as an error naming its own encoding, never a panic.
2222    #[test]
2223    fn text_serialization_past_the_nesting_limit_returns_an_error() {
2224        let err = v2::to_text_format(&nested_package(NESTING_PAST_LIMIT))
2225            .expect_err("serialization past the recursion limit must fail, not panic");
2226        let message = err.to_string();
2227        assert!(
2228            message.contains("recursion limit"),
2229            "the error must name the nesting limit as the known cause, got: {message}"
2230        );
2231        assert!(
2232            message.contains("prototext"),
2233            "the error must name the encoding that failed, got: {message}"
2234        );
2235    }
2236
2237    /// Runs `test` on a thread whose stack fits the recursion the test
2238    /// drives on its own thread. Two groups need one. The prototext parser
2239    /// recurses once per message level with debug-build frames large enough
2240    /// that the default 2 MiB test-thread stack overflows near 45 array
2241    /// levels — under prost's own recursion limit, so the depths
2242    /// [`NESTING_BELOW_LIMIT`] and [`NESTING_PAST_LIMIT`] pin are
2243    /// unreachable on that stack; the production paths are unaffected, since
2244    /// the toolchain writes prototext and never parses it (`ridl diff` and
2245    /// the baselines stay `.ir.json`, ADR-0014 decision 5). And the deep
2246    /// JSON tests drive the pbjson-generated writer, which recurses on the
2247    /// caller's stack (ADR-0014 decision 14 — only the reader sizes a
2248    /// thread of its own, inside `from_json`).
2249    fn with_sized_stack(test: impl FnOnce() + Send + 'static) {
2250        let outcome = std::thread::Builder::new()
2251            .stack_size(16 * 1024 * 1024)
2252            .spawn(test)
2253            .expect("spawn the large-stack test thread")
2254            .join();
2255        if let Err(payload) = outcome {
2256            std::panic::resume_unwind(payload);
2257        }
2258    }
2259
2260    /// The read direction: the text-format parser itself has no depth limit,
2261    /// so the failure is the transcode out of the dynamic message, mapped
2262    /// into the error return instead of expected on (ADR-0014 decision 12).
2263    #[test]
2264    fn text_parse_past_the_nesting_limit_returns_an_error() {
2265        with_sized_stack(|| {
2266            let error = v2::from_text_format(&nested_text(NESTING_PAST_LIMIT))
2267                .expect_err("parsing past the recursion limit must fail, not panic");
2268
2269            // Assert *which* stage failed: prost's transcoding decoder says
2270            // "recursion limit reached", and a parse-stage failure would
2271            // render through the `Parse` variant instead.
2272            let message = error.to_string();
2273            assert!(
2274                message.contains("recursion limit reached"),
2275                "the transcode out of the dynamic message must be the failing \
2276                 stage, got: {message}"
2277            );
2278        });
2279    }
2280
2281    /// The prototext bound must not tighten silently either: below the limit
2282    /// the package still serializes and round-trips.
2283    #[test]
2284    fn text_round_trip_below_the_nesting_limit_succeeds() {
2285        with_sized_stack(|| {
2286            let package = nested_package(NESTING_BELOW_LIMIT);
2287            let text = v2::to_text_format(&package)
2288                .expect("below the recursion limit, serialization succeeds");
2289            let decoded =
2290                v2::from_text_format(&text).expect("below the recursion limit, parsing succeeds");
2291            assert_eq!(package, decoded);
2292        });
2293    }
2294}
2295
2296#[cfg(test)]
2297mod vacuous_constraint {
2298    use crate::v2;
2299
2300    /// A constraint with every field absent. Each test sets only the field it
2301    /// is about, so no assertion can pass through a neighbouring field.
2302    fn constraint() -> v2::Constraint {
2303        v2::Constraint {
2304            min: None,
2305            max: None,
2306            step: None,
2307            len_min: None,
2308            len_max: None,
2309            pattern: None,
2310            pattern_const: None,
2311        }
2312    }
2313
2314    #[test]
2315    fn an_absent_or_empty_constraint_is_vacuous() {
2316        assert!(v2::constraint_is_vacuous(None));
2317        assert!(v2::constraint_is_vacuous(Some(&constraint())));
2318    }
2319
2320    #[test]
2321    fn a_step_constraint_is_non_vacuous() {
2322        let stepped = v2::Constraint {
2323            step: Some("0.5".to_string()),
2324            ..constraint()
2325        };
2326        assert!(!v2::constraint_is_vacuous(Some(&stepped)));
2327    }
2328
2329    /// Every constrained field on its own. A fixture setting a pair — `min`
2330    /// with `max`, or `len_min` with `len_max` — cannot tell a predicate that
2331    /// reads both from one that reads either, so each bound here is one-sided.
2332    /// The paired shapes are pinned separately by
2333    /// [`a_bound_pair_set_together_is_non_vacuous`], which a one-sided fixture
2334    /// cannot do.
2335    #[test]
2336    fn any_single_constrained_field_is_non_vacuous() {
2337        let cases = [
2338            (
2339                "min",
2340                v2::Constraint {
2341                    min: Some("0.0".to_string()),
2342                    ..constraint()
2343                },
2344            ),
2345            (
2346                "max",
2347                v2::Constraint {
2348                    max: Some("250.0".to_string()),
2349                    ..constraint()
2350                },
2351            ),
2352            (
2353                "len_min",
2354                v2::Constraint {
2355                    len_min: Some(1),
2356                    ..constraint()
2357                },
2358            ),
2359            (
2360                "len_max",
2361                v2::Constraint {
2362                    len_max: Some(256),
2363                    ..constraint()
2364                },
2365            ),
2366            (
2367                "pattern",
2368                v2::Constraint {
2369                    pattern: Some("^[a-z]+$".to_string()),
2370                    ..constraint()
2371                },
2372            ),
2373            (
2374                "pattern_const",
2375                v2::Constraint {
2376                    pattern_const: Some("NAME_PATTERN".to_string()),
2377                    ..constraint()
2378                },
2379            ),
2380        ];
2381        for (field, case) in cases {
2382            assert!(
2383                !v2::constraint_is_vacuous(Some(&case)),
2384                "`{field}` alone must be non-vacuous"
2385            );
2386        }
2387    }
2388
2389    /// The two shapes the checker actually emits: a declared range, and the
2390    /// typl §4.4 default `[0..256]` every string and bytes type carries.
2391    ///
2392    /// A one-sided fixture cannot pin these. A predicate reading each bound as
2393    /// a pair — `(c.min.is_none() == c.max.is_none())` and the same for the
2394    /// length bounds — passes every one-sided case and still reports both
2395    /// shapes below as vacuous, which would drop the range check from every
2396    /// bounded number and every string.
2397    #[test]
2398    fn a_bound_pair_set_together_is_non_vacuous() {
2399        let ranged = v2::Constraint {
2400            min: Some("0.0".to_string()),
2401            max: Some("250.0".to_string()),
2402            ..constraint()
2403        };
2404        assert!(!v2::constraint_is_vacuous(Some(&ranged)));
2405
2406        let default_length = v2::Constraint {
2407            len_min: Some(0),
2408            len_max: Some(256),
2409            ..constraint()
2410        };
2411        assert!(!v2::constraint_is_vacuous(Some(&default_length)));
2412    }
2413}
2414
2415#[cfg(test)]
2416mod system_round_trip {
2417    use crate::v2;
2418
2419    fn attribute(namespace: &str, key: &str, value: Option<v2::AttributeValue>) -> v2::Attribute {
2420        v2::Attribute {
2421            namespace: namespace.to_string(),
2422            key: key.to_string(),
2423            value,
2424        }
2425    }
2426
2427    fn scalar(text: &str) -> v2::AttributeValue {
2428        v2::AttributeValue {
2429            kind: Some(v2::attribute_value::Kind::Scalar(text.to_string())),
2430        }
2431    }
2432
2433    fn list(items: Vec<v2::AttributeValue>) -> v2::AttributeValue {
2434        v2::AttributeValue {
2435            kind: Some(v2::attribute_value::Kind::List(v2::AttributeList { items })),
2436        }
2437    }
2438
2439    fn interface(catalog: &str, name: &str, inline: bool) -> Option<v2::InterfaceRef> {
2440        Some(v2::InterfaceRef {
2441            catalog: catalog.to_string(),
2442            name: name.to_string(),
2443            inline,
2444        })
2445    }
2446
2447    fn endpoint(component: &str, instance: &str, machine: &str) -> v2::Endpoint {
2448        v2::Endpoint {
2449            component: component.to_string(),
2450            instance: instance.to_string(),
2451            machine: machine.to_string(),
2452        }
2453    }
2454
2455    /// A reduced rsdl reference Appendix A: `Cruise` with two instances
2456    /// offering `veh.adas.cruise` and requiring `LaneAssist`, the implicit
2457    /// component of `veh.diag.access`, one distribution and one deployment.
2458    /// Every message of `system.proto` appears at least once, with every
2459    /// scalar set to a value other than its default — a flag and a nested-list
2460    /// attribute value included — so a round trip that drops a field is
2461    /// caught.
2462    fn fixture() -> v2::System {
2463        let link = v2::Link {
2464            interface: interface("veh.diag", "veh.diag.access", true),
2465            service: "veh.diag.access".to_string(),
2466            consumer: Some(endpoint("veh.topology.Backend", "Unit", "Cloud")),
2467            producer: Some(endpoint("veh.diag.access", "Unit", "AdasHpc")),
2468            crossing: v2::Crossing::OffBoard as i32,
2469        };
2470        v2::System {
2471            name: "Vehicle".to_string(),
2472            package: "veh.topology".to_string(),
2473            labels: vec!["ASIL_B".to_string()],
2474            attributes: vec![attribute("rust", "crate", Some(scalar("\"vehicle\"")))],
2475            members: vec![
2476                v2::MemberLine {
2477                    component: "veh.topology.Cruise".to_string(),
2478                    attributes: vec![attribute("linux", "pinned", None)],
2479                },
2480                v2::MemberLine {
2481                    component: "veh.diag.access".to_string(),
2482                    attributes: vec![],
2483                },
2484            ],
2485            components: vec![
2486                v2::Component {
2487                    name: "Cruise".to_string(),
2488                    package: "veh.topology".to_string(),
2489                    implicit: false,
2490                    external: true,
2491                    instances: vec!["primary".to_string(), "backup".to_string()],
2492                    offers: vec![v2::Offer {
2493                        service: "veh.adas.cruise".to_string(),
2494                        attributes: vec![attribute("someip", "serviceId", Some(scalar("4097")))],
2495                    }],
2496                    requires: vec![v2::Require {
2497                        interface: interface("veh.adas", "LaneAssist", false),
2498                        service: "veh.adas.lane".to_string(),
2499                        producer: "veh.topology.Lane".to_string(),
2500                        attributes: vec![attribute(
2501                            "linux",
2502                            "cpuset",
2503                            Some(list(vec![scalar("2"), list(vec![scalar("3")])])),
2504                        )],
2505                    }],
2506                    labels: vec!["ASIL_B".to_string()],
2507                    attributes: vec![attribute("rust", "crate", None)],
2508                },
2509                v2::Component {
2510                    name: "veh.diag.access".to_string(),
2511                    package: String::new(),
2512                    implicit: true,
2513                    external: false,
2514                    instances: vec!["Unit".to_string()],
2515                    offers: vec![v2::Offer {
2516                        service: "veh.diag.access".to_string(),
2517                        attributes: vec![],
2518                    }],
2519                    requires: vec![],
2520                    labels: vec![],
2521                    attributes: vec![],
2522                },
2523            ],
2524            producers: vec![v2::Producer {
2525                service: "veh.adas.cruise".to_string(),
2526                component: "veh.topology.Cruise".to_string(),
2527                instances: vec!["primary".to_string(), "backup".to_string()],
2528                not_yet_realizable: true,
2529            }],
2530            grants: vec![v2::Grant {
2531                component: "veh.topology.Backend".to_string(),
2532                external: true,
2533                regions: vec!["veh.adas".to_string(), "veh.diag".to_string()],
2534            }],
2535            regions: vec![v2::Region {
2536                catalog: "veh.diag".to_string(),
2537                interfaces: vec![v2::RegionInterface {
2538                    name: "veh.diag.access".to_string(),
2539                    inline: true,
2540                    number: 2,
2541                    provisional: true,
2542                    service: "veh.diag.access".to_string(),
2543                }],
2544            }],
2545            distributions: vec![v2::Distribution {
2546                name: "Adas".to_string(),
2547                package: "veh.topology".to_string(),
2548                members: vec![v2::MemberLine {
2549                    component: "veh.topology.Cruise".to_string(),
2550                    attributes: vec![],
2551                }],
2552                depends_on: vec!["veh.topology.Base".to_string()],
2553                labels: vec!["PLATFORM_BUNDLE".to_string()],
2554                attributes: vec![attribute("deb", "section", Some(scalar("net")))],
2555            }],
2556            deployments: vec![v2::Deployment {
2557                name: "Production".to_string(),
2558                package: "veh.topology".to_string(),
2559                labels: vec!["FLEET".to_string()],
2560                attributes: vec![attribute("ota", "channel", Some(scalar("stable")))],
2561                machines: vec![v2::Machine {
2562                    name: "Cloud".to_string(),
2563                    external: true,
2564                    labels: vec!["OFF_BOARD".to_string()],
2565                    attributes: vec![attribute("net", "zone", Some(scalar("wan")))],
2566                }],
2567                placements: vec![v2::Placement {
2568                    component: "veh.topology.Cruise".to_string(),
2569                    instance: "backup".to_string(),
2570                    machine: "Cockpit".to_string(),
2571                    attributes: vec![attribute("linux", "cpuset", Some(list(vec![])))],
2572                }],
2573                links: vec![link.clone()],
2574                routes: vec![v2::Route {
2575                    catalog: "veh.adas".to_string(),
2576                    interface_number: 2,
2577                    member_ordinal: 1,
2578                    interface: "LaneAssist".to_string(),
2579                    member: "active".to_string(),
2580                    service: "veh.adas.lane".to_string(),
2581                    producers: vec![endpoint("veh.topology.Lane", "Unit", "AdasHpc")],
2582                }],
2583                surface: vec![v2::Surface {
2584                    link: Some(link),
2585                    direction: v2::SurfaceDirection::ExternalConsumes as i32,
2586                }],
2587                installations: vec![v2::Installation {
2588                    distribution: "veh.topology.Adas".to_string(),
2589                    machines: vec!["AdasHpc".to_string(), "Cockpit".to_string()],
2590                }],
2591            }],
2592        }
2593    }
2594
2595    #[test]
2596    fn system_binary_round_trip_preserves_system() {
2597        let system = fixture();
2598        let decoded = v2::system_from_binary(v2::system_to_binary(&system).as_slice())
2599            .expect("decode must succeed");
2600        assert_eq!(system, decoded);
2601    }
2602
2603    /// The canonical JSON of the system artifact re-reads through the same
2604    /// strict pbjson-generated impl the package uses (ADR-0014 decisions 11
2605    /// and 14): unknown fields rejected, enums by name, the nested attribute
2606    /// list intact.
2607    #[test]
2608    fn system_json_round_trip_preserves_system() {
2609        let system = fixture();
2610        let json = v2::system_to_json_pretty(&system).expect("the fixture serializes as JSON");
2611        assert!(
2612            json.contains("\"crossing\": \"CROSSING_OFF_BOARD\""),
2613            "enums render by name, got:\n{json}"
2614        );
2615        assert!(
2616            json.contains("\"notYetRealizable\": true"),
2617            "fields render in lowerCamelCase, got:\n{json}"
2618        );
2619        assert_eq!(
2620            system,
2621            v2::system_from_json(&json).expect("the JSON parses")
2622        );
2623        assert!(
2624            v2::system_from_json(&json.replacen("\"name\"", "\"nam\"", 1)).is_err(),
2625            "an unknown field is rejected"
2626        );
2627    }
2628
2629    #[test]
2630    fn system_text_format_round_trip_preserves_system() {
2631        let system = fixture();
2632        let text = v2::system_to_text_format(&system).expect("the fixture serializes as prototext");
2633        assert!(
2634            text.starts_with("name:"),
2635            "fields print in schema index order, got: {text}"
2636        );
2637        assert_eq!(
2638            system,
2639            v2::system_from_text_format(&text).expect("prototext parsing must succeed")
2640        );
2641    }
2642
2643    /// `pkg.Name` for a declared name; the implicit component of a lone
2644    /// service, which no package declares, is its own qualified name.
2645    #[test]
2646    fn qualified_names_follow_the_one_derivation() {
2647        let system = fixture();
2648        assert_eq!(system.qualified_name(), "veh.topology.Vehicle");
2649        assert_eq!(system.components[0].qualified_name(), "veh.topology.Cruise");
2650        assert_eq!(system.components[1].qualified_name(), "veh.diag.access");
2651        assert_eq!(
2652            system.distributions[0].qualified_name(),
2653            "veh.topology.Adas"
2654        );
2655    }
2656}