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 and no pattern is present. `step` is excluded on
800    /// purpose: nothing checks a step today, and the design this classifier
801    /// prepares for rounds a value to the nearest step-lattice point rather than
802    /// rejecting it, so a step-only constraint is meant to admit a constructor
803    /// with nothing to check (design spec, Deferred, not yet implemented).
804    ///
805    /// A pattern given by name counts as a pattern: `pattern_const` is read as
806    /// well as `pattern`, because a pattern constant that did not resolve leaves
807    /// `pattern` absent while the type still carries a match constraint.
808    /// `ridl-sem` treats the two fields the same way in its derived-init rule
809    /// (`init.rs`).
810    ///
811    /// Because the checker materializes the typl §4.4 default `[0..256]` into
812    /// `len_min`/`len_max`, every string and bytes type is non-vacuous. In
813    /// practice this reduces to `boolean`, and `integer`/`float` with no declared
814    /// range.
815    pub fn constraint_is_vacuous(constraint: Option<&Constraint>) -> bool {
816        let Some(c) = constraint else { return true };
817        c.min.is_none()
818            && c.max.is_none()
819            && c.len_min.is_none()
820            && c.len_max.is_none()
821            && c.pattern.is_none()
822            && c.pattern_const.is_none()
823    }
824}
825
826pub mod codegen;
827pub mod name;
828pub mod projection;
829
830#[cfg(test)]
831mod v2_round_trip {
832    use crate::v2;
833
834    /// Wraps an interaction kind in the shared `Decl` envelope. Visibility
835    /// and `is_error` stay unset on interactions (ridl §14.1); the ordinal is
836    /// the 1-based declaration order across all interactions of the
837    /// enclosing interface (ridl §11).
838    fn interaction(name: &str, ordinal: u32, kind: v2::decl::Kind) -> v2::Decl {
839        v2::Decl {
840            name: name.to_string(),
841            visibility: v2::Visibility::Unspecified as i32,
842            is_error: false,
843            doc: String::new(),
844            labels: Vec::new(),
845            deprecated: None,
846            ordinal,
847            kind: Some(kind),
848        }
849    }
850
851    fn named_type(name: &str) -> v2::FieldType {
852        v2::FieldType {
853            optional: false,
854            kind: Some(v2::field_type::Kind::Named(name.to_string())),
855        }
856    }
857
858    fn stream_of(element: v2::stream_type::Element) -> v2::FieldType {
859        v2::FieldType {
860            optional: false,
861            kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
862                element: Some(element),
863            })),
864        }
865    }
866
867    /// A representative ridl package: one interface holding all five
868    /// interaction kinds plus a reserved tombstone (ordinals 1–6, the
869    /// tombstone counted, ridl §11), a strict-periodic and a defaulted
870    /// range timing, a fallible query, and two services — a named
871    /// reference and an inline shape holding a stream query.
872    fn fixture() -> v2::Package {
873        // signal speed : Speed @10ms — strict periodic stores the period
874        // in both bounds (ADR-0008 decision 12).
875        let speed = v2::SignalDef {
876            payload: "Speed".to_string(),
877            declared_init: None,
878            init: Some(v2::InitValue {
879                derivable: true,
880                value: Some("0.0".to_string()),
881            }),
882            timing: Some(v2::Timing {
883                mode: v2::TimingMode::StrictPeriodic as i32,
884                min_us: Some("10000".to_string()),
885                max_us: Some("10000".to_string()),
886                default_applied: false,
887            }),
888        };
889
890        // event doorOpened : DoorEvent — untimed in source, so the
891        // configured default range is resolved at compile time (ridl §9.1).
892        let door_opened = v2::EventDef {
893            payload: "DoorEvent".to_string(),
894            timing: Some(v2::Timing {
895                mode: v2::TimingMode::Range as i32,
896                min_us: Some("20000".to_string()),
897                max_us: Some("500000".to_string()),
898                default_applied: true,
899            }),
900        };
901
902        // command setTarget(target : Speed) [ require target >= speed ]
903        let set_target = v2::CommandDef {
904            params: vec![v2::Param {
905                name: "target".to_string(),
906                r#type: Some(named_type("Speed")),
907            }],
908            contracts: vec![v2::Contract {
909                kind: v2::ContractKind::Require as i32,
910                source: "target >= speed".to_string(),
911                signal_refs: vec!["speed".to_string()],
912                param_refs: vec!["target".to_string()],
913                uses_result: false,
914                observer_id: "VehicleStatus.setTarget.require[0]".to_string(),
915            }],
916            timing: None,
917        };
918
919        // query fetchFaults(page : PageSpec) : FaultPage | DiagError
920        //   [ ensure result.count <= page.limit ]
921        let fetch_faults = v2::QueryDef {
922            params: vec![v2::Param {
923                name: "page".to_string(),
924                r#type: Some(named_type("PageSpec")),
925            }],
926            return_type: Some(v2::ReturnType {
927                kind: Some(v2::return_type::Kind::Fallible(v2::FallibleType {
928                    ok: "FaultPage".to_string(),
929                    err: "DiagError".to_string(),
930                })),
931            }),
932            contracts: vec![v2::Contract {
933                kind: v2::ContractKind::Ensure as i32,
934                source: "result.count <= page.limit".to_string(),
935                signal_refs: Vec::new(),
936                param_refs: vec!["page".to_string()],
937                uses_result: true,
938                observer_id: "VehicleStatus.fetchFaults.ensure[0]".to_string(),
939            }],
940            timing: None,
941        };
942
943        // fixed vin : Vin
944        let vin = v2::FixedDef {
945            payload: Some(named_type("Vin")),
946        };
947
948        let vehicle_status = v2::Interface {
949            name: "VehicleStatus".to_string(),
950            visibility: v2::Visibility::Public as i32,
951            doc: "Vehicle status contract".to_string(),
952            labels: Vec::new(),
953            deprecated: None,
954            interactions: vec![
955                interaction("speed", 1, v2::decl::Kind::SignalDef(speed)),
956                interaction("doorOpened", 2, v2::decl::Kind::EventDef(door_opened)),
957                // reserved legacyMode — the tombstone keeps ordinal 3
958                // occupied in the one interaction sequence (ridl §11).
959                v2::Decl {
960                    ordinal: 3,
961                    kind: Some(v2::decl::Kind::ReservedSlot(v2::Reserved {
962                        ordinal: 3,
963                        name: Some("legacyMode".to_string()),
964                        value: None,
965                    })),
966                    ..interaction("", 3, v2::decl::Kind::ReservedSlot(v2::Reserved::default()))
967                },
968                interaction("setTarget", 4, v2::decl::Kind::CommandDef(set_target)),
969                interaction("fetchFaults", 5, v2::decl::Kind::QueryDef(fetch_faults)),
970                interaction("vin", 6, v2::decl::Kind::FixedDef(vin)),
971            ],
972            number: 0,
973            provisional: false,
974        };
975
976        // query tailLogs(pattern : <string>) : <LogLine> — a stream param
977        // and a stream return (ridl §12), inside the inline service shape.
978        let tail_logs = v2::QueryDef {
979            params: vec![v2::Param {
980                name: "pattern".to_string(),
981                r#type: Some(stream_of(v2::stream_type::Element::Primitive(
982                    v2::PrimitiveType::String as i32,
983                ))),
984            }],
985            return_type: Some(v2::ReturnType {
986                kind: Some(v2::return_type::Kind::Value(stream_of(
987                    v2::stream_type::Element::Named("LogLine".to_string()),
988                ))),
989            }),
990            contracts: Vec::new(),
991            timing: None,
992        };
993
994        // service veh.adas.status : VehicleStatus — one named reference in
995        // the service's set (ADR-0015 decision 12).
996        let status_service = v2::Service {
997            name: "veh.adas.status".to_string(),
998            visibility: v2::Visibility::Public as i32,
999            doc: String::new(),
1000            labels: Vec::new(),
1001            deprecated: None,
1002            shapes: vec![v2::ServiceShape {
1003                kind: Some(v2::service_shape::Kind::InterfaceRef(
1004                    "VehicleStatus".to_string(),
1005                )),
1006            }],
1007        };
1008        // service veh.adas.logs { … } — the inline shape as the one entry,
1009        // Interface.name == "" (ridl §14.5).
1010        let logs_service = v2::Service {
1011            name: "veh.adas.logs".to_string(),
1012            visibility: v2::Visibility::Public as i32,
1013            doc: String::new(),
1014            labels: Vec::new(),
1015            deprecated: None,
1016            shapes: vec![v2::ServiceShape {
1017                kind: Some(v2::service_shape::Kind::Inline(v2::Interface {
1018                    name: String::new(),
1019                    visibility: v2::Visibility::Unspecified as i32,
1020                    doc: String::new(),
1021                    labels: Vec::new(),
1022                    deprecated: None,
1023                    interactions: vec![interaction(
1024                        "tailLogs",
1025                        1,
1026                        v2::decl::Kind::QueryDef(tail_logs),
1027                    )],
1028                    number: 0,
1029                    provisional: false,
1030                })),
1031            }],
1032        };
1033
1034        v2::Package {
1035            name: "veh.adas".to_string(),
1036            // One typl declaration proves the verbatim v1 surface rides
1037            // along unchanged in v2; package-level declarations carry
1038            // ordinal 0.
1039            decls: vec![v2::Decl {
1040                name: "Speed".to_string(),
1041                visibility: v2::Visibility::Public as i32,
1042                is_error: false,
1043                doc: String::new(),
1044                labels: Vec::new(),
1045                deprecated: None,
1046                ordinal: 0,
1047                kind: Some(v2::decl::Kind::TypeDef(v2::TypeDef {
1048                    backing: Some(v2::Backing {
1049                        kind: Some(v2::backing::Kind::Unit("km/h".to_string())),
1050                    }),
1051                    constraint: None,
1052                    declared_init: None,
1053                    init: None,
1054                    width: Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F32 as i32)),
1055                })),
1056            }],
1057            interfaces: vec![vehicle_status],
1058            services: vec![status_service, logs_service],
1059            retired: Vec::new(),
1060        }
1061    }
1062
1063    /// The typl vocabulary surface the interaction fixture does not reach:
1064    /// the boxed `inlineScalar` oneof member, genuine 64-bit integer fields
1065    /// (array and map bounds, length bounds, `Reserved.value`,
1066    /// `EnumValue.value`), a tuple, a map, a union, an enum set, a constant,
1067    /// and a set `deprecated`. A second fixture, so each stays readable; the
1068    /// same round-trip tests drive both.
1069    fn vocabulary_fixture() -> v2::Package {
1070        fn decl(name: &str, kind: v2::decl::Kind) -> v2::Decl {
1071            v2::Decl {
1072                name: name.to_string(),
1073                visibility: v2::Visibility::Public as i32,
1074                is_error: false,
1075                doc: String::new(),
1076                labels: Vec::new(),
1077                deprecated: None,
1078                ordinal: 0,
1079                kind: Some(kind),
1080            }
1081        }
1082
1083        fn field(name: &str, ordinal: u32, field_type: v2::FieldType) -> v2::Field {
1084            v2::Field {
1085                name: name.to_string(),
1086                ordinal,
1087                r#type: Some(field_type),
1088                declared_init: None,
1089                init: None,
1090                doc: String::new(),
1091                labels: Vec::new(),
1092                deprecated: None,
1093            }
1094        }
1095
1096        // const MAX_RETRY : integer = 24
1097        let max_retry = v2::ConstDef {
1098            type_ref: Some("integer".to_string()),
1099            value: "24".to_string(),
1100            regex: None,
1101        };
1102
1103        // enum Gear { PARK = 1  DRIVE = 2  reserved 7 } — the tombstone
1104        // retires the integer value, a genuine int64 field.
1105        let gear = v2::EnumDef {
1106            values: vec![
1107                v2::EnumValue {
1108                    name: "PARK".to_string(),
1109                    value: 1,
1110                    doc: String::new(),
1111                },
1112                v2::EnumValue {
1113                    name: "DRIVE".to_string(),
1114                    value: 2,
1115                    doc: String::new(),
1116                },
1117            ],
1118            reserved: vec![v2::Reserved {
1119                ordinal: 0,
1120                name: None,
1121                value: Some(7),
1122            }],
1123        };
1124
1125        // enumset Warnings { LOW_FUEL = 0  ICE_RISK = 33 } — the standalone
1126        // form; bit 33 forces the u64 width and is a genuine int64 value.
1127        let warnings = v2::EnumSetDef {
1128            backing_enum: None,
1129            bits: vec![
1130                v2::EnumValue {
1131                    name: "LOW_FUEL".to_string(),
1132                    value: 0,
1133                    doc: String::new(),
1134                },
1135                v2::EnumValue {
1136                    name: "ICE_RISK".to_string(),
1137                    value: 33,
1138                    doc: String::new(),
1139                },
1140            ],
1141            width: v2::IntWidth::U64 as i32,
1142        };
1143
1144        // type PlateText : string [1..86] — character length bounds, two
1145        // genuine uint64 fields behind proto3 `optional`.
1146        let plate_text = v2::TypeDef {
1147            backing: Some(v2::Backing {
1148                kind: Some(v2::backing::Kind::Primitive(
1149                    v2::PrimitiveType::String as i32,
1150                )),
1151            }),
1152            constraint: Some(v2::Constraint {
1153                min: None,
1154                max: None,
1155                step: None,
1156                len_min: Some(1),
1157                len_max: Some(86),
1158                pattern: None,
1159                pattern_const: None,
1160            }),
1161            declared_init: None,
1162            init: None,
1163            width: None,
1164        };
1165
1166        // union Sample { speed : Speed  gear : Gear }
1167        let sample = v2::UnionDef {
1168            arms: vec![
1169                v2::UnionArm {
1170                    name: "speed".to_string(),
1171                    ordinal: 1,
1172                    type_ref: "Speed".to_string(),
1173                    doc: String::new(),
1174                },
1175                v2::UnionArm {
1176                    name: "gear".to_string(),
1177                    ordinal: 2,
1178                    type_ref: "Gear".to_string(),
1179                    doc: String::new(),
1180                },
1181            ],
1182            is_result: false,
1183            reserved: Vec::new(),
1184        };
1185
1186        // retries : integer [0..24] = 3 — the boxed `inlineScalar` oneof
1187        // member: the committed regression guard for ADR-0014 Open item 2,
1188        // which established that the Rust-side `Box` is invisible to the
1189        // reflection path. The enclosing field carries the init; the nested
1190        // TypeDef's stays unset.
1191        let retries = v2::Field {
1192            declared_init: Some("3".to_string()),
1193            init: Some(v2::InitValue {
1194                derivable: true,
1195                value: Some("3".to_string()),
1196            }),
1197            ..field(
1198                "retries",
1199                1,
1200                v2::FieldType {
1201                    optional: false,
1202                    kind: Some(v2::field_type::Kind::InlineScalar(Box::new(v2::TypeDef {
1203                        backing: Some(v2::Backing {
1204                            kind: Some(v2::backing::Kind::Primitive(
1205                                v2::PrimitiveType::Integer as i32,
1206                            )),
1207                        }),
1208                        constraint: Some(v2::Constraint {
1209                            min: Some("0".to_string()),
1210                            max: Some("24".to_string()),
1211                            step: None,
1212                            len_min: None,
1213                            len_max: None,
1214                            pattern: None,
1215                            pattern_const: None,
1216                        }),
1217                        declared_init: None,
1218                        init: None,
1219                        width: Some(v2::type_def::Width::IntWidth(v2::IntWidth::U8 as i32)),
1220                    }))),
1221                },
1222            )
1223        };
1224
1225        // position : (x : Speed, y : Speed) — an anonymous named-field
1226        // composite (typl §11).
1227        let position = field(
1228            "position",
1229            2,
1230            v2::FieldType {
1231                optional: false,
1232                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
1233                    fields: vec![
1234                        v2::TupleField {
1235                            name: "x".to_string(),
1236                            r#type: Some(named_type("Speed")),
1237                        },
1238                        v2::TupleField {
1239                            name: "y".to_string(),
1240                            r#type: Some(named_type("Speed")),
1241                        },
1242                    ],
1243                })),
1244            },
1245        );
1246
1247        // gears : [Gear; 1..4096] — array bounds are genuine uint64 fields.
1248        let gears = field(
1249            "gears",
1250            3,
1251            v2::FieldType {
1252                optional: false,
1253                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1254                    element: Some(Box::new(named_type("Gear"))),
1255                    min: 1,
1256                    max: 4096,
1257                }))),
1258            },
1259        );
1260
1261        // plates : { PlateText -> Gear } [0..53] — map bounds are genuine
1262        // uint64 fields. The field is deprecated, covering the optional
1263        // string on the Field envelope.
1264        let plates = v2::Field {
1265            deprecated: Some("superseded by gears".to_string()),
1266            ..field(
1267                "plates",
1268                4,
1269                v2::FieldType {
1270                    optional: false,
1271                    kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
1272                        key: Some(Box::new(named_type("PlateText"))),
1273                        value: Some(Box::new(named_type("Gear"))),
1274                        min: 0,
1275                        max: 53,
1276                    }))),
1277                },
1278            )
1279        };
1280
1281        let snapshot = v2::StructDef {
1282            members: [retries, position, gears, plates]
1283                .into_iter()
1284                .map(|field| v2::StructMember {
1285                    member: Some(v2::struct_member::Member::Field(field)),
1286                })
1287                .collect(),
1288            fixed_layout: false,
1289        };
1290
1291        v2::Package {
1292            name: "veh.vocab".to_string(),
1293            decls: vec![
1294                decl("MAX_RETRY", v2::decl::Kind::ConstDef(max_retry)),
1295                decl("Gear", v2::decl::Kind::EnumDef(gear)),
1296                decl("Warnings", v2::decl::Kind::EnumSetDef(warnings)),
1297                decl("PlateText", v2::decl::Kind::TypeDef(plate_text)),
1298                // The union is deprecated — the optional string on the Decl
1299                // envelope.
1300                v2::Decl {
1301                    deprecated: Some("use Snapshot".to_string()),
1302                    ..decl("Sample", v2::decl::Kind::UnionDef(sample))
1303                },
1304                decl("Snapshot", v2::decl::Kind::StructDef(snapshot)),
1305            ],
1306            interfaces: Vec::new(),
1307            services: Vec::new(),
1308            retired: Vec::new(),
1309        }
1310    }
1311
1312    #[test]
1313    fn protobuf_round_trip_preserves_package() {
1314        let package = fixture();
1315
1316        let buf = v2::to_binary(&package);
1317        let decoded = v2::from_binary(buf.as_slice()).expect("decode must succeed");
1318
1319        assert_eq!(package, decoded);
1320
1321        // The vocabulary fixture rides the same round trip.
1322        let vocabulary = vocabulary_fixture();
1323        let decoded_vocabulary =
1324            v2::from_binary(v2::to_binary(&vocabulary).as_slice()).expect("decode must succeed");
1325        assert_eq!(vocabulary, decoded_vocabulary);
1326
1327        let interface = &decoded.interfaces[0];
1328        let ordinals: Vec<u32> = interface.interactions.iter().map(|d| d.ordinal).collect();
1329        assert_eq!(
1330            ordinals,
1331            [1, 2, 3, 4, 5, 6],
1332            "one ordinal sequence, tombstone counted (ridl §11)"
1333        );
1334        let Some(v2::decl::Kind::ReservedSlot(tombstone)) = &interface.interactions[2].kind else {
1335            panic!("ordinal 3 must decode as a reserved tombstone");
1336        };
1337        assert_eq!(tombstone.name.as_deref(), Some("legacyMode"));
1338        let Some(v2::service_shape::Kind::Inline(inline)) = decoded.services[1]
1339            .shapes
1340            .first()
1341            .and_then(|slot| slot.kind.as_ref())
1342        else {
1343            panic!("veh.adas.logs must decode as an inline shape");
1344        };
1345        assert_eq!(inline.name, "", "an inline shape carries no name");
1346        let references: Vec<&str> = decoded.services[0]
1347            .shapes
1348            .iter()
1349            .filter_map(|slot| match &slot.kind {
1350                Some(v2::service_shape::Kind::InterfaceRef(reference)) => Some(reference.as_str()),
1351                _ => None,
1352            })
1353            .collect();
1354        assert_eq!(
1355            references,
1356            ["VehicleStatus"],
1357            "a service's set carries its references and nothing else"
1358        );
1359    }
1360
1361    #[test]
1362    fn json_round_trip_preserves_package() {
1363        for package in [fixture(), vocabulary_fixture()] {
1364            let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
1365            let decoded = v2::from_json(&json).expect("json deserialization must succeed");
1366
1367            assert_eq!(package, decoded);
1368        }
1369    }
1370
1371    /// The interface identity fields the lock design §9 adds — `number` and
1372    /// `provisional` on every `Interface`, an inline shape included, and the
1373    /// package's `retired` list — ride all three encodings unchanged, and the
1374    /// JSON writes them under their canonical names even when they hold their
1375    /// defaults (ADR-0014 decision 2), so a reader can tell `number` 0 from an
1376    /// absent field only by the schema, never by the text.
1377    #[test]
1378    fn number_provisional_and_retired_round_trip_through_json_text_and_binary() {
1379        let mut package = fixture();
1380        package.interfaces[0].number = 4;
1381        package.interfaces[0].provisional = true;
1382        let Some(v2::service_shape::Kind::Inline(inline)) =
1383            package.services[1].shapes[0].kind.as_mut()
1384        else {
1385            panic!("veh.adas.logs holds an inline shape in slot 1");
1386        };
1387        inline.number = 5;
1388        package.retired = vec![
1389            v2::RetiredInterface {
1390                name: "LaneAssist".to_string(),
1391                number: 2,
1392            },
1393            v2::RetiredInterface {
1394                name: "service:veh.hvac.cabin".to_string(),
1395                number: 3,
1396            },
1397        ];
1398
1399        let json = v2::to_json_pretty(&package).expect("the package serializes as IR JSON");
1400        assert_eq!(v2::from_json(&json).expect("the JSON parses back"), package);
1401        let text = v2::to_text_format(&package).expect("the package serializes as prototext");
1402        assert_eq!(
1403            v2::from_text_format(&text).expect("the prototext parses back"),
1404            package
1405        );
1406        assert_eq!(
1407            v2::from_binary(v2::to_binary(&package).as_slice()).expect("the binary decodes"),
1408            package
1409        );
1410
1411        for needle in [
1412            r#""number": 4"#,
1413            r#""provisional": true"#,
1414            r#""number": 5"#,
1415            r#""name": "LaneAssist""#,
1416            r#""name": "service:veh.hvac.cabin""#,
1417        ] {
1418            assert!(
1419                json.contains(needle),
1420                "the JSON must carry {needle}, got: {json}"
1421            );
1422        }
1423
1424        // A default holds its place in the text (decision 2): an interface
1425        // that was never numbered writes `0` and `false`, and a package with
1426        // nothing retired writes an empty list.
1427        let unnumbered = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
1428        for needle in [
1429            r#""number": 0"#,
1430            r#""provisional": false"#,
1431            r#""retired": []"#,
1432        ] {
1433            assert!(
1434                unnumbered.contains(needle),
1435                "a default field must still be written, expected {needle} in: {unnumbered}"
1436            );
1437        }
1438    }
1439
1440    /// A baseline published before the lock existed carries no `number`, no
1441    /// `provisional` and no `retired` field. It still loads — a missing field
1442    /// reads as its default, which is the `number` 0 the lock design §7 names
1443    /// as the one transition case — while an unknown field is still rejected
1444    /// (`json_parse_rejects_an_unknown_field`).
1445    #[test]
1446    fn a_snapshot_lacking_the_number_fields_still_loads() {
1447        let package = v2::from_json(
1448            r#"{"name": "veh.x", "interfaces": [{"name": "LaneKeeping"}], "services": [{"name": "veh.x.s", "shapes": [{"inline": {"name": ""}}]}]}"#,
1449        )
1450        .expect("a pre-lock snapshot loads");
1451
1452        assert_eq!(package.interfaces[0].number, 0);
1453        assert!(!package.interfaces[0].provisional);
1454        let Some(v2::service_shape::Kind::Inline(inline)) =
1455            package.services[0].shapes[0].kind.as_ref()
1456        else {
1457            panic!("the service holds an inline shape");
1458        };
1459        assert_eq!(inline.number, 0);
1460        assert!(!inline.provisional);
1461        assert_eq!(package.retired, Vec::new());
1462    }
1463
1464    /// The prototext read path (ADR-0014 decision 7): both fixtures survive
1465    /// `to_text_format` then `from_text_format` unchanged. With the binary
1466    /// and JSON round trips above, this is what proves all three encodings
1467    /// carry the same IR.
1468    #[test]
1469    fn text_format_round_trip_preserves_package() {
1470        for package in [fixture(), vocabulary_fixture()] {
1471            let text = v2::to_text_format(&package).expect("the fixture serializes as prototext");
1472            let decoded = v2::from_text_format(&text).expect("prototext parsing must succeed");
1473
1474            assert_eq!(package, decoded);
1475        }
1476    }
1477
1478    /// The prototext options ADR-0014 decision 8 fixes — `pretty`,
1479    /// `skip_default_fields(false)`, `print_message_fields_in_index_order`.
1480    /// Any option set round-trips, which is why the round-trip test above
1481    /// cannot guard them.
1482    ///
1483    /// The first two are asserted through a visible consequence. The third is
1484    /// **not guarded here and cannot be on this schema**: every message in
1485    /// `ir.proto` declares its fields in ascending field-number order, and
1486    /// field-number order is also `prost-reflect`'s default, so index order
1487    /// and default order coincide everywhere and dropping the option would
1488    /// change no output. It is set because the schema's ordering is a
1489    /// property of the schema rather than a guarantee, and a message whose
1490    /// declaration order departs from its numbering would otherwise reorder
1491    /// every artifact it appears in.
1492    #[test]
1493    fn text_format_is_pretty_with_defaults_in_index_order() {
1494        let text = v2::to_text_format(&fixture()).expect("the fixture serializes as prototext");
1495
1496        // pretty: nested messages are indented, one field per line.
1497        assert!(
1498            text.contains("\n  "),
1499            "pretty printing must indent nested fields, got: {text}"
1500        );
1501        // skip_default_fields(false): a field holding its default is present
1502        // (decision 2 — `ordinal: 0` is read, not inferred from absence).
1503        assert!(
1504            text.contains("is_error: false"),
1505            "a field holding its default must be emitted, got: {text}"
1506        );
1507        // print_message_fields_in_index_order: `name` is field 1 of
1508        // `Package`, so it opens the output.
1509        assert!(
1510            text.starts_with("name:"),
1511            "fields must print in schema index order, got: {text}"
1512        );
1513    }
1514
1515    /// Parses emitted JSON the way ADR-0014 decision 11's conformance test
1516    /// requires: unknown fields rejected, trailing input rejected. Since
1517    /// decision 14 the strict parser is the pbjson-generated `Deserialize`
1518    /// impl, whose default already rejects unknown fields
1519    /// (`ignore_unknown_fields()` stays unset in `build.rs`), so the
1520    /// strictness needs no option to opt into.
1521    fn strict_parse(json: &str) -> v2::Package {
1522        let mut deserializer = serde_json::Deserializer::from_str(json);
1523        let package = <v2::Package as serde::Deserialize>::deserialize(&mut deserializer)
1524            .expect("a strict conformant parser must accept the emitted JSON");
1525        deserializer.end().expect("no trailing input");
1526        package
1527    }
1528
1529    /// The conformance claim of ADR-0014 decision 11: a conformant protobuf
1530    /// JSON parser configured to reject unknown fields accepts the emitted
1531    /// JSON. Re-reading tests that claim itself; asserting on the rendered
1532    /// text would only restate the serializer's behaviour back to itself.
1533    #[test]
1534    fn emitted_json_survives_a_strict_conformant_parse() {
1535        for package in [fixture(), vocabulary_fixture()] {
1536            let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
1537            assert_eq!(package, strict_parse(&json));
1538        }
1539    }
1540
1541    #[test]
1542    fn json_renders_timing_bounds_and_fallible_arms_exactly() {
1543        let json = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
1544
1545        // Exactness is visible: timing bounds are exact-decimal microsecond
1546        // strings, never floating-point numbers (ADR-0008 decision 12) —
1547        // under the canonical lowerCamelCase field name (ADR-0014 decision 1).
1548        assert!(
1549            json.contains(r#""minUs": "10000""#),
1550            "the timing bound must be a JSON string, got: {json}"
1551        );
1552        // Both arms of the inline T | E return are visible by name.
1553        assert!(
1554            json.contains(r#""ok": "FaultPage""#),
1555            "the ok arm must render, got: {json}"
1556        );
1557        assert!(
1558            json.contains(r#""err": "DiagError""#),
1559            "the err arm must render, got: {json}"
1560        );
1561    }
1562
1563    /// ADR-0014 decision 8's stringification, tested on genuine 64-bit
1564    /// fields. The timing assertion above proves nothing about it —
1565    /// `Timing.min_us` is `optional string` in the schema — so the claim
1566    /// needs fields whose wire type actually is `uint64` or `int64`.
1567    #[test]
1568    fn json_renders_64_bit_integer_fields_as_strings() {
1569        let json = v2::to_json_pretty(&vocabulary_fixture())
1570            .expect("the vocabulary fixture serializes as IR JSON");
1571
1572        // uint64: the array's upper bound.
1573        assert!(
1574            json.contains(r#""max": "4096""#),
1575            "an array bound must be a JSON string, got: {json}"
1576        );
1577        // uint64 behind proto3 `optional`: the character length bound.
1578        assert!(
1579            json.contains(r#""lenMax": "86""#),
1580            "a length bound must be a JSON string, got: {json}"
1581        );
1582        // int64: the retired enum value and the enum-set bit position.
1583        assert!(
1584            json.contains(r#""value": "7""#),
1585            "a retired enum value must be a JSON string, got: {json}"
1586        );
1587        assert!(
1588            json.contains(r#""value": "33""#),
1589            "an enum-set bit position must be a JSON string, got: {json}"
1590        );
1591    }
1592
1593    #[test]
1594    fn fallible_transport_identity_follows_the_derivation_rule() {
1595        // The ADR-0008 decision 4 rule: interface + interaction ordinal +
1596        // both arm references, in that order.
1597        let fallible = v2::FallibleType {
1598            ok: "FaultPage".to_string(),
1599            err: "DiagError".to_string(),
1600        };
1601        assert_eq!(
1602            v2::fallible_transport_identity("VehicleStatus", 9, &fallible),
1603            "VehicleStatus#9:FaultPage|DiagError"
1604        );
1605
1606        // Derived from the fixture: the fallible query sits at ordinal 5.
1607        let package = fixture();
1608        let interface = &package.interfaces[0];
1609        let query_decl = &interface.interactions[4];
1610        let Some(v2::decl::Kind::QueryDef(query)) = &query_decl.kind else {
1611            panic!("ordinal 5 must be the fallible query");
1612        };
1613        let Some(v2::return_type::Kind::Fallible(arms)) = &query.return_type.as_ref().unwrap().kind
1614        else {
1615            panic!("fetchFaults must return a fallible type");
1616        };
1617        assert_eq!(
1618            v2::fallible_transport_identity(&interface.name, query_decl.ordinal, arms),
1619            "VehicleStatus#5:FaultPage|DiagError"
1620        );
1621    }
1622
1623    /// `Package::shapes` yields the named interfaces first, then the inline
1624    /// shapes of the services — and each shape carries the name it is known by
1625    /// OUTSIDE the package. The fixture's inline shape has `Interface.name ==
1626    /// ""` by construction, so a walk that yielded the interface bare would
1627    /// hand every consumer the empty string; two of the six E2 defects were
1628    /// exactly that.
1629    #[test]
1630    fn shapes_walks_named_interfaces_and_inline_service_shapes() {
1631        let package = fixture();
1632        let walk: Vec<(&str, bool, usize)> = package
1633            .shapes()
1634            .map(|shape| {
1635                (
1636                    shape.name,
1637                    shape.is_inline(),
1638                    shape.interface.interactions.len(),
1639                )
1640            })
1641            .collect();
1642        assert_eq!(
1643            walk,
1644            [("VehicleStatus", false, 6), ("veh.adas.logs", true, 1)],
1645            "the named interface, then the inline shape under the service's \
1646             dotted name",
1647        );
1648
1649        // The fixture's third shape-bearing declaration is `service
1650        // veh.adas.status : VehicleStatus`, which names an interface already in
1651        // the walk. Yielding it too would visit `VehicleStatus` twice.
1652        assert_eq!(package.services.len(), 2, "one reference form, one inline");
1653        assert!(
1654            !package
1655                .shapes()
1656                .any(|shape| shape.name == "veh.adas.status"),
1657            "a service naming an interface contributes no shape of its own",
1658        );
1659    }
1660
1661    /// The owning service is carried because `Service.visibility` is the
1662    /// authoritative one: an inline shape's own field is
1663    /// `VISIBILITY_UNSPECIFIED` by construction, which is not "internal" and
1664    /// not "public".
1665    #[test]
1666    fn shape_visibility_reads_the_owning_service_for_an_inline_shape() {
1667        let package = fixture();
1668        let shapes: Vec<v2::InterfaceShape<'_>> = package.shapes().collect();
1669
1670        let named = shapes[0];
1671        assert!(named.service.is_none());
1672        assert_eq!(named.visibility(), v2::Visibility::Public as i32);
1673        assert_eq!(named.visibility(), named.interface.visibility);
1674
1675        let inline = shapes[1];
1676        assert_eq!(
1677            inline.interface.visibility,
1678            v2::Visibility::Unspecified as i32,
1679            "the trap: an inline shape's own visibility field is unset",
1680        );
1681        assert_eq!(
1682            inline.service.expect("an inline shape has an owner").name,
1683            "veh.adas.logs",
1684        );
1685        assert_eq!(
1686            inline.visibility(),
1687            v2::Visibility::Public as i32,
1688            "the accessor reads the owning service's, never the unset field",
1689        );
1690    }
1691
1692    /// A package with no service at all still walks its interfaces, and a
1693    /// package with neither yields nothing — the emptiness both backends test
1694    /// for before emitting any interaction vocabulary.
1695    #[test]
1696    fn shapes_is_empty_only_when_the_package_declares_no_shape() {
1697        let mut package = fixture();
1698        package.services.clear();
1699        assert_eq!(package.shapes().count(), 1);
1700
1701        package.interfaces.clear();
1702        assert_eq!(package.shapes().count(), 0);
1703    }
1704
1705    /// A dotted reference contributes its qualifier; a bare one contributes
1706    /// nothing. Every recursive path through `walk_field_type` — array
1707    /// element, tuple field, map key, map value, stream element — carries a
1708    /// distinct qualifier, so no path's absence can hide behind another
1709    /// path's presence: deleting any one arm's body changes the expected set
1710    /// this test compares against, rather than leaving it unchanged.
1711    #[test]
1712    fn referenced_packages_finds_qualifiers_at_depth() {
1713        fn named(reference: &str) -> v2::FieldType {
1714            v2::FieldType {
1715                kind: Some(v2::field_type::Kind::Named(reference.to_string())),
1716                ..Default::default()
1717            }
1718        }
1719
1720        fn fixed(payload: v2::FieldType) -> v2::decl::Kind {
1721            v2::decl::Kind::FixedDef(v2::FixedDef {
1722                payload: Some(payload),
1723            })
1724        }
1725
1726        let package = v2::Package {
1727            name: "veh.cluster".to_string(),
1728            decls: vec![
1729                v2::Decl {
1730                    name: "Local".to_string(),
1731                    kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
1732                        payload: "Speed".to_string(),
1733                        ..Default::default()
1734                    })),
1735                    ..Default::default()
1736                },
1737                v2::Decl {
1738                    name: "Stamped".to_string(),
1739                    kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
1740                        payload: "ridl.std.Timestamp".to_string(),
1741                        ..Default::default()
1742                    })),
1743                    ..Default::default()
1744                },
1745                v2::Decl {
1746                    name: "ArrLabels".to_string(),
1747                    kind: Some(fixed(v2::FieldType {
1748                        kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1749                            element: Some(Box::new(named("veh.arr.Label"))),
1750                            min: 0,
1751                            max: 32,
1752                        }))),
1753                        ..Default::default()
1754                    })),
1755                    ..Default::default()
1756                },
1757                v2::Decl {
1758                    name: "TupThing".to_string(),
1759                    kind: Some(fixed(v2::FieldType {
1760                        kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
1761                            fields: vec![v2::TupleField {
1762                                name: "x".to_string(),
1763                                r#type: Some(named("veh.tup.X")),
1764                            }],
1765                        })),
1766                        ..Default::default()
1767                    })),
1768                    ..Default::default()
1769                },
1770                v2::Decl {
1771                    name: "MapThing".to_string(),
1772                    kind: Some(fixed(v2::FieldType {
1773                        kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
1774                            key: Some(Box::new(named("veh.key.X"))),
1775                            value: Some(Box::new(named("veh.val.X"))),
1776                            min: 0,
1777                            max: 8,
1778                        }))),
1779                        ..Default::default()
1780                    })),
1781                    ..Default::default()
1782                },
1783                v2::Decl {
1784                    name: "StreamThing".to_string(),
1785                    kind: Some(fixed(v2::FieldType {
1786                        kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
1787                            element: Some(v2::stream_type::Element::Named(
1788                                "veh.strm.X".to_string(),
1789                            )),
1790                        })),
1791                        ..Default::default()
1792                    })),
1793                    ..Default::default()
1794                },
1795            ],
1796            ..Default::default()
1797        };
1798
1799        let found = v2::referenced_packages(&package);
1800        let expected: std::collections::BTreeSet<String> = [
1801            "ridl.std", "veh.arr", "veh.tup", "veh.key", "veh.val", "veh.strm",
1802        ]
1803        .into_iter()
1804        .map(str::to_string)
1805        .collect();
1806        assert_eq!(
1807            found, expected,
1808            "each recursive path must contribute its own distinct qualifier"
1809        );
1810        assert!(
1811            !found.contains("Speed") && !found.contains("veh.cluster"),
1812            "a bare reference contributes no package: {found:?}",
1813        );
1814    }
1815
1816    /// An empty package references nothing — the negative case the emit rule in
1817    /// `ridlc` depends on.
1818    #[test]
1819    fn referenced_packages_is_empty_without_references() {
1820        let package = v2::Package {
1821            name: "veh.solo".to_string(),
1822            ..Default::default()
1823        };
1824        assert!(v2::referenced_packages(&package).is_empty());
1825    }
1826
1827    /// Below prost's recursion limit at two message levels per nesting level
1828    /// — the depth ADR-0014 decision 12 measured as round-tripping correctly.
1829    /// Since decision 14 these two constants bound the prototext transcode
1830    /// alone: JSON no longer transcodes and carries its own read-side
1831    /// ceiling, tested separately below.
1832    const NESTING_BELOW_LIMIT: usize = 45;
1833    /// Past the limit today. The tests assert the outcome — an error, never a
1834    /// panic — not the exact threshold, so a prost release that moves the
1835    /// limit moves these constants, not the assertions.
1836    const NESTING_PAST_LIMIT: usize = 60;
1837
1838    /// One declaration whose payload nests `depth` levels of inline arrays —
1839    /// each level costs two message levels on the wire (`FieldType` plus
1840    /// `ArrayType`), the arithmetic ADR-0014 decision 12 records against
1841    /// prost's recursion limit.
1842    fn nested_package(depth: usize) -> v2::Package {
1843        let mut payload = v2::FieldType {
1844            optional: false,
1845            kind: Some(v2::field_type::Kind::Primitive(
1846                v2::PrimitiveType::Integer as i32,
1847            )),
1848        };
1849        for _ in 0..depth {
1850            payload = v2::FieldType {
1851                optional: false,
1852                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1853                    element: Some(Box::new(payload)),
1854                    min: 1,
1855                    max: 1,
1856                }))),
1857            };
1858        }
1859        v2::Package {
1860            name: "veh.deep".to_string(),
1861            decls: vec![v2::Decl {
1862                name: "deep".to_string(),
1863                kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
1864                    payload: Some(payload),
1865                })),
1866                ..Default::default()
1867            }],
1868            ..Default::default()
1869        }
1870    }
1871
1872    /// One package whose nesting sits exactly `levels` message levels below
1873    /// the `Package` root — the unit the derived binary encoding's bound is
1874    /// stated in (the IR specification, "The derived encodings").
1875    ///
1876    /// The chain under a `FixedDef` costs three levels before any nesting
1877    /// (`Decl`, `FixedDef`, the outermost `FieldType`) and two per array level
1878    /// (`ArrayType`, `FieldType`), so an array-only chain reaches the odd
1879    /// depths alone. One tuple level costs three (`FieldType`, `TupleType`,
1880    /// `TupleField`, then the `FieldType` the next level counts), which is what
1881    /// reaches the even depths. Both shapes are what the front end lowers, so
1882    /// neither is a construction the schema would not otherwise see.
1883    fn package_at_message_depth(levels: usize) -> v2::Package {
1884        assert!(levels >= 3, "the chain costs three levels before nesting");
1885        let (arrays, tuple) = if levels % 2 == 1 {
1886            ((levels - 3) / 2, false)
1887        } else {
1888            assert!(levels >= 6, "one tuple level costs three");
1889            ((levels - 6) / 2, true)
1890        };
1891
1892        let mut payload = v2::FieldType {
1893            optional: false,
1894            kind: Some(v2::field_type::Kind::Primitive(
1895                v2::PrimitiveType::Integer as i32,
1896            )),
1897        };
1898        for _ in 0..arrays {
1899            payload = v2::FieldType {
1900                optional: false,
1901                kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
1902                    element: Some(Box::new(payload)),
1903                    min: 1,
1904                    max: 1,
1905                }))),
1906            };
1907        }
1908        if tuple {
1909            payload = v2::FieldType {
1910                optional: false,
1911                kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
1912                    fields: vec![v2::TupleField {
1913                        name: "f0".to_string(),
1914                        r#type: Some(payload),
1915                    }],
1916                })),
1917            };
1918        }
1919        v2::Package {
1920            name: "veh.deep".to_string(),
1921            decls: vec![v2::Decl {
1922                name: "deep".to_string(),
1923                kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
1924                    payload: Some(payload),
1925                })),
1926                ..Default::default()
1927            }],
1928            ..Default::default()
1929        }
1930    }
1931
1932    /// The nesting of JSON objects in a canonical artifact, which in the
1933    /// protobuf JSON mapping is the nesting of messages: every message is an
1934    /// object, a repeated field is an array of them, and the schema declares no
1935    /// `map<>` field. The root `Package` object is included, so a caller
1936    /// counting levels *below* the root subtracts one. Brackets inside a string
1937    /// literal do not count.
1938    fn message_nesting(json: &str) -> usize {
1939        let (mut depth, mut max) = (0usize, 0usize);
1940        let (mut in_string, mut escaped) = (false, false);
1941        for byte in json.bytes() {
1942            if in_string {
1943                if escaped {
1944                    escaped = false;
1945                } else if byte == b'\\' {
1946                    escaped = true;
1947                } else if byte == b'"' {
1948                    in_string = false;
1949                }
1950                continue;
1951            }
1952            match byte {
1953                b'"' => in_string = true,
1954                b'{' => {
1955                    depth += 1;
1956                    max = max.max(depth);
1957                }
1958                b'}' => depth = depth.saturating_sub(1),
1959                _ => {}
1960            }
1961        }
1962        max
1963    }
1964
1965    /// [`package_at_message_depth`] builds what it claims, on both parities.
1966    /// Without this the two bound tests below would pin a depth nobody
1967    /// measured.
1968    #[test]
1969    fn package_at_message_depth_builds_the_depth_it_names() {
1970        with_sized_stack(|| {
1971            for levels in [3, 6, 7, 99, 100, 101] {
1972                let json = v2::to_json_pretty(&package_at_message_depth(levels))
1973                    .expect("the writer is unrestricted at these depths");
1974                assert_eq!(
1975                    message_nesting(&json) - 1,
1976                    levels,
1977                    "the chain must nest {levels} message levels below the root"
1978                );
1979            }
1980        });
1981    }
1982
1983    /// The derived binary encoding's bound, stated by the IR specification and
1984    /// pinned here: 100 message levels below the root round-trip.
1985    ///
1986    /// `to_binary` writes any depth; it is `from_binary` that stops, at prost's
1987    /// `RECURSION_LIMIT` of 100, decremented once per nested message on decode
1988    /// and not consulted on encode. The test asserts the outcome, not prost's
1989    /// constant: a prost release that moves the limit moves these two tests and
1990    /// the specification's paragraph together.
1991    #[test]
1992    fn binary_round_trip_at_100_message_levels_succeeds() {
1993        let package = package_at_message_depth(100);
1994        let bytes = v2::to_binary(&package);
1995        let decoded = v2::from_binary(&bytes).expect("100 message levels decode");
1996        assert_eq!(package, decoded);
1997    }
1998
1999    /// One level past that bound the binary reader refuses — an error, never a
2000    /// panic — while the canonical encoding carries the same package. This is
2001    /// the asymmetry the specification states as the reason binary is derived
2002    /// rather than canonical (driftsys/ridl#231).
2003    #[test]
2004    fn binary_decode_at_101_message_levels_returns_an_error() {
2005        let package = package_at_message_depth(101);
2006        let bytes = v2::to_binary(&package);
2007        let error = v2::from_binary(&bytes).expect_err("101 message levels must fail, not panic");
2008        assert!(
2009            error.to_string().contains("recursion limit reached"),
2010            "the error must name the limit, got: {error}"
2011        );
2012
2013        let json = v2::to_json_pretty(&package).expect("the canonical encoding has no such bound");
2014        assert_eq!(
2015            package,
2016            v2::from_json(&json).expect("the canonical encoding round-trips the same package")
2017        );
2018    }
2019
2020    /// The write side after ADR-0014 decision 14: the pbjson-generated
2021    /// writer recurses the typed message directly — no transcode, so no
2022    /// message-level recursion limit — and 400 levels of array nesting,
2023    /// roughly eight times the ceiling decision 12 recorded, serialize and
2024    /// round-trip. Run on an explicitly sized stack: the writer recurses on
2025    /// the caller's stack, and debug-build frames at this depth overflow the
2026    /// default test-thread stack (the reader sizes its own thread inside
2027    /// `from_json`).
2028    #[test]
2029    fn json_round_trip_at_400_nested_levels_succeeds() {
2030        with_sized_stack(|| {
2031            let package = nested_package(400);
2032            let json = v2::to_json_pretty(&package).expect("the writer has no message-level limit");
2033            let decoded = v2::from_json(&json).expect("the reader parses within its ceiling");
2034            assert_eq!(package, decoded);
2035        });
2036    }
2037
2038    /// The one error path on the JSON write side (ADR-0014 decision 14),
2039    /// and it is new with the generated impl, not a survivor of the
2040    /// transcode's: an `i32` enum field holding a discriminant outside the
2041    /// schema — data, not depth — which the retired reflection path
2042    /// serialized successfully as its bare number. The checker never
2043    /// produces one, so there is no CLI route to this failure; it is pinned
2044    /// here at the crate surface.
2045    #[test]
2046    fn json_serialization_of_an_out_of_schema_discriminant_returns_an_error() {
2047        let mut package = fixture();
2048        package.decls[0].visibility = 999;
2049        let err = v2::to_json_pretty(&package)
2050            .expect_err("an out-of-schema discriminant must fail, not panic");
2051        let message = err.to_string();
2052        assert!(
2053            message.contains("canonical protobuf JSON"),
2054            "the error must name the encoding that failed, got: {message}"
2055        );
2056        assert!(
2057            message.contains("discriminant outside the schema"),
2058            "the error must name the known cause, got: {message}"
2059        );
2060    }
2061
2062    /// The strictness ADR-0014 decision 11 relies on is the generated
2063    /// deserializer's default: `ignore_unknown_fields()` is the opt-out and
2064    /// stays unset, so a field the schema does not declare is an error,
2065    /// never silently dropped.
2066    #[test]
2067    fn json_parse_rejects_an_unknown_field() {
2068        let error = v2::from_json(r#"{"name": "veh.deep", "notAField": 1}"#)
2069            .expect_err("an unknown field must be rejected");
2070        assert!(
2071            error.to_string().contains("unknown field"),
2072            "the error must name the defect, got: {error}"
2073        );
2074    }
2075
2076    /// A reader narrowing ADR-0014 decision 14 records: the proto3 JSON
2077    /// mapping expects parsers to accept numeric enum values, and the
2078    /// generated deserializer does — within the schema's range. A
2079    /// discriminant outside it (`"visibility": 77`) is rejected, where the
2080    /// retired reflection reader accepted it — and the retired *writer*
2081    /// emitted exactly such a number for an out-of-schema discriminant.
2082    /// Pinned so the narrowing stays a decision rather than an accident: a
2083    /// future mechanism change must confront this test.
2084    #[test]
2085    fn json_parse_rejects_an_out_of_range_numeric_enum_value() {
2086        let with_visibility =
2087            |value: &str| format!(r#"{{"name": "veh.x", "decls": [{{"visibility": {value}}}]}}"#);
2088        v2::from_json(&with_visibility("1"))
2089            .expect("an in-range numeric enum value parses, as the mapping expects");
2090        let error = v2::from_json(&with_visibility("77"))
2091            .expect_err("an out-of-range numeric enum value must be rejected");
2092        assert!(
2093            error.to_string().contains("invalid value: integer `77`"),
2094            "the error must name the value, got: {error}"
2095        );
2096    }
2097
2098    /// A reader narrowing ADR-0014 decision 14 records: the mapping accepts
2099    /// float and exponent notation for integer fields (`"min": 1.0`), and
2100    /// the retired reflection reader did; the generated deserializer
2101    /// rejects both. Pinned for the same reason as the numeric-enum case
2102    /// above.
2103    #[test]
2104    fn json_parse_rejects_a_float_form_integer() {
2105        for spelling in ["1.0", "1e0"] {
2106            let error = v2::from_json(&format!(
2107                r#"{{"name": "veh.x", "decls": [{{"fixedDef": {{"payload": {{"array": {{"min": {spelling}}}}}}}}}]}}"#,
2108            ))
2109            .expect_err("a float-form integer must be rejected");
2110            assert!(
2111                error.to_string().contains("did not match any variant"),
2112                "the integer field's deserializer must be the one refusing `{spelling}`, \
2113                 got: {error}"
2114            );
2115        }
2116    }
2117
2118    /// A reader narrowing ADR-0014 decision 14 records: `null` for a
2119    /// repeated field (`"decls": null`), which the retired reflection
2120    /// reader read as empty, is rejected. `null` for an optional scalar or
2121    /// message field is still accepted — parity with the retired reader,
2122    /// asserted alongside so the narrowing's edge is pinned from both
2123    /// sides.
2124    #[test]
2125    fn json_parse_rejects_null_for_a_repeated_field() {
2126        let error = v2::from_json(r#"{"name": "veh.x", "decls": null}"#)
2127            .expect_err("null for a repeated field must be rejected");
2128        assert!(
2129            error.to_string().contains("invalid type: null"),
2130            "the error must name the null, got: {error}"
2131        );
2132        v2::from_json(r#"{"name": "veh.x", "decls": [{"deprecated": null}]}"#)
2133            .expect("null for an optional scalar field still parses");
2134    }
2135
2136    /// A reader narrowing ADR-0014 decision 14 records: a duplicate JSON
2137    /// key, which the retired reflection reader resolved last-wins, is
2138    /// rejected.
2139    #[test]
2140    fn json_parse_rejects_a_duplicate_key() {
2141        let error = v2::from_json(r#"{"name": "a", "name": "b"}"#)
2142            .expect_err("a duplicate key must be rejected");
2143        assert!(
2144            error.to_string().contains("duplicate field `name`"),
2145            "the error must name the duplicated field, got: {error}"
2146        );
2147    }
2148
2149    /// The read-side ceiling (ADR-0014 decision 14): nesting past 1,000
2150    /// bracket levels returns an error before the parse begins — a
2151    /// diagnostic, where unbounded recursion would eventually abort on a
2152    /// stack overflow no caller can catch. The input is real writer output:
2153    /// past the ceiling the asymmetry is deliberate — the writer is
2154    /// unrestricted, the reader is not.
2155    #[test]
2156    fn json_parse_past_the_nesting_ceiling_returns_an_error() {
2157        with_sized_stack(|| {
2158            let json = v2::to_json_pretty(&nested_package(500))
2159                .expect("the writer is unrestricted at this depth");
2160            let error = v2::from_json(&json).expect_err("the reader must refuse past its ceiling");
2161            assert!(
2162                error.to_string().contains("1000 JSON levels"),
2163                "the error must name the ceiling, got: {error}"
2164            );
2165        });
2166    }
2167
2168    /// The ceiling is exact: 1,000 open brackets pass the scan and reach the
2169    /// parser — which then rejects the input as not a package — and 1,001 do
2170    /// not. The scan runs before the parse, so the over-ceiling probe needs
2171    /// no valid JSON behind its brackets.
2172    #[test]
2173    fn json_nesting_ceiling_binds_exactly_at_1000() {
2174        let at = v2::from_json(&"[".repeat(1_000)).expect_err("an array is not a package");
2175        assert!(
2176            !at.to_string().contains("JSON levels"),
2177            "at the ceiling the parser, not the scan, must be the one refusing, got: {at}"
2178        );
2179
2180        let past = v2::from_json(&"[".repeat(1_001)).expect_err("past the ceiling, the scan");
2181        assert!(
2182            past.to_string().contains("1000 JSON levels"),
2183            "past the ceiling the error must name it, got: {past}"
2184        );
2185    }
2186
2187    /// The nesting scan behind the ceiling: brackets count only outside
2188    /// string literals, an escaped quote does not end a literal, an escaped
2189    /// backslash does not disarm the real closing quote after it, and a
2190    /// stray closer never underflows the running depth.
2191    #[test]
2192    fn nesting_scan_counts_brackets_outside_string_literals_only() {
2193        // Plain structural nesting counts every open bracket.
2194        assert_eq!(v2::max_json_nesting(r#"{"a": [{"b": []}]}"#), 4);
2195        // Brackets inside a string literal do not count.
2196        assert_eq!(v2::max_json_nesting(r#"{"doc": "{[[[{"}"#), 1);
2197        // An escaped quote does not end the literal, so the brackets after
2198        // it are still inside it.
2199        assert_eq!(v2::max_json_nesting(r#"{"doc": "a\"[[[", "x": []}"#), 2);
2200        // An escaped backslash does not escape the closing quote: the
2201        // literal ends, and the brackets after it count.
2202        assert_eq!(v2::max_json_nesting(r#"{"doc": "a\\", "x": [[]]}"#), 3);
2203        // A stray closer saturates at zero rather than underflowing.
2204        assert_eq!(v2::max_json_nesting("]]]{"), 1);
2205    }
2206
2207    /// The prototext form of [`nested_package`], built by hand for the same
2208    /// reason [`nested_json`] is: past the limit the serializer rejects the
2209    /// package, so its prototext cannot come from [`v2::to_text_format`].
2210    fn nested_text(depth: usize) -> String {
2211        let mut payload = "primitive: PRIMITIVE_TYPE_INTEGER".to_string();
2212        for _ in 0..depth {
2213            payload = format!("array {{ element {{ {payload} }} min: 1 max: 1 }}");
2214        }
2215        format!(
2216            r#"name: "veh.deep" decls {{ name: "deep" fixed_def {{ payload {{ {payload} }} }} }}"#
2217        )
2218    }
2219
2220    /// The prototext write path carries the same recursion-limit failure mode
2221    /// as JSON — both go through the one transcode (ADR-0014 decision 12) —
2222    /// and reports it as an error naming its own encoding, never a panic.
2223    #[test]
2224    fn text_serialization_past_the_nesting_limit_returns_an_error() {
2225        let err = v2::to_text_format(&nested_package(NESTING_PAST_LIMIT))
2226            .expect_err("serialization past the recursion limit must fail, not panic");
2227        let message = err.to_string();
2228        assert!(
2229            message.contains("recursion limit"),
2230            "the error must name the nesting limit as the known cause, got: {message}"
2231        );
2232        assert!(
2233            message.contains("prototext"),
2234            "the error must name the encoding that failed, got: {message}"
2235        );
2236    }
2237
2238    /// Runs `test` on a thread whose stack fits the recursion the test
2239    /// drives on its own thread. Two groups need one. The prototext parser
2240    /// recurses once per message level with debug-build frames large enough
2241    /// that the default 2 MiB test-thread stack overflows near 45 array
2242    /// levels — under prost's own recursion limit, so the depths
2243    /// [`NESTING_BELOW_LIMIT`] and [`NESTING_PAST_LIMIT`] pin are
2244    /// unreachable on that stack; the production paths are unaffected, since
2245    /// the toolchain writes prototext and never parses it (`ridl diff` and
2246    /// the baselines stay `.ir.json`, ADR-0014 decision 5). And the deep
2247    /// JSON tests drive the pbjson-generated writer, which recurses on the
2248    /// caller's stack (ADR-0014 decision 14 — only the reader sizes a
2249    /// thread of its own, inside `from_json`).
2250    fn with_sized_stack(test: impl FnOnce() + Send + 'static) {
2251        let outcome = std::thread::Builder::new()
2252            .stack_size(16 * 1024 * 1024)
2253            .spawn(test)
2254            .expect("spawn the large-stack test thread")
2255            .join();
2256        if let Err(payload) = outcome {
2257            std::panic::resume_unwind(payload);
2258        }
2259    }
2260
2261    /// The read direction: the text-format parser itself has no depth limit,
2262    /// so the failure is the transcode out of the dynamic message, mapped
2263    /// into the error return instead of expected on (ADR-0014 decision 12).
2264    #[test]
2265    fn text_parse_past_the_nesting_limit_returns_an_error() {
2266        with_sized_stack(|| {
2267            let error = v2::from_text_format(&nested_text(NESTING_PAST_LIMIT))
2268                .expect_err("parsing past the recursion limit must fail, not panic");
2269
2270            // Assert *which* stage failed: prost's transcoding decoder says
2271            // "recursion limit reached", and a parse-stage failure would
2272            // render through the `Parse` variant instead.
2273            let message = error.to_string();
2274            assert!(
2275                message.contains("recursion limit reached"),
2276                "the transcode out of the dynamic message must be the failing \
2277                 stage, got: {message}"
2278            );
2279        });
2280    }
2281
2282    /// The prototext bound must not tighten silently either: below the limit
2283    /// the package still serializes and round-trips.
2284    #[test]
2285    fn text_round_trip_below_the_nesting_limit_succeeds() {
2286        with_sized_stack(|| {
2287            let package = nested_package(NESTING_BELOW_LIMIT);
2288            let text = v2::to_text_format(&package)
2289                .expect("below the recursion limit, serialization succeeds");
2290            let decoded =
2291                v2::from_text_format(&text).expect("below the recursion limit, parsing succeeds");
2292            assert_eq!(package, decoded);
2293        });
2294    }
2295}
2296
2297#[cfg(test)]
2298mod vacuous_constraint {
2299    use crate::v2;
2300
2301    /// A constraint with every field absent. Each test sets only the field it
2302    /// is about, so no assertion can pass through a neighbouring field.
2303    fn constraint() -> v2::Constraint {
2304        v2::Constraint {
2305            min: None,
2306            max: None,
2307            step: None,
2308            len_min: None,
2309            len_max: None,
2310            pattern: None,
2311            pattern_const: None,
2312        }
2313    }
2314
2315    #[test]
2316    fn an_absent_or_empty_constraint_is_vacuous() {
2317        assert!(v2::constraint_is_vacuous(None));
2318        assert!(v2::constraint_is_vacuous(Some(&constraint())));
2319    }
2320
2321    #[test]
2322    fn vacuous_constraint_ignores_step() {
2323        // A declared step alone leaves a constructor nothing to check: nothing
2324        // checks a step today, and the design rounds to the lattice rather
2325        // than rejecting (design spec, Deferred, not yet implemented).
2326        let stepped = v2::Constraint {
2327            step: Some("0.5".to_string()),
2328            ..constraint()
2329        };
2330        assert!(v2::constraint_is_vacuous(Some(&stepped)));
2331    }
2332
2333    /// Every constrained field on its own. A fixture setting a pair — `min`
2334    /// with `max`, or `len_min` with `len_max` — cannot tell a predicate that
2335    /// reads both from one that reads either, so each bound here is one-sided.
2336    /// The paired shapes are pinned separately by
2337    /// [`a_bound_pair_set_together_is_non_vacuous`], which a one-sided fixture
2338    /// cannot do.
2339    #[test]
2340    fn any_single_constrained_field_is_non_vacuous() {
2341        let cases = [
2342            (
2343                "min",
2344                v2::Constraint {
2345                    min: Some("0.0".to_string()),
2346                    ..constraint()
2347                },
2348            ),
2349            (
2350                "max",
2351                v2::Constraint {
2352                    max: Some("250.0".to_string()),
2353                    ..constraint()
2354                },
2355            ),
2356            (
2357                "len_min",
2358                v2::Constraint {
2359                    len_min: Some(1),
2360                    ..constraint()
2361                },
2362            ),
2363            (
2364                "len_max",
2365                v2::Constraint {
2366                    len_max: Some(256),
2367                    ..constraint()
2368                },
2369            ),
2370            (
2371                "pattern",
2372                v2::Constraint {
2373                    pattern: Some("^[a-z]+$".to_string()),
2374                    ..constraint()
2375                },
2376            ),
2377            (
2378                "pattern_const",
2379                v2::Constraint {
2380                    pattern_const: Some("NAME_PATTERN".to_string()),
2381                    ..constraint()
2382                },
2383            ),
2384        ];
2385        for (field, case) in cases {
2386            assert!(
2387                !v2::constraint_is_vacuous(Some(&case)),
2388                "`{field}` alone must be non-vacuous"
2389            );
2390        }
2391    }
2392
2393    /// The two shapes the checker actually emits: a declared range, and the
2394    /// typl §4.4 default `[0..256]` every string and bytes type carries.
2395    ///
2396    /// A one-sided fixture cannot pin these. A predicate reading each bound as
2397    /// a pair — `(c.min.is_none() == c.max.is_none())` and the same for the
2398    /// length bounds — passes every one-sided case and still reports both
2399    /// shapes below as vacuous, which would drop the range check from every
2400    /// bounded number and every string.
2401    #[test]
2402    fn a_bound_pair_set_together_is_non_vacuous() {
2403        let ranged = v2::Constraint {
2404            min: Some("0.0".to_string()),
2405            max: Some("250.0".to_string()),
2406            ..constraint()
2407        };
2408        assert!(!v2::constraint_is_vacuous(Some(&ranged)));
2409
2410        let default_length = v2::Constraint {
2411            len_min: Some(0),
2412            len_max: Some(256),
2413            ..constraint()
2414        };
2415        assert!(!v2::constraint_is_vacuous(Some(&default_length)));
2416    }
2417}
2418
2419#[cfg(test)]
2420mod system_round_trip {
2421    use crate::v2;
2422
2423    fn attribute(namespace: &str, key: &str, value: Option<v2::AttributeValue>) -> v2::Attribute {
2424        v2::Attribute {
2425            namespace: namespace.to_string(),
2426            key: key.to_string(),
2427            value,
2428        }
2429    }
2430
2431    fn scalar(text: &str) -> v2::AttributeValue {
2432        v2::AttributeValue {
2433            kind: Some(v2::attribute_value::Kind::Scalar(text.to_string())),
2434        }
2435    }
2436
2437    fn list(items: Vec<v2::AttributeValue>) -> v2::AttributeValue {
2438        v2::AttributeValue {
2439            kind: Some(v2::attribute_value::Kind::List(v2::AttributeList { items })),
2440        }
2441    }
2442
2443    fn interface(catalog: &str, name: &str, inline: bool) -> Option<v2::InterfaceRef> {
2444        Some(v2::InterfaceRef {
2445            catalog: catalog.to_string(),
2446            name: name.to_string(),
2447            inline,
2448        })
2449    }
2450
2451    fn endpoint(component: &str, instance: &str, machine: &str) -> v2::Endpoint {
2452        v2::Endpoint {
2453            component: component.to_string(),
2454            instance: instance.to_string(),
2455            machine: machine.to_string(),
2456        }
2457    }
2458
2459    /// A reduced rsdl reference Appendix A: `Cruise` with two instances
2460    /// offering `veh.adas.cruise` and requiring `LaneAssist`, the implicit
2461    /// component of `veh.diag.access`, one distribution and one deployment.
2462    /// Every message of `system.proto` appears at least once, with every
2463    /// scalar set to a value other than its default — a flag and a nested-list
2464    /// attribute value included — so a round trip that drops a field is
2465    /// caught.
2466    fn fixture() -> v2::System {
2467        let link = v2::Link {
2468            interface: interface("veh.diag", "veh.diag.access", true),
2469            service: "veh.diag.access".to_string(),
2470            consumer: Some(endpoint("veh.topology.Backend", "Unit", "Cloud")),
2471            producer: Some(endpoint("veh.diag.access", "Unit", "AdasHpc")),
2472            crossing: v2::Crossing::OffBoard as i32,
2473        };
2474        v2::System {
2475            name: "Vehicle".to_string(),
2476            package: "veh.topology".to_string(),
2477            labels: vec!["ASIL_B".to_string()],
2478            attributes: vec![attribute("rust", "crate", Some(scalar("\"vehicle\"")))],
2479            members: vec![
2480                v2::MemberLine {
2481                    component: "veh.topology.Cruise".to_string(),
2482                    attributes: vec![attribute("linux", "pinned", None)],
2483                },
2484                v2::MemberLine {
2485                    component: "veh.diag.access".to_string(),
2486                    attributes: vec![],
2487                },
2488            ],
2489            components: vec![
2490                v2::Component {
2491                    name: "Cruise".to_string(),
2492                    package: "veh.topology".to_string(),
2493                    implicit: false,
2494                    external: true,
2495                    instances: vec!["primary".to_string(), "backup".to_string()],
2496                    offers: vec![v2::Offer {
2497                        service: "veh.adas.cruise".to_string(),
2498                        attributes: vec![attribute("someip", "serviceId", Some(scalar("4097")))],
2499                    }],
2500                    requires: vec![v2::Require {
2501                        interface: interface("veh.adas", "LaneAssist", false),
2502                        service: "veh.adas.lane".to_string(),
2503                        producer: "veh.topology.Lane".to_string(),
2504                        attributes: vec![attribute(
2505                            "linux",
2506                            "cpuset",
2507                            Some(list(vec![scalar("2"), list(vec![scalar("3")])])),
2508                        )],
2509                    }],
2510                    labels: vec!["ASIL_B".to_string()],
2511                    attributes: vec![attribute("rust", "crate", None)],
2512                },
2513                v2::Component {
2514                    name: "veh.diag.access".to_string(),
2515                    package: String::new(),
2516                    implicit: true,
2517                    external: false,
2518                    instances: vec!["Unit".to_string()],
2519                    offers: vec![v2::Offer {
2520                        service: "veh.diag.access".to_string(),
2521                        attributes: vec![],
2522                    }],
2523                    requires: vec![],
2524                    labels: vec![],
2525                    attributes: vec![],
2526                },
2527            ],
2528            producers: vec![v2::Producer {
2529                service: "veh.adas.cruise".to_string(),
2530                component: "veh.topology.Cruise".to_string(),
2531                instances: vec!["primary".to_string(), "backup".to_string()],
2532                not_yet_realizable: true,
2533            }],
2534            grants: vec![v2::Grant {
2535                component: "veh.topology.Backend".to_string(),
2536                external: true,
2537                regions: vec!["veh.adas".to_string(), "veh.diag".to_string()],
2538            }],
2539            regions: vec![v2::Region {
2540                catalog: "veh.diag".to_string(),
2541                interfaces: vec![v2::RegionInterface {
2542                    name: "veh.diag.access".to_string(),
2543                    inline: true,
2544                    number: 2,
2545                    provisional: true,
2546                    service: "veh.diag.access".to_string(),
2547                }],
2548            }],
2549            distributions: vec![v2::Distribution {
2550                name: "Adas".to_string(),
2551                package: "veh.topology".to_string(),
2552                members: vec![v2::MemberLine {
2553                    component: "veh.topology.Cruise".to_string(),
2554                    attributes: vec![],
2555                }],
2556                depends_on: vec!["veh.topology.Base".to_string()],
2557                labels: vec!["PLATFORM_BUNDLE".to_string()],
2558                attributes: vec![attribute("deb", "section", Some(scalar("net")))],
2559            }],
2560            deployments: vec![v2::Deployment {
2561                name: "Production".to_string(),
2562                package: "veh.topology".to_string(),
2563                labels: vec!["FLEET".to_string()],
2564                attributes: vec![attribute("ota", "channel", Some(scalar("stable")))],
2565                machines: vec![v2::Machine {
2566                    name: "Cloud".to_string(),
2567                    external: true,
2568                    labels: vec!["OFF_BOARD".to_string()],
2569                    attributes: vec![attribute("net", "zone", Some(scalar("wan")))],
2570                }],
2571                placements: vec![v2::Placement {
2572                    component: "veh.topology.Cruise".to_string(),
2573                    instance: "backup".to_string(),
2574                    machine: "Cockpit".to_string(),
2575                    attributes: vec![attribute("linux", "cpuset", Some(list(vec![])))],
2576                }],
2577                links: vec![link.clone()],
2578                routes: vec![v2::Route {
2579                    catalog: "veh.adas".to_string(),
2580                    interface_number: 2,
2581                    member_ordinal: 1,
2582                    interface: "LaneAssist".to_string(),
2583                    member: "active".to_string(),
2584                    service: "veh.adas.lane".to_string(),
2585                    producers: vec![endpoint("veh.topology.Lane", "Unit", "AdasHpc")],
2586                }],
2587                surface: vec![v2::Surface {
2588                    link: Some(link),
2589                    direction: v2::SurfaceDirection::ExternalConsumes as i32,
2590                }],
2591                installations: vec![v2::Installation {
2592                    distribution: "veh.topology.Adas".to_string(),
2593                    machines: vec!["AdasHpc".to_string(), "Cockpit".to_string()],
2594                }],
2595            }],
2596        }
2597    }
2598
2599    #[test]
2600    fn system_binary_round_trip_preserves_system() {
2601        let system = fixture();
2602        let decoded = v2::system_from_binary(v2::system_to_binary(&system).as_slice())
2603            .expect("decode must succeed");
2604        assert_eq!(system, decoded);
2605    }
2606
2607    /// The canonical JSON of the system artifact re-reads through the same
2608    /// strict pbjson-generated impl the package uses (ADR-0014 decisions 11
2609    /// and 14): unknown fields rejected, enums by name, the nested attribute
2610    /// list intact.
2611    #[test]
2612    fn system_json_round_trip_preserves_system() {
2613        let system = fixture();
2614        let json = v2::system_to_json_pretty(&system).expect("the fixture serializes as JSON");
2615        assert!(
2616            json.contains("\"crossing\": \"CROSSING_OFF_BOARD\""),
2617            "enums render by name, got:\n{json}"
2618        );
2619        assert!(
2620            json.contains("\"notYetRealizable\": true"),
2621            "fields render in lowerCamelCase, got:\n{json}"
2622        );
2623        assert_eq!(
2624            system,
2625            v2::system_from_json(&json).expect("the JSON parses")
2626        );
2627        assert!(
2628            v2::system_from_json(&json.replacen("\"name\"", "\"nam\"", 1)).is_err(),
2629            "an unknown field is rejected"
2630        );
2631    }
2632
2633    #[test]
2634    fn system_text_format_round_trip_preserves_system() {
2635        let system = fixture();
2636        let text = v2::system_to_text_format(&system).expect("the fixture serializes as prototext");
2637        assert!(
2638            text.starts_with("name:"),
2639            "fields print in schema index order, got: {text}"
2640        );
2641        assert_eq!(
2642            system,
2643            v2::system_from_text_format(&text).expect("prototext parsing must succeed")
2644        );
2645    }
2646
2647    /// `pkg.Name` for a declared name; the implicit component of a lone
2648    /// service, which no package declares, is its own qualified name.
2649    #[test]
2650    fn qualified_names_follow_the_one_derivation() {
2651        let system = fixture();
2652        assert_eq!(system.qualified_name(), "veh.topology.Vehicle");
2653        assert_eq!(system.components[0].qualified_name(), "veh.topology.Cruise");
2654        assert_eq!(system.components[1].qualified_name(), "veh.diag.access");
2655        assert_eq!(
2656            system.distributions[0].qualified_name(),
2657            "veh.topology.Adas"
2658        );
2659    }
2660}