Skip to main content

odx_rs/
lib.rs

1#![doc = include_str!("../README.md")]
2//!
3//! # Design notes
4//!
5//! Reader for ODX diagnostic descriptions.
6//!
7//! The subject of this crate is ODX itself: the XML documents that describe
8//! how to talk to an ECU. A PDX file is just how they travel, so [`parse`]
9//! opens that ZIP archive (`container`), reads every document in it (`xml`)
10//! and maps the result onto a navigable model (`odx`).
11//!
12//! The crate is plain Rust: it has no browser dependency, so it can be used
13//! from a command line tool or a test as easily as from WebAssembly. The
14//! bindings live in the `pdx-wasm` crate next to this one.
15
16mod conformance;
17mod container;
18mod odx;
19mod xml;
20
21pub mod model;
22
23pub use conformance::{validate, Finding, Severity};
24pub use model::{
25    MessageDirection, OdxCompuScale, OdxDocument, OdxDop, OdxMessage, OdxNode, OdxNodeKind,
26    OdxParam, OdxProperty,
27};
28
29/// Local file header of a ZIP archive; a PDX is a ZIP container.
30const ZIP_LOCAL_FILE_HEADER: [u8; 4] = [0x50, 0x4b, 0x03, 0x04];
31/// End-of-central-directory record, i.e. an archive without any entry.
32const ZIP_EMPTY_ARCHIVE: [u8; 4] = [0x50, 0x4b, 0x05, 0x06];
33
34/// What went wrong, so a caller can react differently per cause.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum ErrorKind {
37    /// The bytes are not a ZIP archive at all.
38    NotAContainer,
39    /// It is an archive, but it could not be opened.
40    UnreadableArchive,
41}
42
43impl ErrorKind {
44    /// Stable identifier, used as the `name` of the error thrown to JS.
45    pub fn as_str(self) -> &'static str {
46        match self {
47            ErrorKind::NotAContainer => "NotAContainer",
48            ErrorKind::UnreadableArchive => "UnreadableArchive",
49        }
50    }
51}
52
53#[derive(Debug, Clone)]
54pub struct ParseError {
55    kind: ErrorKind,
56    message: String,
57}
58
59impl ParseError {
60    pub(crate) fn new(kind: ErrorKind, message: String) -> Self {
61        Self { kind, message }
62    }
63
64    pub fn kind(&self) -> ErrorKind {
65        self.kind
66    }
67
68    pub fn message(&self) -> &str {
69        &self.message
70    }
71}
72
73impl std::fmt::Display for ParseError {
74    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        formatter.write_str(&self.message)
76    }
77}
78
79impl std::error::Error for ParseError {}
80
81/// Name of this crate, shown next to the version in the viewer.
82pub fn name() -> &'static str {
83    env!("CARGO_PKG_NAME")
84}
85
86/// Version of this crate, shown in the viewer's status bar and About dialog.
87pub fn version() -> &'static str {
88    env!("CARGO_PKG_VERSION")
89}
90
91/// Rule identifiers the current validation profile can report.
92///
93/// This includes the numbered Annex B checks and the documented Annex C,
94/// document-readability, identifier, and PDX catalogue checks. The order is
95/// not an API contract; use the identifiers themselves when comparing
96/// profiles or building suppressions.
97pub fn validation_rule_ids() -> &'static [&'static str] {
98    conformance::VALIDATION_RULE_IDS
99}
100
101/// Knobs that change how much of a container ends up in the model.
102///
103/// The defaults are what [`parse`] uses, so a new field never changes the
104/// output of an existing caller.
105#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
106pub struct ParseOptions {
107    /// Upper bound for the special data rows listed on a single element,
108    /// `None` for no bound at all.
109    ///
110    /// `SDGS` is where tools park data of their own, so a container may carry
111    /// far more of it than a property table can usefully show. Whenever the
112    /// bound drops rows, the element keeps an `SDG-TRUNCATED` property holding
113    /// the number of rows left out - "nothing more" and "not shown" are not
114    /// the same answer for whoever reads the model afterwards.
115    pub max_sdg_rows: Option<usize>,
116}
117
118/// Reads a PDX container and returns the model the viewer renders.
119///
120/// `file_name` is only used for the document title and error messages.
121/// Documents inside the archive that fail to parse do not fail the call:
122/// they are reported on the returned model instead.
123pub fn parse(data: &[u8], file_name: &str) -> Result<OdxDocument, ParseError> {
124    parse_with_options(data, file_name, ParseOptions::default())
125}
126
127/// [`parse`], with the limits of [`ParseOptions`] under the caller's control.
128pub fn parse_with_options(
129    data: &[u8],
130    file_name: &str,
131    options: ParseOptions,
132) -> Result<OdxDocument, ParseError> {
133    check_signature(data, file_name)?;
134
135    let archive = container::read(data)
136        .map_err(|message| ParseError::new(ErrorKind::UnreadableArchive, message))?;
137
138    Ok(odx::build(
139        &archive,
140        file_name,
141        data.len(),
142        version(),
143        options,
144    ))
145}
146
147/// The model *and* the findings, from one read of the container.
148///
149/// [`parse`] and [`validate`] each inflate the archive and parse every document
150/// in it, so a caller that wants both — which is what a viewer wants, since it
151/// draws the tree and marks the problems on it — pays for that twice. This does
152/// it once and answers both questions.
153///
154/// Nothing about either answer changes: the two are built from the same
155/// documents by the same code, so the model equals [`parse`]'s and the findings
156/// equal [`validate`]'s, element for element. A test asserts exactly that. The
157/// separate functions stay as they are — a CI job that only gates on findings
158/// should not build a model it will not look at.
159///
160/// ```no_run
161/// let bytes = std::fs::read("ECU.pdx")?;
162/// let (model, findings) = odx_rs::inspect(&bytes, "ECU.pdx")?;
163/// println!("{} finding(s) in {}", findings.len(), model.file_name);
164/// # Ok::<(), Box<dyn std::error::Error>>(())
165/// ```
166pub fn inspect(data: &[u8], file_name: &str) -> Result<(OdxDocument, Vec<Finding>), ParseError> {
167    inspect_with_options(data, file_name, ParseOptions::default())
168}
169
170/// [`inspect`], with the limits of [`ParseOptions`] under the caller's control.
171pub fn inspect_with_options(
172    data: &[u8],
173    file_name: &str,
174    options: ParseOptions,
175) -> Result<(OdxDocument, Vec<Finding>), ParseError> {
176    check_signature(data, file_name)?;
177
178    let archive = container::read(data)
179        .map_err(|message| ParseError::new(ErrorKind::UnreadableArchive, message))?;
180
181    // One workspace: parsing every document is the expensive half, and both
182    // answers come from the same parse.
183    let workspace = odx::Workspace::parse(&archive);
184    let findings = conformance::check_from(&archive, &workspace);
185    let document = odx::build_from(
186        &archive,
187        &workspace,
188        file_name,
189        data.len(),
190        version(),
191        options,
192    );
193    Ok((document, findings))
194}
195
196/// Reads loose ODX documents — a `.odx-d` and the `.odx-cs` beside it, say —
197/// without a PDX archive around them.
198///
199/// Takes a *set* rather than one document because ODX cross-document
200/// references are ordinary: a diagnostic layer points at the comparam subset
201/// that travels with it. Hand over the documents that belong together and the
202/// references resolve; hand over one of them and the rest read as unresolved,
203/// which is true but rarely what the caller meant.
204///
205/// `name` labels the whole set in the model and in error messages.
206///
207/// ```no_run
208/// let layer = std::fs::read("Sample.odx-d")?;
209/// let subset = std::fs::read("ISO_15765_2.odx-cs")?;
210/// let model = odx_rs::parse_documents(
211///     vec![("Sample.odx-d".into(), layer), ("ISO_15765_2.odx-cs".into(), subset)],
212///     "Sample",
213/// );
214/// println!("{}", model.parser_info);
215/// # Ok::<(), std::io::Error>(())
216/// ```
217pub fn parse_documents(documents: Vec<(String, Vec<u8>)>, name: &str) -> OdxDocument {
218    parse_documents_with_options(documents, name, ParseOptions::default())
219}
220
221/// [`parse_documents`], with the limits of [`ParseOptions`] under the caller's
222/// control.
223pub fn parse_documents_with_options(
224    documents: Vec<(String, Vec<u8>)>,
225    name: &str,
226    options: ParseOptions,
227) -> OdxDocument {
228    let size = documents.iter().map(|(_, bytes)| bytes.len()).sum();
229    let container = container::from_documents(documents);
230    odx::build(&container, name, size, version(), options)
231}
232
233/// Checks loose ODX documents against the same profile [`validate`] applies to
234/// an archive, minus the rules that judge the package itself.
235///
236/// The PDX catalogue describes an archive; documents handed over loose never
237/// claimed to be one, so a missing `index.xml` is not reported. Everything
238/// about the documents — and the references between the ones supplied — is
239/// checked exactly as it would be inside a container.
240pub fn validate_documents(documents: Vec<(String, Vec<u8>)>) -> Vec<Finding> {
241    conformance::check_documents(documents)
242}
243
244pub(crate) fn check_signature(data: &[u8], file_name: &str) -> Result<(), ParseError> {
245    let not_a_container = |message: String| ParseError::new(ErrorKind::NotAContainer, message);
246
247    if data.len() < 4 {
248        return Err(not_a_container(format!(
249            "{file_name} is only {} byte(s) long and cannot be a PDX container.",
250            data.len()
251        )));
252    }
253
254    let signature = &data[..4];
255    if signature == ZIP_EMPTY_ARCHIVE {
256        return Err(not_a_container(format!(
257            "{file_name} is an empty ZIP archive."
258        )));
259    }
260    if signature != ZIP_LOCAL_FILE_HEADER {
261        return Err(not_a_container(format!(
262            "{file_name} is not a PDX container: expected the ZIP signature 50 4B 03 04, found {}.",
263            signature
264                .iter()
265                .map(|byte| format!("{byte:02X}"))
266                .collect::<Vec<_>>()
267                .join(" ")
268        )));
269    }
270
271    Ok(())
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277    use serde_json::Value;
278
279    /// The demo container committed under `tests/fixtures/`.
280    const SAMPLE: &[u8] = include_bytes!("../tests/fixtures/DemoVehicle_Diagnostics.pdx");
281
282    fn parsed() -> Value {
283        let document = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx")
284            .expect("the sample container should parse");
285        serde_json::to_value(&document).expect("the model should serialise")
286    }
287
288    /// Depth-first search for the first node with the given name.
289    fn find<'a>(node: &'a Value, name: &str) -> Option<&'a Value> {
290        if node["name"].as_str() == Some(name) {
291            return Some(node);
292        }
293        node["children"]
294            .as_array()?
295            .iter()
296            .find_map(|child| find(child, name))
297    }
298
299    fn find_in(roots: &Value, name: &str) -> Value {
300        roots["roots"]
301            .as_array()
302            .expect("roots is an array")
303            .iter()
304            .find_map(|root| find(root, name))
305            .unwrap_or_else(|| panic!("no node named {name}"))
306            .clone()
307    }
308
309    /// `(depth, name, byte, value)` of every parameter row of a node.
310    fn rows(node: &Value) -> Vec<(u64, String, u64, String)> {
311        node["params"]
312            .as_array()
313            .map(|params| {
314                params
315                    .iter()
316                    .map(|row| {
317                        (
318                            row["depth"].as_u64().unwrap_or(0),
319                            row["name"].as_str().unwrap_or_default().to_owned(),
320                            row["bytePosition"].as_u64().unwrap_or(0),
321                            row["value"].as_str().unwrap_or_default().to_owned(),
322                        )
323                    })
324                    .collect()
325            })
326            .unwrap_or_default()
327    }
328
329    fn child_names(node: &Value) -> Vec<String> {
330        node["children"]
331            .as_array()
332            .map(|children| {
333                children
334                    .iter()
335                    .map(|child| child["name"].as_str().unwrap_or_default().to_owned())
336                    .collect()
337            })
338            .unwrap_or_default()
339    }
340
341    fn property(node: &Value, name: &str) -> Option<String> {
342        node["properties"]
343            .as_array()?
344            .iter()
345            .find(|row| row["name"].as_str() == Some(name))
346            .and_then(|row| row["value"].as_str())
347            .map(str::to_owned)
348    }
349
350    #[test]
351    fn rejects_files_that_are_too_short() {
352        let error = parse(&[0x50, 0x4b], "tiny.pdx")
353            .unwrap_err()
354            .message()
355            .to_owned();
356        assert!(error.contains("cannot be a PDX container"), "{error}");
357    }
358
359    #[test]
360    fn rejects_non_zip_input() {
361        let error = parse(b"<?xml version", "plain.xml")
362            .unwrap_err()
363            .message()
364            .to_owned();
365        assert!(error.contains("3C 3F 78 6D"), "{error}");
366    }
367
368    #[test]
369    fn rejects_empty_archives() {
370        let error = parse(&ZIP_EMPTY_ARCHIVE, "empty.pdx")
371            .unwrap_err()
372            .message()
373            .to_owned();
374        assert!(error.contains("empty ZIP archive"), "{error}");
375    }
376
377    #[test]
378    fn rejects_a_corrupt_archive() {
379        let mut corrupt = ZIP_LOCAL_FILE_HEADER.to_vec();
380        corrupt.extend_from_slice(b"this is not a real archive");
381        let error = parse(&corrupt, "broken.pdx")
382            .unwrap_err()
383            .message()
384            .to_owned();
385        assert!(error.contains("ZIP container"), "{error}");
386    }
387
388    #[test]
389    fn names_the_project_after_the_catalogue() {
390        let model = parsed();
391        assert_eq!(model["fileName"], "DemoVehicle_Diagnostics.pdx");
392        assert_eq!(model["roots"][0]["kind"], "project");
393        assert_eq!(model["roots"][0]["name"], "DemoVehicle_Diagnostics");
394        assert_eq!(
395            property(&model["roots"][0], "ODX-VERSION").as_deref(),
396            Some("2.2.0")
397        );
398    }
399
400    #[test]
401    fn lists_every_archive_entry() {
402        let model = parsed();
403        let files = find_in(&model, "Container Files");
404        let names: Vec<String> = files["children"]
405            .as_array()
406            .expect("files has children")
407            .iter()
408            .map(|child| child["name"].as_str().unwrap_or_default().to_owned())
409            .collect();
410        assert!(names.iter().any(|name| name == "index.xml"), "{names:?}");
411        assert!(
412            names.iter().any(|name| name.ends_with(".odx-d")),
413            "{names:?}"
414        );
415    }
416
417    #[test]
418    fn reads_diag_layers_and_their_comparams() {
419        let model = parsed();
420        let ecu = find_in(&model, "Engine Management System");
421        assert_eq!(ecu["kind"], "ecu");
422        assert_eq!(ecu["shortName"], "EMS_ECU");
423        assert_eq!(
424            property(&ecu, "LAYER-TYPE").as_deref(),
425            Some("Base Variant")
426        );
427
428        let comparams = find(&ecu, "Communication Parameters").expect("comparams folder");
429        assert_eq!(
430            property(comparams, "CP_CanPhysReqId").as_deref(),
431            Some("2016")
432        );
433    }
434
435    #[test]
436    fn resolves_service_requests_and_responses() {
437        let model = parsed();
438        let service = find_in(&model, "ReadDataByIdentifier VIN");
439        assert_eq!(service["kind"], "service");
440        // Taken from the CODED-CONST at byte 0 of the referenced request.
441        assert_eq!(service["badge"], "0x22");
442        assert_eq!(property(&service, "SEMANTIC").as_deref(), Some("DATA"));
443        assert_eq!(
444            property(&service, "AUDIENCE").as_deref(),
445            Some("AFTERSALES, DEVELOPMENT")
446        );
447        let kinds: Vec<&str> = service["children"]
448            .as_array()
449            .expect("service has children")
450            .iter()
451            .filter_map(|child| child["kind"].as_str())
452            .collect();
453        assert_eq!(kinds, ["request", "response", "response"]);
454    }
455
456    #[test]
457    fn reads_service_level_communication_parameters() {
458        let layer = r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><DIAG-COMMS><DIAG-SERVICE ID="S"><SHORT-NAME>Service</SHORT-NAME><COMPARAM-REFS><COMPARAM-REF ID-REF="CP" DOCREF="Subset" DOCTYPE="COMPARAM-SUBSET"><SIMPLE-VALUE>50</SIMPLE-VALUE></COMPARAM-REF></COMPARAM-REFS></DIAG-SERVICE></DIAG-COMMS></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
459        let subset = r#"<ODX MODEL-VERSION="2.2.0"><COMPARAM-SUBSET ID="CS"><SHORT-NAME>Subset</SHORT-NAME><COMPARAMS><COMPARAM ID="CP"><SHORT-NAME>CP_P2</SHORT-NAME><LONG-NAME>P2 timeout</LONG-NAME><PHYSICAL-DEFAULT-VALUE>100</PHYSICAL-DEFAULT-VALUE></COMPARAM></COMPARAMS></COMPARAM-SUBSET></ODX>"#;
460        let bytes =
461            crate::tests_support::zip_with(&[("Layer.odx-d", layer), ("Subset.odx-cs", subset)]);
462        let json = serde_json::to_value(parse(&bytes, "service-comparams.pdx").expect("parses"))
463            .expect("serialises");
464        let service = find_in(&json, "Service");
465        let folder = find(&service, "Communication Parameters").expect("service comparams");
466        let comparam = find(folder, "P2 timeout").expect("resolved comparam");
467
468        assert_eq!(comparam["badge"], "50");
469        assert_eq!(property(comparam, "VALUE").as_deref(), Some("50"));
470    }
471
472    #[test]
473    fn resolves_duplicate_ids_in_the_referencing_document() {
474        let decoy = r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="D"><SHORT-NAME>DecoyContainer</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="DBV"><SHORT-NAME>Decoy</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><DATA-OBJECT-PROPS><DATA-OBJECT-PROP ID="DOP"><SHORT-NAME>DOP</SHORT-NAME><COMPU-METHOD><CATEGORY>IDENTICAL</CATEGORY></COMPU-METHOD><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><BIT-LENGTH>8</BIT-LENGTH></DIAG-CODED-TYPE><PHYSICAL-TYPE BASE-DATA-TYPE="A_UINT32"/></DATA-OBJECT-PROP></DATA-OBJECT-PROPS></DIAG-DATA-DICTIONARY-SPEC></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
475        let source = r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="S"><SHORT-NAME>SourceContainer</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="SBV"><SHORT-NAME>Source</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><DATA-OBJECT-PROPS><DATA-OBJECT-PROP ID="DOP"><SHORT-NAME>DOP</SHORT-NAME><COMPU-METHOD><CATEGORY>IDENTICAL</CATEGORY></COMPU-METHOD><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><BIT-LENGTH>16</BIT-LENGTH></DIAG-CODED-TYPE><PHYSICAL-TYPE BASE-DATA-TYPE="A_UINT32"/></DATA-OBJECT-PROP></DATA-OBJECT-PROPS></DIAG-DATA-DICTIONARY-SPEC><DIAG-COMMS><DIAG-SERVICE ID="SVC"><SHORT-NAME>Service</SHORT-NAME><REQUEST-REF ID-REF="RQ"/></DIAG-SERVICE></DIAG-COMMS><REQUESTS><REQUEST ID="RQ"><SHORT-NAME>SourceRequest</SHORT-NAME><PARAMS><PARAM SEMANTIC="DATA" xsi:type="VALUE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SHORT-NAME>Value</SHORT-NAME><BYTE-POSITION>0</BYTE-POSITION><DOP-REF ID-REF="DOP"/></PARAM></PARAMS></REQUEST></REQUESTS></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
476        let bytes =
477            crate::tests_support::zip_with(&[("Decoy.odx-d", decoy), ("Source.odx-d", source)]);
478        let document = parse(&bytes, "duplicate-ids.pdx").expect("parses");
479        let json = serde_json::to_value(document).expect("serialises");
480        let request = find_in(&json, "SourceRequest");
481
482        assert_eq!(request["params"][0]["bitLength"], 16);
483    }
484
485    #[test]
486    fn keeps_distinct_comparams_with_the_same_leaf_name() {
487        let layer = r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><PROTOCOLS><PROTOCOL ID="P"><SHORT-NAME>Protocol</SHORT-NAME><COMPARAM-REFS><COMPARAM-REF ID-REF="A.CP_X" DOCREF="A" DOCTYPE="COMPARAM-SUBSET"><SIMPLE-VALUE>1</SIMPLE-VALUE></COMPARAM-REF></COMPARAM-REFS></PROTOCOL></PROTOCOLS><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><PARENT-REFS><PARENT-REF ID-REF="P"/></PARENT-REFS><COMPARAM-REFS><COMPARAM-REF ID-REF="B.CP_X" DOCREF="B" DOCTYPE="COMPARAM-SUBSET"><SIMPLE-VALUE>2</SIMPLE-VALUE></COMPARAM-REF></COMPARAM-REFS></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
488        let subset_a = r#"<ODX MODEL-VERSION="2.2.0"><COMPARAM-SUBSET ID="A_ROOT"><SHORT-NAME>A</SHORT-NAME><COMPARAMS><COMPARAM ID="A.CP_X"><SHORT-NAME>CP_X</SHORT-NAME><LONG-NAME>Parameter A</LONG-NAME></COMPARAM></COMPARAMS></COMPARAM-SUBSET></ODX>"#;
489        let subset_b = r#"<ODX MODEL-VERSION="2.2.0"><COMPARAM-SUBSET ID="B_ROOT"><SHORT-NAME>B</SHORT-NAME><COMPARAMS><COMPARAM ID="B.CP_X"><SHORT-NAME>CP_X</SHORT-NAME><LONG-NAME>Parameter B</LONG-NAME></COMPARAM></COMPARAMS></COMPARAM-SUBSET></ODX>"#;
490        let bytes = crate::tests_support::zip_with(&[
491            ("Layer.odx-d", layer),
492            ("A.odx-cs", subset_a),
493            ("B.odx-cs", subset_b),
494        ]);
495        let document = parse(&bytes, "comparams.pdx").expect("parses");
496        let json = serde_json::to_value(document).expect("serialises");
497        let base = find_in(&json, "Base");
498        let comparams = find(&base, "Communication Parameters").expect("folder");
499
500        assert_eq!(child_names(comparams), ["Parameter B", "Parameter A"]);
501    }
502    #[test]
503    fn builds_byte_templates_from_coded_constants() {
504        let model = parsed();
505        let service = find_in(&model, "ReadDataByIdentifier VIN");
506        let messages = service["messages"].as_array().expect("messages");
507        assert_eq!(messages[0]["direction"], "request");
508        assert_eq!(messages[0]["bytes"], "22 F1 90");
509        // The VIN itself is variable, so only the header is known up front.
510        assert!(
511            messages[1]["bytes"]
512                .as_str()
513                .expect("bytes")
514                .starts_with("62 F1 90 .."),
515            "{:?}",
516            messages[1]["bytes"]
517        );
518    }
519
520    #[test]
521    fn describes_request_parameters() {
522        let model = parsed();
523        let service = find_in(&model, "ReadDataByIdentifier VIN");
524        let request = &service["children"][0];
525        let params = request["params"].as_array().expect("params");
526
527        assert_eq!(params[0]["name"], "SID_RQ");
528        assert_eq!(params[0]["bytePosition"], 0);
529        assert_eq!(params[0]["bitLength"], 8);
530        assert_eq!(params[0]["dataType"], "A_UINT32");
531        assert_eq!(params[0]["value"], "0x22");
532
533        // BIT-LENGTH is inherited from the referenced DOP.
534        assert_eq!(params[1]["name"], "Did");
535        assert_eq!(params[1]["bitLength"], 16);
536        assert_eq!(params[1]["value"], "0xF190");
537    }
538
539    #[test]
540    fn reads_data_object_props_with_their_compu_method() {
541        let model = parsed();
542        let dop = find_in(&model, "Coolant temperature");
543        assert_eq!(dop["kind"], "dop");
544        assert_eq!(dop["shortName"], "DOP_CoolantTemperature");
545        assert_eq!(property(&dop, "COMPU-METHOD").as_deref(), Some("LINEAR"));
546        assert_eq!(
547            property(&dop, "FACTOR / OFFSET").as_deref(),
548            Some("1 / -40 (÷ 1)")
549        );
550        assert_eq!(property(&dop, "RANGE").as_deref(), Some("0 .. 255"));
551        assert_eq!(property(&dop, "UNIT").as_deref(), Some("degC"));
552    }
553
554    #[test]
555    fn reads_texttable_entries() {
556        let model = parsed();
557        let dop = find_in(&model, "Ignition state");
558        assert_eq!(property(&dop, "COMPU-METHOD").as_deref(), Some("TEXTTABLE"));
559        assert_eq!(property(&dop, "VALUE 0").as_deref(), Some("Off"));
560        assert_eq!(property(&dop, "VALUE 2").as_deref(), Some("Running"));
561    }
562
563    #[test]
564    fn reads_trouble_codes() {
565        let model = parsed();
566        let folder = find_in(&model, "Diagnostic Trouble Codes");
567        let codes = folder["children"].as_array().expect("dtc children");
568        assert_eq!(codes.len(), 3);
569
570        let first = &codes[0];
571        assert_eq!(first["kind"], "dtc");
572        assert_eq!(first["name"], "P0116 — Coolant temperature circuit range");
573        assert_eq!(first["badge"], "0x010016");
574        assert_eq!(property(first, "LEVEL").as_deref(), Some("2"));
575    }
576
577    #[test]
578    fn reads_vehicle_information() {
579        let model = parsed();
580        let vehicle = find_in(&model, "Demo Vehicle 2026");
581        assert_eq!(vehicle["kind"], "vehicle");
582        assert_eq!(vehicle["shortName"], "DemoVehicle");
583        let links = find(&vehicle, "Logical Links").expect("logical links folder");
584        assert_eq!(links["children"].as_array().expect("links").len(), 1);
585    }
586
587    #[test]
588    fn summarises_what_was_parsed() {
589        let document = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx").expect("parses");
590        let info = &document.parser_info;
591        // Counts are definitions, not tree nodes: the services the EU6
592        // variant inherits are not counted a second time.
593        assert!(info.contains("5 layers"), "{info}");
594        assert!(info.contains("8 services"), "{info}");
595        // 14 from 0.23.0, not 12: the dictionary's MUX and END-OF-PDU-FIELD are
596        // definitions like any other DOP-BASE, and were left out while every
597        // one of them happened to be reachable by expanding a parameter.
598        assert!(info.contains("14 DOPs"), "{info}");
599        assert!(info.contains("3 DTCs"), "{info}");
600        assert!(info.contains("2 jobs"), "{info}");
601        assert!(info.contains("3 env data elements"), "{info}");
602        assert!(info.contains("2 flash blocks"), "{info}");
603        assert!(!info.contains("unreadable"), "{info}");
604    }
605
606    // ---- layer inheritance -------------------------------------------
607
608    #[test]
609    fn inherits_services_from_the_parent_layer() {
610        let model = parsed();
611        let variant = find_in(&model, "Engine Management System EU6");
612        let services = find(&variant, "Diagnostic Services").expect("services folder");
613
614        let names = child_names(services);
615        // Defined locally by the variant.
616        assert!(
617            names.contains(&"ReadDataByIdentifier NOx level".to_owned()),
618            "{names:?}"
619        );
620        // Taken from the base variant.
621        assert!(
622            names.contains(&"ReadDataByIdentifier VIN".to_owned()),
623            "{names:?}"
624        );
625        // Blocked by NOT-INHERITED-DIAG-COMM on the parent reference.
626        assert!(
627            !names.contains(&"ReadDataByIdentifier coolant temperature".to_owned()),
628            "{names:?}"
629        );
630
631        let inherited = services["children"]
632            .as_array()
633            .expect("children")
634            .iter()
635            .find(|child| child["name"] == "ReadDataByIdentifier VIN")
636            .expect("the inherited service");
637        assert_eq!(inherited["origin"], "EMS_ECU");
638    }
639
640    #[test]
641    fn marks_locally_defined_elements_as_not_inherited() {
642        let model = parsed();
643        let base = find_in(&model, "Engine Management System");
644        let services = find(&base, "Diagnostic Services").expect("services folder");
645        let local = &services["children"][0];
646        assert!(local["origin"].is_null(), "{local:?}");
647        assert_eq!(property(&base, "INHERITED ELEMENTS").as_deref(), Some("0"));
648    }
649
650    #[test]
651    fn honours_not_inherited_dops() {
652        let model = parsed();
653        let variant = find_in(&model, "Engine Management System EU6");
654        let dops = find(&variant, "Data Object Properties").expect("dops folder");
655        let names = child_names(dops);
656        assert!(names.contains(&"NOx level".to_owned()), "{names:?}");
657        assert!(
658            names.contains(&"Coolant temperature".to_owned()),
659            "{names:?}"
660        );
661        assert!(!names.contains(&"Ignition state".to_owned()), "{names:?}");
662    }
663
664    /// The services index answers two different questions, and keeping them
665    /// distinct is the whole reason it records inheritance.
666    #[test]
667    fn the_services_index_separates_offered_from_defined() {
668        let model = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx").expect("parses");
669
670        // "How many services exist" counts definitions, which is what the
671        // summary and parser_info report. The two are built from different
672        // walks, so agreeing is a real check rather than a tautology.
673        let defined = model
674            .services
675            .iter()
676            .filter(|service| service.inherited_from.is_none())
677            .count();
678        assert_eq!(defined, model.summary.services);
679
680        // "What does this layer answer to" counts entries, which is larger
681        // whenever a variant inherits from a parent — and the fixture does.
682        assert!(
683            model.services.len() > defined,
684            "the fixture should exercise inheritance: {} entries, {defined} defined",
685            model.services.len()
686        );
687        let inherited = model
688            .services
689            .iter()
690            .find(|service| service.inherited_from.is_some())
691            .expect("an inherited service");
692        assert_ne!(
693            inherited.inherited_from.as_deref(),
694            Some(inherited.layer.as_str()),
695            "a service is never inherited from the layer listing it"
696        );
697    }
698
699    /// The identifier a tester actually sends, as a number rather than the
700    /// `"0x22"` badge the tree renders.
701    #[test]
702    fn services_carry_their_numeric_identifier_and_preconditions() {
703        let model = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx").expect("parses");
704        let read_data = model
705            .services
706            .iter()
707            .find(|service| service.service_id == Some(0x22))
708            .expect("ReadDataByIdentifier");
709
710        assert!(!read_data.short_name.is_empty());
711        assert!(
712            read_data.request_ref.is_some(),
713            "a service names its request"
714        );
715        // The session or security level a tester must reach first, resolved to
716        // names rather than left as references.
717        assert!(
718            !read_data.precondition_states.is_empty(),
719            "0x22 in the fixture is gated on a state"
720        );
721    }
722
723    /// Everything a decoder needs about the value's shape: how the bytes are
724    /// read, what they become, where the length comes from, and which way
725    /// round a multi-byte integer sits.
726    #[test]
727    fn dops_carry_what_decoding_a_value_needs() {
728        let model = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx").expect("parses");
729        let dop = model
730            .dops
731            .iter()
732            .find(|dop| dop.category == "LINEAR")
733            .expect("a linear conversion");
734
735        // The wire type and the physical type are different questions, and a
736        // linear conversion is exactly where they diverge.
737        assert!(dop.base_data_type.is_some());
738        assert!(dop.physical_base_data_type.is_some());
739        assert_eq!(dop.coded_type_kind.as_deref(), Some("STANDARD-LENGTH-TYPE"));
740        // ODX defaults the byte order to true, so a document that says nothing
741        // still has to report the value a decoder should use.
742        assert_eq!(dop.high_low_byte_order, Some(true));
743    }
744
745    /// A consumer comparing a parameter against an expected byte should not
746    /// have to parse `"0x22"` — a rendering whose width depends on the bit
747    /// length — back into a number.
748    #[test]
749    fn parameters_carry_their_kind_and_numeric_coded_value() {
750        let model = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx").expect("parses");
751        let json = serde_json::to_value(&model).expect("serialises");
752
753        fn first_coded(node: &Value) -> Option<Value> {
754            for param in node["params"].as_array().into_iter().flatten() {
755                if param["codedValue"].is_number() {
756                    return Some(param.clone());
757                }
758            }
759            node["children"].as_array()?.iter().find_map(first_coded)
760        }
761        let param = json["roots"]
762            .as_array()
763            .expect("roots")
764            .iter()
765            .find_map(first_coded)
766            .expect("a parameter with a coded value");
767
768        // The rendering and the number agree, and the xsi:type is kept apart
769        // from SEMANTIC rather than collapsed into it.
770        assert_eq!(param["kind"], "CODED-CONST");
771        let coded = param["codedValue"].as_u64().expect("a number");
772        let rendered = param["value"].as_str().expect("a rendering");
773        assert_eq!(
774            u64::from_str_radix(rendered.trim_start_matches("0x"), 16).ok(),
775            Some(coded),
776            "{rendered} should render {coded}"
777        );
778    }
779
780    /// The counts a tool asserts a round-trip with, as numbers rather than as
781    /// the prose of `parser_info`.
782    #[test]
783    fn the_summary_agrees_with_what_the_tree_holds() {
784        let model = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx").expect("parses");
785
786        // The summary counts what the tree shows — each definition once, and
787        // only the diagnostic layers' — while `dops` inventories every
788        // DATA-OBJECT-PROP in the archive, including the two a comparam subset
789        // declares for its own parameters. The narrower number is the summary's.
790        assert!(
791            model.summary.dops <= model.dops.len(),
792            "summary {} vs index {}",
793            model.summary.dops,
794            model.dops.len()
795        );
796        assert!(model.summary.services > 0);
797        assert_eq!(model.summary.unreadable, 0, "the fixture is complete");
798        // The string is built from the same values, so it has to contain them.
799        assert!(
800            model
801                .parser_info
802                .contains(&format!("{} services", model.summary.services)),
803            "{}",
804            model.parser_info
805        );
806    }
807
808    /// Trouble codes as data: a program reading `dtcs` should not have to pull
809    /// the number back out of `"code (0x00C007)"`.
810    #[test]
811    fn trouble_codes_are_indexed_with_their_numeric_code() {
812        let model = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx").expect("parses");
813
814        assert_eq!(model.dtcs.len(), model.summary.dtcs);
815        let coded = model
816            .dtcs
817            .iter()
818            .find(|dtc| dtc.trouble_code.is_some())
819            .expect("a trouble code with a number");
820        assert!(!coded.short_name.is_empty());
821        assert!(
822            coded.dop.is_some(),
823            "each code names the DOP that declared it"
824        );
825    }
826
827    /// The ISO schema gives `ENV-DATA-DESC` a mandatory `ENV-DATA-REFS` list,
828    /// which is where the snapshot records recorded with a trouble code live.
829    #[test]
830    fn reads_environment_data_through_the_schema_wrapper() {
831        let document = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><ENV-DATAS><ENV-DATA ID="ED"><SHORT-NAME>Snapshot</SHORT-NAME><PARAMS><PARAM SEMANTIC="DATA" xsi:type="VALUE"><SHORT-NAME>Mileage</SHORT-NAME><BYTE-POSITION>0</BYTE-POSITION><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE"><BIT-LENGTH>16</BIT-LENGTH></DIAG-CODED-TYPE></PARAM></PARAMS></ENV-DATA></ENV-DATAS><ENV-DATA-DESCS><ENV-DATA-DESC ID="EDD"><SHORT-NAME>SnapshotDesc</SHORT-NAME><PARAM-SNREF SHORT-NAME="RecordNumber"/><ENV-DATA-REFS><ENV-DATA-REF ID-REF="ED"/></ENV-DATA-REFS></ENV-DATA-DESC></ENV-DATA-DESCS></DIAG-DATA-DICTIONARY-SPEC></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
832        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
833        let json = serde_json::to_value(parse(&bytes, "envdata.pdx").expect("parses"))
834            .expect("serialises");
835        let desc = find_in(&json, "SnapshotDesc");
836
837        assert_eq!(property(&desc, "ENV-DATAS").as_deref(), Some("1"));
838        assert_eq!(child_names(&desc), ["Snapshot"]);
839    }
840
841    /// A variant is selected by running a service and comparing one of its
842    /// output parameters against an expected value.
843    #[test]
844    fn reads_the_variant_selection_pattern() {
845        let document = r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><ECU-VARIANTS><ECU-VARIANT ID="EV"><SHORT-NAME>VariantA</SHORT-NAME><ECU-VARIANT-PATTERNS><ECU-VARIANT-PATTERN><MATCHING-PARAMETERS><MATCHING-PARAMETER><EXPECTED-VALUE>1234</EXPECTED-VALUE><DIAG-COMM-SNREF SHORT-NAME="ReadHwId"/><OUT-PARAM-IF-SNREF SHORT-NAME="HwId"/></MATCHING-PARAMETER></MATCHING-PARAMETERS></ECU-VARIANT-PATTERN></ECU-VARIANT-PATTERNS></ECU-VARIANT></ECU-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
846        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
847        let json = serde_json::to_value(parse(&bytes, "variant.pdx").expect("parses"))
848            .expect("serialises");
849        let variant = find_in(&json, "VariantA");
850        assert!(find(&variant, "Variant Patterns").is_some());
851        let pattern = find(&variant, "Pattern 1").expect("the pattern");
852
853        // The row reads "run ReadHwId, compare its HwId output against 1234".
854        assert_eq!(
855            property(pattern, "ReadHwId / HwId").as_deref(),
856            Some("1234")
857        );
858    }
859
860    /// A `PROTOCOL` layer binds to a stack that names the PDU protocol and
861    /// physical link its communication parameters are meant for.
862    #[test]
863    fn reads_the_protocol_stacks_of_a_comparam_spec() {
864        let document = r#"<ODX MODEL-VERSION="2.2.0"><COMPARAM-SPEC ID="CSPEC"><SHORT-NAME>Spec</SHORT-NAME><PROT-STACKS><PROT-STACK ID="PS"><SHORT-NAME>ISO_15765_3_on_ISO_15765_2</SHORT-NAME><PDU-PROTOCOL-TYPE>ISO_15765_3</PDU-PROTOCOL-TYPE><PHYSICAL-LINK-TYPE>ISO_11898_2_DWCAN</PHYSICAL-LINK-TYPE></PROT-STACK></PROT-STACKS></COMPARAM-SPEC></ODX>"#;
865        let bytes = crate::tests_support::zip_with(&[("Spec.odx-c", document)]);
866        let json =
867            serde_json::to_value(parse(&bytes, "spec.pdx").expect("parses")).expect("serialises");
868        let stack = find_in(&json, "ISO_15765_3_on_ISO_15765_2");
869
870        assert_eq!(
871            property(&stack, "PDU-PROTOCOL-TYPE").as_deref(),
872            Some("ISO_15765_3")
873        );
874        assert_eq!(
875            property(&stack, "PHYSICAL-LINK-TYPE").as_deref(),
876            Some("ISO_11898_2_DWCAN")
877        );
878    }
879
880    /// An encoder needs the conversion back from a physical value to the coded
881    /// one, which a method may state in `COMPU-PHYS-TO-INTERNAL`.
882    #[test]
883    fn indexes_the_inverse_conversion_direction() {
884        let document = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><DATA-OBJECT-PROPS><DATA-OBJECT-PROP ID="DOP"><SHORT-NAME>Temp</SHORT-NAME><COMPU-METHOD><CATEGORY>LINEAR</CATEGORY><COMPU-INTERNAL-TO-PHYS><COMPU-SCALES><COMPU-SCALE><COMPU-RATIONAL-COEFFS><COMPU-NUMERATOR><V>-40</V><V>1</V></COMPU-NUMERATOR><COMPU-DENOMINATOR><V>1</V></COMPU-DENOMINATOR></COMPU-RATIONAL-COEFFS></COMPU-SCALE></COMPU-SCALES></COMPU-INTERNAL-TO-PHYS><COMPU-PHYS-TO-INTERNAL><COMPU-SCALES><COMPU-SCALE><COMPU-RATIONAL-COEFFS><COMPU-NUMERATOR><V>40</V><V>1</V></COMPU-NUMERATOR><COMPU-DENOMINATOR><V>1</V></COMPU-DENOMINATOR></COMPU-RATIONAL-COEFFS></COMPU-SCALE></COMPU-SCALES></COMPU-PHYS-TO-INTERNAL></COMPU-METHOD><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE"><BIT-LENGTH>8</BIT-LENGTH></DIAG-CODED-TYPE><PHYSICAL-TYPE BASE-DATA-TYPE="A_INT32"/></DATA-OBJECT-PROP></DATA-OBJECT-PROPS></DIAG-DATA-DICTIONARY-SPEC></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
885        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
886        let model = parse(&bytes, "inverse.pdx").expect("parses");
887        let dop = &model.dops[0];
888
889        // −40 going out, +40 coming back.
890        assert_eq!(dop.scales[0].numerator, vec![-40.0, 1.0]);
891        assert_eq!(dop.inverse_scales[0].numerator, vec![40.0, 1.0]);
892    }
893
894    /// The ISO schema nests a complex comparam's members directly under it as
895    /// an unbounded choice, with no `COMPARAMS` wrapper to look inside.
896    #[test]
897    fn reads_complex_comparam_members_written_without_a_wrapper() {
898        let document = r#"<ODX MODEL-VERSION="2.2.0"><COMPARAM-SUBSET ID="CS"><SHORT-NAME>Subset</SHORT-NAME><COMPLEX-COMPARAMS><COMPLEX-COMPARAM ID="CCP" CPUSAGE="ECU-COMM"><SHORT-NAME>CP_Timing</SHORT-NAME><COMPARAM ID="CP1" CPUSAGE="ECU-COMM"><SHORT-NAME>CP_Session</SHORT-NAME><PHYSICAL-DEFAULT-VALUE>1</PHYSICAL-DEFAULT-VALUE></COMPARAM><COMPARAM ID="CP2" CPUSAGE="ECU-COMM"><SHORT-NAME>CP_P2</SHORT-NAME><PHYSICAL-DEFAULT-VALUE>50</PHYSICAL-DEFAULT-VALUE></COMPARAM><COMPLEX-PHYSICAL-DEFAULT-VALUE><COMPLEX-VALUES><COMPLEX-VALUE><SIMPLE-VALUE>1</SIMPLE-VALUE><SIMPLE-VALUE>50</SIMPLE-VALUE></COMPLEX-VALUE></COMPLEX-VALUES></COMPLEX-PHYSICAL-DEFAULT-VALUE></COMPLEX-COMPARAM></COMPLEX-COMPARAMS></COMPARAM-SUBSET></ODX>"#;
899        let bytes = crate::tests_support::zip_with(&[("Subset.odx-cs", document)]);
900        let json = serde_json::to_value(parse(&bytes, "complex.pdx").expect("parses"))
901            .expect("serialises");
902        let complex = find_in(&json, "CP_Timing");
903
904        assert_eq!(property(&complex, "NESTED COMPARAMS").as_deref(), Some("2"));
905        assert_eq!(
906            property(&complex, "COMPLEX-PHYSICAL-DEFAULT-VALUE").as_deref(),
907            Some("1, 50")
908        );
909        assert_eq!(child_names(&complex), ["CP_Session", "CP_P2"]);
910    }
911
912    /// A unit's SI conversion and the dimension it applies to exist nowhere
913    /// else, so resolving `UNIT-REF` to a display name loses them.
914    #[test]
915    fn reads_the_unit_spec_conversions_and_dimensions() {
916        let document = r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><UNIT-SPEC><UNITS><UNIT ID="U_KMH"><SHORT-NAME>Unit_kmh</SHORT-NAME><DISPLAY-NAME>km/h</DISPLAY-NAME><FACTOR-SI-TO-UNIT>0.2777777777777778</FACTOR-SI-TO-UNIT><OFFSET-SI-TO-UNIT>0</OFFSET-SI-TO-UNIT><PHYSICAL-DIMENSION-REF ID-REF="PD_V"/></UNIT></UNITS><PHYSICAL-DIMENSIONS><PHYSICAL-DIMENSION ID="PD_V"><SHORT-NAME>Velocity</SHORT-NAME><LENGTH-EXP>1</LENGTH-EXP><TIME-EXP>-1</TIME-EXP></PHYSICAL-DIMENSION></PHYSICAL-DIMENSIONS></UNIT-SPEC></DIAG-DATA-DICTIONARY-SPEC></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
917        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
918        let json =
919            serde_json::to_value(parse(&bytes, "units.pdx").expect("parses")).expect("serialises");
920
921        let unit = find_in(&json, "Unit_kmh");
922        assert_eq!(
923            property(&unit, "FACTOR-SI-TO-UNIT").as_deref(),
924            Some("0.2777777777777778")
925        );
926        assert_eq!(
927            property(&unit, "PHYSICAL-DIMENSION").as_deref(),
928            Some("Velocity")
929        );
930        // Velocity is length over time; both exponents have to survive.
931        let dimension = find_in(&json, "Velocity");
932        assert_eq!(property(&dimension, "LENGTH-EXP").as_deref(), Some("1"));
933        assert_eq!(property(&dimension, "TIME-EXP").as_deref(), Some("-1"));
934    }
935
936    /// A variable-length payload states bounds and a termination rule instead
937    /// of a bit length, so without them it reads back as a zero-bit row.
938    #[test]
939    fn reads_the_bounds_and_termination_of_a_variable_length_type() {
940        let document = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><DATA-OBJECT-PROPS><DATA-OBJECT-PROP ID="DOP"><SHORT-NAME>SeedBytes</SHORT-NAME><COMPU-METHOD><CATEGORY>IDENTICAL</CATEGORY></COMPU-METHOD><DIAG-CODED-TYPE BASE-DATA-TYPE="A_BYTEFIELD" xsi:type="MIN-MAX-LENGTH-TYPE" TERMINATION="END-OF-PDU"><MIN-LENGTH>1</MIN-LENGTH><MAX-LENGTH>16</MAX-LENGTH></DIAG-CODED-TYPE><PHYSICAL-TYPE BASE-DATA-TYPE="A_BYTEFIELD"/></DATA-OBJECT-PROP></DATA-OBJECT-PROPS></DIAG-DATA-DICTIONARY-SPEC></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
941        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
942        let json =
943            serde_json::to_value(parse(&bytes, "varlen.pdx").expect("parses")).expect("serialises");
944        let dop = find_in(&json, "SeedBytes");
945
946        assert_eq!(property(&dop, "MIN-LENGTH").as_deref(), Some("1"));
947        assert_eq!(property(&dop, "MAX-LENGTH").as_deref(), Some("16"));
948        assert_eq!(property(&dop, "TERMINATION").as_deref(), Some("END-OF-PDU"));
949    }
950
951    /// A constant conversion states a numeric value in `V` and a textual one in
952    /// `VT`; the machine-readable index has to carry both, plus the per-scale
953    /// label a producer round-trips its own descriptions through.
954    #[test]
955    fn indexes_numeric_compu_constants_and_scale_labels() {
956        let document = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><DATA-OBJECT-PROPS><DATA-OBJECT-PROP ID="DOP"><SHORT-NAME>Sna</SHORT-NAME><COMPU-METHOD><CATEGORY>SCALE-LINEAR</CATEGORY><COMPU-INTERNAL-TO-PHYS><COMPU-SCALES><COMPU-SCALE><SHORT-LABEL>NotAvailable</SHORT-LABEL><LOWER-LIMIT>255</LOWER-LIMIT><COMPU-CONST><V>-1</V></COMPU-CONST></COMPU-SCALE></COMPU-SCALES></COMPU-INTERNAL-TO-PHYS></COMPU-METHOD><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE"><BIT-LENGTH>8</BIT-LENGTH></DIAG-CODED-TYPE><PHYSICAL-TYPE BASE-DATA-TYPE="A_INT32"/></DATA-OBJECT-PROP></DATA-OBJECT-PROPS></DIAG-DATA-DICTIONARY-SPEC></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
957        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
958        let model = parse(&bytes, "compu.pdx").expect("parses");
959        let scale = &model.dops[0].scales[0];
960
961        assert_eq!(scale.const_value, Some(-1.0));
962        assert_eq!(scale.short_label.as_deref(), Some("NotAvailable"));
963    }
964
965    /// What identifies the vehicle, what a tester plugs into and what runs on
966    /// the wire all live in the vehicle-info document beside the logical links.
967    #[test]
968    fn reads_the_vehicle_information_topology() {
969        let document = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><VEHICLE-INFO-SPEC ID="VIS"><SHORT-NAME>Spec</SHORT-NAME><INFO-COMPONENTS><INFO-COMPONENT xsi:type="OEM" ID="IC_OEM"><SHORT-NAME>MANUFACTURER</SHORT-NAME><MATCHING-COMPONENTS><MATCHING-COMPONENT><EXPECTED-VALUE>ExampleOEM</EXPECTED-VALUE></MATCHING-COMPONENT></MATCHING-COMPONENTS></INFO-COMPONENT></INFO-COMPONENTS><VEHICLE-INFORMATIONS><VEHICLE-INFORMATION><SHORT-NAME>Car</SHORT-NAME><INFO-COMPONENT-REFS><INFO-COMPONENT-REF ID-REF="IC_OEM"/></INFO-COMPONENT-REFS><VEHICLE-CONNECTORS><VEHICLE-CONNECTOR ID="CONN"><SHORT-NAME>DLC</SHORT-NAME><VEHICLE-CONNECTOR-PINS><VEHICLE-CONNECTOR-PIN TYPE="SINGLE" ID="PIN6"><SHORT-NAME>CAN_H</SHORT-NAME><PIN-NUMBER>6</PIN-NUMBER></VEHICLE-CONNECTOR-PIN></VEHICLE-CONNECTOR-PINS></VEHICLE-CONNECTOR></VEHICLE-CONNECTORS><PHYSICAL-VEHICLE-LINKS><PHYSICAL-VEHICLE-LINK ID="PVL" TYPE="ISO_13400_2_DoIP"><SHORT-NAME>DoIP</SHORT-NAME><VEHICLE-CONNECTOR-PIN-REFS><VEHICLE-CONNECTOR-PIN-REF ID-REF="PIN6"/></VEHICLE-CONNECTOR-PIN-REFS></PHYSICAL-VEHICLE-LINK></PHYSICAL-VEHICLE-LINKS><LOGICAL-LINKS><LOGICAL-LINK xsi:type="GATEWAY-LOGICAL-LINK" ID="LL"><SHORT-NAME>LL_Gateway</SHORT-NAME><PHYSICAL-VEHICLE-LINK-REF ID-REF="PVL"/></LOGICAL-LINK></LOGICAL-LINKS></VEHICLE-INFORMATION></VEHICLE-INFORMATIONS></VEHICLE-INFO-SPEC></ODX>"#;
970        let bytes = crate::tests_support::zip_with(&[("Vehicle.odx-v", document)]);
971        let json = serde_json::to_value(parse(&bytes, "vehicle.pdx").expect("parses"))
972            .expect("serialises");
973        let car = find_in(&json, "Car");
974
975        assert!(find(&car, "Vehicle Identification").is_some());
976        // The identity a tester matches the vehicle on, resolved from the
977        // reference rather than left as a link.
978        let oem = find(&car, "MANUFACTURER").expect("info component");
979        assert_eq!(
980            property(oem, "EXPECTED-VALUE").as_deref(),
981            Some("ExampleOEM")
982        );
983        // The socket and the pin it offers.
984        let connector = find(&car, "DLC").expect("connector");
985        assert_eq!(
986            property(connector, "PIN 6").as_deref(),
987            Some("CAN_H (SINGLE)")
988        );
989        // The bus, named by the protocol that runs on it.
990        let physical = find(&car, "DoIP").expect("physical link");
991        assert_eq!(
992            property(physical, "TYPE").as_deref(),
993            Some("ISO_13400_2_DoIP")
994        );
995        // Reaching this ECU means going through a gateway.
996        let link = find(&car, "LL_Gateway").expect("logical link");
997        assert_eq!(
998            property(link, "TYPE").as_deref(),
999            Some("GATEWAY-LOGICAL-LINK")
1000        );
1001    }
1002
1003    /// `ADMIN-DATA` is the authorship and revision trail of a delivery.
1004    #[test]
1005    fn reads_the_admin_data_revision_trail() {
1006        let document = r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><ADMIN-DATA><LANGUAGE>en-US</LANGUAGE><DOC-REVISIONS><DOC-REVISION><REVISION-LABEL>0.1</REVISION-LABEL><STATE>DRAFT</STATE><DATE>2026-05-14T00:00:00</DATE><TOOL>udsdoc</TOOL></DOC-REVISION></DOC-REVISIONS></ADMIN-DATA></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
1007        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
1008        let json =
1009            serde_json::to_value(parse(&bytes, "admin.pdx").expect("parses")).expect("serialises");
1010        let base = find_in(&json, "Base");
1011
1012        assert_eq!(property(&base, "LANGUAGE").as_deref(), Some("en-US"));
1013        assert_eq!(
1014            property(&base, "DOC-REVISION").as_deref(),
1015            Some("0.1 · DRAFT · 2026-05-14T00:00:00 · udsdoc")
1016        );
1017    }
1018
1019    /// A flash session says how the ECU must be unlocked, and a segment says
1020    /// where its memory range ends as well as where it starts.
1021    #[test]
1022    fn reads_flash_security_and_the_segment_end_address() {
1023        let document = r#"<ODX MODEL-VERSION="2.2.0"><FLASH ID="F"><SHORT-NAME>Flash</SHORT-NAME><ECU-MEMS><ECU-MEM ID="EM"><SHORT-NAME>MainMemory</SHORT-NAME><MEM><SESSIONS><SESSION ID="S"><SHORT-NAME>Programming</SHORT-NAME><SECURITYS><SECURITY><SECURITY-METHOD>SEED_KEY</SECURITY-METHOD></SECURITY></SECURITYS></SESSION></SESSIONS><DATABLOCKS><DATABLOCK TYPE="FLASH-DATA" ID="DB"><SHORT-NAME>Block</SHORT-NAME><SEGMENTS><SEGMENT ID="SEG"><SHORT-NAME>ApplSeg1</SHORT-NAME><SOURCE-START-ADDRESS>100000</SOURCE-START-ADDRESS><SOURCE-END-ADDRESS>1FFFFF</SOURCE-END-ADDRESS></SEGMENT></SEGMENTS></DATABLOCK></DATABLOCKS></MEM></ECU-MEM></ECU-MEMS></FLASH></ODX>"#;
1024        let bytes = crate::tests_support::zip_with(&[("Flash.odx-f", document)]);
1025        let json =
1026            serde_json::to_value(parse(&bytes, "flash.pdx").expect("parses")).expect("serialises");
1027
1028        let session = find_in(&json, "Programming");
1029        assert_eq!(
1030            property(&session, "SECURITY-METHOD").as_deref(),
1031            Some("SEED_KEY")
1032        );
1033        let segment = find_in(&json, "ApplSeg1");
1034        assert_eq!(
1035            property(&segment, "SOURCE-END-ADDRESS").as_deref(),
1036            Some("1FFFFF")
1037        );
1038    }
1039
1040    /// ODX 2.2.0 repeats `TABLE-ROW` directly under `TABLE`; only some
1041    /// producers wrap the rows in `TABLE-ROWS`. Both shapes must read back.
1042    #[test]
1043    fn reads_table_rows_written_without_the_wrapper() {
1044        let rows = r#"<TABLE-ROW ID="TR1"><SHORT-NAME>Row_One</SHORT-NAME><KEY>1</KEY></TABLE-ROW><TABLE-ROW ID="TR2"><SHORT-NAME>Row_Two</SHORT-NAME><KEY>2</KEY></TABLE-ROW>"#;
1045        let document = format!(
1046            r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><TABLES><TABLE ID="TBL"><SHORT-NAME>Sessions</SHORT-NAME>{rows}</TABLE></TABLES></DIAG-DATA-DICTIONARY-SPEC></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#
1047        );
1048        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document.as_str())]);
1049        let json =
1050            serde_json::to_value(parse(&bytes, "tables.pdx").expect("parses")).expect("serialises");
1051        let table = find_in(&json, "Sessions");
1052
1053        assert_eq!(child_names(&table), ["Row_One", "Row_Two"]);
1054    }
1055
1056    /// No `AUDIENCE` element means no audience data — not five defaults.
1057    ///
1058    /// The three states a consumer must tell apart are "granted", "denied" and
1059    /// "not stated". Returning `Some(true)` for a service that says nothing
1060    /// would fold the third into the first and quietly assert something the
1061    /// document never claimed.
1062    #[test]
1063    fn a_service_without_an_audience_reports_none_rather_than_defaults() {
1064        let document = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>BV</SHORT-NAME><DIAG-COMMS><DIAG-SERVICE ID="SVC" ADDRESSING="PHYSICAL"><SHORT-NAME>Plain</SHORT-NAME></DIAG-SERVICE></DIAG-COMMS></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
1065        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
1066        let model = parse(&bytes, "plain.pdx").expect("parses");
1067
1068        let service = model
1069            .services
1070            .iter()
1071            .find(|service| service.short_name == "Plain")
1072            .expect("the service is indexed");
1073        assert!(
1074            service.audience.is_none(),
1075            "a service that states no audience must carry none: {:?}",
1076            service.audience
1077        );
1078    }
1079
1080    /// A `DOP-BASE` nothing references is still a definition, and the
1081    /// dictionary is allowed to hold one.
1082    ///
1083    /// The reader expands these where a parameter points at one, which covers
1084    /// every *use* — so for a long time listing them separately looked
1085    /// redundant. It is not: odxtools' somersault example defines exactly one
1086    /// `MUX` and references it nowhere, and this reader reported it in no form
1087    /// at all. That container is the first foreign data this crate was run
1088    /// against, and this was the first thing it found.
1089    #[test]
1090    fn a_multiplexer_no_parameter_references_is_still_listed() {
1091        let document = parse(
1092            include_bytes!("../tests/fixtures/DemoVehicle_Diagnostics.pdx"),
1093            "DemoVehicle_Diagnostics.pdx",
1094        )
1095        .expect("parses");
1096
1097        fn walk<'a>(node: &'a model::OdxNode, out: &mut Vec<&'a model::OdxNode>) {
1098            out.push(node);
1099            for child in &node.children {
1100                walk(child, out);
1101            }
1102        }
1103        let mut nodes = Vec::new();
1104        for root in &document.roots {
1105            walk(root, &mut nodes);
1106        }
1107
1108        let folder = nodes
1109            .iter()
1110            .find(|node| node.name == "Multiplexers")
1111            .expect("the dictionary's multiplexers must have a folder");
1112        assert!(!folder.children.is_empty(), "and it must not be empty");
1113        assert!(
1114            nodes
1115                .iter()
1116                .any(|node| node.badge.as_deref() == Some("END-OF-PDU-FIELD")),
1117            "the other DOP-BASE kinds are listed the same way"
1118        );
1119    }
1120
1121    /// A `DOP-REF` may name any `DOP-BASE`, and the demo container uses four
1122    /// of the kinds.
1123    ///
1124    /// `OdxDocument::dops` holds `DATA-OBJECT-PROP` alone, so a consumer
1125    /// joining against it finds nothing for the rest. Before `dop_kind` that
1126    /// was indistinguishable from a dangling reference, and the demo container
1127    /// has three such parameters.
1128    #[test]
1129    fn a_parameter_reports_which_kind_of_dop_it_names() {
1130        let document = parse(
1131            include_bytes!("../tests/fixtures/DemoVehicle_Diagnostics.pdx"),
1132            "DemoVehicle_Diagnostics.pdx",
1133        )
1134        .expect("parses");
1135
1136        fn walk<'a>(node: &'a model::OdxNode, out: &mut Vec<&'a model::OdxParam>) {
1137            out.extend(node.params.iter());
1138            for child in &node.children {
1139                walk(child, out);
1140            }
1141        }
1142        let mut params = Vec::new();
1143        for root in &document.roots {
1144            walk(root, &mut params);
1145        }
1146
1147        let kinds: std::collections::HashSet<&str> = params
1148            .iter()
1149            .filter(|p| p.dop_ref.is_some())
1150            .map(|p| {
1151                p.dop_kind
1152                    .as_deref()
1153                    .unwrap_or_else(|| panic!("{}: DOP-REF resolves to nothing", p.name))
1154            })
1155            .collect();
1156
1157        for expected in ["DATA-OBJECT-PROP", "STRUCTURE", "MUX", "END-OF-PDU-FIELD"] {
1158            assert!(kinds.contains(expected), "no {expected} seen in {kinds:?}");
1159        }
1160        // And the ones the index does not hold are visible as such rather than
1161        // as broken references.
1162        let indexed: std::collections::HashSet<&str> = document
1163            .dops
1164            .iter()
1165            .filter_map(|d| d.id.as_deref())
1166            .collect();
1167        let outside = params
1168            .iter()
1169            .filter(|p| {
1170                p.dop_kind
1171                    .as_deref()
1172                    .is_some_and(|k| k != "DATA-OBJECT-PROP")
1173            })
1174            .filter(|p| !indexed.contains(p.dop_ref.as_deref().unwrap_or_default()))
1175            .count();
1176        assert!(outside > 0, "the demo container has DOPs outside the index");
1177    }
1178
1179    /// `NRC-CONST` states its response codes in the mandatory `CODED-VALUES`
1180    /// list, not as a bare `CODED-VALUE` child the way `CODED-CONST` does.
1181    #[test]
1182    fn reads_negative_response_codes_from_the_coded_values_list() {
1183        let params = r#"<PARAM SEMANTIC="SERVICE-ID" xsi:type="CODED-CONST"><SHORT-NAME>SID</SHORT-NAME><BYTE-POSITION>0</BYTE-POSITION><CODED-VALUE>127</CODED-VALUE><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE"><BIT-LENGTH>8</BIT-LENGTH></DIAG-CODED-TYPE></PARAM><PARAM SEMANTIC="NRC" xsi:type="NRC-CONST"><SHORT-NAME>NRC</SHORT-NAME><BYTE-POSITION>2</BYTE-POSITION><CODED-VALUES><CODED-VALUE>19</CODED-VALUE><CODED-VALUE>49</CODED-VALUE></CODED-VALUES><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE"><BIT-LENGTH>8</BIT-LENGTH></DIAG-CODED-TYPE></PARAM>"#;
1184        let document = format!(
1185            r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><GLOBAL-NEG-RESPONSES><GLOBAL-NEG-RESPONSE ID="GNR"><SHORT-NAME>NegResponse</SHORT-NAME><PARAMS>{params}</PARAMS></GLOBAL-NEG-RESPONSE></GLOBAL-NEG-RESPONSES></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#
1186        );
1187        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document.as_str())]);
1188        let json =
1189            serde_json::to_value(parse(&bytes, "nrc.pdx").expect("parses")).expect("serialises");
1190        let response = find_in(&json, "NegResponse");
1191        let nrc = response["params"]
1192            .as_array()
1193            .expect("params array")
1194            .iter()
1195            .find(|param| param["name"] == "NRC")
1196            .expect("the NRC parameter");
1197
1198        // Both codes survive, rendered as the hex a tester reads them as.
1199        assert_eq!(nrc["value"], "0x13, 0x31");
1200
1201        // And as numbers, so checking which codes a service may return is a
1202        // set comparison rather than a parse of that rendering — whose
1203        // spelling is a presentation choice this crate is free to change.
1204        assert_eq!(nrc["codedValues"], serde_json::json!([19, 49]));
1205        // `codedValue` stays absent where there is a choice: no single value
1206        // represents the parameter.
1207        assert!(nrc["codedValue"].is_null());
1208
1209        // A parameter with exactly one coded value reports it both ways, so a
1210        // consumer can read `codedValues` uniformly.
1211        let sid = response["params"]
1212            .as_array()
1213            .expect("params array")
1214            .iter()
1215            .find(|param| param["name"] == "SID")
1216            .expect("the SID parameter");
1217        assert_eq!(sid["codedValue"], 127);
1218        assert_eq!(sid["codedValues"], serde_json::json!([127]));
1219    }
1220
1221    /// The layer-wide negative-response catalogue is not reachable from any
1222    /// service, so it only appears if the layer lists it.
1223    #[test]
1224    fn shows_the_layer_wide_global_negative_responses() {
1225        let document = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><GLOBAL-NEG-RESPONSES><GLOBAL-NEG-RESPONSE ID="GNR"><SHORT-NAME>GlobalNegResponse</SHORT-NAME><PARAMS><PARAM SEMANTIC="SERVICE-ID" xsi:type="CODED-CONST"><SHORT-NAME>SID</SHORT-NAME><BYTE-POSITION>0</BYTE-POSITION><CODED-VALUE>127</CODED-VALUE><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE"><BIT-LENGTH>8</BIT-LENGTH></DIAG-CODED-TYPE></PARAM></PARAMS></GLOBAL-NEG-RESPONSE></GLOBAL-NEG-RESPONSES></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
1226        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
1227        let json =
1228            serde_json::to_value(parse(&bytes, "global.pdx").expect("parses")).expect("serialises");
1229        let base = find_in(&json, "Base");
1230        let folder = find(&base, "Global Negative Responses").expect("folder");
1231
1232        assert_eq!(child_names(folder), ["GlobalNegResponse"]);
1233    }
1234
1235    #[test]
1236    fn dop_base_specializations_share_one_override_namespace() {
1237        let document = r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME><PROTOCOLS><PROTOCOL ID="P"><SHORT-NAME>Protocol</SHORT-NAME><DIAG-DATA-DICTIONARY-SPEC><DATA-OBJECT-PROPS><DATA-OBJECT-PROP ID="DOP"><SHORT-NAME>Shared</SHORT-NAME><COMPU-METHOD><CATEGORY>IDENTICAL</CATEGORY></COMPU-METHOD><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><BIT-LENGTH>8</BIT-LENGTH></DIAG-CODED-TYPE><PHYSICAL-TYPE BASE-DATA-TYPE="A_UINT32"/></DATA-OBJECT-PROP></DATA-OBJECT-PROPS></DIAG-DATA-DICTIONARY-SPEC></PROTOCOL></PROTOCOLS><BASE-VARIANTS><BASE-VARIANT ID="BV"><SHORT-NAME>Base</SHORT-NAME><PARENT-REFS><PARENT-REF ID-REF="P"/></PARENT-REFS><DIAG-DATA-DICTIONARY-SPEC><STRUCTURES><STRUCTURE ID="ST"><SHORT-NAME>Shared</SHORT-NAME><PARAMS><PARAM SEMANTIC="DATA" xsi:type="VALUE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SHORT-NAME>Value</SHORT-NAME><BYTE-POSITION>0</BYTE-POSITION><DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE"><BIT-LENGTH>8</BIT-LENGTH></DIAG-CODED-TYPE></PARAM></PARAMS></STRUCTURE></STRUCTURES></DIAG-DATA-DICTIONARY-SPEC></BASE-VARIANT></BASE-VARIANTS></DIAG-LAYER-CONTAINER></ODX>"#;
1238        let bytes = crate::tests_support::zip_with(&[("Layer.odx-d", document)]);
1239        let model = parse(&bytes, "namespace.pdx").expect("parses");
1240        let json = serde_json::to_value(model).expect("serialises");
1241        let base = find_in(&json, "Base");
1242        let structures = find(&base, "Structures").expect("structures folder");
1243
1244        assert_eq!(child_names(structures), ["Shared"]);
1245        assert!(find(&base, "Data Object Properties").is_none());
1246    }
1247
1248    #[test]
1249    fn inherits_communication_parameters_from_the_protocol() {
1250        let model = parsed();
1251        let base = find_in(&model, "Engine Management System");
1252        let comparams = find(&base, "Communication Parameters").expect("comparams folder");
1253        // Declared by the base variant itself.
1254        assert_eq!(
1255            property(comparams, "CP_CanPhysReqId").as_deref(),
1256            Some("2016")
1257        );
1258        // Reached through PARENT-REF, and tagged with where it came from.
1259        assert_eq!(
1260            property(comparams, "CP_Baudrate").as_deref(),
1261            Some("500000  ↑ UDS_on_CAN")
1262        );
1263    }
1264
1265    // ---- complex parameters ------------------------------------------
1266
1267    #[test]
1268    fn expands_structures_below_the_parameter_that_uses_them() {
1269        let model = parsed();
1270        let service = find_in(&model, "ReadDataByIdentifier coolant temperature");
1271        let response = &service["children"][1];
1272        let rows = rows(response);
1273        let shape: Vec<(u64, &str, u64)> = rows
1274            .iter()
1275            .map(|(depth, name, byte, _)| (*depth, name.as_str(), *byte))
1276            .collect();
1277
1278        assert_eq!(
1279            shape,
1280            [
1281                (0, "SID_PR", 0),
1282                (0, "Did", 1),
1283                (0, "CoolantRecord", 3),
1284                // The structure's own parameter, offset by the parent position.
1285                (1, "Temperature", 3),
1286            ]
1287        );
1288        // The reference itself carries the size of the structure it points at.
1289        assert_eq!(
1290            property(response, "CODED BYTE LENGTH").as_deref(),
1291            Some("4")
1292        );
1293    }
1294
1295    #[test]
1296    fn shows_the_layout_on_the_parameter_node_too() {
1297        let model = parsed();
1298        let service = find_in(&model, "ReadDataByIdentifier coolant temperature");
1299        let param = &service["children"][1]["children"][2];
1300        assert_eq!(param["name"], "CoolantRecord");
1301        assert_eq!(
1302            rows(param)
1303                .iter()
1304                .map(|(_, name, ..)| name.clone())
1305                .collect::<Vec<_>>(),
1306            ["Temperature".to_owned()]
1307        );
1308    }
1309
1310    #[test]
1311    fn expands_multiplexer_cases_into_the_byte_layout() {
1312        let model = parsed();
1313        let service = find_in(&model, "RoutineControl self test");
1314        let response = &service["children"][1];
1315        assert_eq!(response["shortName"], "PR_SelfTest");
1316
1317        let rows = rows(response);
1318        let shape: Vec<(u64, &str, u64)> = rows
1319            .iter()
1320            .map(|(depth, name, byte, _)| (*depth, name.as_str(), *byte))
1321            .collect();
1322
1323        assert_eq!(
1324            shape,
1325            [
1326                (0, "SID_PR", 0),
1327                (0, "RoutineControlType", 1),
1328                (0, "RoutineIdentifier", 2),
1329                (0, "Result", 4),
1330                (1, "SWITCH-KEY", 4),
1331                (1, "Passed", 4),
1332                (2, "Duration", 4),
1333                (2, "PeakEngineSpeed", 6),
1334                (1, "Failed", 4),
1335                (2, "FailureCode", 4),
1336                (1, "Unknown", 4),
1337                (2, "FailureCode", 4),
1338            ]
1339        );
1340        // The case rows explain which key selects which structure.
1341        assert_eq!(rows[5].3, "key 0 → STRUCT_TestPassed");
1342        assert_eq!(rows[8].3, "key 1..255 → STRUCT_TestFailed");
1343    }
1344
1345    #[test]
1346    fn expands_end_of_pdu_fields_as_a_repeating_item() {
1347        let model = parsed();
1348        let service = find_in(&model, "ReadDTCInformation by status mask");
1349        let response = &service["children"][1];
1350        let rows = rows(response);
1351        let shape: Vec<(u64, &str, u64)> = rows
1352            .iter()
1353            .map(|(depth, name, byte, _)| (*depth, name.as_str(), *byte))
1354            .collect();
1355
1356        assert_eq!(
1357            shape,
1358            [
1359                (0, "SID_PR", 0),
1360                (0, "ReportType", 1),
1361                (0, "StatusAvailabilityMask", 2),
1362                (0, "DtcList", 3),
1363                (1, "STRUCT_DtcAndStatus [item]", 3),
1364                (2, "DtcCode", 3),
1365                (2, "StatusOfDtc", 6),
1366            ]
1367        );
1368        assert_eq!(rows[4].3, "repeats 0.. times, until the end of the PDU");
1369    }
1370
1371    #[test]
1372    fn annotates_table_key_and_table_struct_parameters() {
1373        let model = parsed();
1374        let service = find_in(&model, "ReadDataByIdentifier table driven");
1375        let response = &service["children"][1];
1376        let rows = rows(response);
1377
1378        assert_eq!(rows[1].1, "DidKey");
1379        assert_eq!(rows[1].3, "selects one of 2 rows of TABLE_DataIdentifiers");
1380        assert_eq!(rows[2].1, "DidRecord");
1381        assert_eq!(rows[2].3, "row selected by DidKey");
1382    }
1383
1384    #[test]
1385    fn lists_tables_with_their_rows() {
1386        let model = parsed();
1387        let table = find_in(&model, "Data identifier lookup");
1388        assert_eq!(table["kind"], "table");
1389        assert_eq!(
1390            property(&table, "KEY-DOP").as_deref(),
1391            Some("DOP_DataIdentifier")
1392        );
1393
1394        let names = child_names(&table);
1395        assert_eq!(names.len(), 2);
1396        let row = &table["children"][0];
1397        assert_eq!(row["kind"], "structure");
1398        assert_eq!(property(row, "KEY").as_deref(), Some("61840 (0xF190)"));
1399        assert_eq!(
1400            property(row, "STRUCTURE").as_deref(),
1401            Some("STRUCT_VinRecord")
1402        );
1403    }
1404
1405    #[test]
1406    fn lists_structures_of_a_layer() {
1407        let model = parsed();
1408        let base = find_in(&model, "Engine Management System");
1409        let structures = find(&base, "Structures").expect("structures folder");
1410        assert_eq!(structures["badge"], "4");
1411        let passed = find(structures, "Self test passed").expect("structure node");
1412        assert_eq!(passed["kind"], "structure");
1413        assert_eq!(
1414            rows(passed)
1415                .iter()
1416                .map(|(_, name, byte, _)| (name.clone(), *byte))
1417                .collect::<Vec<_>>(),
1418            [
1419                ("Duration".to_owned(), 0),
1420                ("PeakEngineSpeed".to_owned(), 2)
1421            ]
1422        );
1423    }
1424
1425    #[test]
1426    fn computes_the_byte_length_of_a_structure_reference() {
1427        let model = parsed();
1428        let service = find_in(&model, "RoutineControl self test");
1429        let request = &service["children"][0];
1430        assert_eq!(property(request, "CODED BYTE LENGTH").as_deref(), Some("4"));
1431    }
1432
1433    // ---- inheritance refinements --------------------------------------
1434
1435    #[test]
1436    fn ranks_parent_layers_the_way_odx_does() {
1437        let model = parsed();
1438        let variant = find_in(&model, "Engine Management System EU6");
1439        let dops = find(&variant, "Data Object Properties").expect("dops folder");
1440
1441        // Both parents define DOP_DataIdentifier and the weaker one is listed
1442        // first, so document order alone would pick the protocol.
1443        let names = child_names(dops);
1444        assert!(names.contains(&"Data identifier".to_owned()), "{names:?}");
1445        assert!(
1446            !names.contains(&"Data identifier (protocol default)".to_owned()),
1447            "{names:?}"
1448        );
1449
1450        let winner = dops["children"]
1451            .as_array()
1452            .expect("children")
1453            .iter()
1454            .find(|child| child["name"] == "Data identifier")
1455            .expect("the inherited DOP");
1456        assert_eq!(winner["origin"], "EMS_ECU");
1457    }
1458
1459    #[test]
1460    fn marks_a_local_definition_that_shadows_an_inherited_one() {
1461        let model = parsed();
1462        let variant = find_in(&model, "Engine Management System EU6");
1463        let services = find(&variant, "Diagnostic Services").expect("services folder");
1464
1465        let override_node = services["children"]
1466            .as_array()
1467            .expect("children")
1468            .iter()
1469            .find(|child| child["shortName"] == "DiagnosticSessionControl")
1470            .expect("the redefined service");
1471        assert_eq!(override_node["name"], "Start extended session (EU6 timing)");
1472        assert!(override_node["origin"].is_null());
1473        assert_eq!(override_node["overrides"], "EMS_ECU");
1474
1475        assert_eq!(
1476            property(&variant, "OVERRIDDEN ELEMENTS").as_deref(),
1477            Some("1")
1478        );
1479        // The shadowed definition is gone, not listed twice.
1480        assert_eq!(
1481            child_names(services)
1482                .iter()
1483                .filter(|name| name.starts_with("Start extended session"))
1484                .count(),
1485            1
1486        );
1487    }
1488
1489    // ---- single ECU jobs ----------------------------------------------
1490
1491    #[test]
1492    fn reads_single_ecu_jobs_with_their_program_code() {
1493        let model = parsed();
1494        let job = find_in(&model, "Read freeze frame");
1495        assert_eq!(job["kind"], "job");
1496        assert_eq!(job["shortName"], "JOB_ReadFreezeFrame");
1497        assert_eq!(
1498            property(&job, "CODE-FILE").as_deref(),
1499            Some("jobs/ReadFreezeFrame.jar")
1500        );
1501        assert_eq!(property(&job, "SYNTAX").as_deref(), Some("JAVA"));
1502        assert_eq!(
1503            property(&job, "ENTRYPOINT").as_deref(),
1504            Some("com.demomotors.jobs.ReadFreezeFrame")
1505        );
1506
1507        let rows = rows(&job);
1508        assert_eq!(rows.len(), 2);
1509        assert_eq!(rows[0].1, "RecordNumber");
1510        assert_eq!(rows[0].3, "1");
1511        assert_eq!(rows[1].1, "Snapshot");
1512        // Job parameters are logical values, so they carry no byte position.
1513        assert!(job["params"][0]["bytePosition"].is_null());
1514    }
1515
1516    #[test]
1517    fn a_job_is_inherited_like_a_service() {
1518        let model = parsed();
1519        let variant = find_in(&model, "Engine Management System EU6");
1520        let services = find(&variant, "Diagnostic Services").expect("services folder");
1521        let job = services["children"]
1522            .as_array()
1523            .expect("children")
1524            .iter()
1525            .find(|child| child["kind"] == "job")
1526            .expect("the inherited job");
1527        assert_eq!(job["origin"], "EMS_ECU");
1528    }
1529
1530    // ---- environment data ---------------------------------------------
1531
1532    #[test]
1533    fn reads_environment_data_descriptions() {
1534        let model = parsed();
1535        let description = find_in(&model, "Freeze frame");
1536        assert_eq!(description["kind"], "envData");
1537        assert_eq!(
1538            property(&description, "SELECTED BY").as_deref(),
1539            Some("RecordNumber")
1540        );
1541
1542        let names = child_names(&description);
1543        assert_eq!(names, ["Engine snapshot", "Generic snapshot"]);
1544
1545        let engine = &description["children"][0];
1546        assert_eq!(
1547            property(engine, "DTC-VALUES").as_deref(),
1548            Some("65558, 66049")
1549        );
1550        assert_eq!(
1551            rows(engine)
1552                .iter()
1553                .map(|(_, name, byte, _)| (name.clone(), *byte))
1554                .collect::<Vec<_>>(),
1555            [
1556                ("EngineSpeed".to_owned(), 0),
1557                ("CoolantTemperature".to_owned(), 2)
1558            ]
1559        );
1560
1561        let generic = &description["children"][1];
1562        assert_eq!(
1563            property(generic, "APPLIES TO").as_deref(),
1564            Some("every trouble code")
1565        );
1566    }
1567
1568    #[test]
1569    fn expands_environment_data_behind_a_job_output() {
1570        let model = parsed();
1571        // The job's output points at the description, so the parameter node
1572        // shows every snapshot it may return.
1573        let job = find_in(&model, "Read freeze frame");
1574        let output = job["children"]
1575            .as_array()
1576            .expect("children")
1577            .iter()
1578            .find(|child| child["name"] == "Snapshot")
1579            .expect("the output parameter");
1580        assert_eq!(
1581            property(output, "DOP-BASE-REF").as_deref(),
1582            Some("ENVDESC_FreezeFrame")
1583        );
1584    }
1585
1586    #[test]
1587    fn expands_environment_data_referenced_by_a_parameter() {
1588        // A parameter pointing at the description lists each snapshot and the
1589        // trouble codes it belongs to.
1590        let container = crate::tests_support::zip_with(&[(
1591            "Env.odx-d",
1592            r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
1593                 <DIAG-LAYER-CONTAINER ID="DLC">
1594                   <SHORT-NAME>DLC</SHORT-NAME>
1595                   <ECU-VARIANTS><ECU-VARIANT ID="EV">
1596                     <SHORT-NAME>EV</SHORT-NAME>
1597                     <DIAG-DATA-DICTIONARY-SPEC>
1598                       <ENV-DATA-DESCS><ENV-DATA-DESC ID="ED">
1599                         <SHORT-NAME>ED</SHORT-NAME>
1600                         <ENV-DATAS><ENV-DATA ID="E1">
1601                           <SHORT-NAME>Snapshot</SHORT-NAME>
1602                           <PARAMS><PARAM SEMANTIC="DATA" xsi:type="CODED-CONST">
1603                             <SHORT-NAME>Marker</SHORT-NAME>
1604                             <BYTE-POSITION>0</BYTE-POSITION>
1605                             <CODED-VALUE>7</CODED-VALUE>
1606                             <DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE">
1607                               <BIT-LENGTH>8</BIT-LENGTH>
1608                             </DIAG-CODED-TYPE>
1609                           </PARAM></PARAMS>
1610                           <DTC-VALUES><DTC-VALUE>42</DTC-VALUE></DTC-VALUES>
1611                         </ENV-DATA></ENV-DATAS>
1612                       </ENV-DATA-DESC></ENV-DATA-DESCS>
1613                     </DIAG-DATA-DICTIONARY-SPEC>
1614                     <DIAG-COMMS><DIAG-SERVICE ID="S"><SHORT-NAME>S</SHORT-NAME>
1615                       <REQUEST-REF ID-REF="RQ"/>
1616                     </DIAG-SERVICE></DIAG-COMMS>
1617                     <REQUESTS><REQUEST ID="RQ"><SHORT-NAME>RQ</SHORT-NAME>
1618                       <PARAMS><PARAM SEMANTIC="DATA" xsi:type="VALUE">
1619                         <SHORT-NAME>Frame</SHORT-NAME>
1620                         <BYTE-POSITION>2</BYTE-POSITION>
1621                         <DOP-REF ID-REF="ED"/>
1622                       </PARAM></PARAMS>
1623                     </REQUEST></REQUESTS>
1624                   </ECU-VARIANT></ECU-VARIANTS>
1625                 </DIAG-LAYER-CONTAINER>
1626               </ODX>"#,
1627        )]);
1628
1629        let document = parse(&container, "env.pdx").expect("parses");
1630        let json = serde_json::to_value(&document).expect("serialises");
1631        let request = find_in(&json, "RQ");
1632
1633        assert_eq!(
1634            rows(&request)
1635                .iter()
1636                .map(|(depth, name, byte, value)| (*depth, name.clone(), *byte, value.clone()))
1637                .collect::<Vec<_>>(),
1638            [
1639                (0, "Frame".to_owned(), 2, "ED".to_owned()),
1640                (
1641                    1,
1642                    "Snapshot".to_owned(),
1643                    2,
1644                    "recorded for DTC 42".to_owned()
1645                ),
1646                (2, "Marker".to_owned(), 2, "0x07".to_owned()),
1647            ]
1648        );
1649    }
1650
1651    // ---- flash containers ----------------------------------------------
1652
1653    #[test]
1654    fn reads_flash_containers() {
1655        let model = parsed();
1656        let flash = find_in(&model, "Demo Vehicle flash data");
1657        assert_eq!(flash["kind"], "flash");
1658
1659        let memory = &flash["children"][0];
1660        assert_eq!(memory["shortName"], "ECUMEM_EMS");
1661        assert_eq!(property(memory, "DATABLOCKS").as_deref(), Some("2"));
1662
1663        let session = find(memory, "Full reprogramming").expect("session node");
1664        // Both referenced blocks are resolved to their short names.
1665        let blocks: Vec<String> = session["properties"]
1666            .as_array()
1667            .expect("properties")
1668            .iter()
1669            .filter(|row| row["name"] == "DATABLOCK")
1670            .map(|row| row["value"].as_str().unwrap_or_default().to_owned())
1671            .collect();
1672        assert_eq!(blocks, ["BLOCK_Driver", "BLOCK_Application"]);
1673        assert_eq!(
1674            property(session, "HardwareNumber").as_deref(),
1675            Some("EMS-HW-04, EMS-HW-05")
1676        );
1677    }
1678
1679    #[test]
1680    fn reads_data_blocks_and_their_segments() {
1681        let model = parsed();
1682        let block = find_in(&model, "Application software");
1683        assert_eq!(block["kind"], "dataBlock");
1684        assert_eq!(block["badge"], "FLASH-DATA");
1685        assert_eq!(
1686            property(&block, "FLASHDATA").as_deref(),
1687            Some("FLASHDATA_Application")
1688        );
1689
1690        let segments = child_names(&block);
1691        assert_eq!(segments.len(), 2);
1692        let first = &block["children"][0];
1693        assert_eq!(first["kind"], "segment");
1694        assert_eq!(
1695            property(first, "SOURCE-START-ADDRESS").as_deref(),
1696            Some("0x08010000")
1697        );
1698        assert_eq!(
1699            property(first, "UNCOMPRESSED-SIZE").as_deref(),
1700            Some("458752")
1701        );
1702    }
1703
1704    #[test]
1705    fn reads_intern_and_extern_flash_data() {
1706        let model = parsed();
1707        let extern_data = find_in(&model, "Application image");
1708        assert_eq!(
1709            property(&extern_data, "KIND").as_deref(),
1710            Some("EXTERN-FLASHDATA")
1711        );
1712        assert_eq!(
1713            property(&extern_data, "DATAFILE").as_deref(),
1714            Some("flash/EMS_Application_1_4_0.hex")
1715        );
1716        assert_eq!(
1717            property(&extern_data, "DATAFORMAT").as_deref(),
1718            Some("INTEL-HEX")
1719        );
1720
1721        let intern_data = find_in(&model, "Flash driver image");
1722        assert_eq!(
1723            property(&intern_data, "KIND").as_deref(),
1724            Some("INTERN-FLASHDATA")
1725        );
1726        assert_eq!(
1727            property(&intern_data, "INLINE DATA").as_deref(),
1728            Some("32 character(s)")
1729        );
1730    }
1731
1732    // ---- communication parameter definitions ---------------------------
1733
1734    #[test]
1735    fn resolves_communication_parameters_against_their_subset() {
1736        let model = parsed();
1737        let base = find_in(&model, "Engine Management System");
1738        let folder = find(&base, "Communication Parameters").expect("comparams folder");
1739
1740        let node = folder["children"]
1741            .as_array()
1742            .expect("children")
1743            .iter()
1744            .find(|child| child["shortName"] == "CP_CanPhysReqId")
1745            .expect("the comparam node");
1746
1747        // The subset supplies the readable name and everything around it.
1748        assert_eq!(node["kind"], "comparam");
1749        assert_eq!(node["name"], "CAN physical request identifier");
1750        assert_eq!(node["badge"], "2016");
1751        assert_eq!(property(node, "VALUE").as_deref(), Some("2016"));
1752        assert_eq!(
1753            property(node, "PHYSICAL-DEFAULT-VALUE").as_deref(),
1754            Some("2016")
1755        );
1756        assert_eq!(property(node, "AT DEFAULT").as_deref(), Some("yes"));
1757        assert_eq!(
1758            property(node, "PARAM-CLASS").as_deref(),
1759            Some("UNIQUE_IDENTIFIER")
1760        );
1761        assert_eq!(property(node, "DEFINED BY").as_deref(), Some("this layer"));
1762    }
1763
1764    #[test]
1765    fn shows_the_unit_of_a_timing_parameter() {
1766        let model = parsed();
1767        let base = find_in(&model, "Engine Management System");
1768        let folder = find(&base, "Communication Parameters").expect("comparams folder");
1769        let node = folder["children"]
1770            .as_array()
1771            .expect("children")
1772            .iter()
1773            .find(|child| child["shortName"] == "CP_P2Max")
1774            .expect("the timing comparam");
1775
1776        assert_eq!(node["origin"], "UDS_on_CAN");
1777        assert_eq!(property(node, "UNIT").as_deref(), Some("ms"));
1778        assert_eq!(property(node, "CPUSAGE").as_deref(), Some("TESTER"));
1779    }
1780
1781    #[test]
1782    fn lists_comparam_subsets_including_complex_ones() {
1783        let model = parsed();
1784        let subset = find_in(&model, "UDS on CAN communication parameters");
1785        assert_eq!(
1786            property(&subset, "CATEGORY").as_deref(),
1787            Some("ISO_15765_3")
1788        );
1789        assert_eq!(property(&subset, "COMPARAMS").as_deref(), Some("7"));
1790
1791        let complex = find(&subset, "Transport layer timing").expect("complex comparam");
1792        assert_eq!(complex["kind"], "comparam");
1793        assert_eq!(property(complex, "NESTED COMPARAMS").as_deref(), Some("2"));
1794        assert_eq!(child_names(complex), ["Block size", "Separation time"]);
1795    }
1796
1797    #[test]
1798    fn says_when_a_comparam_definition_is_missing() {
1799        // A container without the subset still shows the value, and says why
1800        // there is nothing more to show.
1801        let container = crate::tests_support::zip_with(&[(
1802            "L.odx-d",
1803            r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="C">
1804                 <SHORT-NAME>C</SHORT-NAME>
1805                 <PROTOCOLS><PROTOCOL ID="P"><SHORT-NAME>P</SHORT-NAME>
1806                   <COMPARAM-REFS>
1807                     <COMPARAM-REF ID-REF="ISO.CP_Missing"><VALUE>7</VALUE></COMPARAM-REF>
1808                   </COMPARAM-REFS>
1809                 </PROTOCOL></PROTOCOLS>
1810               </DIAG-LAYER-CONTAINER></ODX>"#,
1811        )]);
1812        let document = parse(&container, "c.pdx").expect("parses");
1813        let json = serde_json::to_value(&document).expect("serialises");
1814        let node = find_in(&json, "CP_Missing");
1815        assert_eq!(property(&node, "VALUE").as_deref(), Some("7"));
1816        assert_eq!(
1817            property(&node, "DEFINITION").as_deref(),
1818            Some("not in this container (comparam subset missing)")
1819        );
1820    }
1821
1822    // ---- multiple ECU jobs and the function dictionary ------------------
1823
1824    #[test]
1825    fn reads_multiple_ecu_jobs_with_the_layers_they_drive() {
1826        let model = parsed();
1827        let job = find_in(&model, "Clear all trouble codes");
1828        assert_eq!(job["kind"], "job");
1829        assert_eq!(job["badge"], "multi-ECU job");
1830        assert_eq!(
1831            property(&job, "ENTRYPOINT").as_deref(),
1832            Some("com.demomotors.jobs.ClearAllDtcs")
1833        );
1834
1835        let layers: Vec<String> = job["properties"]
1836            .as_array()
1837            .expect("properties")
1838            .iter()
1839            .filter(|row| row["name"] == "DIAG-LAYER")
1840            .map(|row| row["value"].as_str().unwrap_or_default().to_owned())
1841            .collect();
1842        assert_eq!(layers, ["EMS_ECU", "BCM_ECU"]);
1843        assert_eq!(rows(&job).len(), 2);
1844    }
1845
1846    #[test]
1847    fn reads_the_function_dictionary_as_a_tree() {
1848        let model = parsed();
1849        let powertrain = find_in(&model, "Powertrain");
1850        assert_eq!(child_names(&powertrain), ["Identification", "Fault memory"]);
1851
1852        let faults = &powertrain["children"][1];
1853        let comms: Vec<String> = faults["properties"]
1854            .as_array()
1855            .expect("properties")
1856            .iter()
1857            .filter(|row| row["name"] == "DIAG-COMM")
1858            .map(|row| row["value"].as_str().unwrap_or_default().to_owned())
1859            .collect();
1860        // Both a service and a job are reachable from one function node.
1861        assert_eq!(comms, ["RDTCI_ByStatusMask", "JOB_ReadFreezeFrame"]);
1862    }
1863
1864    // ---- state charts and special data ---------------------------------
1865
1866    #[test]
1867    fn reads_state_charts_with_their_states_and_transitions() {
1868        let model = parsed();
1869        let chart = find_in(&model, "Diagnostic session");
1870        assert_eq!(chart["kind"], "state");
1871        assert_eq!(chart["badge"], "2 states");
1872        assert_eq!(property(&chart, "SEMANTIC").as_deref(), Some("SESSION"));
1873        assert_eq!(property(&chart, "START-STATE").as_deref(), Some("Default"));
1874        assert_eq!(
1875            property(&chart, "ST_ToExtended").as_deref(),
1876            Some("Default → Extended")
1877        );
1878        assert_eq!(
1879            child_names(&chart),
1880            ["Default session", "Extended diagnostic session"]
1881        );
1882        assert_eq!(chart["children"][0]["kind"], "state");
1883    }
1884
1885    #[test]
1886    fn reports_the_states_a_service_needs_and_causes() {
1887        let model = parsed();
1888        let session = find_in(&model, "Start extended session");
1889        assert_eq!(
1890            property(&session, "STATE-TRANSITION").as_deref(),
1891            Some("ST_ToExtended (Default → Extended)")
1892        );
1893
1894        let read_vin = find_in(&model, "ReadDataByIdentifier VIN");
1895        assert_eq!(
1896            property(&read_vin, "PRE-CONDITION-STATE").as_deref(),
1897            Some("Extended")
1898        );
1899    }
1900
1901    #[test]
1902    fn lists_the_function_classes_of_a_layer() {
1903        let model = parsed();
1904        let base = find_in(&model, "Engine Management System");
1905        let classes = find(&base, "Function Classes").expect("function classes folder");
1906        assert_eq!(child_names(classes), ["Identification", "Fault memory"]);
1907
1908        // The reference on the service resolves to the same definition.
1909        let service = find_in(&model, "ReadDataByIdentifier VIN");
1910        assert_eq!(
1911            property(&service, "FUNCT-CLASS").as_deref(),
1912            Some("FC_Identification")
1913        );
1914    }
1915
1916    #[test]
1917    fn flattens_special_data_groups_wherever_they_appear() {
1918        let model = parsed();
1919        let service = find_in(&model, "ReadDataByIdentifier VIN");
1920        assert_eq!(
1921            property(&service, "VendorInfo / Author").as_deref(),
1922            Some("Demo Motors diagnostics")
1923        );
1924        assert_eq!(
1925            property(&service, "VendorInfo / Revision").as_deref(),
1926            Some("3")
1927        );
1928        // Nested groups keep the path of the group they sit in.
1929        assert_eq!(
1930            property(&service, "VendorInfo / Tooling / MinimumTesterVersion").as_deref(),
1931            Some("4.2")
1932        );
1933
1934        let dtc = find_in(&model, "P0116 — Coolant temperature circuit range");
1935        assert_eq!(
1936            property(&dtc, "DtcInfo / WarningLamp").as_deref(),
1937            Some("MIL")
1938        );
1939        assert_eq!(property(&dtc, "DtcInfo / TripCount").as_deref(), Some("2"));
1940    }
1941
1942    #[test]
1943    fn reports_documents_it_cannot_read() {
1944        // A container whose only document is malformed still parses, but the
1945        // problem is surfaced instead of silently dropped.
1946        let broken = crate::tests_support::zip_with(&[("broken.odx-d", "<ODX><UNCLOSED>")]);
1947        let document = parse(&broken, "broken.pdx").expect("container still opens");
1948        let json = serde_json::to_value(&document).expect("serialises");
1949        let problems = find(&json["roots"][0], "Problems").expect("problems node");
1950        assert_eq!(problems["badge"], "1");
1951    }
1952
1953    // ---- bit positions -------------------------------------------------
1954
1955    /// Two four-bit fields packed into byte 6, plus a plain byte parameter
1956    /// that leaves `BIT-POSITION` to the ODX default.
1957    const PACKED: &str = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
1958         <DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME>
1959           <ECU-VARIANTS><ECU-VARIANT ID="EV"><SHORT-NAME>EV</SHORT-NAME>
1960             <DIAG-DATA-DICTIONARY-SPEC><DATA-OBJECT-PROPS>
1961               <DATA-OBJECT-PROP ID="DOP_Nibble"><SHORT-NAME>DOP_Nibble</SHORT-NAME>
1962                 <COMPU-METHOD><CATEGORY>IDENTICAL</CATEGORY></COMPU-METHOD>
1963                 <DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE">
1964                   <BIT-LENGTH>4</BIT-LENGTH>
1965                 </DIAG-CODED-TYPE>
1966                 <PHYSICAL-TYPE BASE-DATA-TYPE="A_UINT32"/>
1967               </DATA-OBJECT-PROP>
1968               <DATA-OBJECT-PROP ID="DOP_Byte"><SHORT-NAME>DOP_Byte</SHORT-NAME>
1969                 <COMPU-METHOD><CATEGORY>IDENTICAL</CATEGORY></COMPU-METHOD>
1970                 <DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE">
1971                   <BIT-LENGTH>8</BIT-LENGTH>
1972                 </DIAG-CODED-TYPE>
1973                 <PHYSICAL-TYPE BASE-DATA-TYPE="A_UINT32"/>
1974               </DATA-OBJECT-PROP>
1975             </DATA-OBJECT-PROPS></DIAG-DATA-DICTIONARY-SPEC>
1976             <DIAG-COMMS><DIAG-SERVICE ID="S"><SHORT-NAME>S</SHORT-NAME>
1977               <REQUEST-REF ID-REF="RQ"/>
1978             </DIAG-SERVICE></DIAG-COMMS>
1979             <REQUESTS><REQUEST ID="RQ"><SHORT-NAME>RQ</SHORT-NAME><PARAMS>
1980               <PARAM SEMANTIC="DATA" xsi:type="VALUE"><SHORT-NAME>Plain</SHORT-NAME>
1981                 <BYTE-POSITION>0</BYTE-POSITION><DOP-REF ID-REF="DOP_Byte"/>
1982               </PARAM>
1983               <PARAM SEMANTIC="DATA" xsi:type="VALUE"><SHORT-NAME>LowNibble</SHORT-NAME>
1984                 <BYTE-POSITION>6</BYTE-POSITION><BIT-POSITION>0</BIT-POSITION>
1985                 <DOP-REF ID-REF="DOP_Nibble"/>
1986               </PARAM>
1987               <PARAM SEMANTIC="DATA" xsi:type="VALUE"><SHORT-NAME>HighNibble</SHORT-NAME>
1988                 <BYTE-POSITION>6</BYTE-POSITION><BIT-POSITION>4</BIT-POSITION>
1989                 <DOP-REF ID-REF="DOP_Nibble"/>
1990               </PARAM>
1991             </PARAMS></REQUEST></REQUESTS>
1992           </ECU-VARIANT></ECU-VARIANTS>
1993         </DIAG-LAYER-CONTAINER>
1994       </ODX>"#;
1995
1996    fn packed_request() -> Value {
1997        let container = crate::tests_support::zip_with(&[("Packed.odx-d", PACKED)]);
1998        let document = parse(&container, "packed.pdx").expect("parses");
1999        let json = serde_json::to_value(&document).expect("serialises");
2000        find_in(&json, "RQ")
2001    }
2002
2003    #[test]
2004    fn tells_apart_two_parameters_packed_into_one_byte() {
2005        let request = packed_request();
2006        let params = request["params"].as_array().expect("params");
2007
2008        // Byte position and length are identical for both nibbles, so the bit
2009        // position is the only thing that distinguishes them.
2010        for index in [1, 2] {
2011            assert_eq!(params[index]["bytePosition"], 6);
2012            assert_eq!(params[index]["bitLength"], 4);
2013        }
2014        assert_eq!(params[1]["name"], "LowNibble");
2015        assert_eq!(params[1]["bitPosition"], 0);
2016        assert_eq!(params[2]["name"], "HighNibble");
2017        assert_eq!(params[2]["bitPosition"], 4);
2018    }
2019
2020    #[test]
2021    fn leaves_the_bit_position_unset_when_the_document_omits_it() {
2022        let request = packed_request();
2023        let plain = &request["params"][0];
2024        assert_eq!(plain["name"], "Plain");
2025        // ODX would default this to 0; an absent element stays absent, so an
2026        // explicit 0 and a missing one can still be told apart.
2027        assert!(plain["bitPosition"].is_null(), "{plain:?}");
2028    }
2029
2030    #[test]
2031    fn still_shows_the_bit_position_as_a_property() {
2032        let request = packed_request();
2033        let low = &request["children"][1];
2034        assert_eq!(low["name"], "LowNibble");
2035        assert_eq!(property(low, "BIT-POSITION").as_deref(), Some("0"));
2036        assert_eq!(property(low, "BYTE-POSITION").as_deref(), Some("6"));
2037    }
2038
2039    #[test]
2040    fn notes_which_data_object_prop_a_parameter_uses() {
2041        let request = packed_request();
2042        let params = request["params"].as_array().expect("params");
2043        assert_eq!(params[0]["dopRef"], "DOP_Byte");
2044        assert_eq!(params[1]["dopRef"], "DOP_Nibble");
2045    }
2046
2047    // ---- data object properties as data ---------------------------------
2048
2049    /// A measuring range plus the pattern that says the signal is missing:
2050    /// one `SCALE-LINEAR` method with a scale for each.
2051    const SNA: &str = r#"<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
2052         <DIAG-LAYER-CONTAINER ID="DLC"><SHORT-NAME>DLC</SHORT-NAME>
2053           <ECU-VARIANTS><ECU-VARIANT ID="EV"><SHORT-NAME>EV</SHORT-NAME>
2054             <DIAG-DATA-DICTIONARY-SPEC><DATA-OBJECT-PROPS>
2055               <DATA-OBJECT-PROP ID="DOP_EngineSpeed">
2056                 <SHORT-NAME>DOP_EngineSpeed</SHORT-NAME>
2057                 <SDGS><SDG><SDG-CAPTION ID="SDGC"><SHORT-NAME>Provenance</SHORT-NAME></SDG-CAPTION>
2058                   <SD SI="Generator">udsdoc</SD>
2059                 </SDG></SDGS>
2060                 <COMPU-METHOD>
2061                   <CATEGORY>SCALE-LINEAR</CATEGORY>
2062                   <COMPU-INTERNAL-TO-PHYS><COMPU-SCALES>
2063                     <COMPU-SCALE>
2064                       <LOWER-LIMIT INTERVAL-TYPE="CLOSED">0</LOWER-LIMIT>
2065                       <UPPER-LIMIT INTERVAL-TYPE="CLOSED">65534</UPPER-LIMIT>
2066                       <COMPU-RATIONAL-COEFFS>
2067                         <COMPU-NUMERATOR><V>0</V><V>1</V></COMPU-NUMERATOR>
2068                         <COMPU-DENOMINATOR><V>4</V></COMPU-DENOMINATOR>
2069                       </COMPU-RATIONAL-COEFFS>
2070                     </COMPU-SCALE>
2071                     <COMPU-SCALE>
2072                       <LOWER-LIMIT INTERVAL-TYPE="CLOSED">65535</LOWER-LIMIT>
2073                       <UPPER-LIMIT INTERVAL-TYPE="CLOSED">65535</UPPER-LIMIT>
2074                       <COMPU-CONST><VT>SNA</VT></COMPU-CONST>
2075                     </COMPU-SCALE>
2076                   </COMPU-SCALES></COMPU-INTERNAL-TO-PHYS>
2077                 </COMPU-METHOD>
2078                 <DIAG-CODED-TYPE BASE-DATA-TYPE="A_UINT32" xsi:type="STANDARD-LENGTH-TYPE">
2079                   <BIT-LENGTH>16</BIT-LENGTH>
2080                 </DIAG-CODED-TYPE>
2081                 <PHYSICAL-TYPE BASE-DATA-TYPE="A_FLOAT32"/>
2082                 <INTERNAL-CONSTR>
2083                   <LOWER-LIMIT INTERVAL-TYPE="CLOSED">0</LOWER-LIMIT>
2084                   <UPPER-LIMIT INTERVAL-TYPE="CLOSED">65535</UPPER-LIMIT>
2085                 </INTERNAL-CONSTR>
2086                 <UNIT-REF ID-REF="UNIT_rpm"/>
2087               </DATA-OBJECT-PROP>
2088             </DATA-OBJECT-PROPS>
2089             <UNIT-SPEC><UNITS><UNIT ID="UNIT_rpm"><SHORT-NAME>rpm</SHORT-NAME>
2090               <DISPLAY-NAME>1/min</DISPLAY-NAME>
2091             </UNIT></UNITS></UNIT-SPEC>
2092             </DIAG-DATA-DICTIONARY-SPEC>
2093           </ECU-VARIANT></ECU-VARIANTS>
2094         </DIAG-LAYER-CONTAINER>
2095       </ODX>"#;
2096
2097    #[test]
2098    fn publishes_the_scales_of_a_data_object_prop() {
2099        let container = crate::tests_support::zip_with(&[("Sna.odx-d", SNA)]);
2100        let document = parse(&container, "sna.pdx").expect("parses");
2101
2102        assert_eq!(document.dops.len(), 1);
2103        let dop = &document.dops[0];
2104        assert_eq!(dop.short_name, "DOP_EngineSpeed");
2105        assert_eq!(dop.id.as_deref(), Some("DOP_EngineSpeed"));
2106        assert_eq!(dop.category, "SCALE-LINEAR");
2107        assert_eq!(dop.bit_length, Some(16));
2108        assert_eq!(dop.base_data_type.as_deref(), Some("A_UINT32"));
2109        assert_eq!(dop.unit.as_deref(), Some("1/min"));
2110        assert_eq!(
2111            dop.internal_constr,
2112            Some((Some("0".to_owned()), Some("65535".to_owned())))
2113        );
2114        assert_eq!(
2115            dop.sdgs,
2116            [(
2117                "Provenance".to_owned(),
2118                vec![("Generator".to_owned(), "udsdoc".to_owned())]
2119            )]
2120        );
2121
2122        assert_eq!(dop.scales.len(), 2);
2123
2124        // The measuring range: quarter revolutions per bit, no constant.
2125        let range = &dop.scales[0];
2126        assert_eq!(range.lower_limit.as_deref(), Some("0"));
2127        assert_eq!(range.upper_limit.as_deref(), Some("65534"));
2128        assert_eq!(range.numerator, [0.0, 1.0]);
2129        assert_eq!(range.denominator, [4.0]);
2130        assert_eq!(range.const_text, None);
2131
2132        // The pattern that stands for "no value", which converts to a text.
2133        let sna = &dop.scales[1];
2134        assert_eq!(sna.lower_limit.as_deref(), Some("65535"));
2135        assert_eq!(sna.upper_limit.as_deref(), Some("65535"));
2136        assert_eq!(sna.const_text.as_deref(), Some("SNA"));
2137        assert!(sna.numerator.is_empty(), "{:?}", sna.numerator);
2138    }
2139
2140    #[test]
2141    fn lists_every_data_object_prop_of_the_container_once() {
2142        let document = parse(SAMPLE, "DemoVehicle_Diagnostics.pdx").expect("parses");
2143        // The tree repeats a DOP under every layer that inherits it; this list
2144        // holds definitions. Twelve belong to the diag layers - the number the
2145        // parser summary reports - and two more describe comparam values in
2146        // the subset document, which the tree shows as comparams instead.
2147        assert_eq!(document.dops.len(), 14);
2148
2149        let temperature = document
2150            .dops
2151            .iter()
2152            .find(|dop| dop.short_name == "DOP_CoolantTemperature")
2153            .expect("the coolant temperature DOP");
2154        assert_eq!(temperature.category, "LINEAR");
2155        // DISPLAY-NAME of the unit, as everywhere else in the model; the tree
2156        // shows the SHORT-NAME "degC" that the reference resolves to.
2157        assert_eq!(temperature.unit.as_deref(), Some("°C"));
2158        assert_eq!(temperature.scales[0].numerator, [-40.0, 1.0]);
2159    }
2160
2161    #[test]
2162    fn reads_physical_formatting_from_its_schema_shapes() {
2163        let model = parsed();
2164        let engine_speed = find_in(&model, "Engine speed");
2165        let data_identifier = find_in(&model, "Data identifier");
2166
2167        assert_eq!(property(&engine_speed, "PRECISION").as_deref(), Some("2"));
2168        assert_eq!(
2169            property(&data_identifier, "DISPLAY-RADIX").as_deref(),
2170            Some("HEX")
2171        );
2172    }
2173
2174    // ---- special data limits --------------------------------------------
2175
2176    /// A container whose service carries `rows` special data entries.
2177    fn with_sdg_rows(rows: usize) -> Vec<u8> {
2178        let entries: String = (0..rows)
2179            .map(|index| format!("<SD SI=\"Key{index}\">value {index}</SD>"))
2180            .collect();
2181        let document = format!(
2182            r#"<ODX MODEL-VERSION="2.2.0"><DIAG-LAYER-CONTAINER ID="DLC">
2183                 <SHORT-NAME>DLC</SHORT-NAME>
2184                 <ECU-VARIANTS><ECU-VARIANT ID="EV"><SHORT-NAME>EV</SHORT-NAME>
2185                   <DIAG-COMMS><DIAG-SERVICE ID="S"><SHORT-NAME>S</SHORT-NAME>
2186                     <SDGS><SDG>
2187                       <SDG-CAPTION ID="C"><SHORT-NAME>Trace</SHORT-NAME></SDG-CAPTION>
2188                       {entries}
2189                     </SDG></SDGS>
2190                   </DIAG-SERVICE></DIAG-COMMS>
2191                 </ECU-VARIANT></ECU-VARIANTS>
2192               </DIAG-LAYER-CONTAINER></ODX>"#
2193        );
2194        crate::tests_support::zip_with(&[("Sdg.odx-d", &document)])
2195    }
2196
2197    /// Special data rows of the one service, and the truncation marker.
2198    fn sdg_rows(document: &OdxDocument) -> (usize, Option<String>) {
2199        let json = serde_json::to_value(document).expect("serialises");
2200        let service = find_in(&json, "S");
2201        let rows = service["properties"]
2202            .as_array()
2203            .expect("properties")
2204            .iter()
2205            .filter(|row| {
2206                row["name"]
2207                    .as_str()
2208                    .is_some_and(|name| name.starts_with("Trace / "))
2209            })
2210            .count();
2211        (rows, property(&service, "SDG-TRUNCATED"))
2212    }
2213
2214    #[test]
2215    fn keeps_every_special_data_row_by_default() {
2216        let document = parse(&with_sdg_rows(40), "sdg.pdx").expect("parses");
2217        let (rows, truncated) = sdg_rows(&document);
2218        assert_eq!(rows, 40);
2219        assert_eq!(truncated, None);
2220    }
2221
2222    #[test]
2223    fn keeps_every_special_data_row_when_asked_to() {
2224        let options = ParseOptions { max_sdg_rows: None };
2225        let document = parse_with_options(&with_sdg_rows(40), "sdg.pdx", options).expect("parses");
2226        let (rows, truncated) = sdg_rows(&document);
2227        assert_eq!(rows, 40);
2228        assert_eq!(truncated, None);
2229    }
2230
2231    #[test]
2232    fn honours_a_custom_special_data_limit() {
2233        let options = ParseOptions {
2234            max_sdg_rows: Some(2),
2235        };
2236        let document = parse_with_options(&with_sdg_rows(40), "sdg.pdx", options).expect("parses");
2237        let (rows, truncated) = sdg_rows(&document);
2238        assert_eq!(rows, 2);
2239        assert_eq!(truncated.as_deref(), Some("38"));
2240    }
2241
2242    #[test]
2243    fn leaves_short_special_data_groups_alone() {
2244        // Nothing was dropped, so there is no marker to explain.
2245        let document = parse(&with_sdg_rows(3), "sdg.pdx").expect("parses");
2246        assert_eq!(sdg_rows(&document), (3, None));
2247    }
2248}
2249
2250#[cfg(test)]
2251mod tests_support {
2252    use std::io::Write;
2253
2254    /// Builds an in-memory ZIP archive for tests.
2255    pub fn zip_with(files: &[(&str, &str)]) -> Vec<u8> {
2256        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
2257        let options = zip::write::SimpleFileOptions::default()
2258            .compression_method(zip::CompressionMethod::Stored);
2259        for (name, content) in files {
2260            writer.start_file(*name, options).expect("start entry");
2261            writer.write_all(content.as_bytes()).expect("write entry");
2262        }
2263        writer.finish().expect("finish archive").into_inner()
2264    }
2265}