Skip to main content

viva_genapi/
nodemap.rs

1//! NodeMap implementation for runtime feature access.
2
3mod ports;
4mod refresh;
5
6pub use ports::ChunkData;
7
8use std::cell::Cell;
9use std::collections::{HashMap, HashSet, hash_map::Entry as HashMapEntry};
10
11use tracing::{debug, trace, warn};
12use viva_genapi_xml::{
13    AccessMode, AddressTerm, Addressing, ByteOrder, CommandValueSrc, DocumentIdentity,
14    EnumEntryDecl, EnumValueSrc, FloatEncoding, FormulaBindings, IgnoredElement, IndexOffset,
15    IndexedSrc, IndexedValue, NodeDecl, PortKind, PredicateRefs, Sign, SkippedNode, Slope,
16    Visibility, XmlModel,
17};
18
19use crate::bitops::{extract, insert};
20use crate::conversions::{
21    apply_scale, bytes_to_i64, decode_ieee754, encode_bitfield_value, encode_float, encode_ieee754,
22    get_raw_or_read, i64_to_bytes, interpret_bitfield_value, map_bitops_error, round_to_i64,
23};
24use crate::nodes::{
25    BooleanNode, CategoryNode, CommandNode, ConverterNode, EnumMapping, EnumNode, FloatNode,
26    FormulaVar, Indexed, IntConverterNode, IntegerNode, Node, RegisterNode, SkNode, StringNode,
27};
28use crate::swissknife::{
29    AstNode as SkAst, EvalError as SkEvalError, EvalMode, Value as SkValue, VarAttr,
30    collect_identifiers, evaluate as eval_ast, is_builtin_constant, parse_expression,
31    split_qualified, substitute,
32};
33use crate::{AccessDirection, GenApiError, RangeViolation, RegisterIo, SkOutput};
34
35/// Runtime nodemap built from an [`XmlModel`] capable of reading and writing
36/// feature values via a [`RegisterIo`] transport.
37#[derive(Debug)]
38pub struct NodeMap {
39    version: String,
40    /// The camera the document describes, and the document's version.
41    identity: DocumentIdentity,
42    nodes: HashMap<String, Node>,
43    /// Node names in document order: listings and the restore order of a
44    /// saved configuration follow the XML rather than a hash.
45    order: Vec<String>,
46    dependents: HashMap<String, Vec<String>>,
47    /// See [`NodeMap::command_targets`]; fixed once the map is built.
48    command_targets: HashSet<String>,
49    skipped: Vec<SkippedNode>,
50    /// Child elements the XML parser read past; see [`NodeMap::ignored`].
51    ignored: Vec<IgnoredElement>,
52    generation: Cell<u64>,
53    /// `<Port>` declarations by name: which addresses are the device's and
54    /// which a chunk's or an event's.
55    ports: HashMap<String, PortKind>,
56    /// Chunk and event data attached to those ports.
57    attached: ports::Attached,
58    /// `<Cachable>` and `<PollingTime>` resolved per node, the clock polling
59    /// is measured against, and what changed when (ADR-0029).
60    refresh: refresh::Refresh,
61}
62
63fn register_addressing_dependency(
64    dependents: &mut HashMap<String, Vec<String>>,
65    node_name: &str,
66    addressing: &Addressing,
67) {
68    for provider in addressing.referenced_nodes() {
69        dependents
70            .entry(provider.to_string())
71            .or_default()
72            .push(node_name.to_string());
73    }
74}
75
76fn register_predicate_dependencies(
77    dependents: &mut HashMap<String, Vec<String>>,
78    node_name: &str,
79    predicates: &PredicateRefs,
80) {
81    for provider in predicates.references() {
82        dependents
83            .entry(provider.to_string())
84            .or_default()
85            .push(node_name.to_string());
86    }
87}
88
89/// Record `node_name` as stale whenever any of its `<pInvalidator>` nodes changes.
90///
91/// An invalidator is often also the node's address or selector provider, so a
92/// pair that is already recorded is not pushed again.
93fn register_invalidator_dependencies(
94    dependents: &mut HashMap<String, Vec<String>>,
95    node_name: &str,
96    invalidators: &[String],
97) {
98    for provider in invalidators {
99        let list = dependents.entry(provider.clone()).or_default();
100        if !list.iter().any(|dependent| dependent == node_name) {
101            list.push(node_name.to_string());
102        }
103    }
104}
105
106/// Record `node_name` as stale whenever its index node, or a node one of its
107/// indexed values reads, changes (GenICam Standard v2.1.1 §2.8.5).
108fn register_indexed_dependencies<T>(
109    dependents: &mut HashMap<String, Vec<String>>,
110    node_name: &str,
111    indexed: Option<&IndexedValue<T>>,
112) {
113    let providers = indexed.map(IndexedValue::referenced_nodes);
114    for provider in providers.into_iter().flatten() {
115        let list = dependents.entry(provider.to_string()).or_default();
116        if !list.iter().any(|dependent| dependent == node_name) {
117            list.push(node_name.to_string());
118        }
119    }
120}
121
122/// Record each feature `selector` names in `<pSelected>` as stale whenever
123/// `selector` changes.
124///
125/// GenICam Standard v2.1.1 §2.8.4 puts `<pSelected>` on the selector, naming
126/// features that "will show a different value depending on the value of
127/// selector node" — so the edge runs selector → selected. Reading it the other
128/// way round made the selected feature a provider of its selector, which
129/// invalidated the selector on a feature write and left the feature stale on a
130/// selector write (backlog GA-03). The registers behind each selected feature
131/// are linked too, once the whole map exists: see
132/// [`NodeMap::link_selected_values`].
133fn register_selection_dependencies(
134    dependents: &mut HashMap<String, Vec<String>>,
135    selector: &str,
136    selected: &[String],
137) {
138    let list = dependents.entry(selector.to_string()).or_default();
139    for feature in selected {
140        if !list.contains(feature) {
141            list.push(feature.clone());
142        }
143    }
144}
145
146fn ensure_readable(access: &AccessMode, name: &str) -> Result<(), GenApiError> {
147    if matches!(access, AccessMode::WO) {
148        return Err(GenApiError::access(name, AccessDirection::Read));
149    }
150    Ok(())
151}
152
153/// Every node `node` may take its value from: its `<pValue>`, or each node
154/// an indexed `<Integer>` or `<Float>` can select.
155fn value_providers(node: &Node) -> Vec<&str> {
156    let indexed = match node {
157        Node::Integer(n) => n.indexed.as_ref().map(|i| i.table.value_nodes()),
158        Node::Float(n) => n.indexed.as_ref().map(|i| i.table.value_nodes()),
159        _ => None,
160    };
161    value_provider(node)
162        .into_iter()
163        .chain(indexed.into_iter().flatten())
164        .collect()
165}
166
167/// Whether `a` and `b` together allow reading and writing: what a node that
168/// declares `a` allows over one that declares `b`. `None` allows neither.
169fn combine_access(a: Option<AccessMode>, b: Option<AccessMode>) -> Option<AccessMode> {
170    let (a, b) = (a?, b?);
171    let readable = a != AccessMode::WO && b != AccessMode::WO;
172    let writable = a != AccessMode::RO && b != AccessMode::RO;
173    match (readable, writable) {
174        (true, true) => Some(AccessMode::RW),
175        (true, false) => Some(AccessMode::RO),
176        (false, true) => Some(AccessMode::WO),
177        (false, false) => None,
178    }
179}
180
181/// The node `node` takes its value from through `<pValue>`, if it delegates.
182fn value_provider(node: &Node) -> Option<&str> {
183    match node {
184        Node::Integer(n) => n.pvalue.as_deref(),
185        Node::Float(n) => n.pvalue.as_deref(),
186        Node::Enum(n) => n.pvalue.as_deref(),
187        Node::Boolean(n) => n.pvalue.as_deref(),
188        Node::Command(n) => n.pvalue.as_deref(),
189        Node::Converter(n) => Some(n.p_value.as_str()),
190        Node::IntConverter(n) => Some(n.p_value.as_str()),
191        Node::String(n) => n.pvalue.as_deref(),
192        _ => None,
193    }
194}
195
196/// The longest device register a `<pLength>` node may give: 16 MiB, two
197/// hundred times the largest `<Length>` the vendor corpus declares (the
198/// Micro-Epsilon scanCONTROL's 100 000-byte `FileAccessBuffer`). A chunk or
199/// event port is bounded by the data attached to it instead.
200pub(crate) const MAX_DEVICE_LENGTH: u32 = 16 * 1024 * 1024;
201
202/// A restriction parameter of a numeric node.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub(crate) enum Limit {
205    /// `<Min>` / `<pMin>`.
206    Min,
207    /// `<Max>` / `<pMax>`.
208    Max,
209    /// `<Inc>` / `<pInc>`.
210    Inc,
211}
212
213/// The read direction of a `<Converter>` or `<IntConverter>`, as
214/// [`NodeMap::converter_limit`] needs it.
215struct FromFormula<'a> {
216    name: &'a str,
217    ast: &'a SkAst,
218    vars: &'a [FormulaVar],
219    p_value: &'a str,
220    slope: Slope,
221    mode: EvalMode,
222}
223
224fn ensure_writable(access: &AccessMode, name: &str) -> Result<(), GenApiError> {
225    if matches!(access, AccessMode::RO) {
226        return Err(GenApiError::access(name, AccessDirection::Write));
227    }
228    Ok(())
229}
230
231impl NodeMap {
232    /// Return the schema version string associated with the XML description.
233    pub fn version(&self) -> &str {
234        &self.version
235    }
236
237    /// Fetch a node by name for inspection.
238    pub fn node(&self, name: &str) -> Option<&Node> {
239        self.nodes.get(name)
240    }
241
242    /// The camera the XML describes — `VendorName`, `ModelName` — and the
243    /// version of the XML file itself (GenICam Standard v2.1.1 §2.7).
244    pub fn identity(&self) -> &DocumentIdentity {
245        &self.identity
246    }
247
248    /// Return an iterator over all node names in the map, in the order the
249    /// XML declares them.
250    pub fn node_names(&self) -> impl Iterator<Item = &str> {
251        self.order.iter().map(String::as_str)
252    }
253
254    /// The selectors that select `name` — every node whose `<pSelected>`
255    /// names it — in document order. Empty for a feature no selector selects.
256    pub fn selectors_of(&self, name: &str) -> Vec<&str> {
257        self.node_names()
258            .filter(|candidate| {
259                self.nodes
260                    .get(*candidate)
261                    .is_some_and(|node| node.selected().iter().any(|s| s == name))
262            })
263            .collect()
264    }
265
266    /// Return the list of nodes that should be invalidated when `name` changes.
267    ///
268    /// Returns an empty slice if the node has no dependents.
269    pub fn dependents(&self, name: &str) -> &[String] {
270        self.dependents
271            .get(name)
272            .map(|v| v.as_slice())
273            .unwrap_or(&[])
274    }
275
276    /// Return all category nodes as `(name, children)` pairs.
277    pub fn categories(&self) -> Vec<(&str, &[String])> {
278        self.nodes
279            .values()
280            .filter_map(|node| match node {
281                Node::Category(cat) => Some((cat.name.as_str(), cat.children.as_slice())),
282                _ => None,
283            })
284            .collect()
285    }
286
287    /// Return the names of the nodes a [`Node::Command`] executes through.
288    ///
289    /// A command reaches its register through `<pValue>`, and the target may
290    /// delegate again through its own `<pValue>` — an integer's, or an
291    /// `<IntConverter>`'s — or select one by index: every entry and the
292    /// default of an indexed `<Integer>` on the way. Every node that
293    /// [`NodeMap::exec_command`] can write along is returned, found from the
294    /// declarations rather than from node names.
295    ///
296    /// None of these nodes holds a value worth displaying. Writing one
297    /// triggers an action; reading it is at best meaningless and on some
298    /// devices significant, and many declare it `WO`. A feature snapshot
299    /// should report them without reading them (backlog ST-21, issue #112).
300    ///
301    /// Computed once, when the map is built: a feature snapshot consults it
302    /// for every node.
303    pub fn command_targets(&self) -> &HashSet<String> {
304        &self.command_targets
305    }
306
307    fn find_command_targets(&self) -> HashSet<String> {
308        let mut targets = HashSet::new();
309        for node in self.nodes.values() {
310            let Node::Command(cmd) = node else {
311                continue;
312            };
313            if let Some(first) = cmd.pvalue.as_deref() {
314                targets.extend(self.value_reach(first).into_iter().map(str::to_string));
315            }
316        }
317        targets
318    }
319
320    /// The nodes whose value or state may change when `name` is written.
321    ///
322    /// A write reaches the register at the end of `name`'s `<pValue>` chain
323    /// (through any entry an indexed value can select), and from there it can
324    /// move anything that depends on a node along that chain — directly or
325    /// through other nodes: a converter reading the same register, a node
326    /// whose `<pMin>`/`<pMax>`, address, `pIsAvailable` or `pIsLocked` refers
327    /// to it, a node the selector `name` selects, a node naming it as a
328    /// `<pInvalidator>`. All of them are returned, sorted, without `name`
329    /// itself; a viewer re-reads the ones it shows, so that writing
330    /// `BalanceRatioSelector` refreshes `BalanceRatio` (backlog ST-30).
331    ///
332    /// Empty for an unknown name.
333    pub fn invalidated_by(&self, name: &str) -> Vec<String> {
334        if !self.nodes.contains_key(name) {
335            return Vec::new();
336        }
337        let mut seen: HashSet<&str> = HashSet::new();
338        let mut pending: Vec<&str> = self.value_reach(name);
339        while let Some(current) = pending.pop() {
340            if !seen.insert(current) {
341                continue;
342            }
343            pending.extend(self.dependents(current).iter().map(String::as_str));
344        }
345        seen.remove(name);
346        let mut out: Vec<String> = seen.into_iter().map(str::to_string).collect();
347        out.sort();
348        out
349    }
350
351    /// Whether reading `name` is refused because a node on its value path is
352    /// declared `WO`: the node itself, or one it takes its value from through
353    /// `<pValue>`.
354    ///
355    /// The declared mode of `name` alone is not enough. A feature can be `RW`
356    /// — or declare no access mode at all — and delegate to a `WO` register:
357    /// GigE Vision's `ActionDeviceKey` does exactly that on a Vieworks camera
358    /// in issue #112, and its read failed one hop down. Returns `false` for an
359    /// unknown name.
360    ///
361    /// This is the static part of the answer. The node an indexed value
362    /// selects depends on its index, so whether it is write-only is a
363    /// question for the device: [`NodeMap::effective_access_mode`] answers
364    /// it, and [`NodeMap::feature_state`] and [`NodeMap::is_done`] follow it.
365    pub fn is_write_only(&self, name: &str) -> bool {
366        self.value_chain(name)
367            .into_iter()
368            .any(|link| self.declares_write_only(link))
369    }
370
371    /// Whether `name` declares `WO`, as its access mode or as one it imposes.
372    fn declares_write_only(&self, name: &str) -> bool {
373        self.nodes.get(name).is_some_and(|node| {
374            matches!(node.access_mode(), Some(AccessMode::WO))
375                || node.meta().imposed_access == Some(AccessMode::WO)
376        })
377    }
378
379    /// [`NodeMap::is_write_only`] along the path `name` reads through now.
380    fn write_only_now(&self, name: &str, io: &dyn RegisterIo) -> Result<bool, GenApiError> {
381        Ok(self
382            .value_path_now(name, io)?
383            .into_iter()
384            .any(|link| self.declares_write_only(link)))
385    }
386
387    /// `name`'s [`NodeMap::value_chain`], continued through the node an
388    /// indexed node at its end selects now, and that node's chain, and so on:
389    /// the nodes a read or write of `name` passes through now, each once.
390    fn value_path_now<'a>(
391        &'a self,
392        name: &'a str,
393        io: &dyn RegisterIo,
394    ) -> Result<Vec<&'a str>, GenApiError> {
395        let mut path: Vec<&'a str> = Vec::new();
396        let mut current = name;
397        loop {
398            for link in self.value_chain(current) {
399                if path.contains(&link) {
400                    return Ok(path);
401                }
402                path.push(link);
403            }
404            let last = path.last().copied().unwrap_or(current);
405            match self.indexed_target(last, io)? {
406                Some(next) if !path.contains(&next) => current = next,
407                _ => return Ok(path),
408            }
409        }
410    }
411
412    /// `start` followed by each node it takes its value from through
413    /// `<pValue>`, until a node that delegates no further. A `<pValue>` cycle
414    /// ends the chain rather than looping.
415    pub(crate) fn value_chain<'a>(&'a self, start: &'a str) -> Vec<&'a str> {
416        let mut chain = vec![start];
417        let mut current = start;
418        while let Some(next) = self.nodes.get(current).and_then(value_provider) {
419            if chain.contains(&next) {
420                break;
421            }
422            chain.push(next);
423            current = next;
424        }
425        chain
426    }
427
428    /// `start` followed by every node it may take its value from — through
429    /// `<pValue>`, or as any entry or the default of an indexed node — each
430    /// once: the nodes whose caches can hold `start`'s value.
431    /// [`NodeMap::value_chain`] is the `<pValue>` part.
432    pub(crate) fn value_reach<'a>(&'a self, start: &'a str) -> Vec<&'a str> {
433        let mut reach = vec![start];
434        let mut next = 0;
435        while let Some(&current) = reach.get(next) {
436            next += 1;
437            let Some(node) = self.nodes.get(current) else {
438                continue;
439            };
440            for provider in value_providers(node) {
441                if !reach.contains(&provider) {
442                    reach.push(provider);
443                }
444            }
445        }
446        reach
447    }
448
449    /// Return names of nodes visible at the given level or below.
450    ///
451    /// A node with `Visibility::Expert` is visible at level `Expert` and `Guru`,
452    /// but not at `Beginner`.
453    pub fn nodes_at_visibility(&self, level: Visibility) -> Vec<&str> {
454        self.nodes
455            .iter()
456            .filter(|(_, node)| node.visibility() <= level)
457            .map(|(name, _)| name.as_str())
458            .collect()
459    }
460
461    /// Construct a [`NodeMap`] from an [`XmlModel`], validating formulas.
462    ///
463    /// A declaration that cannot be turned into a runtime node is dropped and
464    /// recorded in [`NodeMap::skipped`] rather than failing the whole model.
465    /// Cameras carry thousands of nodes and only a handful of them matter to
466    /// any one application; refusing to open a camera because one obscure
467    /// feature is unrepresentable serves nobody.
468    pub fn try_from_xml(model: XmlModel) -> Result<Self, GenApiError> {
469        let mut nodes = HashMap::new();
470        let mut dependents: HashMap<String, Vec<String>> = HashMap::new();
471        // Losses from the XML layer travel with the ones from this layer. A
472        // consumer holding a NodeMap has no access to the XmlModel it was
473        // built from, so leaving them behind would make a feature the parser
474        // could not read indistinguishable from one the camera does not have.
475        let ignored = model.ignored();
476        let mut skipped = model.skipped;
477        let ports: HashMap<String, PortKind> = model
478            .ports
479            .into_iter()
480            .map(|port| (port.name, port.kind))
481            .collect();
482        let mut order = Vec::with_capacity(model.nodes.len());
483        for decl in model.nodes {
484            let tag = decl.kind().to_string();
485            let name = Some(decl.name().to_string());
486            // A node we cannot build costs that one feature, not the camera.
487            // The same isolation the XML layer already applies (issue #48) --
488            // a single unusual declaration must not make a camera unopenable.
489            let mut local: HashMap<String, Vec<String>> = HashMap::new();
490            match build_node(decl, &mut local) {
491                Ok((node_name, node)) => {
492                    for (provider, mut names) in local {
493                        dependents.entry(provider).or_default().append(&mut names);
494                    }
495                    if !nodes.contains_key(&node_name) {
496                        order.push(node_name.clone());
497                    }
498                    nodes.insert(node_name, node);
499                }
500                Err(err) => {
501                    warn!(
502                        tag = %tag,
503                        node = name.as_deref().unwrap_or("<unnamed>"),
504                        error = %err,
505                        "dropping GenApi node"
506                    );
507                    skipped.push(SkippedNode::new(tag, name, err.to_string()));
508                }
509            }
510        }
511
512        let mut map = NodeMap {
513            version: model.version,
514            identity: model.identity,
515            nodes,
516            order,
517            dependents,
518            command_targets: HashSet::new(),
519            skipped,
520            ignored,
521            generation: Cell::new(0),
522            ports,
523            attached: ports::Attached::default(),
524            refresh: refresh::Refresh::default(),
525        };
526        map.command_targets = map.find_command_targets();
527        map.link_selected_values();
528        map.link_port_dependents();
529        map.build_refresh();
530        Ok(map)
531    }
532
533    /// Extend each selector's `<pSelected>` edges to the nodes its selected
534    /// features take their values from.
535    ///
536    /// A selected feature usually caches nothing itself: it delegates through
537    /// `<pValue>` to a register, and the register holds the reading.
538    /// Invalidating only the front node would leave that reading in place for
539    /// the next read to answer from. The chain is only known once every node
540    /// exists, hence a pass after the build.
541    fn link_selected_values(&mut self) {
542        let mut links: Vec<(String, String)> = Vec::new();
543        for node in self.nodes.values() {
544            let selected = match node {
545                Node::Integer(n) => &n.selected,
546                Node::Enum(n) => &n.selected,
547                _ => continue,
548            };
549            for feature in selected {
550                // A selected command shows no value; its register holds a
551                // trigger, and linking it would only make every selector write
552                // invalidate whatever names that register.
553                if matches!(self.nodes.get(feature.as_str()), Some(Node::Command(_))) {
554                    continue;
555                }
556                for link in self.value_reach(feature).into_iter().skip(1) {
557                    links.push((node.name().to_string(), link.to_string()));
558                }
559            }
560        }
561        for (selector, link) in links {
562            let list = self.dependents.entry(selector).or_default();
563            if !list.contains(&link) {
564                list.push(link);
565            }
566        }
567    }
568
569    /// Declarations this camera has that we do not expose.
570    ///
571    /// Covers both losses: a node the XML parser could not read, and one it
572    /// read but that could not be turned into a runtime node. Empty for a
573    /// document we fully understand; anything listed here is worth reporting
574    /// as a bug. `viva-camctl report` prints it.
575    pub fn skipped(&self) -> &[SkippedNode] {
576        &self.skipped
577    }
578
579    /// Child elements of the camera's nodes that the XML parser read past
580    /// without interpreting — [`viva_genapi_xml::XmlModel::ignored`], kept
581    /// for a consumer that holds only the nodemap.
582    ///
583    /// The nodes themselves loaded. Most of these elements are
584    /// documentation (`<Extension>`, a port's `<ToolTip>`); one that changes
585    /// a value is worth reporting, as a skipped node is. `viva-camctl
586    /// report` prints them.
587    pub fn ignored(&self) -> &[IgnoredElement] {
588        &self.ignored
589    }
590
591    /// Read an integer feature value using the provided transport.
592    ///
593    /// A `<Converter>` evaluates in floating point; its value is rounded to
594    /// the nearest integer, as [`NodeMap::set_float`] rounds a value written
595    /// to an `<IntConverter>`.
596    pub fn get_integer(&self, name: &str, io: &dyn RegisterIo) -> Result<i64, GenApiError> {
597        match self.nodes.get(name) {
598            Some(Node::IntConverter(_)) => return self.get_int_converter(name, io),
599            Some(Node::Converter(_)) => {
600                return round_to_i64(name, self.get_converter(name, io)?);
601            }
602            _ => {}
603        }
604        if let Some(output) = self.nodes.get(name).and_then(|node| match node {
605            Node::SwissKnife(sk) => Some(sk.output),
606            _ => None,
607        }) {
608            self.ensure_not_imposed(name, AccessMode::WO)?;
609            return match output {
610                SkOutput::Integer => {
611                    let node = match self.nodes.get(name) {
612                        Some(Node::SwissKnife(node)) => node,
613                        _ => unreachable!("node vanished during lookup"),
614                    };
615                    let mut stack = HashSet::new();
616                    let value = self.evaluate_swissknife(node, io, &mut stack)?;
617                    sk_to_i64(name, value)
618                }
619                SkOutput::Float => Err(GenApiError::wrong_kind(
620                    name,
621                    "SwissKnife",
622                    "an integer formula",
623                )),
624            };
625        }
626        let node = self.get_integer_node(name)?;
627        self.ensure_readable_now(&node.access, name)?;
628        // A floating integer: what was written, else its start value.
629        if let Some(start) = node.value {
630            return Ok(node.floating.borrow().unwrap_or(start));
631        }
632        // Delegate to pValue node if present.
633        if let Some(ref pv) = node.pvalue {
634            let pv = pv.clone();
635            return self.get_integer(&pv, io);
636        }
637        if let Some(indexed) = &node.indexed {
638            return match self.indexed_value(name, indexed, io)? {
639                (_, IndexedSrc::FromNode(target)) => self.get_integer(target, io),
640                (slot, IndexedSrc::Literal(start)) => Ok(indexed
641                    .written
642                    .borrow()
643                    .get(&slot)
644                    .copied()
645                    .unwrap_or(*start)),
646            };
647        }
648        let addressing = node
649            .addressing
650            .as_ref()
651            .ok_or_else(|| GenApiError::no_value_source(name))?;
652        let location = self.locate(name, addressing, io)?;
653        if self.may_serve(name)
654            && let Some(value) = *node.cache.borrow()
655        {
656            return Ok(value);
657        }
658        let raw = self.read_location(name, &location, io)?;
659        let value = if let Some(bitfield) = node.bitfield {
660            let extracted = extract(&raw, bitfield).map_err(|err| map_bitops_error(name, err))?;
661            interpret_bitfield_value(
662                name,
663                extracted,
664                bitfield.bit_length,
665                integer_sign(node).is_signed(),
666            )?
667        } else {
668            bytes_to_i64(name, &raw, integer_sign(node), node.byte_order)?
669        };
670        debug!(node = %name, raw = value, "read integer feature");
671        self.note_read(name);
672        if self.may_cache(name) {
673            node.cache.replace(Some(value));
674            node.raw_cache.replace(Some(raw));
675        } else {
676            node.cache.replace(None);
677            node.raw_cache.replace(None);
678        }
679        Ok(value)
680    }
681
682    /// Write an integer feature and update dependent caches.
683    pub fn set_integer(
684        &mut self,
685        name: &str,
686        value: i64,
687        io: &dyn RegisterIo,
688    ) -> Result<(), GenApiError> {
689        if let Some(Node::IntConverter(_)) = self.nodes.get(name) {
690            return self.set_int_converter(name, value, io);
691        }
692        let node = self.get_integer_node(name)?;
693        self.ensure_writable_now(name, &node.access, io)?;
694        // Before any `<pValue>` forward: the front node's own restrictions
695        // bind the write even when the register behind it declares none
696        // (backlog GA-37).
697        self.ensure_integer_in_range(name, value, io)?;
698        let node = self.get_integer_node(name)?;
699        // GenICam Standard v2.1.1 §2.8.5: an integer with a `<Value>` is "a
700        // 'floating' variable that can be set by the user to any value
701        // allowed by the restriction parameters". It has no register; the
702        // value lives here.
703        if node.value.is_some() {
704            debug!(node = %name, value, "write floating integer");
705            node.floating.replace(Some(value));
706            self.invalidate_dependents(name);
707            return Ok(());
708        }
709        if let Some(ref pv) = node.pvalue {
710            let pv = pv.clone();
711            return self.set_integer(&pv, value, io);
712        }
713        if let Some(indexed) = &node.indexed {
714            match self.indexed_value(name, indexed, io)? {
715                (_, IndexedSrc::FromNode(target)) => {
716                    let target = target.clone();
717                    return self.set_integer(&target, value, io);
718                }
719                (slot, IndexedSrc::Literal(_)) => {
720                    debug!(node = %name, ?slot, value, "write indexed constant");
721                    indexed.written.borrow_mut().insert(slot, value);
722                    self.invalidate_dependents(name);
723                    return Ok(());
724                }
725            }
726        }
727        let addressing = node
728            .addressing
729            .as_ref()
730            .ok_or_else(|| GenApiError::no_value_source(name))?;
731        let (address, len) = self.locate_for_write(name, addressing, io)?;
732        if let Some(bitfield) = node.bitfield {
733            let encoded = encode_bitfield_value(
734                name,
735                value,
736                bitfield.bit_length,
737                integer_sign(node).is_signed(),
738            )?;
739            let readable = !matches!(node.access, AccessMode::WO);
740            // The other bits are the device's now: a cached reading it may
741            // since have changed must not be written back over them.
742            if readable && !self.may_serve(name) {
743                node.raw_cache.replace(None);
744            }
745            let mut raw = get_raw_or_read(name, readable, &node.raw_cache, io, address, len)?;
746            insert(&mut raw, bitfield, encoded).map_err(|err| map_bitops_error(name, err))?;
747            debug!(node = %name, raw = value, "write integer feature");
748            io.write(address, &raw)?;
749            self.after_register_write(name, &node.cache, value, &node.raw_cache, raw, readable);
750        } else {
751            let bytes = i64_to_bytes(name, value, len, integer_sign(node), node.byte_order)?;
752            debug!(node = %name, raw = value, "write integer feature");
753            io.write(address, &bytes)?;
754            let readable = !matches!(node.access, AccessMode::WO);
755            self.after_register_write(name, &node.cache, value, &node.raw_cache, bytes, readable);
756        }
757        self.invalidate_dependents(name);
758        Ok(())
759    }
760
761    /// Read a floating point feature.
762    pub fn get_float(&self, name: &str, io: &dyn RegisterIo) -> Result<f64, GenApiError> {
763        match self.nodes.get(name) {
764            Some(Node::Converter(_)) => return self.get_converter(name, io),
765            Some(Node::IntConverter(_)) => {
766                return self.get_int_converter(name, io).map(|v| v as f64);
767            }
768            _ => {}
769        }
770        if let Some(output) = self.nodes.get(name).and_then(|node| match node {
771            Node::SwissKnife(sk) => Some(sk.output),
772            _ => None,
773        }) {
774            self.ensure_not_imposed(name, AccessMode::WO)?;
775            return match output {
776                SkOutput::Float => {
777                    let node = match self.nodes.get(name) {
778                        Some(Node::SwissKnife(node)) => node,
779                        _ => unreachable!("node vanished during lookup"),
780                    };
781                    let mut stack = HashSet::new();
782                    let value = self.evaluate_swissknife(node, io, &mut stack)?;
783                    Ok(value.as_f64())
784                }
785                SkOutput::Integer => self.get_integer(name, io).map(|v| v as f64),
786            };
787        }
788        let node = self.get_float_node(name)?;
789        self.ensure_readable_now(&node.access, name)?;
790        // A floating float: what was written, else its start value.
791        if let Some(start) = node.value {
792            return Ok(node.floating.borrow().unwrap_or(start));
793        }
794        if let Some(ref pv) = node.pvalue {
795            let pv = pv.clone();
796            return self.get_float(&pv, io);
797        }
798        if let Some(indexed) = &node.indexed {
799            return match self.indexed_value(name, indexed, io)? {
800                (_, IndexedSrc::FromNode(target)) => self.get_float(target, io),
801                (slot, IndexedSrc::Literal(start)) => Ok(indexed
802                    .written
803                    .borrow()
804                    .get(&slot)
805                    .copied()
806                    .unwrap_or(*start)),
807            };
808        }
809        let addressing = node
810            .addressing
811            .as_ref()
812            .ok_or_else(|| GenApiError::no_value_source(name))?;
813        let location = self.locate(name, addressing, io)?;
814        if self.may_serve(name)
815            && let Some(value) = *node.cache.borrow()
816        {
817            return Ok(value);
818        }
819        let raw = self.read_location(name, &location, io)?;
820        let value = match node.encoding {
821            FloatEncoding::Ieee754 => {
822                let v = decode_ieee754(name, &raw, node.byte_order)?;
823                debug!(node = %name, value = v, "read float feature (ieee754)");
824                v
825            }
826            FloatEncoding::ScaledInteger => {
827                // `<Float>`/`<FloatReg>` declare no `<Sign>`; a scaled raw
828                // value is conventionally signed so an offset can go either way.
829                let raw_value = bytes_to_i64(name, &raw, Sign::Signed, node.byte_order)?;
830                let v = apply_scale(node, raw_value as f64);
831                debug!(node = %name, raw = raw_value, value = v, "read float feature (scaled)");
832                v
833            }
834        };
835        self.note_read(name);
836        node.cache.replace(self.may_cache(name).then_some(value));
837        Ok(value)
838    }
839
840    /// Write a floating point feature using the scale/offset conversion.
841    pub fn set_float(
842        &mut self,
843        name: &str,
844        value: f64,
845        io: &dyn RegisterIo,
846    ) -> Result<(), GenApiError> {
847        match self.nodes.get(name) {
848            Some(Node::Converter(_)) => return self.set_converter(name, value, io),
849            Some(Node::IntConverter(_)) => {
850                return self.set_int_converter(name, round_to_i64(name, value)?, io);
851            }
852            _ => {}
853        }
854        let node = self.get_float_node(name)?;
855        self.ensure_writable_now(name, &node.access, io)?;
856        // As for integers: bound the write before forwarding it (GA-37). A
857        // float's increment "is not verified on writing" (GenICam Standard
858        // v2.1.1 §2.8.9).
859        self.ensure_float_in_range(name, value, io)?;
860        let node = self.get_float_node(name)?;
861        // A floating float has no register: the value lives here, as a
862        // floating integer's does (§2.8.9 gives a `<Float>` the `<Value>` of
863        // §2.8.5).
864        if node.value.is_some() {
865            debug!(node = %name, value, "write floating float");
866            node.floating.replace(Some(value));
867            self.invalidate_dependents(name);
868            return Ok(());
869        }
870        if let Some(ref pv) = node.pvalue {
871            let pv = pv.clone();
872            return self.set_float(&pv, value, io);
873        }
874        if let Some(indexed) = &node.indexed {
875            match self.indexed_value(name, indexed, io)? {
876                (_, IndexedSrc::FromNode(target)) => {
877                    let target = target.clone();
878                    return self.set_float(&target, value, io);
879                }
880                (slot, IndexedSrc::Literal(_)) => {
881                    debug!(node = %name, ?slot, value, "write indexed constant");
882                    indexed.written.borrow_mut().insert(slot, value);
883                    self.invalidate_dependents(name);
884                    return Ok(());
885                }
886            }
887        }
888        let addressing = node
889            .addressing
890            .as_ref()
891            .ok_or_else(|| GenApiError::no_value_source(name))?;
892        let (address, len) = self.locate_for_write(name, addressing, io)?;
893        let bytes = match node.encoding {
894            FloatEncoding::Ieee754 => {
895                let bytes = encode_ieee754(name, value, len, node.byte_order)?;
896                debug!(node = %name, value, "write float feature (ieee754)");
897                bytes
898            }
899            FloatEncoding::ScaledInteger => {
900                let raw = encode_float(node, value)?;
901                let bytes = i64_to_bytes(name, raw, len, Sign::Signed, node.byte_order)?;
902                debug!(node = %name, raw, value, "write float feature (scaled)");
903                bytes
904            }
905        };
906        io.write(address, &bytes)?;
907        // `WriteAround` — a `<FloatReg>`'s default — keeps nothing: the camera
908        // may store something else, a gain it rounded.
909        if self.keeps_written(name) {
910            node.cache.replace(Some(value));
911            self.note_read(name);
912        } else {
913            node.cache.replace(None);
914        }
915        self.invalidate_dependents(name);
916        Ok(())
917    }
918
919    /// Read an enumeration feature returning the symbolic entry name.
920    pub fn get_enum(&self, name: &str, io: &dyn RegisterIo) -> Result<String, GenApiError> {
921        let node = self.get_enum_node(name)?;
922        self.ensure_readable_now(&node.access, name)?;
923        // When pValue is set, read the integer from the delegate node.
924        // GenICam Standard v2.1.1 §2.8.10: while a polled enumeration holds a
925        // self-clearing entry, "the reading will be performed ignoring the
926        // cache" — the register's behind it too.
927        let active = self.self_clearing_active(name);
928        if active {
929            for link in self.value_reach(name) {
930                if let Some(node) = self.nodes.get(link) {
931                    node.invalidate_cache();
932                }
933            }
934        }
935        if let Some(ref pv) = node.pvalue {
936            let pv = pv.clone();
937            if !active
938                && self.may_serve(name)
939                && let Some(value) = node.value_cache.borrow().clone()
940            {
941                return Ok(value);
942            }
943            let raw_value = self.get_integer(&pv, io)?;
944            let entry = self.lookup_enum_entry(node, raw_value, io)?;
945            self.note_entry(name, entry_is_self_clearing(node, &entry));
946            if self.may_cache(name) {
947                node.value_cache.replace(Some(entry.clone()));
948            }
949            return Ok(entry);
950        }
951        // A floating enumeration: the entry written, else its start value.
952        if node.addressing.is_none()
953            && let Some(start) = node.value
954        {
955            let raw_value = node.floating.borrow().unwrap_or(start);
956            return self.lookup_enum_entry(node, raw_value, io);
957        }
958        let addressing = node
959            .addressing
960            .as_ref()
961            .ok_or_else(|| GenApiError::no_value_source(name))?;
962        let location = self.locate(name, addressing, io)?;
963        if !active
964            && self.may_serve(name)
965            && let Some(value) = node.value_cache.borrow().clone()
966        {
967            return Ok(value);
968        }
969        let raw = self.read_location(name, &location, io)?;
970        // `<Enumeration>` declares no `<Sign>` and no `<Endianess>` — no
971        // document in the vendor corpus declares one — so the GenICam
972        // defaults apply: signed entry values, big-endian payload.
973        let raw_value = bytes_to_i64(name, &raw, Sign::Signed, ByteOrder::Big)?;
974        let entry = self.lookup_enum_entry(node, raw_value, io)?;
975        debug!(node = %name, raw = raw_value, entry = %entry, "read enum feature");
976        self.note_read(name);
977        self.note_entry(name, entry_is_self_clearing(node, &entry));
978        if self.may_cache(name) {
979            node.value_cache.replace(Some(entry.clone()));
980        }
981        Ok(entry)
982    }
983
984    /// Write an enumeration entry.
985    ///
986    /// The entry must exist and be available now: an entry whose
987    /// `pIsImplemented` or `pIsAvailable` reads false is refused with
988    /// [`GenApiError::EnumEntryUnavailable`] and nothing is written, as
989    /// GenApi refuses it. The mvBlueFOX3-2004G accepted a write of
990    /// `TestPattern=GreyHorizontalRamp`, which it does not implement, read it
991    /// back, and streamed zeros.
992    pub fn set_enum(
993        &mut self,
994        name: &str,
995        entry: &str,
996        io: &dyn RegisterIo,
997    ) -> Result<(), GenApiError> {
998        let node = self.get_enum_node(name)?;
999        self.ensure_writable_now(name, &node.access, io)?;
1000        let entry_decl = node
1001            .entries
1002            .iter()
1003            .find(|candidate| candidate.name == entry)
1004            .ok_or_else(|| GenApiError::EnumNoSuchEntry {
1005                node: name.to_string(),
1006                entry: entry.to_string(),
1007            })?;
1008        if !self.entry_available(name, entry_decl, io)? {
1009            return Err(GenApiError::EnumEntryUnavailable {
1010                node: name.to_string(),
1011                entry: entry.to_string(),
1012            });
1013        }
1014        let raw = self.resolve_enum_entry_value(node, entry_decl, io)?;
1015        let self_clearing = entry_decl.is_self_clearing;
1016        if let Some(ref pv) = node.pvalue {
1017            let pv = pv.clone();
1018            self.set_integer(&pv, raw, io)?;
1019            // Re-borrow node after mutable self call.
1020            let node = self.get_enum_node(name)?;
1021            node.invalidate();
1022            self.note_entry(name, self_clearing);
1023            self.invalidate_dependents(name);
1024            return Ok(());
1025        }
1026        // A floating enumeration has no register: the entry lives here, as a
1027        // floating integer's value does (GenICam Standard v2.1.1 §2.8.5).
1028        if node.addressing.is_none() && node.value.is_some() {
1029            debug!(node = %name, raw, entry, "write floating enumeration");
1030            node.floating.replace(Some(raw));
1031            node.value_cache.replace(None);
1032            self.invalidate_dependents(name);
1033            return Ok(());
1034        }
1035        let addressing = node
1036            .addressing
1037            .as_ref()
1038            .ok_or_else(|| GenApiError::no_value_source(name))?;
1039        let (address, len) = self.locate_for_write(name, addressing, io)?;
1040        let bytes = i64_to_bytes(name, raw, len, Sign::Signed, ByteOrder::Big)?;
1041        debug!(node = %name, raw, entry, "write enum feature");
1042        io.write(address, &bytes)?;
1043        node.value_cache.replace(None);
1044        self.note_entry(name, self_clearing);
1045        self.invalidate_dependents(name);
1046        Ok(())
1047    }
1048
1049    /// Whether `entry` of the enumeration `name` can be selected now: its
1050    /// own `pIsImplemented` and `pIsAvailable`, when it declares them.
1051    fn entry_available(
1052        &self,
1053        name: &str,
1054        entry: &EnumEntryDecl,
1055        io: &dyn RegisterIo,
1056    ) -> Result<bool, GenApiError> {
1057        for provider in [
1058            &entry.predicates.p_is_implemented,
1059            &entry.predicates.p_is_available,
1060        ]
1061        .into_iter()
1062        .flatten()
1063        {
1064            if !self.eval_predicate_ref(name, provider, io)? {
1065                return Ok(false);
1066            }
1067        }
1068        Ok(true)
1069    }
1070
1071    /// List the available entry names for an enumeration feature.
1072    ///
1073    /// In the order the XML declares them, which is the order a GUI shows,
1074    /// each name once.
1075    pub fn enum_entries(&self, name: &str) -> Result<Vec<String>, GenApiError> {
1076        let node = self.get_enum_node(name)?;
1077        let mapping = node.mapping_cache.borrow();
1078        let names = node
1079            .entries
1080            .iter()
1081            .map(|entry| entry.name.as_str())
1082            .filter(|entry| {
1083                mapping
1084                    .as_ref()
1085                    .is_none_or(|mapping| mapping.by_name.contains_key(*entry))
1086            });
1087        Ok(unique_in_order(names))
1088    }
1089
1090    /// Evaluate `pIsImplemented` for `name`, returning `true` when the feature
1091    /// is implemented by the device.
1092    ///
1093    /// Absent `pIsImplemented` defaults to `true` (matching the GenICam spec:
1094    /// an undeclared predicate means "always implemented"). Evaluation errors
1095    /// propagate to the caller so bad XML is visible rather than silently
1096    /// reported as implemented.
1097    pub fn is_implemented(&self, name: &str, io: &dyn RegisterIo) -> Result<bool, GenApiError> {
1098        let prefs = self.predicate_refs(name)?;
1099        match &prefs.p_is_implemented {
1100            None => Ok(true),
1101            Some(provider) => self.eval_predicate_ref(name, provider, io),
1102        }
1103    }
1104
1105    /// Evaluate `pIsAvailable` for `name`.
1106    ///
1107    /// Returns `false` when the feature is not implemented or when
1108    /// `pIsAvailable` evaluates to zero.
1109    pub fn is_available(&self, name: &str, io: &dyn RegisterIo) -> Result<bool, GenApiError> {
1110        if !self.is_implemented(name, io)? {
1111            return Ok(false);
1112        }
1113        let prefs = self.predicate_refs(name)?;
1114        match &prefs.p_is_available {
1115            Some(provider) => self.eval_predicate_ref(name, provider, io),
1116            None => Ok(true),
1117        }
1118    }
1119
1120    /// Refuse a write the device's current state does not permit.
1121    ///
1122    /// The static `<AccessMode>` is only half the picture, and for a great
1123    /// many real nodes it is the less informative half: FLIR's `ExposureTime`
1124    /// declares no `<AccessMode>` at all — so it defaults to `RW` — and puts
1125    /// the entire restriction in `<pIsLocked>ExposureTime_Lck</pIsLocked>`, a
1126    /// device register. Checking only the static mode meant we sent writes the
1127    /// camera's own description said were not allowed, and the device answered
1128    /// `ACCESS_DENIED` (issue #45).
1129    ///
1130    /// Deliberately *not* routed through [`NodeMap::effective_access_mode`]:
1131    /// that function collapses "unavailable" into `RO` because it serves a UI
1132    /// that has a separate availability flag. Here the distinction is the
1133    /// whole value of the error, so the two conditions are checked separately.
1134    ///
1135    /// Reads keep the static [`AccessMode::WO`] check only. Evaluating
1136    /// predicates on every `get` would add device round-trips to the hottest
1137    /// path in the library for a check the subsequent read reports anyway; a
1138    /// refused write, by contrast, is worth one predicate evaluation to turn a
1139    /// wire error into a named local one. See backlog GA-06.
1140    /// The `<ImposedAccessMode>` `name` declares, a ceiling on its own
1141    /// `<AccessMode>` (backlog GA-23).
1142    fn imposed_access(&self, name: &str) -> Option<AccessMode> {
1143        self.nodes.get(name).and_then(|n| n.meta().imposed_access)
1144    }
1145
1146    /// Refuse a read of `name` that its imposed access forbids: for the
1147    /// computed nodes, which have no access mode of their own to check
1148    /// (Codex review of #186).
1149    fn ensure_not_imposed(&self, name: &str, forbidden: AccessMode) -> Result<(), GenApiError> {
1150        if self.imposed_access(name) == Some(forbidden) {
1151            let refused = if forbidden == AccessMode::WO {
1152                AccessDirection::Read
1153            } else {
1154                AccessDirection::Write
1155            };
1156            return Err(GenApiError::access(name, refused));
1157        }
1158        Ok(())
1159    }
1160
1161    /// Refuse a read of `name` that its `access`, or the access imposed on
1162    /// it, forbids.
1163    fn ensure_readable_now(&self, access: &AccessMode, name: &str) -> Result<(), GenApiError> {
1164        ensure_readable(access, name)?;
1165        if self.imposed_access(name) == Some(AccessMode::WO) {
1166            return Err(GenApiError::access(name, AccessDirection::Read));
1167        }
1168        Ok(())
1169    }
1170
1171    fn ensure_writable_now(
1172        &self,
1173        name: &str,
1174        access: &AccessMode,
1175        io: &dyn RegisterIo,
1176    ) -> Result<(), GenApiError> {
1177        ensure_writable(access, name)?;
1178        if self.imposed_access(name) == Some(AccessMode::RO) {
1179            return Err(GenApiError::access(name, AccessDirection::Write));
1180        }
1181        if !self.is_available(name, io)? {
1182            return Err(GenApiError::Unavailable(name.to_string()));
1183        }
1184        let prefs = self.predicate_refs(name)?;
1185        if let Some(provider) = &prefs.p_is_locked
1186            && self.eval_predicate_ref(name, provider, io)?
1187        {
1188            return Err(GenApiError::Locked {
1189                name: name.to_string(),
1190                locked_by: provider.to_string(),
1191            });
1192        }
1193        Ok(())
1194    }
1195
1196    /// The access mode `name` declares, before availability and locks.
1197    ///
1198    /// A node that takes its value through `<pValue>` can do no more than the
1199    /// nodes along that chain allow: an `RW` integer over a read-only register
1200    /// cannot be written, and one over a write-only register cannot be read.
1201    /// So the declared modes along the whole chain are combined: any `RO` on
1202    /// the way removes writing, any `WO` removes reading. aravis takes the
1203    /// mode of the linked feature instead of the node's own; combining keeps
1204    /// that and also honours a restriction the node declares itself.
1205    ///
1206    /// An `<ImposedAccessMode>` anywhere on the chain is a ceiling of the
1207    /// same kind: `RO` removes writing, `WO` reading, `RW` nothing (backlog
1208    /// GA-23).
1209    ///
1210    /// A `<Converter>` or `<IntConverter>` declares no mode of its own, so it
1211    /// contributes nothing to the combination. A converter whose chain reaches
1212    /// no node that declares a mode (a dangling `<pValue>`, or converters
1213    /// naming each other) reports `RO`.
1214    ///
1215    /// Returns `None` for an unknown name, for a node with no access mode,
1216    /// such as a category, and for a chain that allows neither reading nor
1217    /// writing (an `RO` node over a `WO` register).
1218    pub fn declared_access_mode(&self, name: &str) -> Option<AccessMode> {
1219        let node = self.nodes.get(name)?;
1220        let is_converter = |n: &Node| matches!(n, Node::Converter(_) | Node::IntConverter(_));
1221        if !is_converter(node) {
1222            node.access_mode()?;
1223        }
1224        let (mut readable, mut writable, mut declared) = (true, true, false);
1225        for link in self.value_chain(name) {
1226            let Some(node) = self.nodes.get(link) else {
1227                continue;
1228            };
1229            match node.meta().imposed_access {
1230                Some(AccessMode::RO) => writable = false,
1231                Some(AccessMode::WO) => readable = false,
1232                Some(AccessMode::RW) | None => {}
1233            }
1234            let Some(mode) = Some(node)
1235                .filter(|n| !is_converter(n))
1236                .and_then(Node::access_mode)
1237            else {
1238                continue;
1239            };
1240            declared = true;
1241            match mode {
1242                AccessMode::RO => writable = false,
1243                AccessMode::WO => readable = false,
1244                AccessMode::RW => {}
1245            }
1246        }
1247        match (declared, readable, writable) {
1248            (false, _, _) => Some(AccessMode::RO),
1249            (true, true, true) => Some(AccessMode::RW),
1250            (true, true, false) => Some(AccessMode::RO),
1251            (true, false, true) => Some(AccessMode::WO),
1252            (true, false, false) => None,
1253        }
1254    }
1255
1256    /// Return the effective [`AccessMode`] for `name` given the current
1257    /// device state.
1258    ///
1259    /// - If the feature is unavailable (see [`NodeMap::is_available`]), the
1260    ///   function returns `AccessMode::RO` — we cannot report "NA" without
1261    ///   introducing a new variant, and Studio's wire protocol carries the
1262    ///   availability flag separately.
1263    /// - If `pIsLocked` evaluates truthy, `RW` downgrades to `RO`; `RO` and
1264    ///   `WO` are unaffected.
1265    /// - Otherwise the statically declared access mode applies.
1266    pub fn effective_access_mode(
1267        &self,
1268        name: &str,
1269        io: &dyn RegisterIo,
1270    ) -> Result<AccessMode, GenApiError> {
1271        if !self.nodes.contains_key(name) {
1272            return Err(GenApiError::NodeNotFound(name.to_string()));
1273        }
1274        if !self.is_available(name, io)? {
1275            return Ok(AccessMode::RO);
1276        }
1277        let base = self.access_now(name, io)?.unwrap_or(AccessMode::RO);
1278        let prefs = self.predicate_refs(name)?;
1279        if let Some(provider) = &prefs.p_is_locked
1280            && self.eval_predicate_ref(name, provider, io)?
1281        {
1282            return Ok(match base {
1283                AccessMode::RW => AccessMode::RO,
1284                other => other,
1285            });
1286        }
1287        Ok(base)
1288    }
1289
1290    /// [`NodeMap::declared_access_mode`] of `name`, combined with that of the
1291    /// node an indexed node at the end of its `<pValue>` chain reads through
1292    /// now, and so on along the nodes it selects: an indexed value is as
1293    /// writable as the node its index selects, as a `<pValue>` is (GenICam
1294    /// Standard v2.1.1 §2.8.5).
1295    pub(crate) fn access_now(
1296        &self,
1297        name: &str,
1298        io: &dyn RegisterIo,
1299    ) -> Result<Option<AccessMode>, GenApiError> {
1300        let mut mode = self.declared_access_mode(name);
1301        let mut seen = HashSet::new();
1302        let mut current = name;
1303        while seen.insert(current) {
1304            let last = self.value_chain(current).last().copied().unwrap_or(current);
1305            let Some(next) = self.indexed_target(last, io)? else {
1306                break;
1307            };
1308            mode = combine_access(mode, self.declared_access_mode(next));
1309            current = next;
1310        }
1311        Ok(mode)
1312    }
1313
1314    /// The node `name`, when it is an indexed `<Integer>` or `<Float>`, reads
1315    /// and writes through now; `None` when its index selects a constant, and
1316    /// for any other node.
1317    fn indexed_target(&self, name: &str, io: &dyn RegisterIo) -> Result<Option<&str>, GenApiError> {
1318        let source = match self.nodes.get(name) {
1319            Some(Node::Integer(IntegerNode {
1320                indexed: Some(indexed),
1321                ..
1322            })) => self.indexed_value(name, indexed, io)?.1.node(),
1323            Some(Node::Float(FloatNode {
1324                indexed: Some(indexed),
1325                ..
1326            })) => self.indexed_value(name, indexed, io)?.1.node(),
1327            _ => None,
1328        };
1329        Ok(source)
1330    }
1331
1332    /// The value an indexed node's `<pIndex>` selects now: the entry naming
1333    /// the index it reads, or the default (GenICam Standard v2.1.1 §2.8.5),
1334    /// with the index of that entry — `None` for the default — under which a
1335    /// constant keeps what is written to it.
1336    fn indexed_value<'a, T>(
1337        &self,
1338        name: &str,
1339        indexed: &'a Indexed<T>,
1340        io: &dyn RegisterIo,
1341    ) -> Result<(Option<i64>, &'a IndexedSrc<T>), GenApiError> {
1342        let table = &indexed.table;
1343        let index = self.get_integer(&table.index, io)?;
1344        if let Some(entry) = table.entries.iter().find(|entry| entry.index == index) {
1345            trace!(node = %name, index, "indexed value: entry");
1346            return Ok((Some(index), &entry.value));
1347        }
1348        trace!(node = %name, index, "indexed value: default");
1349        table
1350            .default
1351            .as_ref()
1352            .map(|value| (None, value))
1353            .ok_or_else(|| GenApiError::NoIndexedValue {
1354                name: name.to_string(),
1355                index_node: table.index.clone(),
1356                index,
1357            })
1358    }
1359
1360    /// Return the subset of enum entries currently reported as available by
1361    /// the device, or the full static list when no entry declares an
1362    /// `pIsImplemented`/`pIsAvailable`.
1363    ///
1364    /// Falling back to the full list preserves current behaviour for XMLs
1365    /// that don't gate individual entries, so callers stop seeing the stale
1366    /// static list when the new predicates are added and otherwise behave as
1367    /// before.
1368    pub fn available_enum_entries(
1369        &self,
1370        name: &str,
1371        io: &dyn RegisterIo,
1372    ) -> Result<Vec<String>, GenApiError> {
1373        let node = self.get_enum_node(name)?;
1374        let any_entry_predicate = node.entries.iter().any(|e| !e.predicates.is_empty());
1375        if !any_entry_predicate {
1376            return self.enum_entries(name);
1377        }
1378        let mut out: Vec<&str> = Vec::new();
1379        for entry in &node.entries {
1380            if self.entry_available(name, entry, io)? {
1381                out.push(entry.name.as_str());
1382            }
1383        }
1384        Ok(unique_in_order(out))
1385    }
1386
1387    /// `name`'s own `<pIsAvailable>`, without its `<pIsImplemented>`: `true`
1388    /// when it declares none.
1389    pub(crate) fn own_availability(
1390        &self,
1391        name: &str,
1392        io: &dyn RegisterIo,
1393    ) -> Result<bool, GenApiError> {
1394        match &self.predicate_refs(name)?.p_is_available {
1395            Some(provider) => self.eval_predicate_ref(name, provider, io),
1396            None => Ok(true),
1397        }
1398    }
1399
1400    /// The provider of `name`'s `<pIsLocked>`, when it reports the feature
1401    /// locked now; `None` when it is not locked or declares no lock.
1402    pub(crate) fn locked_by(
1403        &self,
1404        name: &str,
1405        io: &dyn RegisterIo,
1406    ) -> Result<Option<String>, GenApiError> {
1407        let prefs = self.predicate_refs(name)?;
1408        match &prefs.p_is_locked {
1409            Some(provider) if self.eval_predicate_ref(name, provider, io)? => {
1410                Ok(Some(provider.clone()))
1411            }
1412            _ => Ok(None),
1413        }
1414    }
1415
1416    fn predicate_refs(&self, name: &str) -> Result<&PredicateRefs, GenApiError> {
1417        self.nodes
1418            .get(name)
1419            .map(Node::predicates)
1420            .ok_or_else(|| GenApiError::NodeNotFound(name.to_string()))
1421    }
1422
1423    /// Evaluate a `pIs*` reference by reading the target node as an integer
1424    /// truthy value.
1425    ///
1426    /// `ctx` is the node that owns the predicate; it is used for diagnostics
1427    /// and cycle detection so a predicate that accidentally resolves back to
1428    /// its own owner fails fast rather than recursing. Providers can be any
1429    /// numeric-resolvable node: Integer, Boolean, Enum (integer form),
1430    /// SwissKnife, or a Converter.
1431    fn eval_predicate_ref(
1432        &self,
1433        ctx: &str,
1434        provider: &str,
1435        io: &dyn RegisterIo,
1436    ) -> Result<bool, GenApiError> {
1437        if provider == ctx {
1438            return Err(GenApiError::eval(
1439                ctx,
1440                SkEvalError::Cycle(provider.to_string()),
1441            ));
1442        }
1443        let mut stack = HashSet::new();
1444        stack.insert(ctx.to_string());
1445        let value = self.resolve_numeric(provider, io, &mut stack)?;
1446        trace!(node = %ctx, provider, value, "predicate eval");
1447        Ok(value != 0.0)
1448    }
1449
1450    /// Read a boolean feature.
1451    pub fn get_bool(&self, name: &str, io: &dyn RegisterIo) -> Result<bool, GenApiError> {
1452        let node = self.get_bool_node(name)?;
1453        self.ensure_readable_now(&node.access, name)?;
1454        if let Some(ref pv) = node.pvalue {
1455            let pv = pv.clone();
1456            let raw = self.get_integer(&pv, io)?;
1457            let on = node.on_value.unwrap_or(1);
1458            return Ok(raw == on);
1459        }
1460        // A floating boolean: what was written, else its start value.
1461        if node.addressing.is_none()
1462            && let Some(start) = node.value
1463        {
1464            let raw = node.floating.borrow().unwrap_or(start);
1465            return Ok(raw == node.on_value.unwrap_or(1));
1466        }
1467        let addressing = node
1468            .addressing
1469            .as_ref()
1470            .ok_or_else(|| GenApiError::no_value_source(name))?;
1471        let bitfield = node.bitfield.ok_or_else(|| {
1472            GenApiError::declaration(name, "is a Boolean over a register with no bit field")
1473        })?;
1474        let location = self.locate(name, addressing, io)?;
1475        if self.may_serve(name)
1476            && let Some(value) = *node.cache.borrow()
1477        {
1478            return Ok(value);
1479        }
1480        let raw = self.read_location(name, &location, io)?;
1481        let raw_value = extract(&raw, bitfield).map_err(|err| map_bitops_error(name, err))?;
1482        let value = raw_value != 0;
1483        debug!(node = %name, raw = raw_value, value, "read boolean feature");
1484        self.note_read(name);
1485        if self.may_cache(name) {
1486            node.cache.replace(Some(value));
1487            node.raw_cache.replace(Some(raw));
1488        } else {
1489            node.cache.replace(None);
1490            node.raw_cache.replace(None);
1491        }
1492        Ok(value)
1493    }
1494
1495    /// Write a boolean feature.
1496    pub fn set_bool(
1497        &mut self,
1498        name: &str,
1499        value: bool,
1500        io: &dyn RegisterIo,
1501    ) -> Result<(), GenApiError> {
1502        let node = self.get_bool_node(name)?;
1503        self.ensure_writable_now(name, &node.access, io)?;
1504        if let Some(ref pv) = node.pvalue {
1505            let pv = pv.clone();
1506            let on = node.on_value.unwrap_or(1);
1507            let off = node.off_value.unwrap_or(0);
1508            let raw = if value { on } else { off };
1509            return self.set_integer(&pv, raw, io);
1510        }
1511        // A floating boolean has no register: the value lives here, as a
1512        // floating integer's does (GenICam Standard v2.1.1 §2.8.5).
1513        if node.addressing.is_none() && node.value.is_some() {
1514            let raw = if value {
1515                node.on_value.unwrap_or(1)
1516            } else {
1517                node.off_value.unwrap_or(0)
1518            };
1519            debug!(node = %name, raw, value, "write floating boolean");
1520            node.floating.replace(Some(raw));
1521            self.invalidate_dependents(name);
1522            return Ok(());
1523        }
1524        let addressing = node
1525            .addressing
1526            .as_ref()
1527            .ok_or_else(|| GenApiError::no_value_source(name))?;
1528        let bitfield = node.bitfield.ok_or_else(|| {
1529            GenApiError::declaration(name, "is a Boolean over a register with no bit field")
1530        })?;
1531        let (address, len) = self.locate_for_write(name, addressing, io)?;
1532        let encoded = if value { 1 } else { 0 };
1533        let readable = !matches!(node.access, AccessMode::WO);
1534        if readable && !self.may_serve(name) {
1535            node.raw_cache.replace(None);
1536        }
1537        let mut raw = get_raw_or_read(name, readable, &node.raw_cache, io, address, len)?;
1538        insert(&mut raw, bitfield, encoded).map_err(|err| map_bitops_error(name, err))?;
1539        debug!(node = %name, raw = encoded, value, "write boolean feature");
1540        io.write(address, &raw)?;
1541        self.after_register_write(name, &node.cache, value, &node.raw_cache, raw, readable);
1542        self.invalidate_dependents(name);
1543        Ok(())
1544    }
1545
1546    /// Execute a command feature by writing its command value.
1547    ///
1548    /// GenICam Standard v2.1.1 §2.8.8: the value — `<CommandValue>`, or the
1549    /// node `<pCommandValue>` names, read now — "is written into a node which
1550    /// is referenced to by a pValue element". The command's own guards apply
1551    /// first, whichever way it reaches its register: an imposed `RO`, its
1552    /// `pIsImplemented`/`pIsAvailable` and its `pIsLocked` (backlog GA-10).
1553    /// Hikrobot's `UserSetSave` is unavailable while `Default` is selected,
1554    /// and the register it writes declares nothing of the kind.
1555    ///
1556    /// Returns once the write is acknowledged. A device may still be acting on
1557    /// it: poll [`NodeMap::is_done`] for completion.
1558    pub fn exec_command(&mut self, name: &str, io: &dyn RegisterIo) -> Result<(), GenApiError> {
1559        self.get_command_node(name)?;
1560        self.ensure_writable_now(name, &AccessMode::RW, io)?;
1561        let node = self.get_command_node(name)?;
1562        let value = self.command_value(node, io)?;
1563
1564        if let Some(pv) = node.pvalue.clone() {
1565            // "If the command is write only no polling takes place" (§2.8.8):
1566            // decided on the register this execution writes.
1567            let polls = self.imposed_access(name) != Some(AccessMode::WO)
1568                && !self.write_only_now(&pv, io)?;
1569            debug!(node = %name, value, "execute command via pValue");
1570            self.set_integer(&pv, value, io)?;
1571            self.note_command(name, polls);
1572            self.invalidate_dependents(name);
1573            return Ok(());
1574        }
1575
1576        let address = node
1577            .address
1578            .ok_or_else(|| GenApiError::no_value_source(name))?;
1579        if node.len == 0 {
1580            return Err(GenApiError::declaration(
1581                name,
1582                "is a Command with a zero <Length>",
1583            ));
1584        }
1585        let data = i64_to_bytes(name, value, node.len, Sign::Signed, ByteOrder::Big)?;
1586        debug!(node = %name, value, "execute command");
1587        io.write(address, &data)?;
1588        self.invalidate_dependents(name);
1589        Ok(())
1590    }
1591
1592    /// Whether the command `name` has finished: GenICam's `ICommand::IsDone`.
1593    ///
1594    /// GenICam Standard v2.1.1 §2.8.8: "IsDone reads the value back and
1595    /// returns false as long as return value equals the command value. If the
1596    /// node is WriteOnly IsDone always returns true", and it "always read the
1597    /// device register regardless of the state of the caches". Applications
1598    /// "should always wait for the command completion by calling IsDone
1599    /// immediately after the Execute", because "the state of other nodes can
1600    /// depend on the completion of the Command".
1601    ///
1602    /// So a command whose register path is write-only — a `WO` node along its
1603    /// `<pValue>` chain or on the entry an indexed node on it selects now, or
1604    /// an `<ImposedAccessMode>WO` on the command itself — is done at once, and
1605    /// nothing is read. Otherwise the register is read from the device, past
1606    /// every cache on that path, and compared with the command value.
1607    /// When it differs, the command has finished and everything depending on
1608    /// it is invalidated, so values read while it ran are read again.
1609    ///
1610    /// A direct-address command (a `<Command>` with its own `<Address>`, an
1611    /// extension no vendor document uses) declares no access mode and is
1612    /// treated as write-only.
1613    pub fn is_done(&self, name: &str, io: &dyn RegisterIo) -> Result<bool, GenApiError> {
1614        let node = self.get_command_node(name)?;
1615        let Some(target) = node.pvalue.as_deref() else {
1616            return Ok(true);
1617        };
1618        if self.imposed_access(name) == Some(AccessMode::WO) {
1619            return Ok(true);
1620        }
1621        let chain = self.value_path_now(target, io)?;
1622        if chain.iter().any(|link| self.declares_write_only(link)) {
1623            return Ok(true);
1624        }
1625        let expected = self.command_value(node, io)?;
1626        for link in &chain {
1627            if let Some(node) = self.nodes.get(*link) {
1628                node.invalidate_cache();
1629            }
1630        }
1631        let current = self.get_integer(target, io)?;
1632        let done = current != expected;
1633        trace!(node = %name, current, expected, done, "command IsDone");
1634        if done {
1635            self.note_command(name, false);
1636            self.invalidate_dependents(name);
1637            for link in chain {
1638                self.invalidate_dependents(link);
1639            }
1640        }
1641        Ok(done)
1642    }
1643
1644    /// The value executing `node` writes, read now when it comes from
1645    /// `<pCommandValue>`.
1646    fn command_value(&self, node: &CommandNode, io: &dyn RegisterIo) -> Result<i64, GenApiError> {
1647        match &node.command_value {
1648            CommandValueSrc::Literal(value) => Ok(*value),
1649            CommandValueSrc::FromNode(provider) => {
1650                let mut stack = HashSet::new();
1651                stack.insert(node.name.clone());
1652                let value = self.resolve_value(provider, io, &mut stack)?;
1653                sk_to_i64(provider, value)
1654            }
1655        }
1656    }
1657
1658    fn get_integer_node(&self, name: &str) -> Result<&IntegerNode, GenApiError> {
1659        match self.nodes.get(name) {
1660            Some(Node::Integer(node)) => Ok(node),
1661            Some(other) => Err(GenApiError::wrong_kind(
1662                name,
1663                other.kind_name(),
1664                "an Integer",
1665            )),
1666            None => Err(GenApiError::NodeNotFound(name.to_string())),
1667        }
1668    }
1669
1670    fn get_float_node(&self, name: &str) -> Result<&FloatNode, GenApiError> {
1671        match self.nodes.get(name) {
1672            Some(Node::Float(node)) => Ok(node),
1673            Some(other) => Err(GenApiError::wrong_kind(name, other.kind_name(), "a Float")),
1674            None => Err(GenApiError::NodeNotFound(name.to_string())),
1675        }
1676    }
1677
1678    fn get_enum_node(&self, name: &str) -> Result<&EnumNode, GenApiError> {
1679        match self.nodes.get(name) {
1680            Some(Node::Enum(node)) => Ok(node),
1681            Some(other) => Err(GenApiError::wrong_kind(
1682                name,
1683                other.kind_name(),
1684                "an Enumeration",
1685            )),
1686            None => Err(GenApiError::NodeNotFound(name.to_string())),
1687        }
1688    }
1689
1690    fn get_bool_node(&self, name: &str) -> Result<&BooleanNode, GenApiError> {
1691        match self.nodes.get(name) {
1692            Some(Node::Boolean(node)) => Ok(node),
1693            Some(other) => Err(GenApiError::wrong_kind(
1694                name,
1695                other.kind_name(),
1696                "a Boolean",
1697            )),
1698            None => Err(GenApiError::NodeNotFound(name.to_string())),
1699        }
1700    }
1701
1702    fn get_command_node(&self, name: &str) -> Result<&CommandNode, GenApiError> {
1703        match self.nodes.get(name) {
1704            Some(Node::Command(node)) => Ok(node),
1705            Some(other) => Err(GenApiError::wrong_kind(
1706                name,
1707                other.kind_name(),
1708                "a Command",
1709            )),
1710            None => Err(GenApiError::NodeNotFound(name.to_string())),
1711        }
1712    }
1713
1714    fn lookup_enum_entry(
1715        &self,
1716        node: &EnumNode,
1717        raw_value: i64,
1718        io: &dyn RegisterIo,
1719    ) -> Result<String, GenApiError> {
1720        {
1721            let mut cache = node.mapping_cache.borrow_mut();
1722            if cache.is_none() {
1723                *cache = Some(self.build_enum_mapping(node, io)?);
1724            }
1725            if let Some(mapping) = cache.as_ref()
1726                && let Some(entry) = mapping.by_value.get(&raw_value)
1727            {
1728                return Ok(entry.clone());
1729            }
1730            *cache = Some(self.build_enum_mapping(node, io)?);
1731            if let Some(mapping) = cache.as_ref()
1732                && let Some(entry) = mapping.by_value.get(&raw_value)
1733            {
1734                return Ok(entry.clone());
1735            }
1736        }
1737        Err(GenApiError::EnumValueUnknown {
1738            node: node.name.clone(),
1739            value: raw_value,
1740        })
1741    }
1742
1743    fn build_enum_mapping(
1744        &self,
1745        node: &EnumNode,
1746        io: &dyn RegisterIo,
1747    ) -> Result<EnumMapping, GenApiError> {
1748        let mut by_value = HashMap::new();
1749        let mut by_name = HashMap::new();
1750
1751        for entry in &node.entries {
1752            let value = self.resolve_enum_entry_value(node, entry, io)?;
1753            match by_value.entry(value) {
1754                HashMapEntry::Vacant(slot) => {
1755                    slot.insert(entry.name.clone());
1756                }
1757                HashMapEntry::Occupied(existing) => {
1758                    warn!(
1759                        enum_node = %node.name,
1760                        value,
1761                        kept = %existing.get(),
1762                        dropped = %entry.name,
1763                        "duplicate enum value"
1764                    );
1765                }
1766            }
1767            by_name.insert(entry.name.clone(), value);
1768        }
1769
1770        let mut summary: Vec<_> = by_value
1771            .iter()
1772            .map(|(value, name)| (*value, name.clone()))
1773            .collect();
1774        summary.sort_by_key(|(value, _)| *value);
1775        debug!(node = %node.name, entries = ?summary, "build enum mapping");
1776
1777        Ok(EnumMapping { by_value, by_name })
1778    }
1779
1780    fn resolve_enum_entry_value(
1781        &self,
1782        node: &EnumNode,
1783        entry: &EnumEntryDecl,
1784        io: &dyn RegisterIo,
1785    ) -> Result<i64, GenApiError> {
1786        match &entry.value {
1787            EnumValueSrc::Literal(value) => Ok(*value),
1788            EnumValueSrc::FromNode(provider) => {
1789                let value = self.get_integer(provider, io)?;
1790                trace!(
1791                    enum_node = %node.name,
1792                    entry = %entry.name,
1793                    provider = %provider,
1794                    value,
1795                    "resolved enum entry from provider"
1796                );
1797                Ok(value)
1798            }
1799        }
1800    }
1801
1802    /// Resolve the device register address and length backing a feature.
1803    ///
1804    /// This is the addressing half of typed feature access, exposed for
1805    /// callers that need raw register I/O through [`RegisterIo`] — a
1806    /// file-transfer buffer, for instance, whose address the XML supplies
1807    /// through `<pAddress>` and which no typed accessor covers. Address
1808    /// terms and `<pIndex>` scaling resolve exactly as they do for
1809    /// `get_integer` and friends, so a caller does not have to reimplement
1810    /// GenICam addressing.
1811    ///
1812    /// Returns [`GenApiError::Type`] for a node that has no addressing of its
1813    /// own because it delegates through `<pValue>`, and
1814    /// [`GenApiError::NotDeviceMemory`] for a register on a chunk or event
1815    /// port: its address counts from the start of a chunk or an event, and
1816    /// handing it out as a device address is how such registers ended up
1817    /// reading device memory (GA-12).
1818    pub fn register_address(
1819        &self,
1820        name: &str,
1821        io: &dyn RegisterIo,
1822    ) -> Result<(u64, u32), GenApiError> {
1823        let node = self
1824            .node(name)
1825            .ok_or_else(|| GenApiError::NodeNotFound(name.to_string()))?;
1826        let addressing = crate::nodes::node_addressing(node).ok_or_else(|| {
1827            GenApiError::wrong_kind(name, node.kind_name(), "a node with a register of its own")
1828        })?;
1829        self.locate_for_write(name, addressing, io)
1830            .map_err(|err| match err {
1831                GenApiError::PortNotWritable { node, port } => {
1832                    GenApiError::NotDeviceMemory { node, port }
1833                }
1834                other => other,
1835            })
1836    }
1837
1838    fn resolve_address(
1839        &self,
1840        node_name: &str,
1841        addressing: &Addressing,
1842        io: &dyn RegisterIo,
1843    ) -> Result<(u64, u32), GenApiError> {
1844        match addressing {
1845            Addressing::Sum {
1846                terms,
1847                len,
1848                p_length,
1849                ..
1850            } => {
1851                // First: a bare `<pIndex>` strides by the length, whichever
1852                // way the document gives it.
1853                let len = match p_length {
1854                    Some(provider) => self.length_from(node_name, provider, io)?,
1855                    None => *len,
1856                };
1857                let mut address: u64 = 0;
1858                for term in terms {
1859                    address =
1860                        address.wrapping_add(self.resolve_address_term(node_name, term, len, io)?);
1861                }
1862                if terms.len() > 1 {
1863                    debug!(
1864                        node = %node_name,
1865                        terms = terms.len(),
1866                        address = format_args!("0x{address:X}"),
1867                        len,
1868                        "resolve summed address"
1869                    );
1870                }
1871                Ok((address, len))
1872            }
1873        }
1874    }
1875
1876    /// The length `provider`, a `<pLength>` node, gives `node` now (GenICam
1877    /// Standard v2.1.1 §2.8.3).
1878    fn length_from(
1879        &self,
1880        node: &str,
1881        provider: &str,
1882        io: &dyn RegisterIo,
1883    ) -> Result<u32, GenApiError> {
1884        let len = self.get_integer(provider, io)?;
1885        u32::try_from(len).map_err(|_| GenApiError::BadLength {
1886            name: node.to_string(),
1887            length_node: provider.to_string(),
1888            len,
1889        })
1890    }
1891
1892    /// A register's length now: its `<Length>`, or what its `<pLength>`
1893    /// node reads.
1894    pub(crate) fn register_length(
1895        &self,
1896        node: &str,
1897        addressing: &Addressing,
1898        io: &dyn RegisterIo,
1899    ) -> Result<u32, GenApiError> {
1900        match addressing.length_node() {
1901            Some(provider) => self.length_from(node, provider, io),
1902            None => Ok(addressing.byte_len()),
1903        }
1904    }
1905
1906    /// Resolve a device register's address and length, refusing a length a
1907    /// `<pLength>` node gives beyond [`MAX_DEVICE_LENGTH`]: one read of the
1908    /// device must not allocate whatever a register happens to hold.
1909    pub(crate) fn resolve_device_address(
1910        &self,
1911        node: &str,
1912        addressing: &Addressing,
1913        io: &dyn RegisterIo,
1914    ) -> Result<(u64, u32), GenApiError> {
1915        let (address, len) = self.resolve_address(node, addressing, io)?;
1916        if let Some(provider) = addressing.length_node()
1917            && len > MAX_DEVICE_LENGTH
1918        {
1919            return Err(GenApiError::BadLength {
1920                name: node.to_string(),
1921                length_node: provider.to_string(),
1922                len: i64::from(len),
1923            });
1924        }
1925        Ok((address, len))
1926    }
1927
1928    /// Resolve one address term to the offset it contributes.
1929    fn resolve_address_term(
1930        &self,
1931        node_name: &str,
1932        term: &AddressTerm,
1933        len: u32,
1934        io: &dyn RegisterIo,
1935    ) -> Result<u64, GenApiError> {
1936        let bad = |addr: i64| GenApiError::BadIndirectAddress {
1937            name: node_name.to_string(),
1938            addr,
1939        };
1940        match term {
1941            // Two's complement: a negative literal on a chunk port is an
1942            // offset from the chunk's end, read back as `i64` by `locate`.
1943            AddressTerm::Fixed(offset) => Ok(*offset as u64),
1944            AddressTerm::Node(provider) => {
1945                let value = self.get_integer(provider, io)?;
1946                u64::try_from(value).map_err(|_| bad(value))
1947            }
1948            AddressTerm::Index { node, offset } => {
1949                let index = self.get_integer(node, io)?;
1950                let index = u64::try_from(index).map_err(|_| bad(index))?;
1951                let stride = match offset {
1952                    IndexOffset::Fixed(stride) => *stride,
1953                    IndexOffset::Node(provider) => {
1954                        let value = self.get_integer(provider, io)?;
1955                        u64::try_from(value).map_err(|_| bad(value))?
1956                    }
1957                    // A bare `<pIndex>` strides by the register length.
1958                    IndexOffset::Length => u64::from(len),
1959                };
1960                Ok(index.wrapping_mul(stride))
1961            }
1962        }
1963    }
1964
1965    /// Bind a formula's declared variables and evaluate it.
1966    ///
1967    /// Shared by SwissKnife, Converter and IntConverter: they differ only in
1968    /// which AST and variable list they hand over, in the arithmetic mode, and
1969    /// in any variables the caller binds directly (`FROM` and `OLD` on a
1970    /// write, which have no provider node to read).
1971    #[allow(clippy::too_many_arguments)]
1972    fn eval_formula(
1973        &self,
1974        name: &str,
1975        ast: &SkAst,
1976        vars: &[FormulaVar],
1977        overrides: &[(&str, SkValue)],
1978        mode: EvalMode,
1979        io: &dyn RegisterIo,
1980        stack: &mut HashSet<String>,
1981    ) -> Result<SkValue, GenApiError> {
1982        let mut values: HashMap<String, SkValue> = HashMap::new();
1983        for var in vars {
1984            if overrides.iter().any(|(ident, _)| *ident == var.name) {
1985                continue;
1986            }
1987            let value = self.resolve_formula_var(name, var, io, stack)?;
1988            values.insert(var.name.clone(), value);
1989        }
1990        for (ident, value) in overrides {
1991            values.insert((*ident).to_string(), *value);
1992        }
1993        let mut resolver = |ident: &str| -> Result<SkValue, SkEvalError> {
1994            values
1995                .get(ident)
1996                .copied()
1997                .ok_or_else(|| SkEvalError::UnknownVariable(ident.to_string()))
1998        };
1999        eval_ast(ast, &mut resolver, mode).map_err(|err| expr_error(name, err))
2000    }
2001
2002    fn evaluate_swissknife(
2003        &self,
2004        node: &SkNode,
2005        io: &dyn RegisterIo,
2006        stack: &mut HashSet<String>,
2007    ) -> Result<SkValue, GenApiError> {
2008        if self.may_serve(&node.name)
2009            && let Some((value, generation)) = *node.cache.borrow()
2010            && generation == self.generation.get()
2011        {
2012            return Ok(value);
2013        }
2014        if !stack.insert(node.name.clone()) {
2015            stack.remove(&node.name);
2016            return Err(GenApiError::eval(
2017                &node.name,
2018                SkEvalError::Cycle(node.name.clone()),
2019            ));
2020        }
2021        let current_gen = self.generation.get();
2022        let result = self.eval_formula(
2023            &node.name,
2024            &node.ast,
2025            &node.vars,
2026            &[],
2027            eval_mode(node.output),
2028            io,
2029            stack,
2030        );
2031        stack.remove(&node.name);
2032        let value = result?;
2033        debug!(node = %node.name, value = %value, "evaluate SwissKnife");
2034        if self.may_cache(&node.name) {
2035            node.cache.replace(Some((value, current_gen)));
2036        }
2037        Ok(value)
2038    }
2039
2040    /// Resolve a node reference to the value a formula should see.
2041    ///
2042    /// Integer-typed providers stay integral: routing a 64-bit register value
2043    /// through `f64` on the way into a formula would round away its low bits.
2044    fn resolve_value(
2045        &self,
2046        provider: &str,
2047        io: &dyn RegisterIo,
2048        stack: &mut HashSet<String>,
2049    ) -> Result<SkValue, GenApiError> {
2050        match self.nodes.get(provider) {
2051            Some(Node::Integer(_)) => self.get_integer(provider, io).map(SkValue::Int),
2052            Some(Node::Float(_)) => self.get_float(provider, io).map(SkValue::Float),
2053            Some(Node::Boolean(_)) => self
2054                .get_bool(provider, io)
2055                .map(|flag| SkValue::Int(i64::from(flag))),
2056            Some(Node::Enum(_)) => self.get_enum_numeric(provider, io).map(SkValue::Int),
2057            // The primitive getters check a ceiling themselves; a computed
2058            // node is evaluated here directly, so check its own (Codex review
2059            // of #187).
2060            Some(Node::SwissKnife(node)) => {
2061                self.ensure_not_imposed(provider, AccessMode::WO)?;
2062                self.evaluate_swissknife(node, io, stack)
2063            }
2064            Some(Node::Converter(node)) => {
2065                self.ensure_not_imposed(provider, AccessMode::WO)?;
2066                self.evaluate_converter(node, io, stack)
2067            }
2068            Some(Node::IntConverter(node)) => {
2069                self.ensure_not_imposed(provider, AccessMode::WO)?;
2070                self.evaluate_int_converter(node, io, stack)
2071                    .map(SkValue::Int)
2072            }
2073            Some(other) => Err(GenApiError::wrong_kind(
2074                provider,
2075                other.kind_name(),
2076                "a node with a value",
2077            )),
2078            None => Err(GenApiError::NodeNotFound(provider.to_string())),
2079        }
2080    }
2081
2082    /// Resolve one formula variable: the provider's value, or the property of
2083    /// it that a `.Min` / `.Max` / `.Inc` / `.Entry.<Name>` extension selects.
2084    fn resolve_formula_var(
2085        &self,
2086        formula: &str,
2087        var: &FormulaVar,
2088        io: &dyn RegisterIo,
2089        stack: &mut HashSet<String>,
2090    ) -> Result<SkValue, GenApiError> {
2091        match &var.attr {
2092            VarAttr::Value => self.resolve_value(&var.provider, io, stack),
2093            VarAttr::Entry(entry) => {
2094                let node = match self.nodes.get(&var.provider) {
2095                    Some(Node::Enum(node)) => node,
2096                    Some(other) => {
2097                        return Err(GenApiError::wrong_kind(
2098                            &var.provider,
2099                            other.kind_name(),
2100                            "an Enumeration",
2101                        ));
2102                    }
2103                    None => return Err(GenApiError::NodeNotFound(var.provider.clone())),
2104                };
2105                let decl = node
2106                    .entries
2107                    .iter()
2108                    .find(|decl| decl.name == *entry)
2109                    .ok_or_else(|| GenApiError::EnumNoSuchEntry {
2110                        node: var.provider.clone(),
2111                        entry: entry.clone(),
2112                    })?;
2113                self.resolve_enum_entry_value(node, decl, io)
2114                    .map(SkValue::Int)
2115            }
2116            attr => self.resolve_limit(formula, var, attr, io, stack),
2117        }
2118    }
2119
2120    /// Resolve `.Min`, `.Max` or `.Inc` of a formula variable's node.
2121    ///
2122    /// The bound in force comes from [`NodeMap::limit`]. Where nothing
2123    /// declares one, the GenICam Standard v2.1.1 §3.2 defaults apply: the
2124    /// integer's whole range and an increment of 1, or the largest and
2125    /// smallest double. A `<Float>` has no increment in this model, so `.Inc`
2126    /// on one is an evaluation error rather than a guess.
2127    fn resolve_limit(
2128        &self,
2129        formula: &str,
2130        var: &FormulaVar,
2131        attr: &VarAttr,
2132        io: &dyn RegisterIo,
2133        stack: &mut HashSet<String>,
2134    ) -> Result<SkValue, GenApiError> {
2135        let which = match attr {
2136            VarAttr::Min => Limit::Min,
2137            VarAttr::Max => Limit::Max,
2138            _ => Limit::Inc,
2139        };
2140        let provider = var.provider.as_str();
2141        let integral = match self.nodes.get(provider) {
2142            Some(Node::Integer(_) | Node::IntConverter(_)) => true,
2143            Some(Node::Float(_) | Node::Converter(_)) => false,
2144            Some(_) => {
2145                return Err(GenApiError::eval(
2146                    formula,
2147                    SkEvalError::NoLimit {
2148                        var: var.name.clone(),
2149                        provider: provider.to_string(),
2150                        limit: "minimum, maximum or increment",
2151                    },
2152                ));
2153            }
2154            None => return Err(GenApiError::NodeNotFound(provider.to_string())),
2155        };
2156        let limit = self
2157            .limit(provider, which, io, stack)
2158            .map_err(|err| match err {
2159                GenApiError::ExprEval {
2160                    source: cycle @ SkEvalError::Cycle(_),
2161                    ..
2162                } => GenApiError::eval(formula, cycle),
2163                other => other,
2164            })?;
2165        match (limit, integral) {
2166            (Some(value), true) => sk_to_i64(provider, value).map(SkValue::Int),
2167            (Some(value), false) => Ok(SkValue::Float(value.as_f64())),
2168            (None, true) => Ok(SkValue::Int(match which {
2169                Limit::Min => i64::MIN,
2170                Limit::Max => i64::MAX,
2171                Limit::Inc => 1,
2172            })),
2173            (None, false) => match which {
2174                Limit::Min => Ok(SkValue::Float(f64::MIN)),
2175                Limit::Max => Ok(SkValue::Float(f64::MAX)),
2176                Limit::Inc => Err(GenApiError::eval(
2177                    formula,
2178                    SkEvalError::NoLimit {
2179                        var: var.name.clone(),
2180                        provider: provider.to_string(),
2181                        limit: "increment",
2182                    },
2183                )),
2184            },
2185        }
2186    }
2187
2188    /// The restriction parameter `which` of the numeric node `name` in force
2189    /// now, or `None` when nothing along the way declares one.
2190    ///
2191    /// GenICam Standard v2.1.1 §2.8.5 has an `<Integer>` merge its value and
2192    /// its "Minimum, Maximum, Increment ... from different sources": constants
2193    /// in `<Min>`/`<Max>`/`<Inc>`, or "pointers to other IInteger nodes" in
2194    /// `<pMin>`/`<pMax>`/`<pInc>`; §2.8.9 gives a `<Float>` the same (without
2195    /// an increment we track). A pointer wins over a constant. A node that
2196    /// declares neither takes the bound of the node its `<pValue>` names —
2197    /// otherwise SFNC `Width`, an `<Integer>` over an `<IntReg>`, would have
2198    /// none — and an indexed node that of the node its index selects now.
2199    /// That delegation is our reading; the standard does not spell it out. A
2200    /// `<Converter>` or `<IntConverter>` maps its `<pValue>`'s bounds
2201    /// through `<FormulaFrom>` as its `<Slope>` says (backlog GA-07).
2202    pub(crate) fn limit(
2203        &self,
2204        name: &str,
2205        which: Limit,
2206        io: &dyn RegisterIo,
2207        stack: &mut HashSet<String>,
2208    ) -> Result<Option<SkValue>, GenApiError> {
2209        let mut current = name;
2210        let mut visited = HashSet::new();
2211        loop {
2212            if !visited.insert(current) {
2213                return Err(GenApiError::eval(
2214                    name,
2215                    SkEvalError::Cycle(current.to_string()),
2216                ));
2217            }
2218            let next = match self.nodes.get(current) {
2219                Some(Node::Integer(node)) => {
2220                    let (pointer, declared) = match which {
2221                        Limit::Min => (node.p_min.as_deref(), node.min),
2222                        Limit::Max => (node.p_max.as_deref(), node.max),
2223                        Limit::Inc => (node.p_inc.as_deref(), node.inc),
2224                    };
2225                    if let Some(pointer) = pointer {
2226                        let value = self.resolve_value(pointer, io, stack)?;
2227                        return sk_to_i64(pointer, value).map(|v| Some(SkValue::Int(v)));
2228                    }
2229                    if let Some(value) = declared {
2230                        return Ok(Some(SkValue::Int(value)));
2231                    }
2232                    match node.pvalue.as_deref() {
2233                        Some(pv) => Some(pv),
2234                        None => self.indexed_target(current, io)?,
2235                    }
2236                }
2237                Some(Node::Float(node)) => {
2238                    let (pointer, declared) = match which {
2239                        Limit::Min => (node.p_min.as_deref(), node.min),
2240                        Limit::Max => (node.p_max.as_deref(), node.max),
2241                        Limit::Inc => return Ok(None),
2242                    };
2243                    if let Some(pointer) = pointer {
2244                        let value = self.resolve_value(pointer, io, stack)?;
2245                        return Ok(Some(SkValue::Float(value.as_f64())));
2246                    }
2247                    if let Some(value) = declared {
2248                        return Ok(Some(SkValue::Float(value)));
2249                    }
2250                    match node.pvalue.as_deref() {
2251                        Some(pv) => Some(pv),
2252                        None => self.indexed_target(current, io)?,
2253                    }
2254                }
2255                Some(Node::Converter(node)) => {
2256                    let formula = FromFormula {
2257                        name: &node.name,
2258                        ast: &node.ast_from,
2259                        vars: &node.vars_from,
2260                        p_value: &node.p_value,
2261                        slope: node.slope,
2262                        mode: eval_mode(node.output),
2263                    };
2264                    return self.converter_limit(&formula, which, io, stack);
2265                }
2266                Some(Node::IntConverter(node)) => {
2267                    // "The increment of an IntConvertor is always 1" (§2.8.13),
2268                    // which is what an undeclared increment means anyway.
2269                    let formula = FromFormula {
2270                        name: &node.name,
2271                        ast: &node.ast_from,
2272                        vars: &node.vars_from,
2273                        p_value: &node.p_value,
2274                        slope: node.slope,
2275                        mode: EvalMode::Integer,
2276                    };
2277                    return self.converter_limit(&formula, which, io, stack);
2278                }
2279                Some(_) => None,
2280                None => return Err(GenApiError::NodeNotFound(current.to_string())),
2281            };
2282            match next {
2283                Some(next) => current = next,
2284                None => return Ok(None),
2285            }
2286        }
2287    }
2288
2289    /// A converter's minimum or maximum: its `<pValue>`'s bounds mapped
2290    /// through `<FormulaFrom>`.
2291    ///
2292    /// GenICam Standard v2.1.1 §2.8.13 names four slopes. `Increasing` keeps
2293    /// the order, `Decreasing` swaps it — the raw maximum becomes the
2294    /// feature's minimum — and `Varying` means "the full number range is
2295    /// used", so there is no bound. `Automatic`, the §3.2 default, is
2296    /// "determined ... by probing the function": we evaluate it at both raw
2297    /// bounds and take the smaller and the larger, which is exact for the
2298    /// monotonic formulas the other three values describe.
2299    fn converter_limit(
2300        &self,
2301        formula: &FromFormula<'_>,
2302        which: Limit,
2303        io: &dyn RegisterIo,
2304        stack: &mut HashSet<String>,
2305    ) -> Result<Option<SkValue>, GenApiError> {
2306        if which == Limit::Inc {
2307            return Ok(None);
2308        }
2309        if !stack.insert(formula.name.to_string()) {
2310            stack.remove(formula.name);
2311            return Err(GenApiError::eval(
2312                formula.name,
2313                SkEvalError::Cycle(formula.name.to_string()),
2314            ));
2315        }
2316        let result = self.converter_limit_unguarded(formula, which, io, stack);
2317        stack.remove(formula.name);
2318        result
2319    }
2320
2321    fn converter_limit_unguarded(
2322        &self,
2323        formula: &FromFormula<'_>,
2324        which: Limit,
2325        io: &dyn RegisterIo,
2326        stack: &mut HashSet<String>,
2327    ) -> Result<Option<SkValue>, GenApiError> {
2328        let raw_which = match (formula.slope, which) {
2329            (Slope::Varying, _) => return Ok(None),
2330            (Slope::Decreasing, Limit::Min) => Limit::Max,
2331            (Slope::Decreasing, Limit::Max) => Limit::Min,
2332            (Slope::Increasing | Slope::Decreasing, other) => other,
2333            (Slope::Automatic, _) => {
2334                let low = self.limit(formula.p_value, Limit::Min, io, stack)?;
2335                let high = self.limit(formula.p_value, Limit::Max, io, stack)?;
2336                let (Some(low), Some(high)) = (low, high) else {
2337                    return Ok(None);
2338                };
2339                let (a, b) = (
2340                    self.eval_from(formula, low, io, stack)?,
2341                    self.eval_from(formula, high, io, stack)?,
2342                );
2343                let (small, large) = if a.as_f64() <= b.as_f64() {
2344                    (a, b)
2345                } else {
2346                    (b, a)
2347                };
2348                return Ok(Some(if which == Limit::Min { small } else { large }));
2349            }
2350        };
2351        match self.limit(formula.p_value, raw_which, io, stack)? {
2352            Some(raw) => self.eval_from(formula, raw, io, stack).map(Some),
2353            None => Ok(None),
2354        }
2355    }
2356
2357    /// `<FormulaFrom>` evaluated with `TO` bound to `raw`.
2358    fn eval_from(
2359        &self,
2360        formula: &FromFormula<'_>,
2361        raw: SkValue,
2362        io: &dyn RegisterIo,
2363        stack: &mut HashSet<String>,
2364    ) -> Result<SkValue, GenApiError> {
2365        self.eval_formula(
2366            formula.name,
2367            formula.ast,
2368            formula.vars,
2369            &[("TO", raw)],
2370            formula.mode,
2371            io,
2372            stack,
2373        )
2374    }
2375
2376    /// Refuse an integer write outside the restriction parameters in force.
2377    ///
2378    /// `value` must lie in `[Min, Max]` and be `Min` plus a whole number of
2379    /// `Inc` steps (GenICam Standard v2.1.1 §2.8.5). An undeclared minimum
2380    /// counts the steps from 0.
2381    fn ensure_integer_in_range(
2382        &self,
2383        name: &str,
2384        value: i64,
2385        io: &dyn RegisterIo,
2386    ) -> Result<(), GenApiError> {
2387        let mut stack = HashSet::new();
2388        let mut bound = |which| -> Result<Option<i64>, GenApiError> {
2389            self.limit(name, which, io, &mut stack)?
2390                .map(|v| sk_to_i64(name, v))
2391                .transpose()
2392        };
2393        let (min, max, inc) = (bound(Limit::Min)?, bound(Limit::Max)?, bound(Limit::Inc)?);
2394        if let Some(min) = min
2395            && value < min
2396        {
2397            return Err(GenApiError::range(
2398                name,
2399                SkValue::Int(value),
2400                RangeViolation::BelowMin(SkValue::Int(min)),
2401            ));
2402        }
2403        if let Some(max) = max
2404            && value > max
2405        {
2406            return Err(GenApiError::range(
2407                name,
2408                SkValue::Int(value),
2409                RangeViolation::AboveMax(SkValue::Int(max)),
2410            ));
2411        }
2412        if let Some(inc) = inc
2413            && inc > 1
2414        {
2415            let base = min.unwrap_or(0);
2416            if (i128::from(value) - i128::from(base)) % i128::from(inc) != 0 {
2417                return Err(GenApiError::range(
2418                    name,
2419                    SkValue::Int(value),
2420                    RangeViolation::OffIncrement { base, inc },
2421                ));
2422            }
2423        }
2424        Ok(())
2425    }
2426
2427    /// Refuse a float write outside `[Min, Max]` in force.
2428    fn ensure_float_in_range(
2429        &self,
2430        name: &str,
2431        value: f64,
2432        io: &dyn RegisterIo,
2433    ) -> Result<(), GenApiError> {
2434        let mut stack = HashSet::new();
2435        let min = self.limit(name, Limit::Min, io, &mut stack)?;
2436        let max = self.limit(name, Limit::Max, io, &mut stack)?;
2437        if let Some(min) = min.map(SkValue::as_f64)
2438            && value < min
2439        {
2440            return Err(GenApiError::range(
2441                name,
2442                SkValue::Float(value),
2443                RangeViolation::BelowMin(SkValue::Float(min)),
2444            ));
2445        }
2446        if let Some(max) = max.map(SkValue::as_f64)
2447            && value > max
2448        {
2449            return Err(GenApiError::range(
2450                name,
2451                SkValue::Float(value),
2452                RangeViolation::AboveMax(SkValue::Float(max)),
2453            ));
2454        }
2455        Ok(())
2456    }
2457
2458    fn resolve_numeric(
2459        &self,
2460        provider: &str,
2461        io: &dyn RegisterIo,
2462        stack: &mut HashSet<String>,
2463    ) -> Result<f64, GenApiError> {
2464        self.resolve_value(provider, io, stack)
2465            .map(|value| value.as_f64())
2466    }
2467
2468    fn get_enum_numeric(&self, name: &str, io: &dyn RegisterIo) -> Result<i64, GenApiError> {
2469        let entry = self.get_enum(name, io)?;
2470        let node = self.get_enum_node(name)?;
2471        {
2472            let mut mapping = node.mapping_cache.borrow_mut();
2473            if mapping.is_none() {
2474                *mapping = Some(self.build_enum_mapping(node, io)?);
2475            }
2476            if let Some(map) = mapping.as_ref()
2477                && let Some(value) = map.by_name.get(&entry)
2478            {
2479                return Ok(*value);
2480            }
2481        }
2482        Err(GenApiError::EnumNoSuchEntry {
2483            node: name.to_string(),
2484            entry,
2485        })
2486    }
2487
2488    /// Forget `name`'s cached value — and that of every node it takes its
2489    /// value from through `<pValue>` or an indexed value's entries, which is
2490    /// where a register reading is held — and those of the nodes that depend
2491    /// on it, so the next read asks the device.
2492    ///
2493    /// For a value the device changes in a way its XML does not describe — a
2494    /// timestamp a latch command fills, with nothing linking the two. A value
2495    /// the XML declares `NoCache` needs none of this, and one with a
2496    /// `<PollingTime>` is read again once that has passed (ADR-0029). Every
2497    /// timestamp in the vendor corpus is an `Integer` over an `IntReg`, so
2498    /// clearing the front node alone would change nothing (Codex review of
2499    /// #187). The invalidation is a change for [`NodeMap::changed_since`].
2500    pub fn invalidate(&self, name: &str) {
2501        self.bump_generation();
2502        for link in self.value_reach(name) {
2503            if let Some(node) = self.nodes.get(link) {
2504                node.invalidate_cache();
2505                self.note_changed(link);
2506            }
2507        }
2508        self.invalidate_dependents(name);
2509    }
2510
2511    /// Forget every cached value: for a command known to change the
2512    /// device's state wholesale, such as `UserSetLoad`, on a camera whose XML
2513    /// does not say which features it changes. What the host itself holds —
2514    /// a floating `<Integer>` or `<Boolean>` — is kept.
2515    pub fn invalidate_all(&self) {
2516        for node in self.nodes.values() {
2517            node.invalidate_cache();
2518        }
2519        self.bump_generation();
2520        self.note_all_changed();
2521    }
2522
2523    /// `name` changed: a new generation, recorded against it and against
2524    /// everything that depends on it, whose caches are dropped.
2525    fn invalidate_dependents(&self, name: &str) {
2526        self.bump_generation();
2527        self.note_changed(name);
2528        if let Some(children) = self.dependents.get(name) {
2529            let mut visited = HashSet::new();
2530            for child in children {
2531                self.invalidate_recursive(child, &mut visited);
2532            }
2533        }
2534    }
2535
2536    fn invalidate_recursive(&self, name: &str, visited: &mut HashSet<String>) {
2537        if !visited.insert(name.to_string()) {
2538            return;
2539        }
2540        if let Some(node) = self.nodes.get(name) {
2541            node.invalidate_cache();
2542        }
2543        self.note_changed(name);
2544        if let Some(children) = self.dependents.get(name) {
2545            for child in children {
2546                self.invalidate_recursive(child, visited);
2547            }
2548        }
2549    }
2550
2551    /// Leave a register's cache as its caching mode says after a write:
2552    /// `WriteThrough` keeps the value written; `WriteAround` and `NoCache`
2553    /// keep nothing, so the next read asks the device — except the bytes a
2554    /// write-only register was written, the only way to keep its other bits
2555    /// on the next masked write (GA-31).
2556    fn after_register_write<T>(
2557        &self,
2558        name: &str,
2559        cache: &std::cell::RefCell<Option<T>>,
2560        value: T,
2561        raw_cache: &std::cell::RefCell<Option<Vec<u8>>>,
2562        raw: Vec<u8>,
2563        readable: bool,
2564    ) {
2565        if self.keeps_written(name) {
2566            cache.replace(Some(value));
2567            raw_cache.replace(Some(raw));
2568            self.note_read(name);
2569        } else {
2570            cache.replace(None);
2571            raw_cache.replace((!readable).then_some(raw));
2572        }
2573    }
2574
2575    fn bump_generation(&self) {
2576        let current = self.generation.get();
2577        self.generation.set(current.wrapping_add(1));
2578    }
2579
2580    // ========================================================================
2581    // Converter/IntConverter/String support
2582    // ========================================================================
2583
2584    fn get_converter_node(&self, name: &str) -> Result<&ConverterNode, GenApiError> {
2585        match self.nodes.get(name) {
2586            Some(Node::Converter(node)) => Ok(node),
2587            Some(other) => Err(GenApiError::wrong_kind(
2588                name,
2589                other.kind_name(),
2590                "a Converter",
2591            )),
2592            None => Err(GenApiError::NodeNotFound(name.to_string())),
2593        }
2594    }
2595
2596    fn get_int_converter_node(&self, name: &str) -> Result<&IntConverterNode, GenApiError> {
2597        match self.nodes.get(name) {
2598            Some(Node::IntConverter(node)) => Ok(node),
2599            Some(other) => Err(GenApiError::wrong_kind(
2600                name,
2601                other.kind_name(),
2602                "an IntConverter",
2603            )),
2604            None => Err(GenApiError::NodeNotFound(name.to_string())),
2605        }
2606    }
2607
2608    fn get_string_node(&self, name: &str) -> Result<&StringNode, GenApiError> {
2609        match self.nodes.get(name) {
2610            Some(Node::String(node)) => Ok(node),
2611            Some(other) => Err(GenApiError::wrong_kind(name, other.kind_name(), "a String")),
2612            None => Err(GenApiError::NodeNotFound(name.to_string())),
2613        }
2614    }
2615
2616    fn get_register_node(&self, name: &str) -> Result<&RegisterNode, GenApiError> {
2617        match self.nodes.get(name) {
2618            Some(Node::Register(node)) => Ok(node),
2619            Some(other) => Err(GenApiError::wrong_kind(
2620                name,
2621                other.kind_name(),
2622                "a Register",
2623            )),
2624            None => Err(GenApiError::NodeNotFound(name.to_string())),
2625        }
2626    }
2627
2628    /// Read a Converter feature value (float) using the provided transport.
2629    pub fn get_converter(&self, name: &str, io: &dyn RegisterIo) -> Result<f64, GenApiError> {
2630        let node = self.get_converter_node(name)?;
2631        self.ensure_not_imposed(name, AccessMode::WO)?;
2632        if self.may_serve(name)
2633            && let Some((value, generation)) = *node.cache.borrow()
2634            && generation == self.generation.get()
2635        {
2636            return Ok(value.as_f64());
2637        }
2638        let mut stack = HashSet::new();
2639        let value = self.evaluate_converter(node, io, &mut stack)?;
2640        if self.may_cache(name) {
2641            node.cache.replace(Some((value, self.generation.get())));
2642        }
2643        Ok(value.as_f64())
2644    }
2645
2646    /// Read an IntConverter feature value (integer) using the provided transport.
2647    pub fn get_int_converter(&self, name: &str, io: &dyn RegisterIo) -> Result<i64, GenApiError> {
2648        let node = self.get_int_converter_node(name)?;
2649        self.ensure_not_imposed(name, AccessMode::WO)?;
2650        if self.may_serve(name)
2651            && let Some((value, generation)) = *node.cache.borrow()
2652            && generation == self.generation.get()
2653        {
2654            return Ok(value);
2655        }
2656        let mut stack = HashSet::new();
2657        let value = self.evaluate_int_converter(node, io, &mut stack)?;
2658        if self.may_cache(name) {
2659            node.cache.replace(Some((value, self.generation.get())));
2660        }
2661        Ok(value)
2662    }
2663
2664    /// Write a Converter feature value (float) through its `<FormulaTo>`.
2665    pub fn set_converter(
2666        &mut self,
2667        name: &str,
2668        value: f64,
2669        io: &dyn RegisterIo,
2670    ) -> Result<(), GenApiError> {
2671        // A converter can carry its own `pIsAvailable` or `pIsLocked`; the
2672        // node it writes through is checked again when the write reaches it.
2673        self.ensure_writable_now(name, &AccessMode::RW, io)?;
2674        let node = self.get_converter_node(name)?;
2675        let (p_value, raw) = self.converter_raw_write(
2676            &node.name,
2677            &node.ast_to,
2678            &node.vars_to,
2679            &node.p_value,
2680            SkValue::Float(value),
2681            eval_mode(node.output),
2682            io,
2683        )?;
2684        self.write_converter_raw(&p_value, raw, io)?;
2685        self.invalidate_dependents(name);
2686        Ok(())
2687    }
2688
2689    /// Write an IntConverter feature value through its `<FormulaTo>`.
2690    pub fn set_int_converter(
2691        &mut self,
2692        name: &str,
2693        value: i64,
2694        io: &dyn RegisterIo,
2695    ) -> Result<(), GenApiError> {
2696        // A converter can carry its own `pIsAvailable` or `pIsLocked`; the
2697        // node it writes through is checked again when the write reaches it.
2698        self.ensure_writable_now(name, &AccessMode::RW, io)?;
2699        let node = self.get_int_converter_node(name)?;
2700        let (p_value, raw) = self.converter_raw_write(
2701            &node.name,
2702            &node.ast_to,
2703            &node.vars_to,
2704            &node.p_value,
2705            SkValue::Int(value),
2706            EvalMode::Integer,
2707            io,
2708        )?;
2709        self.write_converter_raw(&p_value, raw, io)?;
2710        self.invalidate_dependents(name);
2711        Ok(())
2712    }
2713
2714    /// Evaluate a converter's `<FormulaTo>` to the raw value to write.
2715    ///
2716    /// `FROM` is the value the caller is setting, and `OLD` — where the
2717    /// formula declares it — is the register's current contents, which
2718    /// read-modify-write formulas such as `(FROM & 0x7FFFFFFF) | (OLD &
2719    /// 0x80000000)` depend on.
2720    #[allow(clippy::too_many_arguments)]
2721    fn converter_raw_write(
2722        &self,
2723        name: &str,
2724        ast_to: &SkAst,
2725        vars_to: &[FormulaVar],
2726        p_value: &str,
2727        value: SkValue,
2728        mode: EvalMode,
2729        io: &dyn RegisterIo,
2730    ) -> Result<(String, SkValue), GenApiError> {
2731        let mut stack = HashSet::new();
2732        let mut overrides = vec![("FROM", value)];
2733        if vars_to.iter().any(|var| var.name == "OLD") {
2734            let old = self.resolve_value(p_value, io, &mut stack)?;
2735            overrides.push(("OLD", old));
2736        }
2737        let raw = self.eval_formula(name, ast_to, vars_to, &overrides, mode, io, &mut stack)?;
2738        Ok((p_value.to_string(), raw))
2739    }
2740
2741    fn write_converter_raw(
2742        &mut self,
2743        p_value: &str,
2744        raw: SkValue,
2745        io: &dyn RegisterIo,
2746    ) -> Result<(), GenApiError> {
2747        match self.nodes.get(p_value) {
2748            Some(Node::Float(_)) => self.set_float(p_value, raw.as_f64(), io),
2749            Some(Node::Boolean(_)) => self.set_bool(p_value, raw.is_truthy(), io),
2750            Some(_) => self.set_integer(p_value, sk_to_i64(p_value, raw)?, io),
2751            None => Err(GenApiError::NodeNotFound(p_value.to_string())),
2752        }
2753    }
2754
2755    /// Read a String feature value using the provided transport.
2756    ///
2757    /// A `<StringReg>` reads its register up to the first NUL. A `<String>`
2758    /// reads the node its `<pValue>` names, or holds its `<Value>` and
2759    /// whatever was last written to it.
2760    pub fn get_string(&self, name: &str, io: &dyn RegisterIo) -> Result<String, GenApiError> {
2761        let node = self.get_string_node(name)?;
2762        self.ensure_readable_now(&node.access, name)?;
2763        if let Some(ref pv) = node.pvalue {
2764            return self.get_string(pv, io);
2765        }
2766        let Some(ref addressing) = node.addressing else {
2767            return match (node.floating.borrow().clone(), &node.value) {
2768                (Some(written), _) => Ok(written),
2769                (None, Some(start)) => Ok(start.clone()),
2770                (None, None) => Err(GenApiError::no_value_source(name)),
2771            };
2772        };
2773        if self.may_serve(name)
2774            && let Some((ref value, generation)) = *node.cache.borrow()
2775            && generation == self.generation.get()
2776        {
2777            return Ok(value.clone());
2778        }
2779        let location = self.locate(name, addressing, io)?;
2780        let raw = self.read_location(name, &location, io)?;
2781        // Convert bytes to string, stopping at first null byte
2782        let end = raw.iter().position(|&b| b == 0).unwrap_or(raw.len());
2783        let value = String::from_utf8_lossy(&raw[..end]).to_string();
2784        self.note_read(name);
2785        node.cache.replace(
2786            self.may_cache(name)
2787                .then(|| (value.clone(), self.generation.get())),
2788        );
2789        debug!(node = %name, value = %value, "get_string");
2790        Ok(value)
2791    }
2792
2793    /// Write a String feature value using the provided transport.
2794    pub fn set_string(
2795        &mut self,
2796        name: &str,
2797        value: &str,
2798        io: &dyn RegisterIo,
2799    ) -> Result<(), GenApiError> {
2800        let node = self.get_string_node(name)?;
2801        self.ensure_writable_now(name, &node.access, io)?;
2802        if let Some(ref pv) = node.pvalue {
2803            let pv = pv.clone();
2804            self.set_string(&pv, value, io)?;
2805            self.invalidate_dependents(name);
2806            return Ok(());
2807        }
2808        let Some(ref addressing) = node.addressing else {
2809            if node.value.is_none() {
2810                return Err(GenApiError::no_value_source(name));
2811            }
2812            // A floating `<String>`: "a floating node which can hold any
2813            // string value" (GenICam Standard v2.1.1 §2.8.12).
2814            debug!(node = %name, value = %value, "write floating string");
2815            node.floating.replace(Some(value.to_string()));
2816            self.invalidate_dependents(name);
2817            return Ok(());
2818        };
2819        let (address, len) = self.locate_for_write(name, addressing, io)?;
2820        // Build byte buffer with null termination
2821        let mut buf = vec![0u8; len as usize];
2822        let bytes = value.as_bytes();
2823        let copy_len = bytes.len().min(len as usize);
2824        buf[..copy_len].copy_from_slice(&bytes[..copy_len]);
2825        io.write(address, &buf)?;
2826        self.invalidate_dependents(name);
2827        if self.keeps_written(name) {
2828            node.cache
2829                .replace(Some((value.to_string(), self.generation.get())));
2830            self.note_read(name);
2831        } else {
2832            node.cache.replace(None);
2833        }
2834        debug!(node = %name, value = %value, "set_string");
2835        Ok(())
2836    }
2837
2838    /// Read a `<Register>` node's bytes using the provided transport.
2839    ///
2840    /// Returns the full declared length. For a large block — the Micro-Epsilon
2841    /// scanCONTROL declares `FileAccessBuffer` as 100 000 bytes — that is
2842    /// hundreds of chunked reads; use [`NodeMap::register_address`] and the
2843    /// transport directly when a partial read is what you want.
2844    pub fn get_register(&self, name: &str, io: &dyn RegisterIo) -> Result<Vec<u8>, GenApiError> {
2845        let node = self.get_register_node(name)?;
2846        self.ensure_readable_now(&node.access, name)?;
2847        if self.may_serve(name)
2848            && let Some((ref value, generation)) = *node.cache.borrow()
2849            && generation == self.generation.get()
2850        {
2851            return Ok(value.clone());
2852        }
2853        let location = self.locate(name, &node.addressing, io)?;
2854        let raw = self.read_location(name, &location, io)?;
2855        self.note_read(name);
2856        node.cache.replace(
2857            self.may_cache(name)
2858                .then(|| (raw.clone(), self.generation.get())),
2859        );
2860        debug!(node = %name, len = raw.len(), "get_register");
2861        Ok(raw)
2862    }
2863
2864    /// Write a `<Register>` node's bytes using the provided transport.
2865    ///
2866    /// `data` must be exactly the declared length. Unlike [`NodeMap::set_string`],
2867    /// which pads with NULs, a short slice is refused: zero-padding a
2868    /// file-transfer buffer to 100 000 bytes because the caller supplied 12 is
2869    /// data loss, not a convenience.
2870    pub fn set_register(
2871        &mut self,
2872        name: &str,
2873        data: &[u8],
2874        io: &dyn RegisterIo,
2875    ) -> Result<(), GenApiError> {
2876        let node = self.get_register_node(name)?;
2877        self.ensure_writable_now(name, &node.access, io)?;
2878        let (address, len) = self.locate_for_write(name, &node.addressing, io)?;
2879        if data.len() != len as usize {
2880            return Err(GenApiError::RegisterLength {
2881                name: name.to_string(),
2882                len,
2883                got: data.len(),
2884            });
2885        }
2886        io.write(address, data)?;
2887        self.invalidate_dependents(name);
2888        if self.keeps_written(name) {
2889            node.cache
2890                .replace(Some((data.to_vec(), self.generation.get())));
2891            self.note_read(name);
2892        } else {
2893            node.cache.replace(None);
2894        }
2895        debug!(node = %name, len = data.len(), "set_register");
2896        Ok(())
2897    }
2898
2899    /// Evaluate a Converter in the read direction (`<FormulaFrom>`).
2900    fn evaluate_converter(
2901        &self,
2902        node: &ConverterNode,
2903        io: &dyn RegisterIo,
2904        stack: &mut HashSet<String>,
2905    ) -> Result<SkValue, GenApiError> {
2906        if !stack.insert(node.name.clone()) {
2907            stack.remove(&node.name);
2908            return Err(GenApiError::eval(
2909                &node.name,
2910                SkEvalError::Cycle(node.name.clone()),
2911            ));
2912        }
2913        let result = self.eval_formula(
2914            &node.name,
2915            &node.ast_from,
2916            &node.vars_from,
2917            &[],
2918            eval_mode(node.output),
2919            io,
2920            stack,
2921        );
2922        stack.remove(&node.name);
2923        let value = result?;
2924        debug!(node = %node.name, value = %value, "evaluate Converter");
2925        Ok(value)
2926    }
2927
2928    /// Evaluate an IntConverter in the read direction (`<FormulaFrom>`).
2929    fn evaluate_int_converter(
2930        &self,
2931        node: &IntConverterNode,
2932        io: &dyn RegisterIo,
2933        stack: &mut HashSet<String>,
2934    ) -> Result<i64, GenApiError> {
2935        if !stack.insert(node.name.clone()) {
2936            stack.remove(&node.name);
2937            return Err(GenApiError::eval(
2938                &node.name,
2939                SkEvalError::Cycle(node.name.clone()),
2940            ));
2941        }
2942        let result = self.eval_formula(
2943            &node.name,
2944            &node.ast_from,
2945            &node.vars_from,
2946            &[],
2947            EvalMode::Integer,
2948            io,
2949            stack,
2950        );
2951        stack.remove(&node.name);
2952        let int_value = result?.as_i64();
2953        debug!(node = %node.name, int_value, "evaluate IntConverter");
2954        Ok(int_value)
2955    }
2956}
2957
2958/// Whether `entry` of `node` is declared `<IsSelfClearing>Yes`.
2959fn entry_is_self_clearing(node: &EnumNode, entry: &str) -> bool {
2960    node.entries
2961        .iter()
2962        .any(|candidate| candidate.name == entry && candidate.is_self_clearing)
2963}
2964
2965/// Build one runtime node from its declaration, recording the nodes it depends
2966/// on in `dependents`.
2967fn build_node(
2968    decl: NodeDecl,
2969    dependents: &mut HashMap<String, Vec<String>>,
2970) -> Result<(String, Node), GenApiError> {
2971    match decl {
2972        NodeDecl::Integer {
2973            name,
2974            meta,
2975            addressing,
2976            len,
2977            access,
2978            min,
2979            max,
2980            inc,
2981            unit,
2982            bitfield,
2983            sign,
2984            byte_order,
2985            selected,
2986            pvalue,
2987            p_max,
2988            p_min,
2989            p_inc,
2990            value,
2991            indexed,
2992            predicates,
2993            invalidators,
2994        } => {
2995            if let Some(ref addr) = addressing {
2996                register_addressing_dependency(dependents, &name, addr);
2997            }
2998            for provider in [&pvalue, &p_min, &p_max, &p_inc].into_iter().flatten() {
2999                dependents
3000                    .entry(provider.clone())
3001                    .or_default()
3002                    .push(name.clone());
3003            }
3004            register_indexed_dependencies(dependents, &name, indexed.as_ref());
3005            register_selection_dependencies(dependents, &name, &selected);
3006            register_predicate_dependencies(dependents, &name, &predicates);
3007            register_invalidator_dependencies(dependents, &name, &invalidators);
3008            let node = IntegerNode {
3009                name: name.clone(),
3010                meta,
3011                addressing,
3012                len,
3013                access,
3014                min,
3015                max,
3016                inc,
3017                unit,
3018                bitfield,
3019                sign,
3020                byte_order,
3021                selected,
3022                pvalue,
3023                p_max,
3024                p_min,
3025                p_inc,
3026                value,
3027                indexed: indexed.map(Indexed::new),
3028                predicates,
3029                cache: std::cell::RefCell::new(None),
3030                raw_cache: std::cell::RefCell::new(None),
3031                floating: std::cell::RefCell::new(None),
3032            };
3033            Ok((name, Node::Integer(node)))
3034        }
3035        NodeDecl::Float {
3036            name,
3037            meta,
3038            addressing,
3039            access,
3040            min,
3041            max,
3042            unit,
3043            scale,
3044            offset,
3045            pvalue,
3046            p_min,
3047            p_max,
3048            value,
3049            indexed,
3050            encoding,
3051            byte_order,
3052            predicates,
3053            invalidators,
3054        } => {
3055            if let Some(ref addr) = addressing {
3056                register_addressing_dependency(dependents, &name, addr);
3057            }
3058            for provider in [&pvalue, &p_min, &p_max].into_iter().flatten() {
3059                dependents
3060                    .entry(provider.clone())
3061                    .or_default()
3062                    .push(name.clone());
3063            }
3064            register_indexed_dependencies(dependents, &name, indexed.as_ref());
3065            register_predicate_dependencies(dependents, &name, &predicates);
3066            register_invalidator_dependencies(dependents, &name, &invalidators);
3067            let node = FloatNode {
3068                name: name.clone(),
3069                meta,
3070                addressing,
3071                access,
3072                min,
3073                max,
3074                unit,
3075                scale,
3076                offset,
3077                pvalue,
3078                p_min,
3079                p_max,
3080                value,
3081                indexed: indexed.map(Indexed::new),
3082                encoding,
3083                byte_order,
3084                predicates,
3085                cache: std::cell::RefCell::new(None),
3086                floating: std::cell::RefCell::new(None),
3087            };
3088            Ok((name, Node::Float(node)))
3089        }
3090        NodeDecl::Enum {
3091            name,
3092            meta,
3093            addressing,
3094            access,
3095            entries,
3096            default,
3097            selected,
3098            pvalue,
3099            value,
3100            predicates,
3101        } => {
3102            if let Some(ref addr) = addressing {
3103                register_addressing_dependency(dependents, &name, addr);
3104            }
3105            if let Some(ref pv) = pvalue {
3106                dependents.entry(pv.clone()).or_default().push(name.clone());
3107            }
3108            register_selection_dependencies(dependents, &name, &selected);
3109            register_predicate_dependencies(dependents, &name, &predicates);
3110            let mut providers = Vec::new();
3111            let mut provider_set = HashSet::new();
3112            for entry in &entries {
3113                if let EnumValueSrc::FromNode(node_name) = &entry.value {
3114                    dependents
3115                        .entry(node_name.clone())
3116                        .or_default()
3117                        .push(name.clone());
3118                    if provider_set.insert(node_name.clone()) {
3119                        providers.push(node_name.clone());
3120                    }
3121                }
3122                register_predicate_dependencies(dependents, &name, &entry.predicates);
3123            }
3124            providers.sort();
3125            let node = EnumNode {
3126                name: name.clone(),
3127                meta,
3128                addressing,
3129                access,
3130                pvalue,
3131                entries,
3132                default,
3133                selected,
3134                providers,
3135                value,
3136                predicates,
3137                value_cache: std::cell::RefCell::new(None),
3138                mapping_cache: std::cell::RefCell::new(None),
3139                floating: std::cell::RefCell::new(None),
3140            };
3141            Ok((name, Node::Enum(node)))
3142        }
3143        NodeDecl::Boolean {
3144            name,
3145            meta,
3146            addressing,
3147            len,
3148            access,
3149            bitfield,
3150            pvalue,
3151            on_value,
3152            off_value,
3153            value,
3154            predicates,
3155        } => {
3156            if let Some(ref addr) = addressing {
3157                register_addressing_dependency(dependents, &name, addr);
3158            }
3159            if let Some(ref pv) = pvalue {
3160                dependents.entry(pv.clone()).or_default().push(name.clone());
3161            }
3162            register_predicate_dependencies(dependents, &name, &predicates);
3163            let node = BooleanNode {
3164                name: name.clone(),
3165                meta,
3166                addressing,
3167                len,
3168                access,
3169                bitfield,
3170                pvalue,
3171                on_value,
3172                off_value,
3173                value,
3174                predicates,
3175                cache: std::cell::RefCell::new(None),
3176                raw_cache: std::cell::RefCell::new(None),
3177                floating: std::cell::RefCell::new(None),
3178            };
3179            Ok((name, Node::Boolean(node)))
3180        }
3181        NodeDecl::Command {
3182            name,
3183            meta,
3184            address,
3185            len,
3186            pvalue,
3187            command_value,
3188            predicates,
3189        } => {
3190            if let Some(ref pv) = pvalue {
3191                dependents.entry(pv.clone()).or_default().push(name.clone());
3192            }
3193            if let CommandValueSrc::FromNode(provider) = &command_value {
3194                dependents
3195                    .entry(provider.clone())
3196                    .or_default()
3197                    .push(name.clone());
3198            }
3199            register_predicate_dependencies(dependents, &name, &predicates);
3200            let node = CommandNode {
3201                name: name.clone(),
3202                meta,
3203                address,
3204                len,
3205                pvalue,
3206                command_value,
3207                predicates,
3208            };
3209            Ok((name, Node::Command(node)))
3210        }
3211        NodeDecl::Category {
3212            name,
3213            meta,
3214            children,
3215            predicates,
3216        } => {
3217            register_predicate_dependencies(dependents, &name, &predicates);
3218            let node = CategoryNode {
3219                name: name.clone(),
3220                meta,
3221                children,
3222                predicates,
3223            };
3224            Ok((name, Node::Category(node)))
3225        }
3226        NodeDecl::SwissKnife(decl) => {
3227            let name = decl.name;
3228            let meta = decl.meta;
3229            let expr = decl.expr;
3230            let variables = decl.variables;
3231            let output = decl.output;
3232            let predicates = decl.predicates;
3233            let mut ast = parse_formula(&name, &expr)?;
3234            substitute(&mut ast, &formula_bindings(&name, &decl.bindings)?);
3235            let vars = formula_vars(&name, &variables, &[&ast])?;
3236            let mut used = HashSet::new();
3237            collect_identifiers(&ast, &mut used);
3238            for ident in &used {
3239                // `E` and `PI` are language constants, not variables, so
3240                // they legitimately appear without a `<pVariable>`.
3241                if !vars.iter().any(|var| var.name == *ident) && !is_builtin_constant(ident) {
3242                    return Err(GenApiError::UnknownVariable {
3243                        name: name.clone(),
3244                        var: ident.clone(),
3245                    });
3246                }
3247            }
3248            register_formula_dependencies(
3249                dependents,
3250                &name,
3251                vars.iter().map(|var| var.provider.as_str()),
3252            );
3253            register_predicate_dependencies(dependents, &name, &predicates);
3254            let node = SkNode {
3255                name: name.clone(),
3256                meta,
3257                output,
3258                ast,
3259                vars,
3260                predicates,
3261                cache: std::cell::RefCell::new(None),
3262            };
3263            Ok((name, Node::SwissKnife(node)))
3264        }
3265        NodeDecl::Converter(decl) => {
3266            let name = decl.name;
3267            let bindings = formula_bindings(&name, &decl.bindings)?;
3268            let mut ast_to = parse_formula(&name, &decl.formula_to)?;
3269            substitute(&mut ast_to, &bindings);
3270            let mut ast_from = parse_formula(&name, &decl.formula_from)?;
3271            substitute(&mut ast_from, &bindings);
3272            let vars_to = formula_vars(&name, &decl.variables_to, &[&ast_to])?;
3273            let vars_from = formula_vars(&name, &decl.variables_from, &[&ast_from])?;
3274            register_formula_dependencies(
3275                dependents,
3276                &name,
3277                vars_to
3278                    .iter()
3279                    .chain(&vars_from)
3280                    .map(|var| var.provider.as_str())
3281                    .chain([decl.p_value.as_str()]),
3282            );
3283            register_predicate_dependencies(dependents, &name, &decl.predicates);
3284            let node = ConverterNode {
3285                name: name.clone(),
3286                meta: decl.meta,
3287                p_value: decl.p_value,
3288                ast_to,
3289                ast_from,
3290                vars_to,
3291                vars_from,
3292                unit: decl.unit,
3293                output: decl.output,
3294                slope: decl.slope,
3295                predicates: decl.predicates,
3296                cache: std::cell::RefCell::new(None),
3297            };
3298            Ok((name, Node::Converter(node)))
3299        }
3300        NodeDecl::IntConverter(decl) => {
3301            let name = decl.name;
3302            let bindings = formula_bindings(&name, &decl.bindings)?;
3303            let mut ast_to = parse_formula(&name, &decl.formula_to)?;
3304            substitute(&mut ast_to, &bindings);
3305            let mut ast_from = parse_formula(&name, &decl.formula_from)?;
3306            substitute(&mut ast_from, &bindings);
3307            let vars_to = formula_vars(&name, &decl.variables_to, &[&ast_to])?;
3308            let vars_from = formula_vars(&name, &decl.variables_from, &[&ast_from])?;
3309            register_formula_dependencies(
3310                dependents,
3311                &name,
3312                vars_to
3313                    .iter()
3314                    .chain(&vars_from)
3315                    .map(|var| var.provider.as_str())
3316                    .chain([decl.p_value.as_str()]),
3317            );
3318            register_predicate_dependencies(dependents, &name, &decl.predicates);
3319            let node = IntConverterNode {
3320                name: name.clone(),
3321                meta: decl.meta,
3322                p_value: decl.p_value,
3323                ast_to,
3324                ast_from,
3325                vars_to,
3326                vars_from,
3327                unit: decl.unit,
3328                slope: decl.slope,
3329                predicates: decl.predicates,
3330                cache: std::cell::RefCell::new(None),
3331            };
3332            Ok((name, Node::IntConverter(node)))
3333        }
3334        NodeDecl::String(decl) => {
3335            let name = decl.name;
3336            if let Some(ref addressing) = decl.addressing {
3337                register_addressing_dependency(dependents, &name, addressing);
3338            }
3339            if let Some(ref provider) = decl.pvalue {
3340                dependents
3341                    .entry(provider.clone())
3342                    .or_default()
3343                    .push(name.clone());
3344            }
3345            register_predicate_dependencies(dependents, &name, &decl.predicates);
3346            register_invalidator_dependencies(dependents, &name, &decl.invalidators);
3347            let node = StringNode {
3348                name: name.clone(),
3349                meta: decl.meta,
3350                addressing: decl.addressing,
3351                pvalue: decl.pvalue,
3352                value: decl.value,
3353                floating: std::cell::RefCell::new(None),
3354                access: decl.access,
3355                predicates: decl.predicates,
3356                cache: std::cell::RefCell::new(None),
3357            };
3358            Ok((name, Node::String(node)))
3359        }
3360        NodeDecl::Register(decl) => {
3361            let name = decl.name;
3362            register_addressing_dependency(dependents, &name, &decl.addressing);
3363            register_predicate_dependencies(dependents, &name, &decl.predicates);
3364            register_invalidator_dependencies(dependents, &name, &decl.invalidators);
3365            let node = RegisterNode {
3366                name: name.clone(),
3367                meta: decl.meta,
3368                addressing: decl.addressing,
3369                access: decl.access,
3370                predicates: decl.predicates,
3371                cache: std::cell::RefCell::new(None),
3372            };
3373            Ok((name, Node::Register(node)))
3374        }
3375        // `NodeDecl` is `#[non_exhaustive]`, so this crate can no longer match
3376        // it exhaustively and the compiler will not point at this function when
3377        // a variant is added. Fail loudly rather than defaulting: a node type
3378        // the XML layer understands but this one silently drops is precisely
3379        // the class of defect GA-02 existed to end.
3380        other => Err(GenApiError::Unsupported {
3381            name: other.name().to_string(),
3382            kind: other.kind(),
3383        }),
3384    }
3385}
3386
3387/// Effective signedness of an integer node's payload.
3388///
3389/// `<Sign>` is the only signal. `<Min>` says nothing about it: it constrains
3390/// the *feature* value, while `<Sign>` describes the *register payload*
3391/// encoding, and the two live on different nodes when a feature delegates
3392/// through `<pValue>`.
3393///
3394/// Inferring "signed" from a negative `<Min>` looks reasonable and is
3395/// unsalvageable in practice. `<Min>` is optional and defaults to `i64::MIN`,
3396/// which is negative — and across the whole vendor corpus **not one** of the
3397/// 4 300 `<IntReg>` or 5 479 `<MaskedIntReg>` nodes declares it. The
3398/// inference therefore fires on every register-backed integer on every real
3399/// camera, which is precisely the case `<Sign>` exists to decide.
3400fn integer_sign(node: &IntegerNode) -> Sign {
3401    node.sign
3402}
3403
3404/// Resolve the variables a formula reads from its `<pVariable>` declarations.
3405///
3406/// Every declaration becomes a [`FormulaVar`]; one whose `Name` carries an
3407/// extension — the standard's own example is
3408/// `<pVariable Name="Gain.Max">Gain</pVariable>` — reads that property of its
3409/// node rather than its value. An identifier in `asts` that is not declared as
3410/// written but qualifies a declared plain variable (`V1.Min` with `V1`
3411/// declared) is added too. Identifiers that match neither are left out; the
3412/// caller decides whether that is an error.
3413///
3414/// An extension the standard does not define fails the build with
3415/// [`GenApiError::UnknownVariableExtension`], which sends the node to
3416/// [`NodeMap::skipped`] rather than evaluating it to a wrong number.
3417fn formula_vars(
3418    node: &str,
3419    declared: &[(String, String)],
3420    asts: &[&SkAst],
3421) -> Result<Vec<FormulaVar>, GenApiError> {
3422    let qualified = |var: &str, extension: &str, provider: &str| {
3423        VarAttr::parse(extension)
3424            .map(|attr| FormulaVar {
3425                name: var.to_string(),
3426                provider: provider.to_string(),
3427                attr,
3428            })
3429            .ok_or_else(|| GenApiError::UnknownVariableExtension {
3430                name: node.to_string(),
3431                var: var.to_string(),
3432                extension: extension.to_string(),
3433            })
3434    };
3435    let mut vars = Vec::with_capacity(declared.len());
3436    for (var, provider) in declared {
3437        vars.push(match split_qualified(var) {
3438            Some((_, extension)) => qualified(var, extension, provider)?,
3439            None => FormulaVar {
3440                name: var.clone(),
3441                provider: provider.clone(),
3442                attr: VarAttr::Value,
3443            },
3444        });
3445    }
3446    let mut used = HashSet::new();
3447    for ast in asts {
3448        collect_identifiers(ast, &mut used);
3449    }
3450    let mut used: Vec<String> = used.into_iter().collect();
3451    used.sort();
3452    for ident in used {
3453        if declared.iter().any(|(var, _)| *var == ident) {
3454            continue;
3455        }
3456        let Some((base, extension)) = split_qualified(&ident) else {
3457            continue;
3458        };
3459        if let Some((_, provider)) = declared.iter().find(|(var, _)| var == base) {
3460            vars.push(qualified(&ident, extension, provider)?);
3461        }
3462    }
3463    Ok(vars)
3464}
3465
3466/// Record `node` as a dependent of every distinct provider its formula reads.
3467fn register_formula_dependencies<'a>(
3468    dependents: &mut HashMap<String, Vec<String>>,
3469    node: &str,
3470    providers: impl IntoIterator<Item = &'a str>,
3471) {
3472    let mut seen = HashSet::new();
3473    for provider in providers {
3474        if seen.insert(provider) {
3475            dependents
3476                .entry(provider.to_string())
3477                .or_default()
3478                .push(node.to_string());
3479        }
3480    }
3481}
3482
3483/// Resolve a formula's `<Constant>` and named `<Expression>` declarations into
3484/// sub-ASTs ready for substitution.
3485///
3486/// Declaration order is significant: an `<Expression>` may reference constants
3487/// and expressions declared before it, so each is substituted against what has
3488/// been bound so far. That also makes a self- or forward-reference resolve to
3489/// nothing rather than looping.
3490fn formula_bindings(
3491    node: &str,
3492    declared: &FormulaBindings,
3493) -> Result<HashMap<String, SkAst>, GenApiError> {
3494    let mut bindings: HashMap<String, SkAst> = HashMap::new();
3495    for (name, literal) in &declared.constants {
3496        let value = parse_formula(node, literal)?;
3497        bindings.insert(name.clone(), value);
3498    }
3499    for (name, formula) in &declared.expressions {
3500        let mut ast = parse_formula(node, formula)?;
3501        substitute(&mut ast, &bindings);
3502        bindings.insert(name.clone(), ast);
3503    }
3504    Ok(bindings)
3505}
3506
3507/// Parse `text`, a formula, constant or expression of the node `node`.
3508fn parse_formula(node: &str, text: &str) -> Result<SkAst, GenApiError> {
3509    parse_expression(text).map_err(|source| GenApiError::ExprParse {
3510        name: node.to_string(),
3511        formula: text.to_string(),
3512        source,
3513    })
3514}
3515
3516/// Narrow a formula result to `i64` for an integer-typed feature.
3517///
3518/// An integer formula that stayed integral is exact; one that picked up a
3519/// float along the way (a fractional literal, a transcendental function)
3520/// rounds, as the GenApi integer output rule requires.
3521fn sk_to_i64(name: &str, value: SkValue) -> Result<i64, GenApiError> {
3522    match value {
3523        SkValue::Int(value) => Ok(value),
3524        SkValue::Float(value) => round_to_i64(name, value),
3525    }
3526}
3527
3528/// Arithmetic mode implied by a formula's declared output type.
3529fn eval_mode(output: SkOutput) -> EvalMode {
3530    match output {
3531        SkOutput::Integer => EvalMode::Integer,
3532        SkOutput::Float => EvalMode::Float,
3533    }
3534}
3535
3536/// Map a formula evaluation failure onto the public error type.
3537fn expr_error(name: &str, err: SkEvalError) -> GenApiError {
3538    match err {
3539        SkEvalError::UnknownVariable(var) => GenApiError::UnknownVariable {
3540            name: name.to_string(),
3541            var,
3542        },
3543        other => GenApiError::eval(name, other),
3544    }
3545}
3546
3547/// `names` without repeats, in the order they first appear.
3548fn unique_in_order<'a>(names: impl IntoIterator<Item = &'a str>) -> Vec<String> {
3549    let mut seen = HashSet::new();
3550    names
3551        .into_iter()
3552        .filter(|name| seen.insert(*name))
3553        .map(str::to_string)
3554        .collect()
3555}
3556
3557impl TryFrom<XmlModel> for NodeMap {
3558    type Error = GenApiError;
3559
3560    fn try_from(model: XmlModel) -> Result<Self, Self::Error> {
3561        NodeMap::try_from_xml(model)
3562    }
3563}