Skip to main content

viva_genapi_xml/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2//! Load and pre-parse GenICam XML using quick-xml.
3//!
4//! This crate provides types and functions for parsing GenICam XML descriptions
5//! into a structured representation that can be used by the core evaluation engine.
6
7#[cfg(feature = "fetch")]
8mod archive;
9mod builders;
10#[cfg(feature = "fetch")]
11mod fetch;
12mod parsers;
13mod util;
14
15#[cfg(feature = "fetch")]
16pub use fetch::{fetch_and_load_xml, fetch_raw_xml};
17
18use quick_xml::Reader;
19use quick_xml::events::{BytesStart, Event};
20use quick_xml::name::QName;
21use serde::{Deserialize, Serialize};
22use thiserror::Error;
23
24use parsers::{
25    missing_command_value, parse_boolean, parse_category, parse_category_empty, parse_command,
26    parse_converter, parse_enum, parse_float, parse_int_converter, parse_integer, parse_port,
27    parse_port_empty, parse_register, parse_string, parse_struct_reg, parse_swissknife,
28};
29use util::{attribute_value, skip_element};
30
31/// Source of the numeric value backing an enumeration entry.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub enum EnumValueSrc {
34    /// Numeric literal declared directly in the XML.
35    Literal(i64),
36    /// Value obtained from another node referenced via `<pValue>`.
37    FromNode(String),
38}
39
40/// Where a `<Command>` takes the value it writes.
41///
42/// GenICam Standard v2.1.1 §2.8.8: the command value "is written into a node
43/// which is referenced to by a pValue element", and it "can alternatively also
44/// be taken from pCommandValue". One of the two is required — the standard's
45/// table of defaults (§3.2) gives none — so a `<Command>` declaring neither is
46/// skipped rather than given an invented value.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub enum CommandValueSrc {
49    /// `<CommandValue>`: a constant.
50    Literal(i64),
51    /// `<pCommandValue>`: the node whose value is written, read each time the
52    /// command executes. Hikrobot's `UserSetSave` takes the selected user
53    /// set's index this way.
54    FromNode(String),
55}
56
57/// One value of an indexed `<Integer>` or `<Float>`: a constant, or the
58/// value of another node.
59#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
60pub enum IndexedSrc<T> {
61    /// `<ValueIndexed>` or `<ValueDefault>`: a constant.
62    Literal(T),
63    /// `<pValueIndexed>` or `<pValueDefault>`: the node whose value it is.
64    FromNode(String),
65}
66
67/// A `<ValueIndexed Index="…">` or `<pValueIndexed Index="…">`: the value an
68/// indexed node holds while its index reads `index`.
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70#[non_exhaustive]
71pub struct IndexedEntry<T> {
72    /// The `Index` attribute.
73    pub index: i64,
74    /// The value for that index.
75    pub value: IndexedSrc<T>,
76}
77
78/// An `<Integer>` or `<Float>` that picks its value from a table by the value
79/// of an index node (GenICam Standard v2.1.1 §2.8.5, §2.8.9):
80///
81/// ```xml
82/// <Integer Name="d_90">
83///     <pIndex>d_88</pIndex>
84///     <pValueIndexed Index="3">d_257</pValueIndexed>
85///     <pValueDefault>d_1049</pValueDefault>
86/// </Integer>
87/// ```
88///
89/// The entry whose index the `<pIndex>` node reads is the value; an index no
90/// entry names takes the default. On such a node `<pIndex>` is not an address
91/// term: reading it as one is how a Basler a2A4096-44g5m's `TriggerMode`
92/// read the GigE Vision bootstrap register at 3 × 4 (issue #210).
93#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
94#[non_exhaustive]
95pub struct IndexedValue<T> {
96    /// `<pIndex>`: the node whose value selects the entry.
97    pub index: String,
98    /// The entries, in document order.
99    pub entries: Vec<IndexedEntry<T>>,
100    /// `<ValueDefault>` or `<pValueDefault>`: the value for an index no entry
101    /// names.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub default: Option<IndexedSrc<T>>,
104}
105
106impl<T> IndexedSrc<T> {
107    /// The node a `<pValueIndexed>` or `<pValueDefault>` names; `None` for a
108    /// constant.
109    pub fn node(&self) -> Option<&str> {
110        match self {
111            IndexedSrc::Literal(_) => None,
112            IndexedSrc::FromNode(node) => Some(node),
113        }
114    }
115}
116
117impl<T> IndexedValue<T> {
118    /// The nodes an entry or the default reads, each once, in document order.
119    pub fn value_nodes(&self) -> Vec<&str> {
120        let mut nodes: Vec<&str> = Vec::new();
121        let values = self.entries.iter().map(|entry| &entry.value);
122        for value in values.chain(self.default.as_ref()) {
123            if let IndexedSrc::FromNode(node) = value
124                && !nodes.contains(&node.as_str())
125            {
126                nodes.push(node);
127            }
128        }
129        nodes
130    }
131
132    /// Every node the value depends on: the index node, then
133    /// [`IndexedValue::value_nodes`].
134    pub fn referenced_nodes(&self) -> Vec<&str> {
135        let mut nodes = vec![self.index.as_str()];
136        nodes.extend(self.value_nodes());
137        nodes
138    }
139}
140
141/// References to predicate provider nodes used for runtime gating.
142///
143/// GenICam's `pIsImplemented`, `pIsAvailable` and `pIsLocked` each point at
144/// another node (typically an Integer, Boolean or IntSwissKnife) whose current
145/// value gates whether a feature is implemented, accessible, or writable.
146/// These three references are shared by most node variants, so we collect them
147/// into one struct to keep the variant fields small.
148///
149/// All three fields are optional; a node with no predicates has
150/// [`PredicateRefs::default()`]. Serde fields use the GenICam XML spelling so
151/// round-trip JSON matches the XML attribute names.
152#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
153#[non_exhaustive]
154pub struct PredicateRefs {
155    /// Name of a node evaluating to non-zero iff the feature is implemented.
156    #[serde(
157        default,
158        skip_serializing_if = "Option::is_none",
159        rename = "pIsImplemented"
160    )]
161    pub p_is_implemented: Option<String>,
162    /// Name of a node evaluating to non-zero iff the feature is accessible now.
163    #[serde(
164        default,
165        skip_serializing_if = "Option::is_none",
166        rename = "pIsAvailable"
167    )]
168    pub p_is_available: Option<String>,
169    /// Name of a node evaluating to non-zero iff the feature is locked (RW→RO).
170    #[serde(default, skip_serializing_if = "Option::is_none", rename = "pIsLocked")]
171    pub p_is_locked: Option<String>,
172}
173
174impl PredicateRefs {
175    /// Iterate over all referenced node names (for dependency-graph walks).
176    pub fn references(&self) -> impl Iterator<Item = &str> {
177        [
178            self.p_is_implemented.as_deref(),
179            self.p_is_available.as_deref(),
180            self.p_is_locked.as_deref(),
181        ]
182        .into_iter()
183        .flatten()
184    }
185
186    /// `true` when every field is `None`.
187    pub fn is_empty(&self) -> bool {
188        self.p_is_implemented.is_none()
189            && self.p_is_available.is_none()
190            && self.p_is_locked.is_none()
191    }
192}
193
194/// Declaration for a single enumeration entry.
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[non_exhaustive]
197pub struct EnumEntryDecl {
198    /// Symbolic entry name exposed to clients.
199    pub name: String,
200    /// Source describing how to resolve the numeric value for this entry.
201    pub value: EnumValueSrc,
202    /// Optional user facing label.
203    pub display_name: Option<String>,
204    /// Predicate refs controlling whether this entry is implemented / available.
205    #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
206    pub predicates: PredicateRefs,
207    /// `<IsSelfClearing>Yes</IsSelfClearing>`: the device leaves this entry by
208    /// itself. GenICam Standard v2.1.1 §2.8.10: an enumeration's
209    /// `<PollingTime>` polls only while its value is such an entry.
210    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
211    pub is_self_clearing: bool,
212}
213
214/// The error a source is carried as when its type is not part of this crate's
215/// API: the XML reader's, a number parser's, a transport's.
216type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
217
218/// Why a GenICam XML document could not be read or fetched.
219///
220/// Every variant names where the problem is and carries the error that caused
221/// it, if any, as its [`source`](std::error::Error::source) — never flattened
222/// into text (ADR-0030).
223#[derive(Debug, Error)]
224#[non_exhaustive]
225pub enum XmlError {
226    /// The document is not well-formed XML. The source is the XML reader's
227    /// own error.
228    #[error("malformed XML: {0}")]
229    Malformed(#[source] BoxError),
230    /// A number in the document does not parse as one.
231    #[error("{text:?} is not {expected}: {source}")]
232    Number {
233        /// The text as written.
234        text: String,
235        /// What was expected, such as `"an integer"`.
236        expected: &'static str,
237        /// The number parser's error.
238        #[source]
239        source: BoxError,
240    },
241    /// A node or element lacks something the GenICam schema requires of it.
242    #[error("{node} is missing {what}")]
243    Missing {
244        /// The node's name, or the element's tag when it has no name yet.
245        node: String,
246        /// What is missing, such as `"<Length>"` or `"attribute Name"`.
247        what: &'static str,
248    },
249    /// A node or element is declared in a way the GenICam schema does not
250    /// allow.
251    #[error("{node} {problem}")]
252    Invalid {
253        /// The node's name, or the element's tag when it has no name.
254        node: String,
255        /// What is wrong, such as `"has a zero bit mask"`.
256        problem: &'static str,
257    },
258    /// A node uses an element this crate does not implement yet, such as
259    /// `<pLength>`. The node is skipped; the rest of the document loads.
260    #[error("{node} declares <{element}>{text}</{element}>, which is not supported yet")]
261    Unsupported {
262        /// The node.
263        node: String,
264        /// The element's tag, such as `"pLength"`.
265        element: &'static str,
266        /// The element's text as written: for a `<pLength>`, the node the
267        /// length would be read from.
268        text: String,
269    },
270    /// The document's ZIP archive cannot be read. The source is the archive
271    /// reader's error.
272    #[error("XML ZIP archive: {0}")]
273    Archive(#[source] BoxError),
274    /// The document's ZIP archive holds no file, or one larger than `limit`
275    /// bytes.
276    #[error("XML ZIP archive is empty or exceeds {limit} bytes")]
277    ArchiveSize {
278        /// The largest document accepted, in bytes.
279        limit: u64,
280    },
281    /// The document is not UTF-8.
282    #[error("the XML document is not UTF-8: {0}")]
283    Encoding(#[from] std::string::FromUtf8Error),
284    /// The device's URL register names no document, or one this crate cannot
285    /// read: an HTTP or file URL, or a malformed `local:` one.
286    #[error("XML URL {url:?} {problem}")]
287    Url {
288        /// The URL as the register holds it; empty when the register is.
289        url: String,
290        /// Why it cannot be followed, such as `"is not supported"`.
291        problem: &'static str,
292    },
293    /// Reading the document from the device failed. The source is the
294    /// transport's error.
295    #[error("reading the XML from the device: {0}")]
296    Transport(#[source] BoxError),
297}
298
299impl XmlError {
300    /// A transport failure reading the document; `err` becomes the source.
301    pub fn transport(err: impl Into<BoxError>) -> Self {
302        XmlError::Transport(err.into())
303    }
304
305    pub(crate) fn malformed(err: impl std::error::Error + Send + Sync + 'static) -> Self {
306        XmlError::Malformed(Box::new(err))
307    }
308
309    pub(crate) fn missing(node: impl AsRef<str>, what: &'static str) -> Self {
310        XmlError::Missing {
311            node: node.as_ref().to_string(),
312            what,
313        }
314    }
315
316    pub(crate) fn invalid(node: impl AsRef<str>, problem: &'static str) -> Self {
317        XmlError::Invalid {
318            node: node.as_ref().to_string(),
319            problem,
320        }
321    }
322
323    pub(crate) fn number(
324        text: &str,
325        expected: &'static str,
326        err: impl std::error::Error + Send + Sync + 'static,
327    ) -> Self {
328        XmlError::Number {
329            text: text.to_string(),
330            expected,
331            source: Box::new(err),
332        }
333    }
334}
335
336/// Visibility level controlling which users see a feature.
337///
338/// GenICam defines four levels; features at a given level are visible to
339/// users at that level and above.
340#[derive(
341    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
342)]
343#[non_exhaustive]
344pub enum Visibility {
345    /// Shown to all users (default).
346    #[default]
347    Beginner,
348    /// Shown to experienced users.
349    Expert,
350    /// Shown only to advanced integrators.
351    Guru,
352    /// Hidden from all UI presentations.
353    Invisible,
354}
355
356impl Visibility {
357    pub(crate) fn parse(s: &str) -> Option<Self> {
358        match s.trim() {
359            "Beginner" => Some(Self::Beginner),
360            "Expert" => Some(Self::Expert),
361            "Guru" => Some(Self::Guru),
362            "Invisible" => Some(Self::Invisible),
363            _ => None,
364        }
365    }
366}
367
368/// Recommended UI representation for a numeric feature.
369#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
370#[non_exhaustive]
371pub enum Representation {
372    /// A linear slider.
373    Linear,
374    /// A logarithmic slider.
375    Logarithmic,
376    /// A check box.
377    Boolean,
378    /// A plain number, no slider.
379    PureNumber,
380    /// A hexadecimal number.
381    HexNumber,
382    /// Display as dotted-quad IPv4 address.
383    IPV4Address,
384    /// Display as colon-separated MAC address.
385    MACAddress,
386}
387
388impl Representation {
389    pub(crate) fn parse(s: &str) -> Option<Self> {
390        match s.trim() {
391            "Linear" => Some(Self::Linear),
392            "Logarithmic" => Some(Self::Logarithmic),
393            "Boolean" => Some(Self::Boolean),
394            "PureNumber" => Some(Self::PureNumber),
395            "HexNumber" => Some(Self::HexNumber),
396            "IPV4Address" => Some(Self::IPV4Address),
397            "MACAddress" => Some(Self::MACAddress),
398            _ => None,
399        }
400    }
401}
402
403/// Shared metadata present on every GenICam node.
404#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
405#[non_exhaustive]
406pub struct NodeMeta {
407    /// Visibility level (Beginner, Expert, Guru, Invisible).
408    pub visibility: Visibility,
409    /// Long-form description of the feature.
410    pub description: Option<String>,
411    /// Short tooltip text for UI hover hints.
412    pub tooltip: Option<String>,
413    /// Human-readable label (may differ from the node name).
414    pub display_name: Option<String>,
415    /// Recommended UI representation for numeric features.
416    pub representation: Option<Representation>,
417    /// `<ImposedAccessMode>`: a ceiling on the node's access, whatever its
418    /// `<AccessMode>` or `<pValue>` allows. `RW` imposes nothing.
419    #[serde(default)]
420    pub imposed_access: Option<AccessMode>,
421    /// `<Streamable>Yes</Streamable>`: the feature belongs in a saved
422    /// configuration. GenICam Standard v2.1.1 §2.8.1: Streamable "denotes that
423    /// the corresponding feature is prepared to be stored to and loaded from a
424    /// file via the GenApi node tree"; absent means `No` (§3.2).
425    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
426    pub streamable: bool,
427    /// `<Cachable>` as the XML declares it; `None` when it declares none.
428    ///
429    /// GenICam Standard v2.1.1 §2.8.3 puts it on a register. Absent, the
430    /// standard's default depends on the element — `WriteAround` for a
431    /// `<FloatReg>`, `WriteThrough` for the other registers (§3.2) — so it is
432    /// resolved where the node's kind is known, in `viva-genapi`. A
433    /// `<StructEntry>` without its own takes its `<StructReg>`'s.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub cachable: Option<CachingMode>,
436    /// `<PollingTime>`, in milliseconds: "a recommended time interval [in ms]
437    /// after which a node should be invalidated" (§2.8.3), a hint. A register
438    /// declares it, and so may a `<Command>` (§2.8.8) or an `<Enumeration>`
439    /// (§2.8.10).
440    #[serde(default, skip_serializing_if = "Option::is_none")]
441    pub polling_time_ms: Option<u64>,
442    /// Child elements the parser read past without interpreting them, by
443    /// tag, in document order: `<Extension>`, `<DocuURL>`, or something that
444    /// changes the value and is not supported yet. A child of an
445    /// enumeration's entry is written `EnumEntry/<tag>`; a `<StructReg>`'s
446    /// own are its entries', as everything else it declares is.
447    /// [`XmlModel::ignored`] lists them for a whole document.
448    #[serde(default, skip_serializing_if = "Vec::is_empty")]
449    pub ignored: Vec<String>,
450}
451
452/// `<Cachable>`: whether a register's value may be answered from a cache.
453///
454/// GenICam Standard v2.1.1 §2.8.3: "WriteThrough means that a value written to
455/// the camera is written to the cache as well. WriteAround means that only read
456/// values are written to the cache" — for a value the camera may change on
457/// writing, such as a gain it rounds. With `NoCache`, every read goes to the
458/// device.
459#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
460pub enum CachingMode {
461    /// Never answered from a cache.
462    NoCache,
463    /// A write caches the written value.
464    WriteThrough,
465    /// A write leaves nothing cached; the next read asks the device.
466    WriteAround,
467}
468
469impl CachingMode {
470    /// The more restrictive of two modes: `NoCache` over `WriteAround` over
471    /// `WriteThrough`. A value read through several registers may be cached
472    /// only as far as each of them allows; the GenApi reference
473    /// implementation's `Combine` computes the same.
474    pub fn combine(self, other: CachingMode) -> CachingMode {
475        use CachingMode::{NoCache, WriteAround, WriteThrough};
476        match (self, other) {
477            (NoCache, _) | (_, NoCache) => NoCache,
478            (WriteAround, _) | (_, WriteAround) => WriteAround,
479            (WriteThrough, WriteThrough) => WriteThrough,
480        }
481    }
482
483    /// Parse a `<Cachable>` value. The standard's own example writes `No`;
484    /// it, and any value the standard does not define, read as `NoCache`: the
485    /// reading that never answers with a stale value.
486    pub(crate) fn parse(value: &str) -> Self {
487        match value.trim() {
488            "WriteThrough" => CachingMode::WriteThrough,
489            "WriteAround" => CachingMode::WriteAround,
490            "NoCache" | "No" => CachingMode::NoCache,
491            other => {
492                tracing::warn!(
493                    cachable = other,
494                    "unknown <Cachable> value, assuming NoCache"
495                );
496                CachingMode::NoCache
497            }
498        }
499    }
500}
501
502/// Access privileges for a GenICam node as described in the XML.
503#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
504pub enum AccessMode {
505    /// Read-only node. The underlying register must not be modified by the client.
506    RO,
507    /// Write-only node. Reading the register is not permitted.
508    WO,
509    /// Read-write node. The register may be read and written by the client.
510    RW,
511}
512
513impl AccessMode {
514    /// This access under the ceiling an `<ImposedAccessMode>` sets: `RO`
515    /// removes writing, `WO` reading, `RW` or no ceiling nothing. `None` when
516    /// nothing is left — an `RO` node imposed `WO`.
517    pub fn capped_by(self, ceiling: Option<AccessMode>) -> Option<AccessMode> {
518        match (self, ceiling) {
519            (access, None | Some(AccessMode::RW)) => Some(access),
520            (AccessMode::WO, Some(AccessMode::RO)) | (AccessMode::RO, Some(AccessMode::WO)) => None,
521            (_, Some(ceiling)) => Some(ceiling),
522        }
523    }
524
525    /// Parse an `<AccessMode>` value.
526    ///
527    /// Beyond the three spellings the standard defines, the single-letter forms
528    /// `R` / `W` are accepted: they appear in third-party GenICam documents
529    /// (including the standard's own conformance fixtures). An unrecognized
530    /// value is logged and read as `RO`: a register whose access we cannot
531    /// read is not written (backlog GA-26), and one odd register still does
532    /// not make a whole camera unusable.
533    pub(crate) fn parse(value: &str) -> Result<Self, XmlError> {
534        let trimmed = value.trim();
535        match trimmed.to_ascii_uppercase().as_str() {
536            "RO" | "R" => Ok(AccessMode::RO),
537            "WO" | "W" => Ok(AccessMode::WO),
538            "RW" | "WR" => Ok(AccessMode::RW),
539            other => {
540                tracing::warn!(
541                    access_mode = other,
542                    "unknown <AccessMode> value, assuming RO"
543                );
544                Ok(AccessMode::RO)
545            }
546        }
547    }
548}
549
550/// Register addressing metadata for a node.
551#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
552pub enum Addressing {
553    /// Register address is the **sum** of every declared address term.
554    ///
555    /// This is the GenICam register address model: `<Address>`, `<pAddress>`
556    /// and `<pIndex>` may each appear any number of times on one register and
557    /// all of them add up. A node such as
558    ///
559    /// ```xml
560    /// <IntReg Name="SerialPortSource_Val">
561    ///   <pAddress>SerialPortSourceAddr</pAddress>
562    ///   <Address>0x00000008</Address>
563    /// </IntReg>
564    /// ```
565    ///
566    /// lives eight bytes past the block base, not at the base and not at
567    /// offset eight. Keeping only one term reads the wrong register and says
568    /// nothing about it — that was issue #35.
569    Sum {
570        /// Terms to add together, in declaration order.
571        terms: Vec<AddressTerm>,
572        /// Length of the register block in bytes.
573        len: u32,
574        /// `<pPort>`: the port the address is relative to, verbatim; `None`
575        /// when the element is absent, which means the device.
576        ///
577        /// A chunk port's addresses count from the start of one chunk in a
578        /// stream buffer, an event port's from the start of one event — not
579        /// from anywhere in the device's memory (GenICam Standard v2.1.1
580        /// §2.8.16). [`XmlModel::ports`] says which port is which.
581        #[serde(default, skip_serializing_if = "Option::is_none")]
582        port: Option<String>,
583        /// `<pLength>`: the node the length is read from at runtime, in
584        /// place of `len` — "alternatively the length can be read from another
585        /// node" (GenICam Standard v2.1.1 §2.8.3). `len` is then `0`, unless
586        /// the document declares a `<Length>` as well. A bare `<pIndex>`
587        /// strides by the length read.
588        #[serde(default, skip_serializing_if = "Option::is_none")]
589        p_length: Option<String>,
590    },
591}
592
593/// One contribution to a register address.
594#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
595pub enum AddressTerm {
596    /// `<Address>` — a literal offset.
597    ///
598    /// Signed: GenICam Standard v2.1.1 §2.8.16 lets a register on a chunk port
599    /// declare a negative address, "interpreted as offset from the back of the
600    /// chunk". Baumer's HXG20 reads `ChunkImageLength` at `-4`. A hex literal
601    /// keeps its bit pattern, so `0xFFFFFFFFFFFFFFFC` is `-4` too.
602    Fixed(i64),
603    /// `<pAddress>` — an offset read from another node at runtime.
604    Node(String),
605    /// `<pIndex>` — an index read from another node, scaled by a stride.
606    Index {
607        /// Node supplying the index.
608        node: String,
609        /// Stride each index step advances the address by.
610        offset: IndexOffset,
611    },
612}
613
614/// Stride applied to a `<pIndex>` value.
615#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
616pub enum IndexOffset {
617    /// `<pIndex Offset="64">` — a literal stride.
618    Fixed(u64),
619    /// `<pIndex pOffset="Node">` — a stride read from another node.
620    Node(String),
621    /// `<pIndex>` with neither attribute: the stride is the register length.
622    Length,
623}
624
625impl Addressing {
626    /// A plain device register at a literal address.
627    pub fn fixed(address: i64, len: u32) -> Self {
628        Addressing::Sum {
629            terms: vec![AddressTerm::Fixed(address)],
630            len,
631            port: None,
632            p_length: None,
633        }
634    }
635
636    /// Register block length in bytes, as declared by `<Length>`; `0` for a
637    /// register whose length is read from [`Addressing::length_node`].
638    pub fn byte_len(&self) -> u32 {
639        match self {
640            Addressing::Sum { len, .. } => *len,
641        }
642    }
643
644    /// The `<pLength>` node the length is read from at runtime, if any.
645    pub fn length_node(&self) -> Option<&str> {
646        match self {
647            Addressing::Sum { p_length, .. } => p_length.as_deref(),
648        }
649    }
650
651    /// The `<pPort>` the address is relative to; `None` means the device.
652    pub fn port(&self) -> Option<&str> {
653        match self {
654            Addressing::Sum { port, .. } => port.as_deref(),
655        }
656    }
657
658    /// Names of every node this addressing reads at resolution time.
659    ///
660    /// Used to build the invalidation graph: when one of these changes, the
661    /// address changes, so anything cached against it is stale.
662    pub fn referenced_nodes(&self) -> Vec<&str> {
663        match self {
664            Addressing::Sum {
665                terms, p_length, ..
666            } => terms
667                .iter()
668                .flat_map(|term| match term {
669                    AddressTerm::Fixed(_) => Vec::new(),
670                    AddressTerm::Node(node) => vec![node.as_str()],
671                    AddressTerm::Index { node, offset } => match offset {
672                        IndexOffset::Node(stride) => vec![node.as_str(), stride.as_str()],
673                        _ => vec![node.as_str()],
674                    },
675                })
676                .chain(p_length.as_deref())
677                .collect(),
678        }
679    }
680}
681
682/// Whether a register's bits are interpreted as a signed or unsigned integer.
683///
684/// GenICam's default is `Unsigned`; `<Sign>Signed</Sign>` opts in. Getting
685/// this wrong is invisible until a register's top bit is set — a
686/// `GevCurrentIPAddress` of 192.168.1.160 then reads as a large negative
687/// number, and a mask comparison such as `(CTRL | 0xFDFFFFFF) = 0xFFFFFFFF`
688/// can never be true.
689#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
690pub enum Sign {
691    /// `<Sign>Unsigned</Sign>`, and the default when `<Sign>` is absent.
692    #[default]
693    Unsigned,
694    /// `<Sign>Signed</Sign>`: the payload is two's complement.
695    Signed,
696}
697
698impl Sign {
699    pub(crate) fn parse(tag: &str) -> Option<Self> {
700        match tag.trim().to_ascii_lowercase().as_str() {
701            "signed" => Some(Sign::Signed),
702            "unsigned" => Some(Sign::Unsigned),
703            _ => None,
704        }
705    }
706
707    /// Whether values should be sign-extended.
708    pub fn is_signed(self) -> bool {
709        matches!(self, Sign::Signed)
710    }
711}
712
713/// Byte order used to interpret a multi-byte register payload.
714#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
715pub enum ByteOrder {
716    /// The first byte contains the least significant bits.
717    Little,
718    /// The first byte contains the most significant bits.
719    Big,
720}
721
722impl ByteOrder {
723    pub(crate) fn parse(tag: &str) -> Option<Self> {
724        match tag.trim().to_ascii_lowercase().as_str() {
725            "littleendian" => Some(ByteOrder::Little),
726            "bigendian" => Some(ByteOrder::Big),
727            _ => None,
728        }
729    }
730}
731
732fn default_big_endian() -> ByteOrder {
733    ByteOrder::Big
734}
735
736/// Bitfield metadata describing a sub-range of a register payload.
737#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
738pub struct BitField {
739    /// Starting bit offset within the interpreted register value.
740    pub bit_offset: u16,
741    /// Number of bits covered by the field.
742    pub bit_length: u16,
743    /// Byte order used when interpreting the enclosing register.
744    pub byte_order: ByteOrder,
745}
746
747/// Byte-level encoding of the payload behind a `<Float>` / `<FloatReg>` node.
748///
749/// GenICam's XSD lets a float feature be backed by either:
750///
751/// - a native IEEE 754 register — a `<FloatReg>` element, or a `<Float>` whose
752///   addressing reads exactly 4 or 8 bytes and carries no `<Scale>`/`<Offset>`;
753/// - a scaled integer register — a `<Float>` that declares `<Scale>` and/or
754///   `<Offset>` and reads the register bytes as a signed integer.
755///
756/// Prior to this field, `get_float`/`set_float` always used the scaled-integer
757/// codec. That returned the bit pattern of the IEEE 754 value decoded as i64
758/// for fields such as `AcquisitionFrameRate` (e.g. `1106247680` for 30.0) —
759/// see `doc/2026-04-12-genapi-numeric-type-dispatch.md`.
760#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
761pub enum FloatEncoding {
762    /// Register bytes are an IEEE 754 value (4 bytes → f32, 8 bytes → f64).
763    Ieee754,
764    /// Register bytes are a signed integer; `Scale` and `Offset` map to the
765    /// user-facing value.
766    #[default]
767    ScaledInteger,
768}
769
770/// Output type of a SwissKnife expression node.
771#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
772pub enum SkOutput {
773    /// Integer output. The runtime rounds the computed value to the nearest
774    /// integer with ties going towards zero.
775    Integer,
776    /// Floating point output. The runtime exposes the value as a `f64` without
777    /// any additional processing.
778    #[default]
779    Float,
780}
781
782impl SkOutput {
783    pub(crate) fn parse(tag: &str) -> Option<Self> {
784        match tag.trim().to_ascii_lowercase().as_str() {
785            "integer" => Some(SkOutput::Integer),
786            "float" => Some(SkOutput::Float),
787            _ => None,
788        }
789    }
790}
791/// How a converter's `<FormulaFrom>` moves with its raw value.
792///
793/// GenICam Standard v2.1.1 §2.8.13: `<Slope>` "indicates if the formula is
794/// monotonously Increasing or Decreasing, if it is Varying (in this case the
795/// full number range is used), or if the slope is determined in an Automatic
796/// way by probing the function". It decides how the raw node's minimum and
797/// maximum map onto the converter's: a decreasing formula turns the raw
798/// maximum into the feature's minimum. §3.2 makes `Automatic` the default.
799#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
800pub enum Slope {
801    /// The feature value grows with the raw value.
802    Increasing,
803    /// The feature value falls as the raw value grows.
804    Decreasing,
805    /// Neither: the converter's range is the full number range.
806    Varying,
807    /// Found by evaluating the formula at the raw bounds.
808    #[default]
809    Automatic,
810}
811
812impl Slope {
813    pub(crate) fn parse(text: &str) -> Option<Self> {
814        match text.trim() {
815            "Increasing" => Some(Slope::Increasing),
816            "Decreasing" => Some(Slope::Decreasing),
817            "Varying" => Some(Slope::Varying),
818            "Automatic" => Some(Slope::Automatic),
819            _ => None,
820        }
821    }
822}
823
824/// Named literals and sub-formulas declared alongside a formula.
825///
826/// GenApi lets a `<SwissKnife>`, `<IntSwissKnife>` or `<Converter>` name parts
827/// of its own formula:
828///
829/// ```xml
830/// <Constant Name="TEN">10</Constant>
831/// <Expression Name="XPLUS2">TEN + X</Expression>
832/// <Formula>TEN * XPLUS2</Formula>
833/// ```
834///
835/// Both are resolved by substitution when the runtime builds the node, so the
836/// evaluator never sees them. Declaration order matters: an `<Expression>` may
837/// refer to constants and to expressions declared before it.
838#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
839#[non_exhaustive]
840pub struct FormulaBindings {
841    /// `<Constant Name="..">literal</Constant>` pairs, in declaration order.
842    #[serde(default, skip_serializing_if = "Vec::is_empty")]
843    pub constants: Vec<(String, String)>,
844    /// `<Expression Name="..">formula</Expression>` pairs, in declaration order.
845    #[serde(default, skip_serializing_if = "Vec::is_empty")]
846    pub expressions: Vec<(String, String)>,
847}
848
849impl FormulaBindings {
850    /// Whether nothing was declared.
851    pub fn is_empty(&self) -> bool {
852        self.constants.is_empty() && self.expressions.is_empty()
853    }
854}
855
856/// Declaration of a SwissKnife node consisting of an arithmetic expression.
857#[derive(Debug, Clone, Serialize, Deserialize)]
858#[non_exhaustive]
859pub struct SwissKnifeDecl {
860    /// Feature name exposed to clients.
861    pub name: String,
862    /// Shared metadata.
863    pub meta: NodeMeta,
864    /// Raw expression string to be parsed by the runtime.
865    pub expr: String,
866    /// Mapping of variables used in the expression to provider node names.
867    pub variables: Vec<(String, String)>,
868    /// Desired output type (integer or float).
869    pub output: SkOutput,
870    /// Named literals and sub-formulas referenced by `expr`.
871    #[serde(default, skip_serializing_if = "FormulaBindings::is_empty")]
872    pub bindings: FormulaBindings,
873    /// Predicate refs gating implementation / availability.
874    #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
875    pub predicates: PredicateRefs,
876}
877
878/// Declaration of a Converter node for bidirectional value transformation.
879///
880/// Converters expose a floating-point value computed from an underlying
881/// register or node via a formula.
882#[derive(Debug, Clone, Serialize, Deserialize)]
883#[non_exhaustive]
884pub struct ConverterDecl {
885    /// Feature name exposed to clients.
886    pub name: String,
887    /// Shared metadata.
888    pub meta: NodeMeta,
889    /// Name of the node providing the raw register value.
890    pub p_value: String,
891    /// `<FormulaTo>`: converts the feature value to the raw register value.
892    /// This is the *write* direction; its `FROM` variable is the incoming
893    /// value.
894    pub formula_to: String,
895    /// `<FormulaFrom>`: converts the raw register value to the feature value.
896    /// This is the *read* direction; its `TO` variable is the raw value.
897    pub formula_from: String,
898    /// Mapping of formula variables to provider node names for `formula_to`.
899    pub variables_to: Vec<(String, String)>,
900    /// Mapping of formula variables to provider node names for `formula_from`.
901    pub variables_from: Vec<(String, String)>,
902    /// Named literals and sub-formulas referenced by either formula.
903    #[serde(default, skip_serializing_if = "FormulaBindings::is_empty")]
904    pub bindings: FormulaBindings,
905    /// Engineering unit (if provided).
906    pub unit: Option<String>,
907    /// Desired output type.
908    pub output: SkOutput,
909    /// `<Slope>`: how the feature value moves with the raw one.
910    #[serde(default)]
911    pub slope: Slope,
912    /// Predicate refs gating implementation / availability / lock state.
913    #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
914    pub predicates: PredicateRefs,
915}
916
917/// Declaration of an IntConverter node for integer-specific bidirectional conversion.
918#[derive(Debug, Clone, Serialize, Deserialize)]
919#[non_exhaustive]
920pub struct IntConverterDecl {
921    /// Feature name exposed to clients.
922    pub name: String,
923    /// Shared metadata.
924    pub meta: NodeMeta,
925    /// Name of the node providing the raw register value.
926    pub p_value: String,
927    /// `<FormulaTo>`: converts the feature value to the raw register value.
928    /// This is the *write* direction; its `FROM` variable is the incoming
929    /// value.
930    pub formula_to: String,
931    /// `<FormulaFrom>`: converts the raw register value to the feature value.
932    /// This is the *read* direction; its `TO` variable is the raw value.
933    pub formula_from: String,
934    /// Mapping of formula variables to provider node names for `formula_to`.
935    pub variables_to: Vec<(String, String)>,
936    /// Mapping of formula variables to provider node names for `formula_from`.
937    pub variables_from: Vec<(String, String)>,
938    /// Named literals and sub-formulas referenced by either formula.
939    #[serde(default, skip_serializing_if = "FormulaBindings::is_empty")]
940    pub bindings: FormulaBindings,
941    /// Engineering unit (if provided).
942    pub unit: Option<String>,
943    /// `<Slope>`: how the feature value moves with the raw one.
944    #[serde(default)]
945    pub slope: Slope,
946    /// Predicate refs gating implementation / availability / lock state.
947    #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
948    pub predicates: PredicateRefs,
949}
950
951/// Declaration of a string feature: a `<StringReg>`, which reads a register,
952/// or a `<String>`, which holds a `<Value>` or takes its value from the node
953/// `<pValue>` names (GenICam Standard v2.1.1 §2.8.11 and §2.8.12).
954#[derive(Debug, Clone, Serialize, Deserialize)]
955#[non_exhaustive]
956pub struct StringDecl {
957    /// Feature name exposed to clients.
958    pub name: String,
959    /// Shared metadata.
960    pub meta: NodeMeta,
961    /// The register a `<StringReg>` reads; `None` for a `<String>`.
962    pub addressing: Option<Addressing>,
963    /// `<pValue>`: the node a `<String>` reads and writes its value through.
964    #[serde(default, skip_serializing_if = "Option::is_none")]
965    pub pvalue: Option<String>,
966    /// `<Value>`: the start value of a `<String>` that has no `<pValue>`, a
967    /// floating node holding whatever is written to it.
968    #[serde(default, skip_serializing_if = "Option::is_none")]
969    pub value: Option<String>,
970    /// Access privileges: a `<StringReg>`'s `<AccessMode>`, read-only when it
971    /// declares none. A `<String>` declares none: a floating one is `RW`, and
972    /// one with a `<pValue>` is as writable as the node it names.
973    pub access: AccessMode,
974    /// Predicate refs gating implementation / availability / lock state.
975    #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
976    pub predicates: PredicateRefs,
977    /// GenICam `<pInvalidator>` references, in declaration order: each names a
978    /// node whose change makes this node's cached value stale.
979    #[serde(default, skip_serializing_if = "Vec::is_empty")]
980    pub invalidators: Vec<String>,
981}
982
983/// Declaration of a `<Register>` node — raw byte-array register access.
984///
985/// The base register type: an address, a byte count, and no interpretation of
986/// the bytes at all. `<StringReg>` is this plus UTF-8/NUL decoding.
987///
988/// The length lives in [`Addressing`] rather than in a field here, because a
989/// bare `<pIndex>` strides by the register's length and address resolution
990/// already reads it from there — a `<Length>`, or the node a `<pLength>`
991/// names ([`Addressing::length_node`]).
992#[derive(Debug, Clone, Serialize, Deserialize)]
993#[non_exhaustive]
994pub struct RegisterDecl {
995    /// Feature name exposed to clients.
996    pub name: String,
997    /// Shared metadata.
998    pub meta: NodeMeta,
999    /// Addressing metadata for the register block, including its byte length.
1000    pub addressing: Addressing,
1001    /// Access privileges. An absent `<AccessMode>` means read-only.
1002    pub access: AccessMode,
1003    /// Predicate refs gating implementation / availability / lock state.
1004    #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
1005    pub predicates: PredicateRefs,
1006    /// GenICam `<pInvalidator>` references, in declaration order: each names a
1007    /// node whose change makes this node's cached value stale.
1008    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1009    pub invalidators: Vec<String>,
1010}
1011
1012/// Declaration of a node extracted from the GenICam XML description.
1013#[derive(Debug, Clone, Serialize, Deserialize)]
1014#[non_exhaustive]
1015pub enum NodeDecl {
1016    /// Integer feature backed by a register block or delegated via pValue.
1017    Integer {
1018        /// Feature name.
1019        name: String,
1020        /// Shared metadata (visibility, description, tooltip, etc.).
1021        meta: NodeMeta,
1022        /// Addressing metadata (absent when delegated via `pvalue`).
1023        addressing: Option<Addressing>,
1024        /// Length in bytes of the register payload; `0` when a `<pLength>`
1025        /// node gives it ([`Addressing::length_node`]).
1026        len: u32,
1027        /// Access privileges.
1028        access: AccessMode,
1029        /// `<Min>`; `None` when the XML declares none.
1030        ///
1031        /// Absent is not the same as `i64::MIN`: a document may declare the
1032        /// full domain, and a feature delegating through `<pValue>` takes the
1033        /// bound of the node it delegates to when it declares none itself.
1034        min: Option<i64>,
1035        /// `<Max>`; `None` when the XML declares none.
1036        max: Option<i64>,
1037        /// `<Inc>`; `None` when the XML declares none (GenICam's default
1038        /// increment is 1).
1039        inc: Option<i64>,
1040        /// Engineering unit (if provided).
1041        unit: Option<String>,
1042        /// Optional bitfield metadata describing the active bit range.
1043        bitfield: Option<BitField>,
1044        /// Whether the register payload is signed. Defaults to unsigned.
1045        #[serde(default)]
1046        sign: Sign,
1047        /// Byte order of the register payload. Defaults to [`ByteOrder::Big`]
1048        /// (the GenICam default). Recorded here as well as on `bitfield`,
1049        /// because an unmasked register has no bitfield to carry it.
1050        #[serde(default = "default_big_endian")]
1051        byte_order: ByteOrder,
1052        /// `<pSelected>`: the features this node selects.
1053        ///
1054        /// GenICam Standard v2.1.1 §2.8.4 puts `<pSelected>` on the
1055        /// *selector*, naming each feature that "will show a different value
1056        /// depending on the value of selector node".
1057        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1058        selected: Vec<String>,
1059        /// Node providing the value (delegates read/write to another node).
1060        pvalue: Option<String>,
1061        /// Node providing the dynamic maximum.
1062        p_max: Option<String>,
1063        /// Node providing the dynamic minimum.
1064        p_min: Option<String>,
1065        /// Node providing the dynamic increment.
1066        #[serde(default, skip_serializing_if = "Option::is_none")]
1067        p_inc: Option<String>,
1068        /// Static value (for constant integer nodes with `<Value>`).
1069        value: Option<i64>,
1070        /// `<pIndex>` with `<ValueIndexed>`/`<pValueIndexed>` and
1071        /// `<ValueDefault>`/`<pValueDefault>`: a value picked from a table.
1072        #[serde(default, skip_serializing_if = "Option::is_none")]
1073        indexed: Option<IndexedValue<i64>>,
1074        /// Predicate refs gating implementation / availability / lock state.
1075        #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
1076        predicates: PredicateRefs,
1077        /// GenICam `<pInvalidator>` references, in declaration order: each names a
1078        /// node whose change makes this node's cached value stale.
1079        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1080        invalidators: Vec<String>,
1081    },
1082    /// Floating point feature backed by an integer register with scaling,
1083    /// a native IEEE 754 register, or delegated via pValue.
1084    Float {
1085        /// The feature's name.
1086        name: String,
1087        /// Shared metadata: visibility, description, tooltip.
1088        meta: NodeMeta,
1089        /// Addressing metadata (absent when delegated via `pvalue`).
1090        addressing: Option<Addressing>,
1091        /// Declared access mode.
1092        access: AccessMode,
1093        /// `<Min>`; `None` when the XML declares none.
1094        min: Option<f64>,
1095        /// `<Max>`; `None` when the XML declares none.
1096        max: Option<f64>,
1097        /// `<Unit>`, such as `"us"`.
1098        unit: Option<String>,
1099        /// Optional rational scale applied to the raw register value.
1100        scale: Option<(i64, i64)>,
1101        /// Optional additive offset applied after scaling.
1102        offset: Option<f64>,
1103        /// Node providing the value (delegates read/write to another node).
1104        pvalue: Option<String>,
1105        /// Node providing the dynamic minimum.
1106        #[serde(default, skip_serializing_if = "Option::is_none")]
1107        p_min: Option<String>,
1108        /// Node providing the dynamic maximum.
1109        #[serde(default, skip_serializing_if = "Option::is_none")]
1110        p_max: Option<String>,
1111        /// `<Value>`: the start value of a floating `<Float>`, one with no
1112        /// register and no `<pValue>` (GenICam Standard v2.1.1 §2.8.9).
1113        #[serde(default, skip_serializing_if = "Option::is_none")]
1114        value: Option<f64>,
1115        /// `<pIndex>` with `<ValueIndexed>`/`<pValueIndexed>` and
1116        /// `<ValueDefault>`/`<pValueDefault>`: a value picked from a table.
1117        #[serde(default, skip_serializing_if = "Option::is_none")]
1118        indexed: Option<IndexedValue<f64>>,
1119        /// How the register payload should be interpreted — native IEEE 754
1120        /// or scaled integer. Defaults to [`FloatEncoding::ScaledInteger`] to
1121        /// preserve existing behaviour for XML that relied on it.
1122        #[serde(default)]
1123        encoding: FloatEncoding,
1124        /// Byte order of the register payload. Defaults to [`ByteOrder::Big`]
1125        /// (the GenICam default).
1126        #[serde(default = "default_big_endian")]
1127        byte_order: ByteOrder,
1128        /// Predicate refs gating implementation / availability / lock state.
1129        #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
1130        predicates: PredicateRefs,
1131        /// GenICam `<pInvalidator>` references, in declaration order: each names a
1132        /// node whose change makes this node's cached value stale.
1133        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1134        invalidators: Vec<String>,
1135    },
1136    /// Enumeration feature exposing a list of named integer values.
1137    Enum {
1138        /// The feature's name.
1139        name: String,
1140        /// Shared metadata: visibility, description, tooltip.
1141        meta: NodeMeta,
1142        /// Addressing metadata (absent when delegated via `pvalue`).
1143        addressing: Option<Addressing>,
1144        /// Declared access mode.
1145        access: AccessMode,
1146        /// The entries, in document order.
1147        entries: Vec<EnumEntryDecl>,
1148        /// The entry selected when nothing else says.
1149        default: Option<String>,
1150        /// `<pSelected>`: the features this enumeration selects (GenICam
1151        /// Standard v2.1.1 §2.8.4).
1152        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1153        selected: Vec<String>,
1154        /// Node providing the integer value (delegates register read/write).
1155        pvalue: Option<String>,
1156        /// `<Value>`: the start value of an enumeration with no register
1157        /// behind it, a selector the host keeps (AVT's `GainSelector`).
1158        #[serde(default, skip_serializing_if = "Option::is_none")]
1159        value: Option<i64>,
1160        /// Predicate refs gating implementation / availability / lock state.
1161        #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
1162        predicates: PredicateRefs,
1163    },
1164    /// Boolean feature backed by a single bit/byte register or delegated via pValue.
1165    Boolean {
1166        /// The feature's name.
1167        name: String,
1168        /// Shared metadata: visibility, description, tooltip.
1169        meta: NodeMeta,
1170        /// Addressing metadata (absent when delegated via `pvalue`).
1171        addressing: Option<Addressing>,
1172        /// Register length in bytes.
1173        len: u32,
1174        /// Declared access mode.
1175        access: AccessMode,
1176        /// The bit holding the value, when the register has more.
1177        bitfield: Option<BitField>,
1178        /// Node providing the value (delegates read/write to another node).
1179        pvalue: Option<String>,
1180        /// On value for pValue-backed booleans.
1181        on_value: Option<i64>,
1182        /// Off value for pValue-backed booleans.
1183        off_value: Option<i64>,
1184        /// `<Value>`: the start value of a boolean with no register behind
1185        /// it, compared with `on_value`. AVT and Prosilica declare
1186        /// `TLParamsLocked` this way.
1187        #[serde(default, skip_serializing_if = "Option::is_none")]
1188        value: Option<i64>,
1189        /// Predicate refs gating implementation / availability / lock state.
1190        #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
1191        predicates: PredicateRefs,
1192    },
1193    /// Command feature that triggers an action when written.
1194    Command {
1195        /// The feature's name.
1196        name: String,
1197        /// Shared metadata: visibility, description, tooltip.
1198        meta: NodeMeta,
1199        /// Fixed register address (absent when delegated via `pvalue`).
1200        address: Option<u64>,
1201        /// Register length in bytes.
1202        len: u32,
1203        /// Node providing the command register (delegates write).
1204        pvalue: Option<String>,
1205        /// The value executing the command writes: `<CommandValue>` or
1206        /// `<pCommandValue>`.
1207        command_value: CommandValueSrc,
1208        /// Predicate refs gating implementation / availability / lock state.
1209        #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
1210        predicates: PredicateRefs,
1211    },
1212    /// Category used to organise features.
1213    Category {
1214        /// The category's name.
1215        name: String,
1216        /// Shared metadata: visibility, description, tooltip.
1217        meta: NodeMeta,
1218        /// The features and categories it contains, in document order.
1219        children: Vec<String>,
1220        /// Predicate refs gating implementation / availability.
1221        #[serde(default, skip_serializing_if = "PredicateRefs::is_empty")]
1222        predicates: PredicateRefs,
1223    },
1224    /// Computed value backed by an arithmetic expression referencing other nodes.
1225    SwissKnife(SwissKnifeDecl),
1226    /// Converter transforming raw values to/from user-facing floating-point values.
1227    Converter(ConverterDecl),
1228    /// IntConverter transforming raw values to/from user-facing integer values.
1229    IntConverter(IntConverterDecl),
1230    /// StringReg for string-typed register access.
1231    String(StringDecl),
1232    /// Raw byte-array register access.
1233    Register(RegisterDecl),
1234}
1235
1236impl NodeDecl {
1237    /// Feature name declared by this node.
1238    pub fn name(&self) -> &str {
1239        match self {
1240            NodeDecl::Integer { name, .. }
1241            | NodeDecl::Float { name, .. }
1242            | NodeDecl::Enum { name, .. }
1243            | NodeDecl::Boolean { name, .. }
1244            | NodeDecl::Command { name, .. }
1245            | NodeDecl::Category { name, .. } => name,
1246            NodeDecl::SwissKnife(decl) => &decl.name,
1247            NodeDecl::Converter(decl) => &decl.name,
1248            NodeDecl::IntConverter(decl) => &decl.name,
1249            NodeDecl::String(decl) => &decl.name,
1250            NodeDecl::Register(decl) => &decl.name,
1251        }
1252    }
1253
1254    /// The metadata every node kind carries.
1255    pub fn meta(&self) -> &NodeMeta {
1256        match self {
1257            NodeDecl::Integer { meta, .. }
1258            | NodeDecl::Float { meta, .. }
1259            | NodeDecl::Enum { meta, .. }
1260            | NodeDecl::Boolean { meta, .. }
1261            | NodeDecl::Command { meta, .. }
1262            | NodeDecl::Category { meta, .. } => meta,
1263            NodeDecl::SwissKnife(decl) => &decl.meta,
1264            NodeDecl::Converter(decl) => &decl.meta,
1265            NodeDecl::IntConverter(decl) => &decl.meta,
1266            NodeDecl::String(decl) => &decl.meta,
1267            NodeDecl::Register(decl) => &decl.meta,
1268        }
1269    }
1270
1271    /// Node kind, matching the variant name.
1272    ///
1273    /// This is the declaration kind rather than the originating XML tag: an
1274    /// `<IntReg>` and a `<MaskedIntReg>` both report `Integer`. Useful for
1275    /// grouping and for reporting nodes that were dropped downstream of
1276    /// parsing.
1277    pub fn kind(&self) -> &'static str {
1278        match self {
1279            NodeDecl::Integer { .. } => "Integer",
1280            NodeDecl::Float { .. } => "Float",
1281            NodeDecl::Enum { .. } => "Enum",
1282            NodeDecl::Boolean { .. } => "Boolean",
1283            NodeDecl::Command { .. } => "Command",
1284            NodeDecl::Category { .. } => "Category",
1285            NodeDecl::SwissKnife(_) => "SwissKnife",
1286            NodeDecl::Converter(_) => "Converter",
1287            NodeDecl::IntConverter(_) => "IntConverter",
1288            NodeDecl::String(_) => "String",
1289            NodeDecl::Register(_) => "Register",
1290        }
1291    }
1292}
1293
1294/// A node element that could not be parsed and was left out of the model.
1295///
1296/// Parsing isolates each node, so a declaration we cannot make sense of costs
1297/// that one feature instead of the whole document. These records exist so the
1298/// loss is visible rather than silent — surface them in a UI, log them, or
1299/// assert on them in tests.
1300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1301#[non_exhaustive]
1302pub struct SkippedNode {
1303    /// XML tag of the node element, e.g. `Integer`.
1304    pub tag: String,
1305    /// `Name` attribute, when the element had one.
1306    pub name: Option<String>,
1307    /// Rendered parse error explaining why the node was dropped.
1308    pub error: String,
1309}
1310
1311impl SkippedNode {
1312    /// A node dropped from the document: its tag, its name when it had one,
1313    /// and why.
1314    pub fn new(tag: impl Into<String>, name: Option<String>, error: impl Into<String>) -> Self {
1315        Self {
1316            tag: tag.into(),
1317            name,
1318            error: error.into(),
1319        }
1320    }
1321}
1322
1323/// A child element of a node that the parser read past without interpreting
1324/// it: the node loaded, but whatever the element says was not taken into
1325/// account.
1326///
1327/// Most such elements are documentation or presentation — `<Extension>`, a
1328/// vendor's own block — but not all: a `<String>`'s `<pValue>` was read past
1329/// this way, so the string read empty and nothing said why (found on an
1330/// mvBlueFOX3-2004G). These records make that class of loss visible, as
1331/// [`SkippedNode`] does for whole nodes. See [`XmlModel::ignored`].
1332#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1333#[non_exhaustive]
1334pub struct IgnoredElement {
1335    /// The node's name.
1336    pub node: String,
1337    /// The node's kind, as [`NodeDecl::kind`] names it, or `Port`.
1338    pub kind: String,
1339    /// The element's tag, as [`NodeMeta::ignored`] writes it.
1340    pub element: String,
1341}
1342
1343impl IgnoredElement {
1344    /// An element of `node`, a node of `kind`, read past.
1345    pub fn new(
1346        node: impl Into<String>,
1347        kind: impl Into<String>,
1348        element: impl Into<String>,
1349    ) -> Self {
1350        Self {
1351            node: node.into(),
1352            kind: kind.into(),
1353            element: element.into(),
1354        }
1355    }
1356}
1357
1358/// What a `<Port>` gives access to.
1359///
1360/// GenICam Standard v2.1.1 §2.8.16: a port "is just a proxy that forwards Read
1361/// and Write calls to the transport layer". One with a `<ChunkID>` "does not
1362/// give access to a real device, but rather to the chunk of data residing in
1363/// memory"; one with an `<EventID>` likewise to the data an event message
1364/// carries. The ids are hexadecimal numbers written without a `0x`: FLIR's
1365/// `TimestampPort` is `<ChunkID>0508000E</ChunkID>`, its
1366/// `EventExposureEndPort` `<EventID>9C43</EventID>`.
1367#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1368#[non_exhaustive]
1369pub enum PortKind {
1370    /// The device's own register space.
1371    Device,
1372    /// One chunk of a stream buffer, found by its chunk ID.
1373    Chunk {
1374        /// `<ChunkID>`.
1375        chunk_id: u64,
1376    },
1377    /// One event message, found by its event ID.
1378    Event {
1379        /// `<EventID>`.
1380        event_id: u64,
1381    },
1382}
1383
1384/// A `<Port>` declaration.
1385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1386#[non_exhaustive]
1387pub struct PortDecl {
1388    /// Port name, as `<pPort>` elements refer to it.
1389    pub name: String,
1390    /// What the port reads.
1391    pub kind: PortKind,
1392    /// Child elements read past without interpretation, as
1393    /// [`NodeMeta::ignored`].
1394    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1395    pub ignored: Vec<String>,
1396}
1397
1398/// Which camera a document describes, and which revision of the document it
1399/// is: the `<RegisterDescription>` attributes of GenICam Standard v2.1.1 §2.7.
1400///
1401/// "The camera described is identified by the VendorName / ModelName pair";
1402/// `MajorVersion.MinorVersion.SubMinorVersion` is the version of the XML file
1403/// itself, distinct from the schema version in [`XmlModel::version`]. Empty
1404/// strings where the document leaves an attribute out.
1405#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1406#[non_exhaustive]
1407pub struct DocumentIdentity {
1408    /// `VendorName`.
1409    pub vendor_name: String,
1410    /// `ModelName`.
1411    pub model_name: String,
1412    /// `MajorVersion.MinorVersion.SubMinorVersion`, or empty when the
1413    /// document declares none of the three.
1414    pub version: String,
1415}
1416
1417impl DocumentIdentity {
1418    /// The identity of a document by vendor, model and version.
1419    pub fn new(
1420        vendor_name: impl Into<String>,
1421        model_name: impl Into<String>,
1422        version: impl Into<String>,
1423    ) -> Self {
1424        Self {
1425            vendor_name: vendor_name.into(),
1426            model_name: model_name.into(),
1427            version: version.into(),
1428        }
1429    }
1430}
1431
1432/// Full XML model describing the GenICam schema version and all declared nodes.
1433#[derive(Debug, Clone, Serialize, Deserialize)]
1434#[non_exhaustive]
1435pub struct XmlModel {
1436    /// Combined schema version extracted from the RegisterDescription attributes.
1437    pub version: String,
1438    /// The camera the document describes, and the document's own version.
1439    #[serde(default)]
1440    pub identity: DocumentIdentity,
1441    /// Flat list of node declarations present in the document.
1442    pub nodes: Vec<NodeDecl>,
1443    /// The `<Port>` declarations, in document order.
1444    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1445    pub ports: Vec<PortDecl>,
1446    /// Node elements that failed to parse and were skipped. Empty for a clean
1447    /// document.
1448    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1449    pub skipped: Vec<SkippedNode>,
1450}
1451
1452impl XmlModel {
1453    /// Every child element the parser read past without interpreting it,
1454    /// node by node in document order, then the ports'. Empty when the
1455    /// parser understood every element of every node it kept; see
1456    /// [`IgnoredElement`].
1457    pub fn ignored(&self) -> Vec<IgnoredElement> {
1458        let nodes = self.nodes.iter().flat_map(|node| {
1459            node.meta()
1460                .ignored
1461                .iter()
1462                .map(|element| IgnoredElement::new(node.name(), node.kind(), element.as_str()))
1463        });
1464        let ports = self.ports.iter().flat_map(|port| {
1465            port.ignored
1466                .iter()
1467                .map(|element| IgnoredElement::new(port.name.as_str(), "Port", element.as_str()))
1468        });
1469        nodes.chain(ports).collect()
1470    }
1471}
1472
1473/// Minimal metadata extracted from a quick XML scan.
1474#[derive(Debug, Clone, PartialEq, Eq)]
1475#[non_exhaustive]
1476pub struct MinimalXmlInfo {
1477    /// `SchemaMajorVersion.SchemaMinorVersion.SchemaSubMinorVersion`, when declared.
1478    pub schema_version: Option<String>,
1479    /// The features the root category lists.
1480    pub top_level_features: Vec<String>,
1481}
1482
1483/// Drop a leading UTF-8 byte-order mark.
1484///
1485/// A BOM is valid UTF-8 (`U+FEFF`), so it survives `String::from_utf8` and
1486/// reaches the parser intact; The Imaging Source's DMK 33GP2000e ships one
1487/// (issue #122). quick-xml removes it from its own view of the input but does
1488/// **not** advance `Reader::buffer_position`, so every offset it reports is
1489/// three bytes short of the true offset into `xml`. [`parse`] slices node
1490/// elements out of `xml` by those offsets, so each slice lost its closing `>`
1491/// and every node in the document was skipped. Stripping here keeps quick-xml's
1492/// positions and our `&str` talking about the same bytes.
1493fn strip_bom(xml: &str) -> &str {
1494    xml.strip_prefix('\u{feff}').unwrap_or(xml)
1495}
1496
1497/// Parse a GenICam XML snippet and collect minimal metadata.
1498pub fn parse_into_minimal_nodes(xml: &str) -> Result<MinimalXmlInfo, XmlError> {
1499    let xml = strip_bom(xml);
1500    let mut reader = Reader::from_str(xml);
1501    reader.config_mut().trim_text(true);
1502    // Vendor XML is not ours to fix: a lone `&` in a tooltip must not stop us
1503    // from reading the document.
1504    reader.config_mut().allow_dangling_amp = true;
1505    let mut buf = Vec::new();
1506    let mut depth = 0usize;
1507    let mut schema_version: Option<String> = None;
1508    let mut top_level_features = Vec::new();
1509
1510    loop {
1511        match reader.read_event_into(&mut buf) {
1512            Ok(Event::Start(e)) => {
1513                depth += 1;
1514                handle_start(&e, depth, &mut schema_version, &mut top_level_features)?;
1515            }
1516            Ok(Event::Empty(e)) => {
1517                depth += 1;
1518                handle_start(&e, depth, &mut schema_version, &mut top_level_features)?;
1519                depth = depth.saturating_sub(1);
1520            }
1521            Ok(Event::End(_)) => {
1522                depth = depth.saturating_sub(1);
1523            }
1524            Ok(Event::Eof) => break,
1525            Err(err) => return Err(XmlError::malformed(err)),
1526            _ => {}
1527        }
1528        buf.clear();
1529    }
1530
1531    Ok(MinimalXmlInfo {
1532        schema_version,
1533        top_level_features,
1534    })
1535}
1536
1537/// `true` for tags this parser turns into one or more [`NodeDecl`]s.
1538fn is_node_tag(tag: &str) -> bool {
1539    matches!(
1540        tag,
1541        "Integer"
1542            | "IntReg"
1543            | "MaskedIntReg"
1544            | "IntSwissKnife"
1545            | "SwissKnife"
1546            | "Float"
1547            | "FloatReg"
1548            | "Enumeration"
1549            | "Boolean"
1550            | "Command"
1551            | "Category"
1552            | "Converter"
1553            | "IntConverter"
1554            | "Register"
1555            | "StringReg"
1556            | "String"
1557            | "StructReg"
1558    )
1559}
1560
1561/// Record an element this parser has no node type for, or `None` if it is not
1562/// a node at all.
1563///
1564/// A node declaration is told from a structural element by its `Name`
1565/// attribute, which the GenApi schema requires on every node and on nothing
1566/// else at this level. Without this, an unlisted tag fell through to
1567/// `skip_element` and vanished — no log line, no [`XmlModel::skipped`] entry,
1568/// nothing for a corpus test to trip over. `<Register>`, 56 declarations
1569/// across 14 corpus documents, disappeared exactly this way.
1570fn unknown_node(tag: &str, start: &BytesStart<'_>) -> Result<Option<SkippedNode>, XmlError> {
1571    let Some(name) = attribute_value(start, "Name")? else {
1572        return Ok(None);
1573    };
1574    let tag = tag.to_owned();
1575    tracing::warn!(
1576        tag = %tag,
1577        node = %name,
1578        "skipping node of an unsupported type"
1579    );
1580    Ok(Some(SkippedNode {
1581        error: format!("unsupported node type <{tag}>"),
1582        tag,
1583        name: Some(name),
1584    }))
1585}
1586
1587/// Dispatch a node element to its parser. `start` must be the element's start
1588/// event and `reader` must be positioned just after it.
1589fn parse_node(
1590    reader: &mut Reader<&[u8]>,
1591    start: BytesStart<'_>,
1592) -> Result<Vec<NodeDecl>, XmlError> {
1593    let tag = start.name().as_ref().to_string();
1594    let node = match tag.as_str() {
1595        "Integer" | "IntReg" | "MaskedIntReg" => parse_integer(reader, start)?,
1596        "IntSwissKnife" | "SwissKnife" => parse_swissknife(reader, start)?,
1597        "Float" | "FloatReg" => parse_float(reader, start)?,
1598        "Enumeration" => parse_enum(reader, start)?,
1599        "Boolean" => parse_boolean(reader, start)?,
1600        "Command" => parse_command(reader, start)?,
1601        "Category" => parse_category(reader, start)?,
1602        "Converter" => parse_converter(reader, start)?,
1603        "IntConverter" => parse_int_converter(reader, start)?,
1604        "Register" => parse_register(reader, start)?,
1605        "StringReg" | "String" => parse_string(reader, start)?,
1606        "StructReg" => return parse_struct_reg(reader, start),
1607        other => {
1608            return Err(XmlError::invalid(other, "is not a node element"));
1609        }
1610    };
1611    Ok(vec![node])
1612}
1613
1614/// Parse one node element in isolation, from a slice spanning the whole element.
1615///
1616/// A fresh reader over just this element means a parse failure cannot leave the
1617/// document-level reader at an unknown position — the caller has already
1618/// consumed exactly this element and is correctly positioned either way.
1619fn parse_isolated_node(element: &str) -> Result<Vec<NodeDecl>, XmlError> {
1620    let mut reader = Reader::from_str(element);
1621    reader.config_mut().trim_text(true);
1622    reader.config_mut().allow_dangling_amp = true;
1623    let mut buf = Vec::new();
1624    loop {
1625        match reader.read_event_into(&mut buf) {
1626            Ok(Event::Start(e)) => {
1627                let start = e.into_owned();
1628                let mut nodes = parse_node(&mut reader, start)?;
1629                nodes.extend(parsers::embedded_knives(element)?);
1630                return Ok(nodes);
1631            }
1632            Ok(Event::Eof) => {
1633                return Err(XmlError::invalid("node element", "is empty"));
1634            }
1635            Err(err) => return Err(XmlError::malformed(err)),
1636            // Leading whitespace or a comment before the start tag.
1637            _ => {}
1638        }
1639    }
1640}
1641
1642/// Parse one `<Port>` element in isolation, as [`parse_isolated_node`] does
1643/// for a node.
1644fn parse_isolated_port(element: &str) -> Result<PortDecl, XmlError> {
1645    let mut reader = Reader::from_str(element);
1646    reader.config_mut().trim_text(true);
1647    reader.config_mut().allow_dangling_amp = true;
1648    let mut buf = Vec::new();
1649    loop {
1650        match reader.read_event_into(&mut buf) {
1651            Ok(Event::Start(e)) => {
1652                let start = e.into_owned();
1653                return parse_port(&mut reader, start);
1654            }
1655            Ok(Event::Empty(e)) => return parse_port_empty(&e),
1656            Ok(Event::Eof) => {
1657                return Err(XmlError::invalid("<Port>", "is empty"));
1658            }
1659            Err(err) => return Err(XmlError::malformed(err)),
1660            _ => {}
1661        }
1662    }
1663}
1664
1665/// Parse a GenICam XML document into an [`XmlModel`].
1666///
1667/// The parser only understands a practical subset of the schema. Unknown tags
1668/// are skipped which keeps the implementation forward compatible with richer
1669/// documents.
1670///
1671/// Each node element is parsed in isolation: one declaration we cannot make
1672/// sense of costs that single feature and is recorded in [`XmlModel::skipped`],
1673/// rather than failing the load and leaving the camera unopenable. Only errors
1674/// that make the document as a whole unreadable are returned.
1675pub fn parse(xml: &str) -> Result<XmlModel, XmlError> {
1676    let xml = strip_bom(xml);
1677    let mut reader = Reader::from_str(xml);
1678    reader.config_mut().trim_text(true);
1679    // Vendor XML is not ours to fix: a lone `&` in a tooltip must not stop us
1680    // from opening the camera.
1681    reader.config_mut().allow_dangling_amp = true;
1682    let mut buf = Vec::new();
1683    let mut version = String::from("0.0.0");
1684    let mut identity = DocumentIdentity::default();
1685    let mut nodes = Vec::new();
1686    let mut ports = Vec::new();
1687    let mut skipped = Vec::new();
1688
1689    loop {
1690        // Captured before the read so a node element's slice can be recovered
1691        // verbatim, start tag included.
1692        let element_start = reader.buffer_position() as usize;
1693        match reader.read_event_into(&mut buf) {
1694            Ok(Event::Start(ref e)) => match e.name().as_ref() {
1695                "RegisterDescription" => {
1696                    version = schema_version_from(e)?;
1697                    identity = identity_from(e)?;
1698                }
1699                "Group" => {
1700                    // Group is a transparent container wrapping feature nodes;
1701                    // let child events surface in the next loop iterations.
1702                }
1703                "Port" => {
1704                    let name = attribute_value(e, "Name")?;
1705                    reader
1706                        .read_to_end(QName("Port"))
1707                        .map_err(XmlError::malformed)?;
1708                    let element = xml
1709                        .get(element_start..reader.buffer_position() as usize)
1710                        .ok_or_else(|| {
1711                            XmlError::invalid(
1712                                name.as_deref().unwrap_or("<Port>"),
1713                                "does not start and end on character boundaries",
1714                            )
1715                        });
1716                    match element.and_then(parse_isolated_port) {
1717                        Ok(port) => ports.push(port),
1718                        Err(err) => {
1719                            tracing::warn!(
1720                                port = name.as_deref().unwrap_or("<unnamed>"),
1721                                error = %err,
1722                                "skipping unparsable port"
1723                            );
1724                            skipped.push(SkippedNode {
1725                                tag: "Port".to_string(),
1726                                name,
1727                                error: err.to_string(),
1728                            });
1729                        }
1730                    }
1731                }
1732                tag if is_node_tag(tag) => {
1733                    let tag = tag.to_owned();
1734                    let name = attribute_value(e, "Name")?;
1735                    // Consume the element up front: whatever the node parser
1736                    // makes of it, the document reader stays in step.
1737                    reader
1738                        .read_to_end(QName(&tag))
1739                        .map_err(XmlError::malformed)?;
1740                    // `get`, not `[..]`: this slice is built from reader
1741                    // offsets rather than from `xml` itself, and a byte-order
1742                    // mark used to desynchronise the two (#122). Indexing
1743                    // panics on a non-character-boundary index; `get` turns the
1744                    // same disagreement into one skipped feature, which is the
1745                    // right price to pay in the middle of a camera connect.
1746                    let element = xml
1747                        .get(element_start..reader.buffer_position() as usize)
1748                        .ok_or_else(|| {
1749                            XmlError::invalid(
1750                                name.as_deref().unwrap_or(&tag),
1751                                "does not start and end on character boundaries",
1752                            )
1753                        });
1754                    match element.and_then(parse_isolated_node) {
1755                        Ok(parsed) => nodes.extend(parsed),
1756                        Err(err) => {
1757                            tracing::warn!(
1758                                tag = %tag,
1759                                node = name.as_deref().unwrap_or("<unnamed>"),
1760                                error = %err,
1761                                "skipping unparsable node"
1762                            );
1763                            skipped.push(SkippedNode {
1764                                tag,
1765                                name,
1766                                error: err.to_string(),
1767                            });
1768                        }
1769                    }
1770                }
1771                tag => {
1772                    let unknown = unknown_node(tag, e)?;
1773                    skip_element(&mut reader, e.name().as_ref())?;
1774                    if let Some(record) = unknown {
1775                        skipped.push(record);
1776                    }
1777                }
1778            },
1779            Ok(Event::Empty(ref e)) => match e.name().as_ref() {
1780                "RegisterDescription" => {
1781                    version = schema_version_from(e)?;
1782                }
1783                // An empty `<Command/>` has no `<CommandValue>` to write.
1784                "Command" => {
1785                    let name = attribute_value(e, "Name")?;
1786                    let error = missing_command_value(name.as_deref().unwrap_or("<unnamed>"));
1787                    tracing::warn!(error = %error, "skipping unparsable node");
1788                    skipped.push(SkippedNode {
1789                        tag: "Command".to_string(),
1790                        name,
1791                        error: error.to_string(),
1792                    });
1793                }
1794                "Category" => {
1795                    let node = parse_category_empty(e)?;
1796                    nodes.push(node);
1797                }
1798                // Four corpus documents declare `<Port Name="Device"/>`.
1799                "Port" => match parse_port_empty(e) {
1800                    Ok(port) => ports.push(port),
1801                    Err(err) => skipped.push(SkippedNode {
1802                        tag: "Port".to_string(),
1803                        name: None,
1804                        error: err.to_string(),
1805                    }),
1806                },
1807                tag => {
1808                    if let Some(record) = unknown_node(tag, e)? {
1809                        skipped.push(record);
1810                    }
1811                }
1812            },
1813            Ok(Event::Eof) => break,
1814            Err(err) => return Err(XmlError::malformed(err)),
1815            _ => {}
1816        }
1817        buf.clear();
1818    }
1819
1820    if !skipped.is_empty() {
1821        tracing::warn!(
1822            count = skipped.len(),
1823            total = nodes.len() + skipped.len(),
1824            "some GenApi nodes could not be parsed and were skipped"
1825        );
1826    }
1827
1828    Ok(XmlModel {
1829        version,
1830        identity,
1831        nodes,
1832        ports,
1833        skipped,
1834    })
1835}
1836
1837fn schema_version_from(event: &BytesStart<'_>) -> Result<String, XmlError> {
1838    let major = attribute_value(event, "SchemaMajorVersion")?;
1839    let minor = attribute_value(event, "SchemaMinorVersion")?;
1840    let sub = attribute_value(event, "SchemaSubMinorVersion")?;
1841    let major = major.unwrap_or_else(|| "0".to_string());
1842    let minor = minor.unwrap_or_else(|| "0".to_string());
1843    let sub = sub.unwrap_or_else(|| "0".to_string());
1844    Ok(format!("{major}.{minor}.{sub}"))
1845}
1846
1847/// The camera and document version `<RegisterDescription>` names (§2.7).
1848fn identity_from(event: &BytesStart<'_>) -> Result<DocumentIdentity, XmlError> {
1849    let text = |name: &str| -> Result<String, XmlError> {
1850        Ok(attribute_value(event, name)?
1851            .map(|value| value.trim().to_string())
1852            .unwrap_or_default())
1853    };
1854    let parts = [
1855        text("MajorVersion")?,
1856        text("MinorVersion")?,
1857        text("SubMinorVersion")?,
1858    ];
1859    let version = if parts.iter().all(String::is_empty) {
1860        String::new()
1861    } else {
1862        parts
1863            .map(|part| {
1864                if part.is_empty() {
1865                    "0".to_string()
1866                } else {
1867                    part
1868                }
1869            })
1870            .join(".")
1871    };
1872    Ok(DocumentIdentity {
1873        vendor_name: text("VendorName")?,
1874        model_name: text("ModelName")?,
1875        version,
1876    })
1877}
1878
1879fn handle_start(
1880    event: &BytesStart<'_>,
1881    depth: usize,
1882    schema_version: &mut Option<String>,
1883    top_level: &mut Vec<String>,
1884) -> Result<(), XmlError> {
1885    if depth == 1 && schema_version.is_none() {
1886        *schema_version = extract_schema_version(event);
1887    } else if depth == 2 {
1888        if let Some(name) = attribute_value(event, "Name")? {
1889            top_level.push(name);
1890        } else {
1891            top_level.push(event.name().as_ref().to_string());
1892        }
1893    }
1894    Ok(())
1895}
1896
1897fn extract_schema_version(event: &BytesStart<'_>) -> Option<String> {
1898    let major = attribute_value(event, "SchemaMajorVersion").ok().flatten();
1899    let minor = attribute_value(event, "SchemaMinorVersion").ok().flatten();
1900    let sub = attribute_value(event, "SchemaSubMinorVersion")
1901        .ok()
1902        .flatten();
1903    if major.is_none() && minor.is_none() && sub.is_none() {
1904        None
1905    } else {
1906        let major = major.unwrap_or_else(|| "0".to_string());
1907        let minor = minor.unwrap_or_else(|| "0".to_string());
1908        let sub = sub.unwrap_or_else(|| "0".to_string());
1909        Some(format!("{major}.{minor}.{sub}"))
1910    }
1911}
1912
1913#[cfg(test)]
1914mod tests {
1915    use super::*;
1916
1917    const FIXTURE: &str = r#"
1918        <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="2" SchemaSubMinorVersion="3">
1919            <Category Name="Root">
1920                <pFeature>Gain</pFeature>
1921                <pFeature>GainSelector</pFeature>
1922            </Category>
1923            <Integer Name="Width">
1924                <Address>0x0000_0100</Address>
1925                <Length>4</Length>
1926                <AccessMode>RW</AccessMode>
1927                <Min>16</Min>
1928                <Max>4096</Max>
1929                <Inc>2</Inc>
1930            </Integer>
1931            <Float Name="ExposureTime">
1932                <Address>0x0000_0200</Address>
1933                <Length>4</Length>
1934                <AccessMode>RW</AccessMode>
1935                <Min>10.0</Min>
1936                <Max>200000.0</Max>
1937                <Scale>1/1000</Scale>
1938                <Offset>0.0</Offset>
1939            </Float>
1940            <Enumeration Name="GainSelector">
1941                <Address>0x0000_0300</Address>
1942                <Length>2</Length>
1943                <AccessMode>RW</AccessMode>
1944                <EnumEntry Name="AnalogAll" Value="0" />
1945                <EnumEntry Name="DigitalAll" Value="1" />
1946                <pSelected>Gain</pSelected>
1947            </Enumeration>
1948            <Integer Name="Gain">
1949                <Address>0x0000_0304</Address>
1950                <Length>2</Length>
1951                <AccessMode>RW</AccessMode>
1952                <Min>0</Min>
1953                <Max>48</Max>
1954            </Integer>
1955            <Boolean Name="GammaEnable">
1956                <Address>0x0000_0400</Address>
1957                <Length>1</Length>
1958                <AccessMode>RW</AccessMode>
1959            </Boolean>
1960            <Command Name="AcquisitionStart">
1961                <Address>0x0000_0500</Address>
1962                <Length>4</Length>
1963                <CommandValue>1</CommandValue>
1964            </Command>
1965        </RegisterDescription>
1966    "#;
1967
1968    #[test]
1969    fn parse_minimal_xml() {
1970        let info = parse_into_minimal_nodes(FIXTURE).expect("parse xml");
1971        assert_eq!(info.schema_version.as_deref(), Some("1.2.3"));
1972        assert_eq!(info.top_level_features.len(), 7);
1973        assert_eq!(info.top_level_features[0], "Root");
1974    }
1975
1976    #[test]
1977    fn parse_fixture_model() {
1978        let model = parse(FIXTURE).expect("parse fixture");
1979        assert_eq!(model.version, "1.2.3");
1980        assert_eq!(model.nodes.len(), 7);
1981        match &model.nodes[0] {
1982            NodeDecl::Category { name, children, .. } => {
1983                assert_eq!(name, "Root");
1984                assert_eq!(
1985                    children,
1986                    &vec!["Gain".to_string(), "GainSelector".to_string()]
1987                );
1988            }
1989            other => panic!("unexpected node: {other:?}"),
1990        }
1991        match &model.nodes[1] {
1992            NodeDecl::Integer {
1993                name,
1994                min,
1995                max,
1996                inc,
1997                ..
1998            } => {
1999                assert_eq!(name, "Width");
2000                assert_eq!(*min, Some(16));
2001                assert_eq!(*max, Some(4096));
2002                assert_eq!(*inc, Some(2));
2003            }
2004            other => panic!("unexpected node: {other:?}"),
2005        }
2006        match &model.nodes[2] {
2007            NodeDecl::Float {
2008                name,
2009                scale,
2010                offset,
2011                ..
2012            } => {
2013                assert_eq!(name, "ExposureTime");
2014                assert_eq!(*scale, Some((1, 1000)));
2015                assert_eq!(*offset, Some(0.0));
2016            }
2017            other => panic!("unexpected node: {other:?}"),
2018        }
2019        match &model.nodes[3] {
2020            NodeDecl::Enum {
2021                name,
2022                entries,
2023                selected,
2024                ..
2025            } => {
2026                assert_eq!(name, "GainSelector");
2027                assert_eq!(entries.len(), 2);
2028                assert!(matches!(entries[0].value, EnumValueSrc::Literal(0)));
2029                assert!(matches!(entries[1].value, EnumValueSrc::Literal(1)));
2030                // GenICam Standard v2.1.1 §2.8.4: the selector names what it
2031                // selects (backlog GA-03).
2032                assert_eq!(selected, &["Gain".to_string()]);
2033            }
2034            other => panic!("unexpected node: {other:?}"),
2035        }
2036        match &model.nodes[4] {
2037            NodeDecl::Integer {
2038                name, addressing, ..
2039            } => {
2040                assert_eq!(name, "Gain");
2041                assert_eq!(addressing, &Some(Addressing::fixed(0x304, 2)));
2042            }
2043            other => panic!("unexpected node: {other:?}"),
2044        }
2045    }
2046
2047    /// GA-17: an `<IntSwissKnife>` embedded in a register is one of its
2048    /// address terms (GenICam Standard v2.1.1 §2.8.3), declared as a node of
2049    /// the document under its own name — the schema's node-name key covers
2050    /// it. A StructReg takes one the same way; one that does not parse costs
2051    /// its register, recorded as skipped.
2052    #[test]
2053    fn an_embedded_intswissknife_is_declared_and_summed() {
2054        const XML: &str = r#"
2055            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
2056                <MaskedIntReg Name="MacHigh">
2057                    <Address>0x10</Address>
2058                    <IntSwissKnife Name="MacHighAddress">
2059                        <pVariable Name="INTERFACE">InterfaceSelector</pVariable>
2060                        <Formula>(INTERFACE = 0)? 0x0008 : 0x0680</Formula>
2061                    </IntSwissKnife>
2062                    <Length>4</Length>
2063                    <AccessMode>RO</AccessMode>
2064                    <pPort>Device</pPort>
2065                    <LSB>31</LSB>
2066                    <MSB>16</MSB>
2067                </MaskedIntReg>
2068                <StructReg Comment="flags">
2069                    <IntSwissKnife Name="FlagsAddress">
2070                        <Formula>0x2000 + 4</Formula>
2071                    </IntSwissKnife>
2072                    <Length>4</Length>
2073                    <AccessMode>RO</AccessMode>
2074                    <pPort>Device</pPort>
2075                    <StructEntry Name="FlagA"><Bit>0</Bit></StructEntry>
2076                </StructReg>
2077                <IntReg Name="Broken">
2078                    <IntSwissKnife Name="BrokenAddress">
2079                        <Formula></Formula>
2080                    </IntSwissKnife>
2081                    <Length>4</Length>
2082                    <AccessMode>RO</AccessMode>
2083                    <pPort>Device</pPort>
2084                </IntReg>
2085            </RegisterDescription>
2086        "#;
2087
2088        let model = parse(XML).expect("parse");
2089        let terms = |name: &str| match model.nodes.iter().find(|n| n.name() == name) {
2090            Some(NodeDecl::Integer {
2091                addressing: Some(Addressing::Sum { terms, .. }),
2092                ..
2093            }) => terms.clone(),
2094            other => panic!("{name}: {other:?}"),
2095        };
2096        assert_eq!(
2097            terms("MacHigh"),
2098            [
2099                AddressTerm::Fixed(0x10),
2100                AddressTerm::Node("MacHighAddress".to_string())
2101            ]
2102        );
2103        assert_eq!(
2104            terms("FlagA"),
2105            [AddressTerm::Node("FlagsAddress".to_string())]
2106        );
2107        let knife = |name: &str| match model.nodes.iter().find(|n| n.name() == name) {
2108            Some(NodeDecl::SwissKnife(knife)) => knife.clone(),
2109            other => panic!("{name}: {other:?}"),
2110        };
2111        let mac = knife("MacHighAddress");
2112        assert_eq!(mac.output, SkOutput::Integer);
2113        assert_eq!(mac.expr, "(INTERFACE = 0)? 0x0008 : 0x0680");
2114        assert_eq!(
2115            mac.variables,
2116            [("INTERFACE".to_string(), "InterfaceSelector".to_string())]
2117        );
2118        assert_eq!(knife("FlagsAddress").expr, "0x2000 + 4");
2119
2120        assert!(model.nodes.iter().all(|n| n.name() != "Broken"));
2121        assert!(model.nodes.iter().all(|n| n.name() != "BrokenAddress"));
2122        assert!(
2123            model
2124                .skipped
2125                .iter()
2126                .any(|s| s.name.as_deref() == Some("Broken")),
2127            "{:?}",
2128            model.skipped
2129        );
2130    }
2131
2132    #[test]
2133    fn parse_swissknife_node() {
2134        const XML: &str = r#"
2135            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2136                <Integer Name="GainRaw">
2137                    <Address>0x3000</Address>
2138                    <Length>4</Length>
2139                    <AccessMode>RW</AccessMode>
2140                    <Min>0</Min>
2141                    <Max>1000</Max>
2142                </Integer>
2143                <Float Name="Offset">
2144                    <Address>0x3008</Address>
2145                    <Length>4</Length>
2146                    <AccessMode>RW</AccessMode>
2147                    <Min>-100.0</Min>
2148                    <Max>100.0</Max>
2149                </Float>
2150                <SwissKnife Name="ComputedGain">
2151                    <Expression>(GainRaw * 0.5) + Offset</Expression>
2152                    <pVariable Name="GainRaw">GainRaw</pVariable>
2153                    <pVariable Name="Offset">Offset</pVariable>
2154                    <Output>Float</Output>
2155                </SwissKnife>
2156            </RegisterDescription>
2157        "#;
2158
2159        let model = parse(XML).expect("parse swissknife xml");
2160        assert_eq!(model.nodes.len(), 3);
2161        let swiss = model
2162            .nodes
2163            .iter()
2164            .find_map(|decl| match decl {
2165                NodeDecl::SwissKnife(node) => Some(node),
2166                _ => None,
2167            })
2168            .expect("swissknife present");
2169        assert_eq!(swiss.name, "ComputedGain");
2170        assert_eq!(swiss.expr, "(GainRaw * 0.5) + Offset");
2171        assert_eq!(swiss.output, SkOutput::Float);
2172        assert_eq!(swiss.variables.len(), 2);
2173        assert_eq!(
2174            swiss.variables[0],
2175            ("GainRaw".to_string(), "GainRaw".to_string())
2176        );
2177        assert_eq!(
2178            swiss.variables[1],
2179            ("Offset".to_string(), "Offset".to_string())
2180        );
2181    }
2182
2183    #[test]
2184    fn parse_int_swissknife_with_hex_and_ampersand() {
2185        // Test that &amp; is decoded to & and hex literals are supported.
2186        const XML: &str = r#"
2187            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2188                <IntSwissKnife Name="PayloadSize">
2189                    <pVariable Name="W">Width</pVariable>
2190                    <pVariable Name="H">Height</pVariable>
2191                    <pVariable Name="PF">PixelFormat</pVariable>
2192                    <Formula>W * H * ((PF>>16)&amp;0xFF) / 8</Formula>
2193                </IntSwissKnife>
2194            </RegisterDescription>
2195        "#;
2196
2197        let model = parse(XML).expect("parse intswissknife");
2198        assert_eq!(model.nodes.len(), 1);
2199        let swiss = model
2200            .nodes
2201            .iter()
2202            .find_map(|decl| match decl {
2203                NodeDecl::SwissKnife(node) => Some(node),
2204                _ => None,
2205            })
2206            .expect("swissknife present");
2207        assert_eq!(swiss.name, "PayloadSize");
2208        // &amp; should be decoded to &
2209        assert!(
2210            swiss.expr.contains('&'),
2211            "expression should contain decoded '&': {}",
2212            swiss.expr
2213        );
2214        assert!(
2215            swiss.expr.contains("0xFF"),
2216            "expression should contain hex literal: {}",
2217            swiss.expr
2218        );
2219    }
2220
2221    #[test]
2222    fn parse_enum_entry_with_pvalue() {
2223        const XML: &str = r#"
2224            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2225                <Enumeration Name="Mode">
2226                    <Address>0x0000_4000</Address>
2227                    <Length>4</Length>
2228                    <AccessMode>RW</AccessMode>
2229                    <EnumEntry Name="Fixed10">
2230                        <Value>10</Value>
2231                    </EnumEntry>
2232                    <EnumEntry Name="DynFromReg">
2233                        <pValue>RegModeVal</pValue>
2234                    </EnumEntry>
2235                </Enumeration>
2236                <Integer Name="RegModeVal">
2237                    <Address>0x0000_4100</Address>
2238                    <Length>4</Length>
2239                    <AccessMode>RW</AccessMode>
2240                    <Min>0</Min>
2241                    <Max>65535</Max>
2242                </Integer>
2243            </RegisterDescription>
2244        "#;
2245
2246        let model = parse(XML).expect("parse enum pvalue");
2247        assert_eq!(model.nodes.len(), 2);
2248        match &model.nodes[0] {
2249            NodeDecl::Enum { entries, .. } => {
2250                assert_eq!(entries.len(), 2);
2251                assert!(matches!(entries[0].value, EnumValueSrc::Literal(10)));
2252                match &entries[1].value {
2253                    EnumValueSrc::FromNode(node) => assert_eq!(node, "RegModeVal"),
2254                    other => panic!("unexpected entry value: {other:?}"),
2255                }
2256            }
2257            other => panic!("unexpected node: {other:?}"),
2258        }
2259    }
2260
2261    /// `<Address>` and `<pAddress>` on the same register are summed, in the
2262    /// order they were declared.
2263    ///
2264    /// FLIR and Point Grey write exactly this shape — `<pAddress>` for the
2265    /// block base, `<Address>` for the offset within it — and dropping either
2266    /// term reads the wrong register (issue #35).
2267    #[test]
2268    fn address_terms_are_summed() {
2269        const XML: &str = r#"
2270            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2271                <Integer Name="RegAddr">
2272                    <Address>0x2000</Address>
2273                    <Length>4</Length>
2274                    <AccessMode>RW</AccessMode>
2275                    <Min>0</Min>
2276                    <Max>65535</Max>
2277                </Integer>
2278                <Integer Name="Gain">
2279                    <pAddress>RegAddr</pAddress>
2280                    <Address>0x00000008</Address>
2281                    <Length>4</Length>
2282                    <AccessMode>RW</AccessMode>
2283                    <Min>0</Min>
2284                    <Max>255</Max>
2285                </Integer>
2286            </RegisterDescription>
2287        "#;
2288
2289        let model = parse(XML).expect("parse indirect xml");
2290        assert_eq!(model.nodes.len(), 2);
2291        match &model.nodes[0] {
2292            NodeDecl::Integer {
2293                name, addressing, ..
2294            } => {
2295                assert_eq!(name, "RegAddr");
2296                assert_eq!(addressing.as_ref(), Some(&Addressing::fixed(0x2000, 4)));
2297            }
2298            other => panic!("unexpected node: {other:?}"),
2299        }
2300        match &model.nodes[1] {
2301            NodeDecl::Integer {
2302                name, addressing, ..
2303            } => {
2304                assert_eq!(name, "Gain");
2305                match addressing {
2306                    Some(Addressing::Sum { terms, len, .. }) => {
2307                        assert_eq!(
2308                            terms,
2309                            &[AddressTerm::Node("RegAddr".into()), AddressTerm::Fixed(0x8),]
2310                        );
2311                        assert_eq!(*len, 4);
2312                    }
2313                    other => panic!("expected summed addressing, got {other:?}"),
2314                }
2315            }
2316            other => panic!("unexpected node: {other:?}"),
2317        }
2318    }
2319
2320    /// `<pIndex>` contributes an index scaled by its stride.
2321    #[test]
2322    fn parse_p_index_term() {
2323        const XML: &str = r#"
2324            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2325                <MaskedIntReg Name="RegTriggerInqDelay">
2326                    <Address>0x13400</Address>
2327                    <pIndex Offset="64">IntTriggerSelector</pIndex>
2328                    <Length>4</Length>
2329                    <AccessMode>RO</AccessMode>
2330                    <Bit>30</Bit>
2331                </MaskedIntReg>
2332            </RegisterDescription>
2333        "#;
2334
2335        let model = parse(XML).expect("parse pIndex xml");
2336        match &model.nodes[0] {
2337            NodeDecl::Integer { addressing, .. } => match addressing {
2338                Some(Addressing::Sum { terms, .. }) => assert_eq!(
2339                    terms,
2340                    &[
2341                        AddressTerm::Fixed(0x13400),
2342                        AddressTerm::Index {
2343                            node: "IntTriggerSelector".into(),
2344                            offset: IndexOffset::Fixed(64),
2345                        },
2346                    ]
2347                ),
2348                other => panic!("expected summed addressing, got {other:?}"),
2349            },
2350            other => panic!("unexpected node: {other:?}"),
2351        }
2352    }
2353
2354    /// A `<StructReg>` shares its address terms with every `<StructEntry>`.
2355    ///
2356    /// Point Grey declares `<Address>` next to `<pAddress>` here; before the
2357    /// additive model the base was dropped and all 38 inquiry bits in the
2358    /// document read register 0.
2359    #[test]
2360    fn struct_reg_inherits_all_address_terms() {
2361        const XML: &str = r#"
2362            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2363                <StructReg Comment="Gain Inquiry Register">
2364                    <Address>0x520</Address>
2365                    <pAddress>CamRegBaseAddress</pAddress>
2366                    <Length>4</Length>
2367                    <AccessMode>RO</AccessMode>
2368                    <Endianess>BigEndian</Endianess>
2369                    <StructEntry Name="GainPresInq_Bit"><Bit>0</Bit></StructEntry>
2370                    <StructEntry Name="GainAutoInq_Bit"><Bit>6</Bit></StructEntry>
2371                </StructReg>
2372            </RegisterDescription>
2373        "#;
2374
2375        let model = parse(XML).expect("parse struct reg");
2376        assert_eq!(model.nodes.len(), 2);
2377        for node in &model.nodes {
2378            match node {
2379                NodeDecl::Integer { addressing, .. } => match addressing {
2380                    Some(Addressing::Sum { terms, len, .. }) => {
2381                        assert_eq!(
2382                            terms,
2383                            &[
2384                                AddressTerm::Fixed(0x520),
2385                                AddressTerm::Node("CamRegBaseAddress".into()),
2386                            ]
2387                        );
2388                        assert_eq!(*len, 4);
2389                    }
2390                    other => panic!("expected summed addressing, got {other:?}"),
2391                },
2392                other => panic!("unexpected node: {other:?}"),
2393            }
2394        }
2395    }
2396
2397    /// A `<StructReg>` with no address at all is dropped rather than silently
2398    /// pointed at register zero.
2399    #[test]
2400    fn struct_reg_without_address_is_skipped() {
2401        const XML: &str = r#"
2402            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2403                <StructReg>
2404                    <Length>4</Length>
2405                    <AccessMode>RO</AccessMode>
2406                    <StructEntry Name="SomeInq_Bit"><Bit>0</Bit></StructEntry>
2407                </StructReg>
2408            </RegisterDescription>
2409        "#;
2410
2411        let model = parse(XML).expect("document still parses");
2412        assert!(model.nodes.is_empty());
2413        assert_eq!(model.skipped.len(), 1);
2414        assert!(model.skipped[0].error.contains("Address"));
2415    }
2416
2417    #[test]
2418    fn parse_indirect_float_is_scaled_integer() {
2419        // Regression test: indirect <Float> with Length=4 and no
2420        // <Scale>/<Offset> must NOT be reclassified as IEEE 754. Pointer-
2421        // backed float features on real cameras are almost always scaled
2422        // integer registers; silently decoding their bytes as IEEE 754
2423        // corrupts the value.
2424        const XML: &str = r#"
2425            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2426                <Integer Name="RegAddr">
2427                    <Address>0x2000</Address>
2428                    <Length>4</Length>
2429                    <AccessMode>RW</AccessMode>
2430                </Integer>
2431                <Float Name="Exposure">
2432                    <pAddress>RegAddr</pAddress>
2433                    <Length>4</Length>
2434                    <AccessMode>RW</AccessMode>
2435                </Float>
2436            </RegisterDescription>
2437        "#;
2438
2439        let model = parse(XML).expect("parse indirect float");
2440        let float = model
2441            .nodes
2442            .iter()
2443            .find(|n| matches!(n, NodeDecl::Float { name, .. } if name == "Exposure"))
2444            .expect("Exposure node");
2445        match float {
2446            NodeDecl::Float {
2447                encoding,
2448                addressing,
2449                ..
2450            } => {
2451                assert!(
2452                    matches!(
2453                        addressing,
2454                        Some(Addressing::Sum { terms, .. })
2455                            if terms.iter().any(|t| matches!(t, AddressTerm::Node(_)))
2456                    ),
2457                    "expected a pAddress term"
2458                );
2459                assert_eq!(*encoding, FloatEncoding::ScaledInteger);
2460            }
2461            _ => unreachable!(),
2462        }
2463    }
2464
2465    /// Big-endian `<LSB>`/`<MSB>` are counted **from the MSB**, so a
2466    /// conformant document has `<LSB>` >= `<MSB>` and the pair's *minimum* is
2467    /// the offset of the field's most significant bit.
2468    ///
2469    /// The fixture is real: `AVT_Manta_G125B.xml` declares GigE Vision's
2470    /// bootstrap `GevSCPSPacketSize` at `0xD04` exactly this way, and the
2471    /// standard fixes that register's layout — the packet size is the *low*
2472    /// 16 bits. `viva_genapi::bitops` turns `bit_offset = 16` over 4 bytes into
2473    /// `shift = 32 - 16 - 16 = 0`, i.e. the low half. The end-to-end decode is
2474    /// asserted in `viva-genapi`, which owns the extraction.
2475    ///
2476    /// This test previously used `<Lsb>8</Lsb><Msb>15</Msb>` with `BigEndian` —
2477    /// a shape that appears **zero** times in the 38-document vendor corpus and
2478    /// is inverted against its own byte order. It encoded the issue-#120 defect
2479    /// rather than catching it.
2480    #[test]
2481    fn parse_integer_bitfield_big_endian() {
2482        const XML: &str = r#"
2483            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2484                <Integer Name="RegSCPSPacketSize">
2485                    <Address>0xD04</Address>
2486                    <Length>4</Length>
2487                    <AccessMode>RW</AccessMode>
2488                    <LSB>31</LSB>
2489                    <MSB>16</MSB>
2490                    <Endianess>BigEndian</Endianess>
2491                </Integer>
2492            </RegisterDescription>
2493        "#;
2494
2495        let model = parse(XML).expect("parse big-endian bitfield");
2496        assert_eq!(model.nodes.len(), 1);
2497        match &model.nodes[0] {
2498            NodeDecl::Integer { len, bitfield, .. } => {
2499                assert_eq!(*len, 4);
2500                let field = bitfield.as_ref().expect("bitfield present");
2501                assert_eq!(field.byte_order, ByteOrder::Big);
2502                assert_eq!(field.bit_length, 16);
2503                assert_eq!(field.bit_offset, 16);
2504            }
2505            other => panic!("unexpected node: {other:?}"),
2506        }
2507    }
2508
2509    /// `<Bit>` is `<LSB>` and `<MSB>` at the same index, so it inherits the same
2510    /// orientation: on a big-endian register `<Bit>0</Bit>` is the *most*
2511    /// significant bit.
2512    ///
2513    /// This is the exact shape behind issue #120 — FLIR gates `ExposureTime` on
2514    /// three such registers sharing one 32-bit word at `0x000C1000`.
2515    #[test]
2516    fn parse_big_endian_single_bit_is_counted_from_the_msb() {
2517        const XML: &str = r#"
2518            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2519                <Integer Name="ExposureTime_Imp">
2520                    <Address>0x000C1000</Address>
2521                    <Length>4</Length>
2522                    <AccessMode>RO</AccessMode>
2523                    <Bit>0</Bit>
2524                    <Endianess>BigEndian</Endianess>
2525                </Integer>
2526            </RegisterDescription>
2527        "#;
2528
2529        let model = parse(XML).expect("parse big-endian single bit");
2530        match &model.nodes[0] {
2531            NodeDecl::Integer { bitfield, .. } => {
2532                let field = bitfield.as_ref().expect("bitfield present");
2533                assert_eq!(field.bit_length, 1);
2534                // Offset from the MSB, so `bitops` shifts by 31 and reads the
2535                // top bit. Before #120 this was 31, which shifted by 0.
2536                assert_eq!(field.bit_offset, 0);
2537            }
2538            other => panic!("unexpected node: {other:?}"),
2539        }
2540    }
2541
2542    /// The GenICam schema spells the bit-range elements `LSB` and `MSB`, and
2543    /// every one of the 1 419 declarations inside register nodes across the
2544    /// vendor corpus uses that spelling — none uses `Lsb`.
2545    ///
2546    /// `parsers::numeric` matched only the mixed-case form, so it dropped the
2547    /// bit range from every `<MaskedIntReg>` in every real document and read the
2548    /// whole register instead. `parsers::struct_reg` already accepted both,
2549    /// which is another way the two bitfield paths had drifted apart. Both
2550    /// spellings must parse, and to the same field.
2551    #[test]
2552    fn both_spellings_of_lsb_and_msb_are_accepted() {
2553        fn bitfield_of(lsb_tag: &str, msb_tag: &str) -> BitField {
2554            let xml = format!(
2555                r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="1">
2556                     <MaskedIntReg Name="Field">
2557                       <Address>0xD04</Address><Length>4</Length><AccessMode>RW</AccessMode>
2558                       <{lsb_tag}>31</{lsb_tag}><{msb_tag}>16</{msb_tag}>
2559                       <Endianess>BigEndian</Endianess>
2560                     </MaskedIntReg>
2561                   </RegisterDescription>"#
2562            );
2563            let model = parse(&xml).expect("parse");
2564            match &model.nodes[0] {
2565                NodeDecl::Integer { bitfield, .. } => *bitfield.as_ref().expect("bitfield present"),
2566                other => panic!("unexpected node: {other:?}"),
2567            }
2568        }
2569
2570        let schema = bitfield_of("LSB", "MSB");
2571        let mixed = bitfield_of("Lsb", "Msb");
2572        assert_eq!(schema.bit_offset, 16);
2573        assert_eq!(schema.bit_length, 16);
2574        assert_eq!(schema, mixed);
2575    }
2576
2577    /// Both spellings must reach the `<Boolean>` parser too, not only the
2578    /// numeric one.
2579    ///
2580    /// `<Boolean>` is parsed by `parsers::symbolic`, a different function from
2581    /// the `<Integer>`/`<MaskedIntReg>` path, and it matched the shared
2582    /// `TAG_LSB`/`TAG_MSB` constants. Renaming those to the schema spelling for
2583    /// GA-22 therefore *swapped* which spelling worked here instead of
2584    /// accepting both — and a register-backed Boolean wider than one byte whose
2585    /// bit range is dropped is not merely misread, it fails
2586    /// `Boolean node {name} requires explicit bitfield metadata` and is skipped
2587    /// outright. Caught in review on
2588    /// [#124](https://github.com/VitalyVorobyev/viva-genicam/pull/124).
2589    #[test]
2590    fn boolean_accepts_both_spellings_of_lsb_and_msb() {
2591        fn flag_bitfield(lsb_tag: &str, msb_tag: &str) -> BitField {
2592            let xml = format!(
2593                r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="1">
2594                     <Boolean Name="Flag">
2595                       <Address>0x2000</Address><Length>4</Length><AccessMode>RW</AccessMode>
2596                       <{lsb_tag}>31</{lsb_tag}><{msb_tag}>31</{msb_tag}>
2597                       <Endianess>BigEndian</Endianess>
2598                     </Boolean>
2599                   </RegisterDescription>"#
2600            );
2601            let model = parse(&xml).expect("parse");
2602            assert!(model.skipped.is_empty(), "skipped: {:?}", model.skipped);
2603            match &model.nodes[0] {
2604                NodeDecl::Boolean { bitfield, .. } => *bitfield.as_ref().expect("bitfield present"),
2605                other => panic!("unexpected node: {other:?}"),
2606            }
2607        }
2608
2609        let schema = flag_bitfield("LSB", "MSB");
2610        let mixed = flag_bitfield("Lsb", "Msb");
2611        // Index 31 from the MSB of a 4-byte register is the least significant
2612        // bit, so `bitops` shifts by zero.
2613        assert_eq!(schema.bit_offset, 31);
2614        assert_eq!(schema.bit_length, 1);
2615        assert_eq!(schema, mixed);
2616    }
2617
2618    /// `<Mask>` is the one bitfield source that stays LSB-relative under `Big`,
2619    /// because it is a literal register value rather than a GenICam bit index.
2620    ///
2621    /// It has zero corpus occurrences, so only this test keeps the distinction
2622    /// honest: the #120 fix removes the endianness conversion for `<LSB>`/
2623    /// `<MSB>`/`<Bit>` and must **keep** it here.
2624    #[test]
2625    fn big_endian_mask_stays_lsb_relative() {
2626        const XML: &str = r#"
2627            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2628                <Integer Name="Masked">
2629                    <Address>0x3000</Address>
2630                    <Length>4</Length>
2631                    <AccessMode>RW</AccessMode>
2632                    <Mask>0x0000FF00</Mask>
2633                    <Endianess>BigEndian</Endianess>
2634                </Integer>
2635            </RegisterDescription>
2636        "#;
2637
2638        let model = parse(XML).expect("parse big-endian mask");
2639        match &model.nodes[0] {
2640            NodeDecl::Integer { bitfield, .. } => {
2641                let field = bitfield.as_ref().expect("bitfield present");
2642                assert_eq!(field.byte_order, ByteOrder::Big);
2643                assert_eq!(field.bit_length, 8);
2644                // Bits 8..15 counted from the LSB are bits 16..23 from the MSB.
2645                assert_eq!(field.bit_offset, 16);
2646            }
2647            other => panic!("unexpected node: {other:?}"),
2648        }
2649    }
2650    #[test]
2651    fn parse_boolean_bitfield_default_length() {
2652        const XML: &str = r#"
2653            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2654                <Boolean Name="Flag">
2655                    <Address>0x2000</Address>
2656                    <Length>1</Length>
2657                    <AccessMode>RW</AccessMode>
2658                    <Bit>3</Bit>
2659                </Boolean>
2660            </RegisterDescription>
2661        "#;
2662
2663        let model = parse(XML).expect("parse boolean bitfield");
2664        assert_eq!(model.nodes.len(), 1);
2665        match &model.nodes[0] {
2666            NodeDecl::Boolean { len, bitfield, .. } => {
2667                assert_eq!(*len, 1);
2668                let bf = bitfield.as_ref().expect("bitfield present");
2669                assert_eq!(bf.byte_order, ByteOrder::Little);
2670                assert_eq!(bf.bit_length, 1);
2671                assert_eq!(bf.bit_offset, 3);
2672            }
2673            other => panic!("unexpected node: {other:?}"),
2674        }
2675    }
2676
2677    /// GA-28: `<Endianess>` on a plain `<IntReg>` used to go only into the
2678    /// bitfield builder, which discards it when nothing sets a bit range — so
2679    /// 311 declarations across 16 of the 38 corpus documents decoded
2680    /// byte-swapped. All three spellings the parser accepts are checked,
2681    /// because vendors use all three.
2682    #[test]
2683    fn plain_integer_records_its_declared_byte_order() {
2684        for tag in ["Endianess", "Endianness", "ByteOrder"] {
2685            let xml = format!(
2686                r#"
2687            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2688                <IntReg Name="Reg">
2689                    <Address>0x3000</Address>
2690                    <Length>4</Length>
2691                    <AccessMode>RO</AccessMode>
2692                    <{tag}>LittleEndian</{tag}>
2693                </IntReg>
2694            </RegisterDescription>
2695        "#
2696            );
2697
2698            let model = parse(&xml).unwrap_or_else(|err| panic!("parse <{tag}>: {err}"));
2699            match &model.nodes[0] {
2700                NodeDecl::Integer {
2701                    byte_order,
2702                    bitfield,
2703                    ..
2704                } => {
2705                    assert_eq!(*byte_order, ByteOrder::Little, "<{tag}>");
2706                    // No <LSB>/<MSB>/<Bit>/<Mask>, so there is no bitfield to
2707                    // have carried the order — which is the whole defect.
2708                    assert!(bitfield.is_none(), "<{tag}>");
2709                }
2710                other => panic!("unexpected node: {other:?}"),
2711            }
2712        }
2713    }
2714
2715    /// GenICam's default is big-endian, and a document that says nothing must
2716    /// keep getting it.
2717    #[test]
2718    fn plain_integer_without_endianness_defaults_to_big() {
2719        const XML: &str = r#"
2720            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2721                <IntReg Name="Reg">
2722                    <Address>0x3000</Address>
2723                    <Length>4</Length>
2724                    <AccessMode>RO</AccessMode>
2725                </IntReg>
2726            </RegisterDescription>
2727        "#;
2728
2729        let model = parse(XML).expect("parse");
2730        match &model.nodes[0] {
2731            NodeDecl::Integer { byte_order, .. } => assert_eq!(*byte_order, ByteOrder::Big),
2732            other => panic!("unexpected node: {other:?}"),
2733        }
2734    }
2735
2736    /// Negative control. A masked register takes the bitfield path, which
2737    /// already handled byte order and must keep doing so — the decl field is
2738    /// recorded but not consulted. Asserting both stops a later refactor
2739    /// quietly routing masked registers through the new path.
2740    #[test]
2741    fn masked_integer_keeps_the_bitfield_byte_order_path() {
2742        const XML: &str = r#"
2743            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2744                <IntReg Name="Reg">
2745                    <Address>0x3000</Address>
2746                    <Length>4</Length>
2747                    <AccessMode>RO</AccessMode>
2748                    <Endianess>LittleEndian</Endianess>
2749                    <LSB>15</LSB>
2750                    <MSB>0</MSB>
2751                </IntReg>
2752            </RegisterDescription>
2753        "#;
2754
2755        let model = parse(XML).expect("parse");
2756        match &model.nodes[0] {
2757            NodeDecl::Integer {
2758                byte_order,
2759                bitfield,
2760                ..
2761            } => {
2762                assert_eq!(*byte_order, ByteOrder::Little);
2763                let field = bitfield.as_ref().expect("bitfield present");
2764                assert_eq!(field.byte_order, ByteOrder::Little);
2765            }
2766            other => panic!("unexpected node: {other:?}"),
2767        }
2768    }
2769
2770    #[test]
2771    fn parse_integer_bitfield_mask() {
2772        const XML: &str = r#"
2773            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2774                <Integer Name="Masked">
2775                    <Address>0x3000</Address>
2776                    <Length>4</Length>
2777                    <AccessMode>RW</AccessMode>
2778                    <Min>0</Min>
2779                    <Max>65535</Max>
2780                    <Mask>0x0000FF00</Mask>
2781                </Integer>
2782            </RegisterDescription>
2783        "#;
2784
2785        let model = parse(XML).expect("parse mask bitfield");
2786        assert_eq!(model.nodes.len(), 1);
2787        match &model.nodes[0] {
2788            NodeDecl::Integer { bitfield, .. } => {
2789                let field = bitfield.as_ref().expect("bitfield present");
2790                assert_eq!(field.byte_order, ByteOrder::Little);
2791                assert_eq!(field.bit_length, 8);
2792                assert_eq!(field.bit_offset, 8);
2793            }
2794            other => panic!("unexpected node: {other:?}"),
2795        }
2796    }
2797
2798    #[test]
2799    fn parse_node_metadata() {
2800        const XML: &str = r#"
2801            <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="0" SchemaSubMinorVersion="0">
2802                <Integer Name="Width">
2803                    <Address>0x100</Address>
2804                    <Length>4</Length>
2805                    <AccessMode>RW</AccessMode>
2806                    <Min>16</Min>
2807                    <Max>4096</Max>
2808                    <Visibility>Expert</Visibility>
2809                    <Description>Image width in pixels.</Description>
2810                    <ToolTip>Width of the acquired image</ToolTip>
2811                    <DisplayName>Image Width</DisplayName>
2812                    <Representation>Linear</Representation>
2813                </Integer>
2814                <Float Name="Gain">
2815                    <Address>0x200</Address>
2816                    <Length>4</Length>
2817                    <AccessMode>RW</AccessMode>
2818                    <Min>0.0</Min>
2819                    <Max>48.0</Max>
2820                    <Unit>dB</Unit>
2821                    <Visibility>Beginner</Visibility>
2822                    <Representation>Logarithmic</Representation>
2823                </Float>
2824                <Category Name="Root">
2825                    <Visibility>Guru</Visibility>
2826                    <Description>Top-level category</Description>
2827                    <pFeature>Width</pFeature>
2828                    <pFeature>Gain</pFeature>
2829                </Category>
2830                <Enumeration Name="PixelFormat">
2831                    <Address>0x300</Address>
2832                    <Length>4</Length>
2833                    <AccessMode>RW</AccessMode>
2834                    <Visibility>Beginner</Visibility>
2835                    <ToolTip>Pixel format selector</ToolTip>
2836                    <EnumEntry Name="Mono8" Value="0" />
2837                </Enumeration>
2838            </RegisterDescription>
2839        "#;
2840
2841        let model = parse(XML).expect("parse metadata xml");
2842        assert_eq!(model.nodes.len(), 4);
2843
2844        // Integer with full metadata
2845        match &model.nodes[0] {
2846            NodeDecl::Integer { name, meta, .. } => {
2847                assert_eq!(name, "Width");
2848                assert_eq!(meta.visibility, Visibility::Expert);
2849                assert_eq!(meta.description.as_deref(), Some("Image width in pixels."));
2850                assert_eq!(meta.tooltip.as_deref(), Some("Width of the acquired image"));
2851                assert_eq!(meta.display_name.as_deref(), Some("Image Width"));
2852                assert_eq!(meta.representation, Some(Representation::Linear));
2853            }
2854            other => panic!("unexpected node: {other:?}"),
2855        }
2856
2857        // Float with visibility + representation
2858        match &model.nodes[1] {
2859            NodeDecl::Float { name, meta, .. } => {
2860                assert_eq!(name, "Gain");
2861                assert_eq!(meta.visibility, Visibility::Beginner);
2862                assert_eq!(meta.representation, Some(Representation::Logarithmic));
2863                assert!(meta.description.is_none());
2864            }
2865            other => panic!("unexpected node: {other:?}"),
2866        }
2867
2868        // Category with visibility + description
2869        match &model.nodes[2] {
2870            NodeDecl::Category { name, meta, .. } => {
2871                assert_eq!(name, "Root");
2872                assert_eq!(meta.visibility, Visibility::Guru);
2873                assert_eq!(meta.description.as_deref(), Some("Top-level category"));
2874            }
2875            other => panic!("unexpected node: {other:?}"),
2876        }
2877
2878        // Enum with visibility + tooltip
2879        match &model.nodes[3] {
2880            NodeDecl::Enum { name, meta, .. } => {
2881                assert_eq!(name, "PixelFormat");
2882                assert_eq!(meta.visibility, Visibility::Beginner);
2883                assert_eq!(meta.tooltip.as_deref(), Some("Pixel format selector"));
2884            }
2885            other => panic!("unexpected node: {other:?}"),
2886        }
2887    }
2888
2889    /// Wrap a node fragment in a minimal document and parse it.
2890    fn parse_fragment(node: &str) -> XmlModel {
2891        let xml = format!(
2892            r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">{node}</RegisterDescription>"#
2893        );
2894        parse(&xml).expect("parse fragment")
2895    }
2896
2897    fn string_decl(model: &XmlModel, name: &str) -> StringDecl {
2898        match model.nodes.iter().find(|n| n.name() == name) {
2899            Some(NodeDecl::String(decl)) => decl.clone(),
2900            other => panic!("{name}: not a string: {other:?}"),
2901        }
2902    }
2903
2904    /// GenICam Standard v2.1.1 §2.8.12 and the GenApi schema: a `<String>`
2905    /// has no register; it holds a `<Value>` or names a `<pValue>`. Parsed as
2906    /// a `<StringReg>`, the mvBlueFOX3-2004G's `DeviceFirmwareVersion` got
2907    /// address 0, length 0, and read empty.
2908    #[test]
2909    fn a_string_keeps_its_p_value_or_its_value_and_has_no_register() {
2910        let model = parse_fragment(
2911            r#"<String Name="DeviceFirmwareVersion"><pIsImplemented>QO</pIsImplemented><pValue>DBB</pValue></String>
2912               <String Name="StringNodeB"><Value>Hello World!</Value></String>
2913               <StringReg Name="DBB"><Address>0x1000134</Address><Length>32</Length><AccessMode>RO</AccessMode></StringReg>"#,
2914        );
2915        assert!(model.skipped.is_empty(), "{:?}", model.skipped);
2916        let delegating = string_decl(&model, "DeviceFirmwareVersion");
2917        assert_eq!(delegating.pvalue.as_deref(), Some("DBB"));
2918        assert!(delegating.addressing.is_none());
2919        assert_eq!(delegating.access, AccessMode::RW, "a String declares none");
2920        assert!(
2921            delegating.meta.ignored.is_empty(),
2922            "{:?}",
2923            delegating.meta.ignored
2924        );
2925        let floating = string_decl(&model, "StringNodeB");
2926        assert_eq!(floating.value.as_deref(), Some("Hello World!"));
2927        assert!(floating.addressing.is_none());
2928        let register = string_decl(&model, "DBB");
2929        assert_eq!(register.access, AccessMode::RO);
2930        assert_eq!(register.addressing.map(|a| a.byte_len()), Some(32));
2931    }
2932
2933    /// The schema requires one of the two; a `<String>` with neither has no
2934    /// value at all, and is skipped with the reason rather than read as an
2935    /// empty register.
2936    #[test]
2937    fn a_string_with_neither_value_nor_p_value_is_skipped() {
2938        let model = parse_fragment(r#"<String Name="Nothing"><ToolTip>t</ToolTip></String>"#);
2939        assert!(model.nodes.is_empty());
2940        assert_eq!(model.skipped.len(), 1);
2941        assert!(
2942            model.skipped[0].error.contains("<Value> or <pValue>"),
2943            "{:?}",
2944            model.skipped
2945        );
2946    }
2947
2948    /// GenICam Standard v2.1.1 §2.8.3's `<pLength>` on a `<StringReg>`:
2949    /// Basler's acA1600-20gm `DeviceFirmwareVersion` and FLIR's
2950    /// `ChunkSerialData`. It used to be read past, leaving a length of 0.
2951    #[test]
2952    fn a_string_reg_keeps_its_p_length() {
2953        let model = parse_fragment(
2954            r#"<StringReg Name="DeviceFirmwareVersion"><Address>0xf2f01014</Address><pLength>DeviceFirmwareVersion_InqLengthFao</pLength><AccessMode>RO</AccessMode></StringReg>"#,
2955        );
2956        let decl = string_decl(&model, "DeviceFirmwareVersion");
2957        let addressing = decl.addressing.expect("a register");
2958        assert_eq!(
2959            addressing.length_node(),
2960            Some("DeviceFirmwareVersion_InqLengthFao")
2961        );
2962        assert!(decl.meta.ignored.is_empty(), "{:?}", decl.meta.ignored);
2963    }
2964
2965    /// `<pLength>` on an `<IntReg>`: the Lucid TRT009S's event frame IDs
2966    /// (`N248`/`N252`, behind `EventExposureStartFrameID`) are 2 or 8 bytes,
2967    /// as the extended-ID bit says. It used to be read past, leaving the
2968    /// default 4.
2969    #[test]
2970    fn an_int_reg_keeps_its_p_length() {
2971        let model = parse_fragment(
2972            r#"<IntReg Name="N248"><pAddress>N256</pAddress><pLength>N257</pLength><AccessMode>RO</AccessMode><pPort>EventPort</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>"#,
2973        );
2974        match model.nodes.iter().find(|n| n.name() == "N248") {
2975            Some(NodeDecl::Integer {
2976                addressing: Some(addressing),
2977                len,
2978                meta,
2979                ..
2980            }) => {
2981                assert_eq!(addressing.length_node(), Some("N257"));
2982                assert_eq!(*len, 0);
2983                assert!(meta.ignored.is_empty(), "{:?}", meta.ignored);
2984            }
2985            other => panic!("not an addressed integer: {other:?}"),
2986        }
2987    }
2988
2989    /// A bit field has to be placed within a length known when the document
2990    /// is read, so a `<MaskedIntReg>` whose length only a `<pLength>` gives
2991    /// is skipped with the reason, not with "zero-length register".
2992    #[test]
2993    fn a_masked_int_reg_with_only_a_p_length_is_skipped_with_the_reason() {
2994        let model = parse_fragment(
2995            r#"<MaskedIntReg Name="Field"><Address>0x10</Address><pLength>Len</pLength><Bit>3</Bit></MaskedIntReg>"#,
2996        );
2997        assert!(model.nodes.is_empty());
2998        assert!(
2999            model.skipped[0].error.contains("only its <pLength> gives"),
3000            "{:?}",
3001            model.skipped
3002        );
3003    }
3004
3005    /// H-2: a child element no parser interprets is recorded on its node, in
3006    /// document order, and listed for the whole document — the class of loss
3007    /// a `<String>`'s `<pValue>` fell into.
3008    #[test]
3009    fn an_element_no_parser_reads_is_recorded_on_its_node() {
3010        let model = parse_fragment(
3011            r#"<Integer Name="Gain">
3012                 <Extension><Vendor>1</Vendor></Extension>
3013                 <pValue>GainReg</pValue>
3014                 <DocuURL>http://example.com</DocuURL>
3015               </Integer>
3016               <Enumeration Name="Mode">
3017                 <EnumEntry Name="Off"><Value>0</Value><NumericValue>0</NumericValue></EnumEntry>
3018                 <Value>0</Value>
3019               </Enumeration>
3020               <Port Name="Device"><ToolTip>the device</ToolTip></Port>"#,
3021        );
3022        assert_eq!(
3023            model.ignored(),
3024            vec![
3025                IgnoredElement::new("Gain", "Integer", "Extension"),
3026                IgnoredElement::new("Gain", "Integer", "DocuURL"),
3027                IgnoredElement::new("Mode", "Enum", "EnumEntry/NumericValue"),
3028                IgnoredElement::new("Device", "Port", "ToolTip"),
3029            ]
3030        );
3031    }
3032
3033    /// GenICam Standard v2.1.1 §2.8.6: each entry "gets [...] all elements
3034    /// from the StructReg node which are not present already in the
3035    /// <StructEntry> element". 202 corpus `<StructReg>`s declare a
3036    /// `<Visibility>`, which their entries used to lose.
3037    #[test]
3038    fn a_struct_entry_inherits_what_its_struct_reg_declares() {
3039        let model = parse_fragment(
3040            r#"<StructReg Comment="Inq">
3041                 <Address>0x10</Address><Length>4</Length><AccessMode>RO</AccessMode>
3042                 <Visibility>Invisible</Visibility><ToolTip>shared</ToolTip><Extension/>
3043                 <StructEntry Name="A"><Bit>0</Bit></StructEntry>
3044                 <StructEntry Name="B"><Bit>1</Bit><Visibility>Guru</Visibility></StructEntry>
3045               </StructReg>"#,
3046        );
3047        let meta = |name: &str| {
3048            model
3049                .nodes
3050                .iter()
3051                .find(|n| n.name() == name)
3052                .expect(name)
3053                .meta()
3054                .clone()
3055        };
3056        assert_eq!(meta("A").visibility, Visibility::Invisible);
3057        assert_eq!(meta("A").tooltip.as_deref(), Some("shared"));
3058        assert_eq!(meta("B").visibility, Visibility::Guru, "its own wins");
3059        assert_eq!(meta("A").ignored, vec!["Extension".to_string()]);
3060    }
3061
3062    /// GA-14: `<Streamable>` on every node kind that GenICam Standard v2.1.1
3063    /// §3.2 gives a Streamable default — the numeric, symbolic and string
3064    /// features, the register types and the struct entries. `No`, an absent
3065    /// element and the empty `<Streamable/>` Basler's acA1600 declares on
3066    /// `GlobalResetReleaseModeEnable` are all not streamable: the schema's
3067    /// values are `Yes` and `No`, and the default is `No`.
3068    #[test]
3069    fn streamable_is_read_on_every_node_kind_that_carries_it() {
3070        let model = parse_fragment(
3071            r#"<Integer Name="I"><Streamable>Yes</Streamable><Value>1</Value></Integer>
3072            <IntReg Name="IR"><Streamable>Yes</Streamable><Address>0x0</Address><Length>4</Length><AccessMode>RW</AccessMode></IntReg>
3073            <MaskedIntReg Name="M"><Streamable>Yes</Streamable><Address>0x4</Address><Length>4</Length><AccessMode>RW</AccessMode><Bit>0</Bit></MaskedIntReg>
3074            <Float Name="F"><Streamable>Yes</Streamable><Value>1.0</Value></Float>
3075            <FloatReg Name="FR"><Streamable>Yes</Streamable><Address>0x8</Address><Length>4</Length><AccessMode>RW</AccessMode></FloatReg>
3076            <Enumeration Name="E"><Streamable>Yes</Streamable><EnumEntry Name="A"><Value>0</Value></EnumEntry><pValue>IR</pValue></Enumeration>
3077            <Boolean Name="B"><Streamable> Yes </Streamable><pValue>IR</pValue></Boolean>
3078            <StringReg Name="S"><Streamable>Yes</Streamable><Address>0x10</Address><Length>8</Length><AccessMode>RW</AccessMode></StringReg>
3079            <Register Name="R"><Streamable>Yes</Streamable><Address>0x20</Address><Length>8</Length><AccessMode>RW</AccessMode></Register>
3080            <Converter Name="C"><Streamable>Yes</Streamable><FormulaTo>FROM</FormulaTo><FormulaFrom>TO</FormulaFrom><pValue>IR</pValue></Converter>
3081            <IntConverter Name="IC"><Streamable>Yes</Streamable><FormulaTo>FROM</FormulaTo><FormulaFrom>TO</FormulaFrom><pValue>IR</pValue></IntConverter>
3082            <IntSwissKnife Name="ISK"><Streamable>Yes</Streamable><pVariable Name="X">IR</pVariable><Formula>X</Formula></IntSwissKnife>
3083            <SwissKnife Name="SK"><Streamable>Yes</Streamable><pVariable Name="X">IR</pVariable><Formula>X</Formula></SwissKnife>
3084            <StructReg Comment="pair"><Address>0x30</Address><Length>4</Length><AccessMode>RW</AccessMode>
3085              <StructEntry Name="SE"><Streamable>Yes</Streamable><Bit>0</Bit></StructEntry>
3086              <StructEntry Name="SE2"><Bit>1</Bit></StructEntry>
3087            </StructReg>
3088            <Integer Name="No"><Streamable>No</Streamable><Value>1</Value></Integer>
3089            <Integer Name="Empty"><Streamable/><Value>1</Value></Integer>
3090            <Integer Name="Absent"><Value>1</Value></Integer>"#,
3091        );
3092        assert!(model.skipped.is_empty(), "{:?}", model.skipped);
3093        let streamable: Vec<&str> = model
3094            .nodes
3095            .iter()
3096            .filter(|node| node.meta().streamable)
3097            .map(NodeDecl::name)
3098            .collect();
3099        assert_eq!(
3100            streamable,
3101            [
3102                "I", "IR", "M", "F", "FR", "E", "B", "S", "R", "C", "IC", "ISK", "SK", "SE"
3103            ]
3104        );
3105    }
3106
3107    /// GA-05: `<Cachable>` and `<PollingTime>` on every element the corpus or
3108    /// the standard puts them on — the register kinds (§2.8.3), a command
3109    /// (§2.8.8) and an enumeration (§2.8.10) — as declared, with no default
3110    /// filled in: the default depends on the element and is `viva-genapi`'s.
3111    #[test]
3112    fn cachable_and_polling_time_are_read_where_they_are_declared() {
3113        let model = parse_fragment(
3114            r#"<IntReg Name="IR"><Address>0x0</Address><Length>4</Length><AccessMode>RO</AccessMode><Cachable>NoCache</Cachable><PollingTime>500</PollingTime></IntReg>
3115            <MaskedIntReg Name="M"><Address>0x4</Address><Length>4</Length><AccessMode>RW</AccessMode><Bit>0</Bit><Cachable>WriteAround</Cachable></MaskedIntReg>
3116            <FloatReg Name="FR"><Address>0x8</Address><Length>4</Length><AccessMode>RW</AccessMode><PollingTime>1000</PollingTime></FloatReg>
3117            <StringReg Name="S"><Address>0x10</Address><Length>8</Length><AccessMode>RO</AccessMode><Cachable>WriteThrough</Cachable></StringReg>
3118            <Register Name="R"><Address>0x20</Address><Length>8</Length><AccessMode>RO</AccessMode><Cachable>NoCache</Cachable><PollingTime>10000</PollingTime></Register>
3119            <Command Name="C"><pValue>IR</pValue><CommandValue>1</CommandValue><PollingTime>5</PollingTime></Command>
3120            <Enumeration Name="E"><EnumEntry Name="Idle"><Value>0</Value></EnumEntry><EnumEntry Name="Active"><Value>1</Value><IsSelfClearing>Yes</IsSelfClearing></EnumEntry><pValue>IR</pValue><PollingTime>10</PollingTime></Enumeration>
3121            <Integer Name="Plain"><pValue>IR</pValue></Integer>"#,
3122        );
3123        assert!(model.skipped.is_empty(), "{:?}", model.skipped);
3124        let declared: Vec<(&str, Option<CachingMode>, Option<u64>)> = model
3125            .nodes
3126            .iter()
3127            .map(|node| {
3128                let meta = node.meta();
3129                (node.name(), meta.cachable, meta.polling_time_ms)
3130            })
3131            .collect();
3132        use CachingMode::{NoCache, WriteAround, WriteThrough};
3133        assert_eq!(
3134            declared,
3135            [
3136                ("IR", Some(NoCache), Some(500)),
3137                ("M", Some(WriteAround), None),
3138                ("FR", None, Some(1000)),
3139                ("S", Some(WriteThrough), None),
3140                ("R", Some(NoCache), Some(10000)),
3141                ("C", None, Some(5)),
3142                ("E", None, Some(10)),
3143                ("Plain", None, None),
3144            ]
3145        );
3146        let NodeDecl::Enum { entries, .. } = &model.nodes[6] else {
3147            panic!("an enumeration");
3148        };
3149        let clearing: Vec<(&str, bool)> = entries
3150            .iter()
3151            .map(|entry| (entry.name.as_str(), entry.is_self_clearing))
3152            .collect();
3153        assert_eq!(clearing, [("Idle", false), ("Active", true)]);
3154    }
3155
3156    /// GA-05: a `<StructEntry>` is a view of its `<StructReg>`'s register and
3157    /// takes the struct's `<Cachable>` and `<PollingTime>` unless it declares
3158    /// its own — FLIR's `Power Supply Control Register` declares `NoCache` once
3159    /// for seven entries, Point Grey's GPIO registers per entry.
3160    #[test]
3161    fn struct_entries_take_their_registers_cachable_unless_they_declare_one() {
3162        let model = parse_fragment(
3163            r#"<StructReg Comment="power"><Address>0x30</Address><Length>4</Length><AccessMode>RW</AccessMode><Cachable>NoCache</Cachable><PollingTime>250</PollingTime>
3164              <StructEntry Name="Inherits"><Bit>0</Bit></StructEntry>
3165              <StructEntry Name="Overrides"><Bit>1</Bit><Cachable>WriteAround</Cachable><PollingTime>1000</PollingTime></StructEntry>
3166            </StructReg>
3167            <StructReg Comment="gpio"><Address>0x34</Address><Length>4</Length><AccessMode>RW</AccessMode>
3168              <StructEntry Name="Own"><Bit>0</Bit><Cachable>NoCache</Cachable></StructEntry>
3169              <StructEntry Name="Undeclared"><Bit>1</Bit></StructEntry>
3170            </StructReg>"#,
3171        );
3172        let declared: Vec<(&str, Option<CachingMode>, Option<u64>)> = model
3173            .nodes
3174            .iter()
3175            .map(|node| {
3176                (
3177                    node.name(),
3178                    node.meta().cachable,
3179                    node.meta().polling_time_ms,
3180                )
3181            })
3182            .collect();
3183        use CachingMode::{NoCache, WriteAround};
3184        assert_eq!(
3185            declared,
3186            [
3187                ("Inherits", Some(NoCache), Some(250)),
3188                ("Overrides", Some(WriteAround), Some(1000)),
3189                ("Own", Some(NoCache), None),
3190                ("Undeclared", None, None),
3191            ]
3192        );
3193    }
3194
3195    /// GA-05: the standard's own example writes `<Cachable>No</Cachable>`
3196    /// and its prose spells the element `<Cacheable>`; a value it does not
3197    /// define is read as `NoCache`, which never answers with a stale value. A
3198    /// `<PollingTime>` that is not a number is dropped rather than the node.
3199    #[test]
3200    fn cachable_spellings_and_odd_values_read_as_no_cache() {
3201        let model = parse_fragment(
3202            r#"<IntReg Name="No"><Address>0x0</Address><Length>4</Length><Cachable>No</Cachable></IntReg>
3203            <IntReg Name="Prose"><Address>0x4</Address><Length>4</Length><Cacheable>WriteAround</Cacheable></IntReg>
3204            <IntReg Name="Odd"><Address>0x8</Address><Length>4</Length><Cachable>Sometimes</Cachable><PollingTime>soon</PollingTime></IntReg>"#,
3205        );
3206        assert!(model.skipped.is_empty(), "{:?}", model.skipped);
3207        let declared: Vec<(Option<CachingMode>, Option<u64>)> = model
3208            .nodes
3209            .iter()
3210            .map(|node| (node.meta().cachable, node.meta().polling_time_ms))
3211            .collect();
3212        use CachingMode::{NoCache, WriteAround};
3213        assert_eq!(
3214            declared,
3215            [
3216                (Some(NoCache), None),
3217                (Some(WriteAround), None),
3218                (Some(NoCache), None)
3219            ]
3220        );
3221    }
3222
3223    /// `combine` is the most restrictive of two modes.
3224    #[test]
3225    fn caching_modes_combine_to_the_most_restrictive() {
3226        use CachingMode::{NoCache, WriteAround, WriteThrough};
3227        assert_eq!(WriteThrough.combine(WriteThrough), WriteThrough);
3228        assert_eq!(WriteThrough.combine(WriteAround), WriteAround);
3229        assert_eq!(WriteAround.combine(WriteThrough), WriteAround);
3230        assert_eq!(WriteAround.combine(NoCache), NoCache);
3231        assert_eq!(NoCache.combine(WriteThrough), NoCache);
3232    }
3233
3234    /// GA-14: a saved configuration names the camera it came from, so a load
3235    /// onto another model can warn. GenICam Standard v2.1.1 §2.7: "The camera
3236    /// described is identified by the VendorName / ModelName pair", and
3237    /// `MajorVersion`/`MinorVersion`/`SubMinorVersion` version the file itself,
3238    /// apart from the schema.
3239    #[test]
3240    fn the_document_names_its_camera_and_its_own_version() {
3241        let model = parse(
3242            r#"<RegisterDescription ModelName="acA1600-20gm" VendorName="Basler" SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0" MajorVersion="3" MinorVersion="2" SubMinorVersion="1"><Integer Name="I"><Value>1</Value></Integer></RegisterDescription>"#,
3243        )
3244        .expect("parse");
3245        assert_eq!(
3246            model.identity,
3247            DocumentIdentity {
3248                vendor_name: "Basler".into(),
3249                model_name: "acA1600-20gm".into(),
3250                version: "3.2.1".into(),
3251            }
3252        );
3253        assert_eq!(model.version, "1.1.0", "the schema version is separate");
3254        let bare = parse_fragment(r#"<Integer Name="I"><Value>1</Value></Integer>"#);
3255        assert_eq!(bare.identity, DocumentIdentity::default());
3256    }
3257
3258    /// Extract the metadata of the single node in a parsed fragment.
3259    fn only_meta(model: &XmlModel) -> &NodeMeta {
3260        match model.nodes.first().expect("one node") {
3261            NodeDecl::Integer { meta, .. } => meta,
3262            other => panic!("unexpected node: {other:?}"),
3263        }
3264    }
3265
3266    /// Regression for issue #122: The Imaging Source's DMK 33GP2000e ships its
3267    /// GenApi XML with a UTF-8 byte-order mark.
3268    ///
3269    /// The BOM is valid UTF-8, so nothing upstream rejected it and `parse`
3270    /// returned `Ok` — with every node in the document skipped, because
3271    /// quick-xml strips the BOM from its own view without advancing
3272    /// `buffer_position`, leaving each sliced element three bytes short of its
3273    /// closing `>`. Assert the node count *and* an empty skip list: asserting
3274    /// `parse(..).is_ok()` alone passed throughout the bug.
3275    #[test]
3276    fn byte_order_mark_does_not_shift_node_slices() {
3277        let body = r#"<Integer Name="Width"><Address>0x100</Address><Length>4</Length></Integer><Integer Name="Height"><Address>0x104</Address><Length>4</Length></Integer>"#;
3278        let doc = format!(
3279            r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="1">{body}</RegisterDescription>"#
3280        );
3281        let with_bom = format!("\u{feff}{doc}");
3282
3283        let plain = parse(&doc).expect("parse without BOM");
3284        let bom = parse(&with_bom).expect("parse with BOM");
3285
3286        assert!(
3287            bom.skipped.is_empty(),
3288            "BOM document skipped nodes: {:?}",
3289            bom.skipped
3290        );
3291        assert_eq!(bom.nodes.len(), plain.nodes.len());
3292        assert_eq!(bom.version, plain.version);
3293    }
3294
3295    /// The same document, through the offset-free scan `viva-camctl` and the
3296    /// `fetch_xml` example use first. This half always worked — which is why
3297    /// issue #122 reported 291 top-level features listed correctly and then
3298    /// every node failing. Pin it so the two entry points cannot diverge again.
3299    #[test]
3300    fn byte_order_mark_does_not_disturb_the_minimal_scan() {
3301        let doc = r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="1"><Category Name="Root"><pFeature>Width</pFeature></Category></RegisterDescription>"#;
3302        let with_bom = format!("\u{feff}{doc}");
3303
3304        let info = parse_into_minimal_nodes(&with_bom).expect("minimal scan with BOM");
3305        assert_eq!(info.schema_version.as_deref(), Some("1.1.1"));
3306        assert_eq!(info.top_level_features, vec!["Root".to_string()]);
3307    }
3308
3309    /// A BOM in a document that also carries multi-byte text.
3310    ///
3311    /// The three-byte shift lands on ASCII markup for any XML we have seen, so
3312    /// this is not a second failure mode — it is the same one, checked on
3313    /// content where a wrong slice would corrupt text rather than only truncate
3314    /// a tag. The `xml.get(..)` guard in [`parse`] is defensive on top of that:
3315    /// no document in the corpus reaches a non-character-boundary index, and it
3316    /// exists so that if one ever does the cost is one skipped feature instead
3317    /// of a panic in the middle of a camera connect.
3318    #[test]
3319    fn byte_order_mark_before_multibyte_text_keeps_the_text_intact() {
3320        let doc = r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="1"><Integer Name="Gain"><Address>0x100</Address><Length>4</Length><ToolTip>Verstärkung in dB — Meßwert</ToolTip></Integer></RegisterDescription>"#;
3321        let with_bom = format!("\u{feff}{doc}");
3322
3323        let model = parse(&with_bom).expect("parse with BOM and multi-byte text");
3324        assert!(model.skipped.is_empty(), "skipped: {:?}", model.skipped);
3325        assert_eq!(
3326            only_meta(&model).tooltip.as_deref(),
3327            Some("Verstärkung in dB — Meßwert")
3328        );
3329    }
3330
3331    /// Regression for issue #45: a FLIR BFS-PGE camera failed to open because a
3332    /// CDATA section in a text element was run through XML unescaping, where the
3333    /// literal `&` it legally contains has no `;` to terminate it.
3334    #[test]
3335    fn cdata_text_is_taken_literally() {
3336        let model = parse_fragment(
3337            r#"<Integer Name="Gain">
3338                 <Address>0x100</Address>
3339                 <ToolTip><![CDATA[Gain in dB & raw units, 0 < x < 10]]></ToolTip>
3340               </Integer>"#,
3341        );
3342        assert_eq!(
3343            only_meta(&model).tooltip.as_deref(),
3344            Some("Gain in dB & raw units, 0 < x < 10")
3345        );
3346    }
3347
3348    /// Non-conformant vendor XML with a lone `&` must not stop the document from
3349    /// loading — a cosmetic tooltip is never worth failing a camera connect over.
3350    #[test]
3351    fn dangling_ampersand_is_kept_verbatim() {
3352        let model = parse_fragment(
3353            r#"<Integer Name="Gain">
3354                 <Address>0x100</Address>
3355                 <ToolTip>Exposure & gain</ToolTip>
3356               </Integer>"#,
3357        );
3358        assert_eq!(
3359            only_meta(&model).tooltip.as_deref(),
3360            Some("Exposure & gain")
3361        );
3362    }
3363
3364    /// Comments are markup, not text: they are dropped, and a `&` inside one is
3365    /// not an entity reference.
3366    #[test]
3367    fn comments_inside_text_elements_are_dropped() {
3368        let model = parse_fragment(
3369            r#"<Integer Name="Gain">
3370                 <Address>0x100</Address>
3371                 <Description>Analog <!-- R&D note --> gain</Description>
3372               </Integer>"#,
3373        );
3374        assert_eq!(
3375            only_meta(&model).description.as_deref(),
3376            Some("Analog  gain")
3377        );
3378    }
3379
3380    /// Entity references still resolve, and the whitespace around them survives
3381    /// even though the reader splits character data at each reference.
3382    #[test]
3383    fn entity_references_resolve_and_preserve_spacing() {
3384        let model = parse_fragment(
3385            r#"<Integer Name="Gain">
3386                 <Address>0x100</Address>
3387                 <ToolTip>A &amp; B &lt; C &gt; D &quot;E&quot; &apos;F&apos;</ToolTip>
3388               </Integer>"#,
3389        );
3390        assert_eq!(
3391            only_meta(&model).tooltip.as_deref(),
3392            Some(r#"A & B < C > D "E" 'F'"#)
3393        );
3394    }
3395
3396    /// Numeric character references, both hexadecimal and decimal.
3397    #[test]
3398    fn character_references_resolve() {
3399        let model = parse_fragment(
3400            r#"<Integer Name="Gain">
3401                 <Address>0x100</Address>
3402                 <ToolTip>&#x2014; dash &#8212;</ToolTip>
3403               </Integer>"#,
3404        );
3405        assert_eq!(only_meta(&model).tooltip.as_deref(), Some("— dash —"));
3406    }
3407
3408    /// GenICam declares no DTD, so an entity we cannot resolve is kept as written
3409    /// rather than failing the document.
3410    #[test]
3411    fn unknown_entity_is_kept_as_written() {
3412        let model = parse_fragment(
3413            r#"<Integer Name="Gain">
3414                 <Address>0x100</Address>
3415                 <ToolTip>copyright &copy; vendor</ToolTip>
3416               </Integer>"#,
3417        );
3418        assert_eq!(
3419            only_meta(&model).tooltip.as_deref(),
3420            Some("copyright &copy; vendor")
3421        );
3422    }
3423
3424    /// SwissKnife formulas escape their bitwise/comparison operators; the parsed
3425    /// expression must contain the operators, not the entities.
3426    #[test]
3427    fn swissknife_formula_entities_resolve_to_operators() {
3428        let model = parse_fragment(
3429            r#"<IntSwissKnife Name="GainMask">
3430                 <pVariable Name="RAW">Gain</pVariable>
3431                 <Formula>(RAW &amp; 0xFF) &lt; 16</Formula>
3432               </IntSwissKnife>"#,
3433        );
3434        match model.nodes.first().expect("one node") {
3435            NodeDecl::SwissKnife(node) => assert_eq!(node.expr, "(RAW & 0xFF) < 16"),
3436            other => panic!("unexpected node: {other:?}"),
3437        }
3438    }
3439
3440    /// A SwissKnife whose formula is constant needs no `<pVariable>`. Rejecting
3441    /// these blocked a Hikrobot MV-CS050-10GC on `PixelDynamicRangeMin_Value`
3442    /// (reported in #35) and appears in the standard's own conformance document.
3443    #[test]
3444    fn swissknife_without_variables_is_accepted() {
3445        let model = parse_fragment(
3446            r#"<IntSwissKnife Name="PixelDynamicRangeMin_Value">
3447                 <Formula>0x1234</Formula>
3448               </IntSwissKnife>"#,
3449        );
3450        match model.nodes.first().expect("one node") {
3451            NodeDecl::SwissKnife(node) => {
3452                assert_eq!(node.expr, "0x1234");
3453                assert!(node.variables.is_empty());
3454            }
3455            other => panic!("unexpected node: {other:?}"),
3456        }
3457    }
3458
3459    /// `<AccessMode>` values beyond the standard's three spellings appear in
3460    /// third-party documents; an odd one must not cost the whole camera.
3461    #[test]
3462    fn access_mode_accepts_aliases_and_defaults_unknown_to_rw() {
3463        assert_eq!(AccessMode::parse("R").unwrap(), AccessMode::RO);
3464        assert_eq!(AccessMode::parse("W").unwrap(), AccessMode::WO);
3465        assert_eq!(AccessMode::parse("WR").unwrap(), AccessMode::RW);
3466        assert_eq!(AccessMode::parse(" ro ").unwrap(), AccessMode::RO);
3467        // A ceiling caps and never grants (backlog GA-23).
3468        assert_eq!(
3469            AccessMode::RW.capped_by(Some(AccessMode::RO)),
3470            Some(AccessMode::RO)
3471        );
3472        assert_eq!(
3473            AccessMode::RO.capped_by(Some(AccessMode::RW)),
3474            Some(AccessMode::RO)
3475        );
3476        assert_eq!(AccessMode::RW.capped_by(None), Some(AccessMode::RW));
3477        assert_eq!(AccessMode::RO.capped_by(Some(AccessMode::WO)), None);
3478        // An access we cannot read is not one we write (backlog GA-26).
3479        assert_eq!(AccessMode::parse("Bogus").unwrap(), AccessMode::RO);
3480    }
3481
3482    /// A node we cannot parse costs that one feature, not the whole document —
3483    /// and the reader stays in step, so nodes after it still load.
3484    #[test]
3485    fn unparsable_node_is_skipped_not_fatal() {
3486        let model = parse_fragment(
3487            r#"<Integer Name="Before">
3488                 <Address>0x100</Address>
3489                 <Length>4</Length>
3490               </Integer>
3491               <Integer Name="Broken">
3492                 <Address>0xZZZZ</Address>
3493                 <Length>4</Length>
3494               </Integer>
3495               <Integer Name="After">
3496                 <Address>0x200</Address>
3497                 <Length>4</Length>
3498               </Integer>"#,
3499        );
3500
3501        let names: Vec<&str> = model
3502            .nodes
3503            .iter()
3504            .map(|node| match node {
3505                NodeDecl::Integer { name, .. } => name.as_str(),
3506                other => panic!("unexpected node: {other:?}"),
3507            })
3508            .collect();
3509        assert_eq!(names, ["Before", "After"]);
3510
3511        assert_eq!(model.skipped.len(), 1);
3512        let skipped = &model.skipped[0];
3513        assert_eq!(skipped.tag, "Integer");
3514        assert_eq!(skipped.name.as_deref(), Some("Broken"));
3515        assert!(
3516            skipped.error.contains("is not a hexadecimal integer"),
3517            "unexpected error: {}",
3518            skipped.error
3519        );
3520    }
3521
3522    /// Isolation must survive a node whose failure happens before the parser has
3523    /// consumed any children — the outer reader is positioned by the caller, not
3524    /// by how far the node parser got.
3525    #[test]
3526    fn node_missing_required_name_is_skipped() {
3527        let model = parse_fragment(
3528            r#"<Integer>
3529                 <Address>0x100</Address>
3530               </Integer>
3531               <Integer Name="Good">
3532                 <Address>0x200</Address>
3533                 <Length>4</Length>
3534               </Integer>"#,
3535        );
3536        assert_eq!(model.nodes.len(), 1);
3537        assert_eq!(model.skipped.len(), 1);
3538        assert_eq!(model.skipped[0].name, None);
3539    }
3540
3541    /// A clean document reports nothing skipped.
3542    #[test]
3543    fn clean_document_skips_nothing() {
3544        let model = parse(FIXTURE).expect("parse fixture");
3545        assert!(model.skipped.is_empty());
3546    }
3547
3548    /// The `<pInvalidator>` list of any node kind that can carry one.
3549    fn invalidators_of(decl: &NodeDecl) -> &[String] {
3550        match decl {
3551            NodeDecl::Integer { invalidators, .. } | NodeDecl::Float { invalidators, .. } => {
3552                invalidators
3553            }
3554            NodeDecl::String(decl) => &decl.invalidators,
3555            NodeDecl::Register(decl) => &decl.invalidators,
3556            other => panic!("{} carries no invalidators", other.kind()),
3557        }
3558    }
3559
3560    /// GA-24: a register may name any number of invalidators — FLIR declares
3561    /// up to nineteen on one node — and each must survive, in order.
3562    #[test]
3563    fn int_reg_keeps_every_invalidator_in_order() {
3564        let model = parse_fragment(
3565            r#"<IntReg Name="ExposureTime_Val">
3566                 <Address>0x100</Address>
3567                 <Length>4</Length>
3568                 <pInvalidator>ExposureAuto_Val</pInvalidator>
3569                 <pInvalidator> UserSetLoad_Val </pInvalidator>
3570               </IntReg>"#,
3571        );
3572        assert_eq!(
3573            invalidators_of(&model.nodes[0]),
3574            ["ExposureAuto_Val", "UserSetLoad_Val"]
3575        );
3576    }
3577
3578    #[test]
3579    fn masked_int_float_string_and_register_nodes_carry_invalidators() {
3580        let model = parse_fragment(
3581            r#"<MaskedIntReg Name="Bits">
3582                 <Address>0x100</Address><Length>4</Length><Bit>0</Bit>
3583                 <pInvalidator>A</pInvalidator>
3584               </MaskedIntReg>
3585               <FloatReg Name="Exposure">
3586                 <Address>0x200</Address><Length>8</Length>
3587                 <pInvalidator>B</pInvalidator>
3588               </FloatReg>
3589               <StringReg Name="Model">
3590                 <Address>0x300</Address><Length>16</Length>
3591                 <pInvalidator>C</pInvalidator>
3592               </StringReg>
3593               <Register Name="Raw">
3594                 <Address>0x400</Address><Length>16</Length>
3595                 <pInvalidator>D</pInvalidator>
3596               </Register>"#,
3597        );
3598        assert!(model.skipped.is_empty(), "{:?}", model.skipped);
3599        let lists: Vec<&[String]> = model.nodes.iter().map(invalidators_of).collect();
3600        assert_eq!(lists, [["A"], ["B"], ["C"], ["D"]]);
3601    }
3602
3603    /// Declared once on the `<StructReg>`, the invalidator applies to every
3604    /// entry: each is a view of the same register.
3605    #[test]
3606    fn struct_reg_invalidator_lands_on_every_entry() {
3607        let model = parse_fragment(
3608            r#"<StructReg Comment="Inquiry">
3609                 <Address>0x100</Address>
3610                 <Length>4</Length>
3611                 <pInvalidator>UserSetLoad_Val</pInvalidator>
3612                 <StructEntry Name="First"><Bit>0</Bit></StructEntry>
3613                 <StructEntry Name="Second"><Bit>1</Bit></StructEntry>
3614               </StructReg>"#,
3615        );
3616        assert_eq!(model.nodes.len(), 2);
3617        for node in &model.nodes {
3618            assert_eq!(
3619                invalidators_of(node),
3620                ["UserSetLoad_Val"],
3621                "{}",
3622                node.name()
3623            );
3624        }
3625    }
3626
3627    /// An empty reference must not become an edge from a node named "".
3628    #[test]
3629    fn empty_invalidator_is_ignored() {
3630        let model = parse_fragment(
3631            r#"<IntReg Name="Reg">
3632                 <Address>0x100</Address>
3633                 <Length>4</Length>
3634                 <pInvalidator></pInvalidator>
3635                 <pInvalidator>   </pInvalidator>
3636                 <pInvalidator/>
3637               </IntReg>"#,
3638        );
3639        assert!(model.skipped.is_empty(), "{:?}", model.skipped);
3640        assert!(invalidators_of(&model.nodes[0]).is_empty());
3641    }
3642
3643    /// GA-12: `<pPort>` is read on every register-backed node, and `<Port>`
3644    /// declarations say what each port reads. Shapes from the corpus: FLIR's
3645    /// chunk and event ports, Baumer's negative chunk address, Basler's
3646    /// `<MaskedIntReg>` on a chunk port, scanCONTROL's `<Register>` and
3647    /// `<StringReg>` on chunk ports.
3648    #[test]
3649    fn ports_and_the_registers_on_them() {
3650        let model = parse(
3651            r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
3652                 <Port Name="Device"/>
3653                 <Port Name="TimestampPort"><ChunkID>0508000E</ChunkID></Port>
3654                 <Port Name="EventExposureEndPort" NameSpace="Custom">
3655                   <ToolTip>Exposure end</ToolTip><EventID>9C43</EventID>
3656                 </Port>
3657                 <IntReg Name="Ts"><Address>0x0</Address><Length>8</Length><pPort>TimestampPort</pPort></IntReg>
3658                 <MaskedIntReg Name="Masked"><Address>0x4</Address><Length>4</Length><pPort>TimestampPort</pPort><LSB>7</LSB><MSB>0</MSB></MaskedIntReg>
3659                 <FloatReg Name="Exposure"><Address>0x0</Address><Length>4</Length><pPort>TimestampPort</pPort></FloatReg>
3660                 <StringReg Name="Message"><Address>0x20</Address><Length>32</Length><pPort>EventExposureEndPort</pPort></StringReg>
3661                 <Register Name="Results"><Address>0x0</Address><Length>104</Length><pPort>TimestampPort</pPort></Register>
3662                 <IntReg Name="Length"><Address>-4</Address><Length>4</Length><pPort>TimestampPort</pPort></IntReg>
3663                 <StructReg Comment="Status">
3664                   <Address>0x8</Address><Length>4</Length><pPort>EventExposureEndPort</pPort>
3665                   <StructEntry Name="Flag"><Bit>0</Bit></StructEntry>
3666                 </StructReg>
3667                 <IntReg Name="OnDevice"><Address>0x100</Address><Length>4</Length></IntReg>
3668               </RegisterDescription>"#,
3669        )
3670        .expect("parse");
3671        assert!(model.skipped.is_empty(), "{:?}", model.skipped);
3672        assert_eq!(
3673            model.ports,
3674            vec![
3675                PortDecl {
3676                    name: "Device".into(),
3677                    kind: PortKind::Device,
3678                    ignored: Vec::new(),
3679                },
3680                PortDecl {
3681                    name: "TimestampPort".into(),
3682                    kind: PortKind::Chunk {
3683                        chunk_id: 0x0508_000E
3684                    },
3685                    ignored: Vec::new(),
3686                },
3687                PortDecl {
3688                    name: "EventExposureEndPort".into(),
3689                    kind: PortKind::Event { event_id: 0x9C43 },
3690                    // A port is not a feature: its documentation has nowhere
3691                    // to go, and is recorded as read past.
3692                    ignored: vec!["ToolTip".into()],
3693                },
3694            ]
3695        );
3696        let port_of = |name: &str| -> Option<String> {
3697            let node = model.nodes.iter().find(|n| n.name() == name).expect(name);
3698            let addressing = match node {
3699                NodeDecl::Integer { addressing, .. } | NodeDecl::Float { addressing, .. } => {
3700                    addressing.clone().expect("addressed")
3701                }
3702                NodeDecl::String(decl) => decl.addressing.clone().expect("a StringReg"),
3703                NodeDecl::Register(decl) => decl.addressing.clone(),
3704                other => panic!("unexpected {other:?}"),
3705            };
3706            addressing.port().map(str::to_string)
3707        };
3708        for name in ["Ts", "Masked", "Exposure", "Results", "Length"] {
3709            assert_eq!(port_of(name).as_deref(), Some("TimestampPort"), "{name}");
3710        }
3711        for name in ["Message", "Flag"] {
3712            assert_eq!(
3713                port_of(name).as_deref(),
3714                Some("EventExposureEndPort"),
3715                "{name}"
3716            );
3717        }
3718        assert_eq!(port_of("OnDevice"), None);
3719        match model.nodes.iter().find(|n| n.name() == "Length") {
3720            Some(NodeDecl::Integer {
3721                addressing: Some(Addressing::Sum { terms, .. }),
3722                ..
3723            }) => assert_eq!(terms, &[AddressTerm::Fixed(-4)]),
3724            other => panic!("unexpected {other:?}"),
3725        }
3726    }
3727
3728    /// What a port cannot be is recorded, not guessed: a `<pChunkID>` (no
3729    /// corpus document uses one) and a port claiming to be both kinds.
3730    #[test]
3731    fn unsupported_ports_are_skipped_and_say_why() {
3732        let model = parse(
3733            r#"<RegisterDescription>
3734                 <Port Name="Indirect"><pChunkID>ChunkIdNode</pChunkID></Port>
3735                 <Port Name="Both"><ChunkID>1</ChunkID><EventID>2</EventID></Port>
3736                 <Port Name="NotHex"><ChunkID>xyz</ChunkID></Port>
3737               </RegisterDescription>"#,
3738        )
3739        .expect("parse");
3740        assert!(model.ports.is_empty(), "{:?}", model.ports);
3741        let reasons: Vec<(&str, &str)> = model
3742            .skipped
3743            .iter()
3744            .map(|s| (s.name.as_deref().unwrap_or(""), s.error.as_str()))
3745            .collect();
3746        assert_eq!(reasons.len(), 3, "{reasons:?}");
3747        assert!(reasons[0].0 == "Indirect" && reasons[0].1.contains("<pChunkID>"));
3748        assert!(reasons[1].0 == "Both" && reasons[1].1.contains("both"));
3749        assert!(reasons[2].0 == "NotHex" && reasons[2].1.contains("hexadecimal"));
3750    }
3751
3752    /// GenICam Standard v2.1.1 §2.8.5, issue #210: on an `<Integer>`,
3753    /// `<pIndex>` selects a `<pValueIndexed>` or `<ValueIndexed>` entry, else
3754    /// the default. It is no address term: read as one, Basler's `d_90`
3755    /// addressed bootstrap register 0x000C.
3756    #[test]
3757    fn an_integer_p_index_selects_an_indexed_value() {
3758        let model = parse_fragment(
3759            r#"<Integer Name="d_90">
3760                 <pIndex>d_88</pIndex>
3761                 <pValueIndexed Index="3">d_257</pValueIndexed>
3762                 <ValueIndexed Index="0x4">7</ValueIndexed>
3763                 <pValueDefault>d_1049</pValueDefault>
3764               </Integer>"#,
3765        );
3766        assert!(model.skipped.is_empty(), "{:?}", model.skipped);
3767        assert!(model.ignored().is_empty(), "{:?}", model.ignored());
3768        let NodeDecl::Integer {
3769            addressing,
3770            indexed: Some(indexed),
3771            ..
3772        } = &model.nodes[0]
3773        else {
3774            panic!("not an indexed integer: {:?}", model.nodes[0]);
3775        };
3776        assert!(addressing.is_none(), "{addressing:?}");
3777        assert_eq!(indexed.index, "d_88");
3778        assert_eq!(
3779            indexed.entries,
3780            [
3781                IndexedEntry {
3782                    index: 3,
3783                    value: IndexedSrc::FromNode("d_257".into())
3784                },
3785                IndexedEntry {
3786                    index: 4,
3787                    value: IndexedSrc::Literal(7)
3788                },
3789            ]
3790        );
3791        assert_eq!(indexed.default, Some(IndexedSrc::FromNode("d_1049".into())));
3792        assert_eq!(indexed.referenced_nodes(), ["d_88", "d_257", "d_1049"]);
3793    }
3794
3795    /// The same on a `<Float>`, as `aravis_genicam.xml`'s `FloatTable`; and
3796    /// a `<Float>`'s own `<Value>` (backlog GA-49).
3797    #[test]
3798    fn a_float_reads_indexed_values_and_a_constant_value() {
3799        let model = parse_fragment(
3800            r#"<Float Name="FloatTable">
3801                 <pIndex>FloatTableSelector</pIndex>
3802                 <ValueIndexed Index="10">100.1</ValueIndexed>
3803                 <ValueDefault>600.6</ValueDefault>
3804               </Float>
3805               <Float Name="GainDbPerRawStep"><Value>1e-1</Value></Float>"#,
3806        );
3807        assert!(model.ignored().is_empty(), "{:?}", model.ignored());
3808        let NodeDecl::Float {
3809            indexed: Some(indexed),
3810            addressing: None,
3811            ..
3812        } = &model.nodes[0]
3813        else {
3814            panic!("not an indexed float: {:?}", model.nodes[0]);
3815        };
3816        assert_eq!(indexed.index, "FloatTableSelector");
3817        assert_eq!(indexed.entries[0].value, IndexedSrc::Literal(100.1));
3818        assert_eq!(indexed.default, Some(IndexedSrc::Literal(600.6)));
3819        assert!(matches!(
3820            model.nodes[1],
3821            NodeDecl::Float {
3822                value: Some(0.1),
3823                ..
3824            }
3825        ));
3826    }
3827
3828    /// A register's `<pIndex>` is an address term, as is an `<Integer>`'s
3829    /// when the `<Integer>` declares an address of its own and no indexed
3830    /// value — a form hand-written documents use.
3831    #[test]
3832    fn a_p_index_beside_an_address_stays_an_address_term() {
3833        let model = parse_fragment(
3834            r#"<IntReg Name="Reg">
3835                 <pIndex Offset="4">Sel</pIndex>
3836                 <Address>0x100</Address><Length>4</Length>
3837               </IntReg>
3838               <Integer Name="Lenient">
3839                 <Address>0x200</Address>
3840                 <pIndex Offset="64">Sel</pIndex>
3841                 <Length>4</Length>
3842               </Integer>"#,
3843        );
3844        for node in &model.nodes {
3845            let NodeDecl::Integer {
3846                addressing: Some(Addressing::Sum { terms, .. }),
3847                indexed: None,
3848                ..
3849            } = node
3850            else {
3851                panic!("not a register: {node:?}");
3852            };
3853            assert!(
3854                terms
3855                    .iter()
3856                    .any(|term| matches!(term, AddressTerm::Index { node, .. } if node == "Sel")),
3857                "{terms:?}"
3858            );
3859        }
3860    }
3861
3862    /// Indexed values with nothing to index them by: the node is skipped and
3863    /// says why, rather than read from a register it does not have.
3864    #[test]
3865    fn indexed_values_without_p_index_are_refused() {
3866        let model = parse_fragment(
3867            r#"<Integer Name="Orphan"><ValueIndexed Index="1">5</ValueIndexed></Integer>"#,
3868        );
3869        assert!(model.nodes.is_empty(), "{:?}", model.nodes);
3870        assert!(
3871            model.skipped[0].error.contains("<pIndex>"),
3872            "{:?}",
3873            model.skipped
3874        );
3875    }
3876
3877    /// A `<StructEntry>`'s own `<pInvalidator>`s join the `<StructReg>`'s:
3878    /// the Basler a2A4096-44g5m's `d_1664` names its sibling bits this way.
3879    #[test]
3880    fn struct_entry_invalidators_join_the_struct_regs() {
3881        let model = parse_fragment(
3882            r#"<StructReg Comment="d_1664">
3883                 <Address>0x10007de8</Address><Length>4</Length>
3884                 <pInvalidator>Shared</pInvalidator>
3885                 <StructEntry Name="d_1664_0">
3886                   <pInvalidator>d_1664</pInvalidator>
3887                   <pInvalidator>Shared</pInvalidator>
3888                   <Bit>31</Bit>
3889                 </StructEntry>
3890                 <StructEntry Name="d_1664_1"><Bit>30</Bit></StructEntry>
3891               </StructReg>"#,
3892        );
3893        assert!(model.ignored().is_empty(), "{:?}", model.ignored());
3894        let lists: Vec<&[String]> = model.nodes.iter().map(invalidators_of).collect();
3895        assert_eq!(lists, [&["Shared", "d_1664"][..], &["Shared"][..]]);
3896    }
3897
3898    /// A hex address keeps its bit pattern: device addresses above 2^31 stay
3899    /// positive, and a full-width pattern is the negative number it spells.
3900    #[test]
3901    fn addresses_parse_signed() {
3902        assert_eq!(util::parse_address("-4").expect("dec"), -4);
3903        assert_eq!(util::parse_address("0xFFFFF0F0").expect("hex"), 0xFFFF_F0F0);
3904        assert_eq!(util::parse_address("0xFFFFFFFFFFFFFFFC").expect("hex"), -4);
3905        assert!(util::parse_address("-0x4").is_err());
3906    }
3907}