Skip to main content

viva_genapi/
swissknife.rs

1//! GenApi formula parser and evaluator.
2//!
3//! Covers the expression language used by `<SwissKnife>`, `<IntSwissKnife>`,
4//! `<Converter>` and `<IntConverter>` nodes:
5//!
6//! - Arithmetic: `+ - * / %` and `**` for power
7//! - Comparison: `< <= > >=`, `=` (equality) and `<>` (inequality)
8//! - Logical: `&& ||`
9//! - Bitwise: `& | ^ ~ << >>`
10//! - Ternary: `condition ? then : else`
11//! - Functions: `SGN NEG ATAN SIN COS TAN ABS EXP LN LG SQRT TRUNC ROUND
12//!   FLOOR CEIL ASIN ACOS`, plus the constants `E` and `PI`
13//!
14//! Two details trip up implementations that reach for a C-like grammar, and
15//! both appear in the majority of real vendor descriptions:
16//!
17//! 1. **`=` is equality, `<>` is inequality.** There is no assignment in the
18//!    language, so `=` is never ambiguous. `==` and `!=` are accepted as
19//!    tolerated aliases.
20//! 2. **Integer formulas evaluate in `i64`, not `f64`.** `IntSwissKnife` and
21//!    `IntConverter` use [`EvalMode::Integer`], where `/` truncates and 64-bit
22//!    register values stay exact. Evaluating `(HIGH << 32) | LOW` in `f64`
23//!    silently loses the low bits.
24//!
25//! Operator precedence and the integer/float promotion rules follow the GenApi
26//! specification, cross-checked against the reference implementation in
27//! aravis (`src/arvevaluator.c`: `arv_evaluator_token_infos` for precedence,
28//! the `integer_mode` branches of `arv_evaluator_evaluate` for promotion).
29
30use std::collections::HashSet;
31use std::fmt;
32
33/// Numeric value flowing through a GenApi formula.
34///
35/// The language is dynamically typed over `i64` and `f64`. Keeping the two
36/// apart matters: register values are integers up to 64 bits wide, and `f64`
37/// cannot represent them all exactly.
38#[derive(Debug, Clone, Copy, PartialEq)]
39pub enum Value {
40    /// Integer value.
41    Int(i64),
42    /// Floating point value.
43    Float(f64),
44}
45
46impl Value {
47    /// View the value as an `i64`, truncating a float towards zero.
48    pub fn as_i64(self) -> i64 {
49        match self {
50            Value::Int(value) => value,
51            Value::Float(value) => value as i64,
52        }
53    }
54
55    /// View the value as an `f64`.
56    pub fn as_f64(self) -> f64 {
57        match self {
58            Value::Int(value) => value as f64,
59            Value::Float(value) => value,
60        }
61    }
62
63    /// Whether the value is held as an integer.
64    pub fn is_int(self) -> bool {
65        matches!(self, Value::Int(_))
66    }
67
68    /// Whether the value counts as true in a condition (non-zero).
69    pub fn is_truthy(self) -> bool {
70        match self {
71            Value::Int(value) => value != 0,
72            Value::Float(value) => value != 0.0,
73        }
74    }
75
76    fn from_bool(value: bool) -> Self {
77        Value::Int(i64::from(value))
78    }
79}
80
81impl fmt::Display for Value {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Value::Int(value) => write!(f, "{value}"),
85            Value::Float(value) => write!(f, "{value}"),
86        }
87    }
88}
89
90/// Arithmetic mode for a formula.
91///
92/// `IntSwissKnife` and `IntConverter` declare integer semantics; `SwissKnife`
93/// and `Converter` declare floating point ones. The distinction is observable:
94/// `7 / 2` is `3` in [`EvalMode::Integer`] and `3.5` in [`EvalMode::Float`].
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
96pub enum EvalMode {
97    /// Integer arithmetic: `/` truncates, results stay in `i64`.
98    Integer,
99    /// Floating point arithmetic. Bitwise operators still work on `i64`.
100    #[default]
101    Float,
102}
103
104/// Parsed GenApi formula represented as an abstract syntax tree.
105#[derive(Debug, Clone)]
106#[non_exhaustive]
107pub enum AstNode {
108    /// Numeric literal.
109    Literal(Value),
110    /// Variable lookup resolved at evaluation time.
111    Variable(String),
112    /// Unary operator applied to a sub-expression.
113    Unary {
114        /// Operator kind.
115        op: UnaryOp,
116        /// Operand expression.
117        expr: Box<AstNode>,
118    },
119    /// Binary operator combining two sub-expressions.
120    Binary {
121        /// Operator kind.
122        op: BinaryOp,
123        /// Left-hand side operand.
124        left: Box<AstNode>,
125        /// Right-hand side operand.
126        right: Box<AstNode>,
127    },
128    /// Ternary conditional: `condition ? then_expr : else_expr`.
129    Ternary {
130        /// Condition expression (non-zero is truthy).
131        cond: Box<AstNode>,
132        /// Expression evaluated when condition is truthy.
133        then_expr: Box<AstNode>,
134        /// Expression evaluated when condition is falsy.
135        else_expr: Box<AstNode>,
136    },
137    /// Function call with arguments.
138    FnCall {
139        /// Function name.
140        name: String,
141        /// Arguments to the function.
142        args: Vec<AstNode>,
143    },
144}
145
146/// Binary operator kinds supported by the GenApi formula language.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148#[non_exhaustive]
149pub enum BinaryOp {
150    // Arithmetic
151    /// `+`
152    Add,
153    /// `-`
154    Sub,
155    /// `*`
156    Mul,
157    /// `/`: truncating in integer mode.
158    Div,
159    /// `%`
160    Mod,
161    /// `**`
162    Pow,
163    // Comparison
164    /// `<`
165    Lt,
166    /// `<=`
167    Le,
168    /// `>`
169    Gt,
170    /// `>=`
171    Ge,
172    /// `=` (and the tolerated `==`)
173    Eq,
174    /// `<>` (and the tolerated `!=`)
175    Ne,
176    // Logical
177    /// `&&`
178    And,
179    /// `||`
180    Or,
181    // Bitwise
182    /// `&`
183    BitAnd,
184    /// `|`
185    BitOr,
186    /// `^`
187    BitXor,
188    /// `<<`
189    Shl,
190    /// `>>`
191    Shr,
192}
193
194/// Unary operator kinds supported by the GenApi formula language.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196#[non_exhaustive]
197pub enum UnaryOp {
198    /// Unary `+`.
199    Plus,
200    /// Unary `-`.
201    Minus,
202    /// `!`: logical not.
203    Not,
204    /// `~`: bitwise not.
205    BitNot,
206}
207
208/// Error produced while parsing a GenApi formula.
209#[derive(Debug, Clone)]
210#[non_exhaustive]
211pub struct ParseError {
212    msg: String,
213    offset: usize,
214}
215
216impl ParseError {
217    fn new<S: Into<String>>(msg: S, offset: usize) -> Self {
218        Self {
219            msg: msg.into(),
220            offset,
221        }
222    }
223
224    /// Byte offset within the formula at which the error was detected.
225    pub fn offset(&self) -> usize {
226        self.offset
227    }
228}
229
230impl fmt::Display for ParseError {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        write!(f, "{} (at offset {})", self.msg, self.offset)
233    }
234}
235
236impl std::error::Error for ParseError {}
237
238/// Error produced while evaluating a GenApi formula, or the nodes its
239/// variables read.
240#[derive(Debug, Clone, PartialEq, thiserror::Error)]
241#[non_exhaustive]
242pub enum EvalError {
243    /// Variable referenced by the expression has no bound value.
244    #[error("unknown variable {0}")]
245    UnknownVariable(String),
246    /// Division by zero occurred.
247    #[error("division by zero")]
248    DivisionByZero,
249    /// Unknown function name.
250    #[error("unknown function {0}")]
251    UnknownFunction(String),
252    /// Wrong number of arguments to function.
253    #[error("function {name} expects {expected} args, got {got}")]
254    ArityMismatch {
255        /// The function.
256        name: String,
257        /// The arguments it takes.
258        expected: usize,
259        /// The arguments given.
260        got: usize,
261    },
262    /// An integer was needed and the result is not one: not finite, beyond
263    /// `i64`, or not whole.
264    #[error("{0} is not a representable integer")]
265    NotAnInteger(f64),
266    /// A value depends on itself: through formula variables, `<pValue>`
267    /// delegation, or a predicate that reads the node it gates.
268    #[error("cyclic dependency through {0}")]
269    Cycle(String),
270    /// A variable reads the `.Min`, `.Max` or `.Inc` of a node that declares
271    /// none.
272    #[error("{var}: {provider} declares no {limit}")]
273    NoLimit {
274        /// The variable as the formula names it.
275        var: String,
276        /// The node it reads.
277        provider: String,
278        /// `"minimum"`, `"maximum"` or `"increment"`.
279        limit: &'static str,
280    },
281}
282
283/// Parse a GenApi formula into an [`AstNode`].
284pub fn parse_expression(input: &str) -> Result<AstNode, ParseError> {
285    let mut parser = Parser::new(input)?;
286    let expr = parser.parse_ternary()?;
287    if !matches!(parser.lookahead, Token::End) {
288        return Err(ParseError::new("unexpected trailing tokens", parser.pos));
289    }
290    Ok(expr)
291}
292
293/// Value of a GenApi built-in constant, if `name` denotes one.
294///
295/// The language defines `E` and `PI` as constants rather than variables, so a
296/// formula may reference them without a matching `<pVariable>`. Matching is
297/// case-insensitive, as in the reference implementation.
298pub fn builtin_constant(name: &str) -> Option<Value> {
299    match name.to_ascii_lowercase().as_str() {
300        "e" => Some(Value::Float(std::f64::consts::E)),
301        "pi" => Some(Value::Float(std::f64::consts::PI)),
302        _ => None,
303    }
304}
305
306/// Whether `name` denotes a GenApi built-in constant.
307///
308/// Callers validating that every identifier in a formula has a `<pVariable>`
309/// must exempt these.
310pub fn is_builtin_constant(name: &str) -> bool {
311    builtin_constant(name).is_some()
312}
313
314/// The property of a `<pVariable>`'s node that a formula identifier reads.
315///
316/// GenICam Standard v2.1.1, §2.8.13 (SwissKnife, IntSwissKnife, Converter,
317/// and IntConverter): "you can access the minimum, maximum, and increment of a
318/// node by using the variable name extensions .Min, .Max, .Inc, and – for
319/// completeness – also .Value. In addition .Entry.Name is allowed which
320/// accesses the integer value of an EnumEntry described by Name."
321///
322/// The standard's own example puts the extension in the declaration —
323/// `<pVariable Name="Gain.Max">Gain</pVariable>` — and a formula may also
324/// qualify a plainly declared variable (`V1.Min` with only `V1` declared).
325/// Both resolve to the same thing.
326#[derive(Debug, Clone, PartialEq, Eq)]
327#[non_exhaustive]
328pub enum VarAttr {
329    /// The node's value — what a plain identifier reads.
330    Value,
331    /// The node's minimum (`<pMin>` or `<Min>`).
332    Min,
333    /// The node's maximum (`<pMax>` or `<Max>`).
334    Max,
335    /// The node's increment (`<Inc>`, 1 when undeclared).
336    Inc,
337    /// The integer value of the enumeration entry with this `Name`.
338    Entry(String),
339}
340
341impl VarAttr {
342    /// Parse the extension after a variable name's first `.`: `Value`, `Min`,
343    /// `Max`, `Inc` or `Entry.<EntryName>`.
344    ///
345    /// The keyword is matched case-insensitively, since formula variables are
346    /// conventionally upper case; the entry name is matched exactly. Returns
347    /// `None` for anything else.
348    pub fn parse(extension: &str) -> Option<Self> {
349        let (keyword, rest) = match extension.split_once('.') {
350            Some((keyword, rest)) => (keyword, Some(rest)),
351            None => (extension, None),
352        };
353        let attr = match (keyword.to_ascii_lowercase().as_str(), rest) {
354            ("value", None) => VarAttr::Value,
355            ("min", None) => VarAttr::Min,
356            ("max", None) => VarAttr::Max,
357            ("inc", None) => VarAttr::Inc,
358            ("entry", Some(entry)) if !entry.is_empty() && !entry.contains('.') => {
359                VarAttr::Entry(entry.to_string())
360            }
361            _ => return None,
362        };
363        Some(attr)
364    }
365}
366
367/// Split a qualified identifier such as `V1.Min` at its first `.`.
368///
369/// Returns `None` for a plain identifier. The lexer admits `.` inside an
370/// identifier (a number such as `1.5` never reaches here, because it starts
371/// with a digit), so this is where a variable is told apart from its
372/// extension.
373pub fn split_qualified(ident: &str) -> Option<(&str, &str)> {
374    ident.split_once('.')
375}
376
377/// Evaluate an [`AstNode`] using the provided variable resolver.
378///
379/// The resolver receives variable identifiers and must return their value.
380/// An identifier the resolver rejects with [`EvalError::UnknownVariable`] is
381/// retried against the built-in constants before the error is propagated, so a
382/// declared `<pVariable>` always shadows a same-named constant.
383pub fn evaluate(
384    ast: &AstNode,
385    vars: &mut dyn FnMut(&str) -> Result<Value, EvalError>,
386    mode: EvalMode,
387) -> Result<Value, EvalError> {
388    match ast {
389        AstNode::Literal(value) => Ok(*value),
390        AstNode::Variable(name) => match vars(name) {
391            Ok(value) => Ok(value),
392            Err(EvalError::UnknownVariable(_)) => {
393                builtin_constant(name).ok_or_else(|| EvalError::UnknownVariable(name.clone()))
394            }
395            Err(other) => Err(other),
396        },
397        AstNode::Unary { op, expr } => {
398            let inner = evaluate(expr, vars, mode)?;
399            Ok(eval_unary(*op, inner, mode))
400        }
401        AstNode::Binary { op, left, right } => {
402            // Short-circuit evaluation for logical operators
403            match op {
404                BinaryOp::And => {
405                    let lhs = evaluate(left, vars, mode)?;
406                    if !lhs.is_truthy() {
407                        return Ok(Value::from_bool(false));
408                    }
409                    let rhs = evaluate(right, vars, mode)?;
410                    Ok(Value::from_bool(rhs.is_truthy()))
411                }
412                BinaryOp::Or => {
413                    let lhs = evaluate(left, vars, mode)?;
414                    if lhs.is_truthy() {
415                        return Ok(Value::from_bool(true));
416                    }
417                    let rhs = evaluate(right, vars, mode)?;
418                    Ok(Value::from_bool(rhs.is_truthy()))
419                }
420                _ => {
421                    let lhs = evaluate(left, vars, mode)?;
422                    let rhs = evaluate(right, vars, mode)?;
423                    eval_binary(*op, lhs, rhs, mode)
424                }
425            }
426        }
427        AstNode::Ternary {
428            cond,
429            then_expr,
430            else_expr,
431        } => {
432            if evaluate(cond, vars, mode)?.is_truthy() {
433                evaluate(then_expr, vars, mode)
434            } else {
435                evaluate(else_expr, vars, mode)
436            }
437        }
438        AstNode::FnCall { name, args } => {
439            let evaluated: Result<Vec<Value>, _> =
440                args.iter().map(|a| evaluate(a, vars, mode)).collect();
441            let arg_vals = evaluated?;
442            eval_function(name, &arg_vals, mode)
443        }
444    }
445}
446
447fn eval_unary(op: UnaryOp, value: Value, mode: EvalMode) -> Value {
448    match op {
449        UnaryOp::Plus => value,
450        UnaryOp::Minus => {
451            if mode == EvalMode::Integer || value.is_int() {
452                Value::Int(value.as_i64().wrapping_neg())
453            } else {
454                Value::Float(-value.as_f64())
455            }
456        }
457        UnaryOp::Not => Value::from_bool(!value.is_truthy()),
458        UnaryOp::BitNot => Value::Int(!value.as_i64()),
459    }
460}
461
462/// Whether an arithmetic result should stay integral.
463fn integral(mode: EvalMode, lhs: Value, rhs: Value) -> bool {
464    mode == EvalMode::Integer || (lhs.is_int() && rhs.is_int())
465}
466
467/// Shift counts are masked to the register width, matching the reference
468/// implementation's reliance on hardware shift semantics. Without this,
469/// `HIGH << 32` on a wide value panics in a debug build.
470fn shift_amount(value: Value) -> u32 {
471    (value.as_i64() as u64 & 63) as u32
472}
473
474fn eval_binary(op: BinaryOp, lhs: Value, rhs: Value, mode: EvalMode) -> Result<Value, EvalError> {
475    Ok(match op {
476        BinaryOp::Add => {
477            if integral(mode, lhs, rhs) {
478                Value::Int(lhs.as_i64().wrapping_add(rhs.as_i64()))
479            } else {
480                Value::Float(lhs.as_f64() + rhs.as_f64())
481            }
482        }
483        BinaryOp::Sub => {
484            if integral(mode, lhs, rhs) {
485                Value::Int(lhs.as_i64().wrapping_sub(rhs.as_i64()))
486            } else {
487                Value::Float(lhs.as_f64() - rhs.as_f64())
488            }
489        }
490        BinaryOp::Mul => {
491            if integral(mode, lhs, rhs) {
492                Value::Int(lhs.as_i64().wrapping_mul(rhs.as_i64()))
493            } else {
494                Value::Float(lhs.as_f64() * rhs.as_f64())
495            }
496        }
497        // Division is the one operator where the mode alone decides: an
498        // integer formula truncates even when a literal happens to be
499        // fractional, and a float formula never truncates.
500        BinaryOp::Div => {
501            if mode == EvalMode::Integer {
502                let divisor = rhs.as_i64();
503                if divisor == 0 {
504                    return Err(EvalError::DivisionByZero);
505                }
506                Value::Int(lhs.as_i64().wrapping_div(divisor))
507            } else {
508                let divisor = rhs.as_f64();
509                if divisor == 0.0 {
510                    return Err(EvalError::DivisionByZero);
511                }
512                Value::Float(lhs.as_f64() / divisor)
513            }
514        }
515        BinaryOp::Mod => {
516            let divisor = rhs.as_i64();
517            if divisor == 0 {
518                return Err(EvalError::DivisionByZero);
519            }
520            Value::Int(lhs.as_i64().wrapping_rem(divisor))
521        }
522        BinaryOp::Pow => {
523            let result = lhs.as_f64().powf(rhs.as_f64());
524            if mode == EvalMode::Integer {
525                Value::Int(result as i64)
526            } else {
527                Value::Float(result)
528            }
529        }
530        BinaryOp::Lt => compare(lhs, rhs, mode, |a, b| a < b, |a, b| a < b),
531        BinaryOp::Le => compare(lhs, rhs, mode, |a, b| a <= b, |a, b| a <= b),
532        BinaryOp::Gt => compare(lhs, rhs, mode, |a, b| a > b, |a, b| a > b),
533        BinaryOp::Ge => compare(lhs, rhs, mode, |a, b| a >= b, |a, b| a >= b),
534        BinaryOp::Eq => compare(lhs, rhs, mode, |a, b| a == b, |a, b| a == b),
535        BinaryOp::Ne => compare(lhs, rhs, mode, |a, b| a != b, |a, b| a != b),
536        BinaryOp::And | BinaryOp::Or => unreachable!("handled by short-circuit"),
537        BinaryOp::BitAnd => Value::Int(lhs.as_i64() & rhs.as_i64()),
538        BinaryOp::BitOr => Value::Int(lhs.as_i64() | rhs.as_i64()),
539        BinaryOp::BitXor => Value::Int(lhs.as_i64() ^ rhs.as_i64()),
540        BinaryOp::Shl => Value::Int(lhs.as_i64().wrapping_shl(shift_amount(rhs))),
541        BinaryOp::Shr => Value::Int(lhs.as_i64().wrapping_shr(shift_amount(rhs))),
542    })
543}
544
545/// Compare two values, exactly when both sides are integral.
546///
547/// Comparing register values through `f64` would make `0x100000000000001` and
548/// `0x100000000000000` equal; comparing them as `i64` does not.
549fn compare(
550    lhs: Value,
551    rhs: Value,
552    mode: EvalMode,
553    int_cmp: fn(i64, i64) -> bool,
554    float_cmp: fn(f64, f64) -> bool,
555) -> Value {
556    if integral(mode, lhs, rhs) {
557        Value::from_bool(int_cmp(lhs.as_i64(), rhs.as_i64()))
558    } else {
559        Value::from_bool(float_cmp(lhs.as_f64(), rhs.as_f64()))
560    }
561}
562
563fn eval_function(name: &str, args: &[Value], mode: EvalMode) -> Result<Value, EvalError> {
564    // GenApi function names are case-insensitive; vendors write both `LG` and
565    // `lg`, `SGN` and `sgn`.
566    let name_lower = name.to_ascii_lowercase();
567
568    // Transcendental functions always produce a float, matching the reference
569    // implementation.
570    let float_fn = |f: fn(f64) -> f64| -> Result<Value, EvalError> {
571        expect_args(name, args, 1).map(|a| Value::Float(f(a[0].as_f64())))
572    };
573    // Functions that preserve integrality when their argument is integral.
574    let rounding_fn = |f: fn(f64) -> f64| -> Result<Value, EvalError> {
575        expect_args(name, args, 1).map(|a| {
576            if mode == EvalMode::Integer || a[0].is_int() {
577                Value::Int(a[0].as_i64())
578            } else {
579                Value::Float(f(a[0].as_f64()))
580            }
581        })
582    };
583
584    match name_lower.as_str() {
585        // --- GenApi standard functions -----------------------------------
586        "sin" => float_fn(f64::sin),
587        "cos" => float_fn(f64::cos),
588        "tan" => float_fn(f64::tan),
589        "asin" => float_fn(f64::asin),
590        "acos" => float_fn(f64::acos),
591        "atan" => float_fn(f64::atan),
592        "sqrt" => float_fn(f64::sqrt),
593        "exp" => float_fn(f64::exp),
594        "ln" => float_fn(f64::ln),
595        // `LG` is the base-10 logarithm. Omitting it made every Baumer TXG
596        // description fail at evaluation time.
597        "lg" => float_fn(f64::log10),
598        "trunc" => rounding_fn(f64::trunc),
599        "floor" => rounding_fn(f64::floor),
600        "ceil" => rounding_fn(f64::ceil),
601        "round" => rounding_fn(f64::round),
602        "abs" => expect_args(name, args, 1).map(|a| {
603            if mode == EvalMode::Integer || a[0].is_int() {
604                Value::Int(a[0].as_i64().wrapping_abs())
605            } else {
606                Value::Float(a[0].as_f64().abs())
607            }
608        }),
609        "neg" => expect_args(name, args, 1).map(|a| eval_unary(UnaryOp::Minus, a[0], mode)),
610        "sgn" | "sign" => expect_args(name, args, 1).map(|a| {
611            if mode == EvalMode::Integer || a[0].is_int() {
612                Value::Int(a[0].as_i64().signum())
613            } else {
614                let value = a[0].as_f64();
615                Value::Float(if value > 0.0 {
616                    1.0
617                } else if value < 0.0 {
618                    -1.0
619                } else {
620                    0.0
621                })
622            }
623        }),
624        // The constants are usually written bare, but the call form appears
625        // in the wild too.
626        "e" => expect_args(name, args, 0).map(|_| Value::Float(std::f64::consts::E)),
627        "pi" => expect_args(name, args, 0).map(|_| Value::Float(std::f64::consts::PI)),
628
629        // --- Accepted extensions ------------------------------------------
630        // Not in the GenApi standard, but harmless to accept and already
631        // relied on by our own fixtures.
632        "log" | "log10" => float_fn(f64::log10),
633        "log2" => float_fn(f64::log2),
634        "atan2" => {
635            expect_args(name, args, 2).map(|a| Value::Float(a[0].as_f64().atan2(a[1].as_f64())))
636        }
637        "pow" => eval_binary(BinaryOp::Pow, args_at(name, args, 2)?[0], args[1], mode),
638        "fmod" => eval_binary(BinaryOp::Mod, args_at(name, args, 2)?[0], args[1], mode),
639        "min" => expect_args(name, args, 2).map(|a| pick(a[0], a[1], mode, true)),
640        "max" => expect_args(name, args, 2).map(|a| pick(a[0], a[1], mode, false)),
641
642        _ => Err(EvalError::UnknownFunction(name.to_string())),
643    }
644}
645
646fn pick(lhs: Value, rhs: Value, mode: EvalMode, want_min: bool) -> Value {
647    let take_lhs = if integral(mode, lhs, rhs) {
648        (lhs.as_i64() <= rhs.as_i64()) == want_min
649    } else {
650        (lhs.as_f64() <= rhs.as_f64()) == want_min
651    };
652    if take_lhs { lhs } else { rhs }
653}
654
655fn args_at<'a>(name: &str, args: &'a [Value], expected: usize) -> Result<&'a [Value], EvalError> {
656    expect_args(name, args, expected)
657}
658
659fn expect_args<'a>(
660    name: &str,
661    args: &'a [Value],
662    expected: usize,
663) -> Result<&'a [Value], EvalError> {
664    if args.len() != expected {
665        Err(EvalError::ArityMismatch {
666            name: name.to_string(),
667            expected,
668            got: args.len(),
669        })
670    } else {
671        Ok(args)
672    }
673}
674
675/// Replace variable references with sub-expressions.
676///
677/// Backs the GenApi `<Constant>` and named `<Expression>` elements, which let
678/// a formula name a literal or a reusable sub-formula:
679///
680/// ```xml
681/// <IntSwissKnife Name="Example">
682///   <pVariable Name="X">X</pVariable>
683///   <Constant Name="TEN">10</Constant>
684///   <Expression Name="XPLUS2">TEN + X</Expression>
685///   <Formula>TEN * XPLUS2</Formula>
686/// </IntSwissKnife>
687/// ```
688///
689/// Substitution happens once, at build time, so evaluation stays a plain walk
690/// over the tree.
691pub fn substitute(ast: &mut AstNode, bindings: &std::collections::HashMap<String, AstNode>) {
692    match ast {
693        AstNode::Literal(_) => {}
694        AstNode::Variable(name) => {
695            if let Some(replacement) = bindings.get(name.as_str()) {
696                *ast = replacement.clone();
697            }
698        }
699        AstNode::Unary { expr, .. } => substitute(expr, bindings),
700        AstNode::Binary { left, right, .. } => {
701            substitute(left, bindings);
702            substitute(right, bindings);
703        }
704        AstNode::Ternary {
705            cond,
706            then_expr,
707            else_expr,
708        } => {
709            substitute(cond, bindings);
710            substitute(then_expr, bindings);
711            substitute(else_expr, bindings);
712        }
713        AstNode::FnCall { args, .. } => {
714            for arg in args {
715                substitute(arg, bindings);
716            }
717        }
718    }
719}
720
721/// Collect all variable identifiers referenced by the AST.
722///
723/// Built-in constants are reported like any other identifier; callers that
724/// validate against `<pVariable>` declarations should filter them with
725/// [`is_builtin_constant`].
726pub fn collect_identifiers(ast: &AstNode, out: &mut HashSet<String>) {
727    match ast {
728        AstNode::Literal(_) => {}
729        AstNode::Variable(name) => {
730            out.insert(name.clone());
731        }
732        AstNode::Unary { expr, .. } => collect_identifiers(expr, out),
733        AstNode::Binary { left, right, .. } => {
734            collect_identifiers(left, out);
735            collect_identifiers(right, out);
736        }
737        AstNode::Ternary {
738            cond,
739            then_expr,
740            else_expr,
741        } => {
742            collect_identifiers(cond, out);
743            collect_identifiers(then_expr, out);
744            collect_identifiers(else_expr, out);
745        }
746        AstNode::FnCall { args, .. } => {
747            for arg in args {
748                collect_identifiers(arg, out);
749            }
750        }
751    }
752}
753
754// ============================================================================
755// Lexer
756// ============================================================================
757
758#[derive(Debug, Clone, PartialEq)]
759enum Token {
760    Int(i64),
761    Float(f64),
762    Ident(String),
763    // Arithmetic
764    Plus,
765    Minus,
766    Star,
767    Slash,
768    Percent,
769    StarStar, // **
770    // Comparison
771    Lt,
772    Le,
773    Gt,
774    Ge,
775    Eq, // `=` (and the tolerated `==`)
776    Ne, // `<>` (and the tolerated `!=`)
777    // Logical
778    AmpAmp,
779    PipePipe,
780    Bang,
781    // Bitwise
782    Amp,
783    Pipe,
784    Caret,
785    Tilde,
786    LtLt,
787    GtGt,
788    // Ternary
789    Question,
790    Colon,
791    // Grouping
792    LParen,
793    RParen,
794    Comma,
795    End,
796}
797
798struct Lexer<'a> {
799    input: &'a [u8],
800    pos: usize,
801}
802
803impl<'a> Lexer<'a> {
804    fn new(input: &'a str) -> Self {
805        Lexer {
806            input: input.as_bytes(),
807            pos: 0,
808        }
809    }
810
811    fn peek(&self) -> Option<u8> {
812        self.input.get(self.pos).copied()
813    }
814
815    fn peek_next(&self) -> Option<u8> {
816        self.input.get(self.pos + 1).copied()
817    }
818
819    fn advance_by(&mut self, n: usize) {
820        self.pos += n;
821    }
822
823    fn next_token(&mut self) -> Result<Token, ParseError> {
824        self.skip_ws();
825        let Some(byte) = self.peek() else {
826            return Ok(Token::End);
827        };
828
829        match byte {
830            b'0'..=b'9' | b'.' => self.lex_number(),
831            b'a'..=b'z' | b'A'..=b'Z' | b'_' => self.lex_ident(),
832            b'+' => {
833                self.advance_by(1);
834                Ok(Token::Plus)
835            }
836            b'-' => {
837                self.advance_by(1);
838                Ok(Token::Minus)
839            }
840            b'*' => {
841                if self.peek_next() == Some(b'*') {
842                    self.advance_by(2);
843                    Ok(Token::StarStar)
844                } else {
845                    self.advance_by(1);
846                    Ok(Token::Star)
847                }
848            }
849            b'/' => {
850                self.advance_by(1);
851                Ok(Token::Slash)
852            }
853            b'%' => {
854                self.advance_by(1);
855                Ok(Token::Percent)
856            }
857            b'<' => match self.peek_next() {
858                Some(b'=') => {
859                    self.advance_by(2);
860                    Ok(Token::Le)
861                }
862                Some(b'<') => {
863                    self.advance_by(2);
864                    Ok(Token::LtLt)
865                }
866                // `<>` is the GenApi inequality operator.
867                Some(b'>') => {
868                    self.advance_by(2);
869                    Ok(Token::Ne)
870                }
871                _ => {
872                    self.advance_by(1);
873                    Ok(Token::Lt)
874                }
875            },
876            b'>' => match self.peek_next() {
877                Some(b'=') => {
878                    self.advance_by(2);
879                    Ok(Token::Ge)
880                }
881                Some(b'>') => {
882                    self.advance_by(2);
883                    Ok(Token::GtGt)
884                }
885                _ => {
886                    self.advance_by(1);
887                    Ok(Token::Gt)
888                }
889            },
890            // `=` is equality. The language has no assignment, so there is
891            // nothing to disambiguate; `==` is accepted as an alias.
892            b'=' => {
893                if self.peek_next() == Some(b'=') {
894                    self.advance_by(2);
895                } else {
896                    self.advance_by(1);
897                }
898                Ok(Token::Eq)
899            }
900            b'!' => {
901                if self.peek_next() == Some(b'=') {
902                    self.advance_by(2);
903                    Ok(Token::Ne)
904                } else {
905                    self.advance_by(1);
906                    Ok(Token::Bang)
907                }
908            }
909            b'&' => {
910                if self.peek_next() == Some(b'&') {
911                    self.advance_by(2);
912                    Ok(Token::AmpAmp)
913                } else {
914                    self.advance_by(1);
915                    Ok(Token::Amp)
916                }
917            }
918            b'|' => {
919                if self.peek_next() == Some(b'|') {
920                    self.advance_by(2);
921                    Ok(Token::PipePipe)
922                } else {
923                    self.advance_by(1);
924                    Ok(Token::Pipe)
925                }
926            }
927            b'^' => {
928                self.advance_by(1);
929                Ok(Token::Caret)
930            }
931            b'~' => {
932                self.advance_by(1);
933                Ok(Token::Tilde)
934            }
935            b'?' => {
936                self.advance_by(1);
937                Ok(Token::Question)
938            }
939            b':' => {
940                self.advance_by(1);
941                Ok(Token::Colon)
942            }
943            b'(' => {
944                self.advance_by(1);
945                Ok(Token::LParen)
946            }
947            b')' => {
948                self.advance_by(1);
949                Ok(Token::RParen)
950            }
951            b',' => {
952                self.advance_by(1);
953                Ok(Token::Comma)
954            }
955            _ => Err(ParseError::new(
956                format!("unexpected character '{}'", byte as char),
957                self.pos,
958            )),
959        }
960    }
961
962    fn skip_ws(&mut self) {
963        while let Some(byte) = self.peek() {
964            if byte.is_ascii_whitespace() {
965                self.pos += 1;
966            } else {
967                break;
968            }
969        }
970    }
971
972    fn lex_number(&mut self) -> Result<Token, ParseError> {
973        let start = self.pos;
974
975        // Check for hex literal: 0x or 0X
976        if self.peek() == Some(b'0') {
977            let next = self.input.get(self.pos + 1).copied();
978            if next == Some(b'x') || next == Some(b'X') {
979                self.pos += 2; // skip "0x"
980                let hex_start = self.pos;
981                while let Some(b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F') = self.peek() {
982                    self.pos += 1;
983                }
984                if self.pos == hex_start {
985                    return Err(ParseError::new("hex literal has no digits", start));
986                }
987                let hex_text = std::str::from_utf8(&self.input[hex_start..self.pos])
988                    .map_err(|_| ParseError::new("invalid UTF-8 in hex literal", start))?;
989                let value = u64::from_str_radix(hex_text, 16).map_err(|_| {
990                    ParseError::new(format!("invalid hex literal: 0x{hex_text}"), start)
991                })?;
992                // Masks such as 0xFFFFFFFFFFFFFFFF wrap to their two's
993                // complement, as they do in the reference implementation.
994                return Ok(Token::Int(value as i64));
995            }
996        }
997
998        let mut seen_digit = false;
999        let mut seen_dot = false;
1000        let mut seen_exp = false;
1001
1002        while let Some(byte) = self.peek() {
1003            match byte {
1004                b'0'..=b'9' => {
1005                    seen_digit = true;
1006                    self.pos += 1;
1007                }
1008                b'.' if !seen_dot && !seen_exp => {
1009                    seen_dot = true;
1010                    self.pos += 1;
1011                }
1012                b'e' | b'E' if !seen_exp && seen_digit => {
1013                    // `1e3` is scientific notation, but `1 e` would be a
1014                    // literal followed by the constant E. Only treat it as an
1015                    // exponent when a digit or sign follows.
1016                    match self.peek_next() {
1017                        Some(b'0'..=b'9' | b'+' | b'-') => {
1018                            seen_exp = true;
1019                            self.pos += 1;
1020                            if let Some(b'+' | b'-') = self.peek() {
1021                                self.pos += 1;
1022                            }
1023                        }
1024                        _ => break,
1025                    }
1026                }
1027                _ => break,
1028            }
1029        }
1030        if !seen_digit {
1031            return Err(ParseError::new("invalid number literal", start));
1032        }
1033        let slice = &self.input[start..self.pos];
1034        let text = std::str::from_utf8(slice)
1035            .map_err(|_| ParseError::new("invalid UTF-8 in number", start))?;
1036        if !seen_dot
1037            && !seen_exp
1038            && let Ok(value) = text.parse::<i64>()
1039        {
1040            return Ok(Token::Int(value));
1041        }
1042        let value = text
1043            .parse::<f64>()
1044            .map_err(|_| ParseError::new(format!("failed to parse number: {text}"), start))?;
1045        Ok(Token::Float(value))
1046    }
1047
1048    fn lex_ident(&mut self) -> Result<Token, ParseError> {
1049        let start = self.pos;
1050        self.pos += 1;
1051        while let Some(byte) = self.peek() {
1052            if byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'.' {
1053                self.pos += 1;
1054            } else {
1055                break;
1056            }
1057        }
1058        let slice = &self.input[start..self.pos];
1059        let text = std::str::from_utf8(slice)
1060            .map_err(|_| ParseError::new("invalid UTF-8 in identifier", start))?;
1061        Ok(Token::Ident(text.to_string()))
1062    }
1063}
1064
1065// ============================================================================
1066// Parser
1067//
1068// Precedence, loosest to tightest. This chain mirrors the priority column of
1069// aravis' `arv_evaluator_token_infos` table, which is itself the GenApi
1070// specification's table:
1071//
1072//  1. Ternary:        ?:      (right-associative)
1073//  2. Logical OR:     ||
1074//  3. Logical AND:    &&
1075//  4. Bitwise OR:     |
1076//  5. Bitwise XOR:    ^
1077//  6. Bitwise AND:    &
1078//  7. Equality:       =  <>
1079//  8. Comparison:     <  <=  >  >=
1080//  9. Shift:          << >>
1081// 10. Additive:       +  -
1082// 11. Multiplicative: *  /  %
1083// 12. Power:          **      (right-associative)
1084// 13. Unary:          +  -  !  ~
1085// 14. Primary:        numbers, identifiers, function calls, (expr)
1086//
1087// Note that equality binds *looser* than comparison, so `A < B = C` parses as
1088// `(A < B) = C`. That is what the standard says, and vendors rely on it.
1089// ============================================================================
1090
1091struct Parser<'a> {
1092    lexer: Lexer<'a>,
1093    lookahead: Token,
1094    /// Offset of the start of the lookahead token, for error reporting.
1095    pos: usize,
1096}
1097
1098impl<'a> Parser<'a> {
1099    fn new(input: &'a str) -> Result<Self, ParseError> {
1100        let mut lexer = Lexer::new(input);
1101        let lookahead = lexer.next_token()?;
1102        let pos = lexer.pos;
1103        Ok(Parser {
1104            lexer,
1105            lookahead,
1106            pos,
1107        })
1108    }
1109
1110    fn advance(&mut self) -> Result<(), ParseError> {
1111        self.lookahead = self.lexer.next_token()?;
1112        self.pos = self.lexer.pos;
1113        Ok(())
1114    }
1115
1116    // Level 1: Ternary
1117    fn parse_ternary(&mut self) -> Result<AstNode, ParseError> {
1118        let cond = self.parse_or()?;
1119        if matches!(self.lookahead, Token::Question) {
1120            self.advance()?;
1121            let then_expr = self.parse_ternary()?;
1122            if !matches!(self.lookahead, Token::Colon) {
1123                return Err(ParseError::new(
1124                    "expected ':' in ternary expression",
1125                    self.pos,
1126                ));
1127            }
1128            self.advance()?;
1129            let else_expr = self.parse_ternary()?;
1130            Ok(AstNode::Ternary {
1131                cond: Box::new(cond),
1132                then_expr: Box::new(then_expr),
1133                else_expr: Box::new(else_expr),
1134            })
1135        } else {
1136            Ok(cond)
1137        }
1138    }
1139
1140    // Level 2: Logical OR
1141    fn parse_or(&mut self) -> Result<AstNode, ParseError> {
1142        let mut node = self.parse_and()?;
1143        while matches!(self.lookahead, Token::PipePipe) {
1144            self.advance()?;
1145            let rhs = self.parse_and()?;
1146            node = AstNode::Binary {
1147                op: BinaryOp::Or,
1148                left: Box::new(node),
1149                right: Box::new(rhs),
1150            };
1151        }
1152        Ok(node)
1153    }
1154
1155    // Level 3: Logical AND
1156    fn parse_and(&mut self) -> Result<AstNode, ParseError> {
1157        let mut node = self.parse_bitor()?;
1158        while matches!(self.lookahead, Token::AmpAmp) {
1159            self.advance()?;
1160            let rhs = self.parse_bitor()?;
1161            node = AstNode::Binary {
1162                op: BinaryOp::And,
1163                left: Box::new(node),
1164                right: Box::new(rhs),
1165            };
1166        }
1167        Ok(node)
1168    }
1169
1170    // Level 4: Bitwise OR
1171    fn parse_bitor(&mut self) -> Result<AstNode, ParseError> {
1172        let mut node = self.parse_bitxor()?;
1173        while matches!(self.lookahead, Token::Pipe) {
1174            self.advance()?;
1175            let rhs = self.parse_bitxor()?;
1176            node = AstNode::Binary {
1177                op: BinaryOp::BitOr,
1178                left: Box::new(node),
1179                right: Box::new(rhs),
1180            };
1181        }
1182        Ok(node)
1183    }
1184
1185    // Level 5: Bitwise XOR
1186    fn parse_bitxor(&mut self) -> Result<AstNode, ParseError> {
1187        let mut node = self.parse_bitand()?;
1188        while matches!(self.lookahead, Token::Caret) {
1189            self.advance()?;
1190            let rhs = self.parse_bitand()?;
1191            node = AstNode::Binary {
1192                op: BinaryOp::BitXor,
1193                left: Box::new(node),
1194                right: Box::new(rhs),
1195            };
1196        }
1197        Ok(node)
1198    }
1199
1200    // Level 6: Bitwise AND
1201    fn parse_bitand(&mut self) -> Result<AstNode, ParseError> {
1202        let mut node = self.parse_equality()?;
1203        while matches!(self.lookahead, Token::Amp) {
1204            self.advance()?;
1205            let rhs = self.parse_equality()?;
1206            node = AstNode::Binary {
1207                op: BinaryOp::BitAnd,
1208                left: Box::new(node),
1209                right: Box::new(rhs),
1210            };
1211        }
1212        Ok(node)
1213    }
1214
1215    // Level 7: Equality
1216    fn parse_equality(&mut self) -> Result<AstNode, ParseError> {
1217        let mut node = self.parse_comparison()?;
1218        loop {
1219            let op = match &self.lookahead {
1220                Token::Eq => BinaryOp::Eq,
1221                Token::Ne => BinaryOp::Ne,
1222                _ => break,
1223            };
1224            self.advance()?;
1225            let rhs = self.parse_comparison()?;
1226            node = AstNode::Binary {
1227                op,
1228                left: Box::new(node),
1229                right: Box::new(rhs),
1230            };
1231        }
1232        Ok(node)
1233    }
1234
1235    // Level 8: Comparison
1236    fn parse_comparison(&mut self) -> Result<AstNode, ParseError> {
1237        let mut node = self.parse_shift()?;
1238        loop {
1239            let op = match &self.lookahead {
1240                Token::Lt => BinaryOp::Lt,
1241                Token::Le => BinaryOp::Le,
1242                Token::Gt => BinaryOp::Gt,
1243                Token::Ge => BinaryOp::Ge,
1244                _ => break,
1245            };
1246            self.advance()?;
1247            let rhs = self.parse_shift()?;
1248            node = AstNode::Binary {
1249                op,
1250                left: Box::new(node),
1251                right: Box::new(rhs),
1252            };
1253        }
1254        Ok(node)
1255    }
1256
1257    // Level 9: Shift
1258    fn parse_shift(&mut self) -> Result<AstNode, ParseError> {
1259        let mut node = self.parse_additive()?;
1260        loop {
1261            let op = match &self.lookahead {
1262                Token::LtLt => BinaryOp::Shl,
1263                Token::GtGt => BinaryOp::Shr,
1264                _ => break,
1265            };
1266            self.advance()?;
1267            let rhs = self.parse_additive()?;
1268            node = AstNode::Binary {
1269                op,
1270                left: Box::new(node),
1271                right: Box::new(rhs),
1272            };
1273        }
1274        Ok(node)
1275    }
1276
1277    // Level 10: Additive
1278    fn parse_additive(&mut self) -> Result<AstNode, ParseError> {
1279        let mut node = self.parse_multiplicative()?;
1280        loop {
1281            let op = match &self.lookahead {
1282                Token::Plus => BinaryOp::Add,
1283                Token::Minus => BinaryOp::Sub,
1284                _ => break,
1285            };
1286            self.advance()?;
1287            let rhs = self.parse_multiplicative()?;
1288            node = AstNode::Binary {
1289                op,
1290                left: Box::new(node),
1291                right: Box::new(rhs),
1292            };
1293        }
1294        Ok(node)
1295    }
1296
1297    // Level 11: Multiplicative
1298    fn parse_multiplicative(&mut self) -> Result<AstNode, ParseError> {
1299        let mut node = self.parse_power()?;
1300        loop {
1301            let op = match &self.lookahead {
1302                Token::Star => BinaryOp::Mul,
1303                Token::Slash => BinaryOp::Div,
1304                Token::Percent => BinaryOp::Mod,
1305                _ => break,
1306            };
1307            self.advance()?;
1308            let rhs = self.parse_power()?;
1309            node = AstNode::Binary {
1310                op,
1311                left: Box::new(node),
1312                right: Box::new(rhs),
1313            };
1314        }
1315        Ok(node)
1316    }
1317
1318    // Level 12: Power (right-associative)
1319    fn parse_power(&mut self) -> Result<AstNode, ParseError> {
1320        let base = self.parse_unary()?;
1321        if matches!(self.lookahead, Token::StarStar) {
1322            self.advance()?;
1323            let exp = self.parse_power()?; // Right-associative
1324            Ok(AstNode::Binary {
1325                op: BinaryOp::Pow,
1326                left: Box::new(base),
1327                right: Box::new(exp),
1328            })
1329        } else {
1330            Ok(base)
1331        }
1332    }
1333
1334    // Level 13: Unary
1335    fn parse_unary(&mut self) -> Result<AstNode, ParseError> {
1336        let op = match &self.lookahead {
1337            Token::Plus => UnaryOp::Plus,
1338            Token::Minus => UnaryOp::Minus,
1339            Token::Bang => UnaryOp::Not,
1340            Token::Tilde => UnaryOp::BitNot,
1341            _ => return self.parse_primary(),
1342        };
1343        self.advance()?;
1344        let expr = self.parse_unary()?;
1345        Ok(AstNode::Unary {
1346            op,
1347            expr: Box::new(expr),
1348        })
1349    }
1350
1351    // Level 14: Primary
1352    fn parse_primary(&mut self) -> Result<AstNode, ParseError> {
1353        match self.lookahead.clone() {
1354            Token::Int(value) => {
1355                self.advance()?;
1356                Ok(AstNode::Literal(Value::Int(value)))
1357            }
1358            Token::Float(value) => {
1359                self.advance()?;
1360                Ok(AstNode::Literal(Value::Float(value)))
1361            }
1362            Token::Ident(name) => {
1363                self.advance()?;
1364                // Check for function call
1365                if matches!(self.lookahead, Token::LParen) {
1366                    self.advance()?;
1367                    let mut args = Vec::new();
1368                    if !matches!(self.lookahead, Token::RParen) {
1369                        args.push(self.parse_ternary()?);
1370                        while matches!(self.lookahead, Token::Comma) {
1371                            self.advance()?;
1372                            args.push(self.parse_ternary()?);
1373                        }
1374                    }
1375                    if !matches!(self.lookahead, Token::RParen) {
1376                        return Err(ParseError::new(
1377                            "expected ')' after function arguments",
1378                            self.pos,
1379                        ));
1380                    }
1381                    self.advance()?;
1382                    Ok(AstNode::FnCall { name, args })
1383                } else {
1384                    Ok(AstNode::Variable(name))
1385                }
1386            }
1387            Token::LParen => {
1388                self.advance()?;
1389                let expr = self.parse_ternary()?;
1390                if !matches!(self.lookahead, Token::RParen) {
1391                    return Err(ParseError::new("missing closing ')'", self.pos));
1392                }
1393                self.advance()?;
1394                Ok(expr)
1395            }
1396            Token::End => Err(ParseError::new("unexpected end of expression", self.pos)),
1397            other => Err(ParseError::new(
1398                format!("unexpected token {other:?}"),
1399                self.pos,
1400            )),
1401        }
1402    }
1403}
1404
1405#[cfg(test)]
1406mod tests {
1407    use super::*;
1408
1409    fn eval_with(expr: &str, vars: &[(&str, Value)], mode: EvalMode) -> Value {
1410        let ast = parse_expression(expr).expect("parse failed");
1411        let mut resolver = |name: &str| {
1412            vars.iter()
1413                .find(|(n, _)| *n == name)
1414                .map(|(_, v)| *v)
1415                .ok_or_else(|| EvalError::UnknownVariable(name.to_string()))
1416        };
1417        evaluate(&ast, &mut resolver, mode).expect("eval failed")
1418    }
1419
1420    /// Evaluate in float mode with float variables (the `SwissKnife` case).
1421    fn eval_expr(expr: &str, vars: &[(&str, f64)]) -> f64 {
1422        let bound: Vec<(&str, Value)> = vars.iter().map(|(n, v)| (*n, Value::Float(*v))).collect();
1423        eval_with(expr, &bound, EvalMode::Float).as_f64()
1424    }
1425
1426    /// Evaluate in integer mode with integer variables (the `IntSwissKnife`
1427    /// case).
1428    fn eval_int(expr: &str, vars: &[(&str, i64)]) -> i64 {
1429        let bound: Vec<(&str, Value)> = vars.iter().map(|(n, v)| (*n, Value::Int(*v))).collect();
1430        eval_with(expr, &bound, EvalMode::Integer).as_i64()
1431    }
1432
1433    #[test]
1434    fn basic_arithmetic() {
1435        assert!((eval_expr("(A + 2) * 3 - B / 4", &[("A", 4.0), ("B", 8.0)]) - 16.0).abs() < 1e-6);
1436        assert!((eval_expr("-A + 10 / (B - 5)", &[("A", 3.0), ("B", 7.0)]) - 2.0).abs() < 1e-6);
1437    }
1438
1439    #[test]
1440    fn comparisons() {
1441        assert_eq!(eval_expr("5 < 10", &[]), 1.0);
1442        assert_eq!(eval_expr("5 > 10", &[]), 0.0);
1443        assert_eq!(eval_expr("5 <= 5", &[]), 1.0);
1444        assert_eq!(eval_expr("5 >= 6", &[]), 0.0);
1445        assert_eq!(eval_expr("A < B", &[("A", 3.0), ("B", 5.0)]), 1.0);
1446    }
1447
1448    /// `=` is the GenApi equality operator. Rejecting it made 27 of the 30
1449    /// documents in the vendor corpus unopenable (issue #35).
1450    #[test]
1451    fn single_equals_is_equality() {
1452        assert_eq!(eval_int("5 = 5", &[]), 1);
1453        assert_eq!(eval_int("5 = 6", &[]), 0);
1454        // The formula from the reporter's Hikrobot MV-CS050-10GC.
1455        assert_eq!(
1456            eval_int("(TEMPCTRLMODE = 1) ? 1 : 0", &[("TEMPCTRLMODE", 1)]),
1457            1
1458        );
1459        assert_eq!(
1460            eval_int("(TEMPCTRLMODE = 1) ? 1 : 0", &[("TEMPCTRLMODE", 0)]),
1461            0
1462        );
1463        // `==` stays accepted.
1464        assert_eq!(eval_int("5 == 5", &[]), 1);
1465    }
1466
1467    /// `<>` is the GenApi inequality operator.
1468    #[test]
1469    fn angle_brackets_are_inequality() {
1470        assert_eq!(eval_int("5 <> 6", &[]), 1);
1471        assert_eq!(eval_int("5 <> 5", &[]), 0);
1472        assert_eq!(eval_int("(DS <> 0) ? 1 : 0", &[("DS", 3)]), 1);
1473        // Still distinct from shift and comparison.
1474        assert_eq!(eval_int("1 << 3", &[]), 8);
1475        assert_eq!(eval_int("(1 < 3) = 1", &[]), 1);
1476        // `!=` stays accepted.
1477        assert_eq!(eval_int("5 != 5", &[]), 0);
1478    }
1479
1480    #[test]
1481    fn equality_binds_looser_than_comparison() {
1482        // `A < B = C` is `(A < B) = C`, not `A < (B = C)`.
1483        assert_eq!(eval_int("1 < 3 = 1", &[]), 1);
1484        assert_eq!(eval_int("3 < 1 = 0", &[]), 1);
1485        // And bitwise AND binds looser than equality.
1486        assert_eq!(eval_int("1 & 1 = 1", &[]), 1);
1487    }
1488
1489    #[test]
1490    fn ternary_expression() {
1491        assert_eq!(eval_expr("1 ? 10 : 20", &[]), 10.0);
1492        assert_eq!(eval_expr("0 ? 10 : 20", &[]), 20.0);
1493        assert_eq!(eval_expr("A > 5 ? A : 5", &[("A", 3.0)]), 5.0);
1494        assert_eq!(eval_expr("A > 5 ? A : 5", &[("A", 10.0)]), 10.0);
1495        // Nested ternary
1496        assert_eq!(
1497            eval_expr("A < 0 ? -1 : A > 0 ? 1 : 0", &[("A", -5.0)]),
1498            -1.0
1499        );
1500        assert_eq!(eval_expr("A < 0 ? -1 : A > 0 ? 1 : 0", &[("A", 5.0)]), 1.0);
1501        assert_eq!(eval_expr("A < 0 ? -1 : A > 0 ? 1 : 0", &[("A", 0.0)]), 0.0);
1502    }
1503
1504    #[test]
1505    fn logical_operators() {
1506        assert_eq!(eval_expr("1 && 1", &[]), 1.0);
1507        assert_eq!(eval_expr("1 && 0", &[]), 0.0);
1508        assert_eq!(eval_expr("0 || 1", &[]), 1.0);
1509        assert_eq!(eval_expr("0 || 0", &[]), 0.0);
1510        assert_eq!(eval_expr("!0", &[]), 1.0);
1511        assert_eq!(eval_expr("!1", &[]), 0.0);
1512        assert_eq!(eval_expr("!5", &[]), 0.0);
1513    }
1514
1515    #[test]
1516    fn bitwise_operators() {
1517        assert_eq!(eval_expr("5 & 3", &[]), 1.0); // 101 & 011 = 001
1518        assert_eq!(eval_expr("5 | 3", &[]), 7.0); // 101 | 011 = 111
1519        assert_eq!(eval_expr("5 ^ 3", &[]), 6.0); // 101 ^ 011 = 110
1520        assert_eq!(eval_expr("1 << 3", &[]), 8.0);
1521        assert_eq!(eval_expr("8 >> 2", &[]), 2.0);
1522        assert_eq!(eval_int("~0", &[]), -1);
1523    }
1524
1525    /// A 64-bit register split across two 32-bit halves is the canonical
1526    /// reason integer formulas cannot go through `f64`: the low bits of the
1527    /// result are not representable.
1528    #[test]
1529    fn wide_shifts_stay_exact() {
1530        assert_eq!(
1531            eval_int(
1532                "(HIGH << 32) | LOW",
1533                &[("HIGH", 0x1234_5678), ("LOW", 0x9ABC_DEF1)]
1534            ),
1535            0x1234_5678_9ABC_DEF1
1536        );
1537        // MAC address composition, as used by GevMACAddrHigh/Low.
1538        assert_eq!(
1539            eval_int(
1540                "( ( HI & 0x0000FFFF ) << 32 ) | LO",
1541                &[("HI", 0x205C), ("LO", 0x208F_8000)]
1542            ),
1543            0x205C_208F_8000
1544        );
1545        // A shift wide enough to overflow must not panic in a debug build.
1546        assert_eq!(eval_int("V << 63", &[("V", 3)]), i64::MIN);
1547        assert_eq!(eval_int("V << 64", &[("V", 3)]), 3);
1548    }
1549
1550    /// Integer formulas truncate on division; float formulas do not.
1551    #[test]
1552    fn division_follows_the_mode() {
1553        assert_eq!(eval_int("7 / 2", &[]), 3);
1554        assert_eq!(eval_int("(IDX / 2) * 4", &[("IDX", 3)]), 4);
1555        assert!((eval_expr("7 / 2", &[]) - 3.5).abs() < 1e-9);
1556        // Reported by the Hikrobot: an offset table that only lands on the
1557        // right register because the division truncates.
1558        assert_eq!(eval_int("OFFSET * 4 / 2", &[("OFFSET", 3)]), 6);
1559    }
1560
1561    #[test]
1562    fn hex_literals() {
1563        assert_eq!(eval_expr("0xFF", &[]), 255.0);
1564        assert_eq!(eval_expr("0x10", &[]), 16.0);
1565        assert_eq!(eval_expr("0x0", &[]), 0.0);
1566        assert_eq!(eval_expr("0xDEAD", &[]), 0xDEAD as f64);
1567        assert_eq!(eval_expr("(0x01080001 >> 16) & 0xFF", &[]), 8.0);
1568        // The aravis PayloadSize formula
1569        assert_eq!(
1570            eval_expr(
1571                "W * H * ((PF>>16)&0xFF) / 8",
1572                &[("W", 512.0), ("H", 512.0), ("PF", 0x01080001_u32 as f64)]
1573            ),
1574            512.0 * 512.0 * 8.0 / 8.0
1575        );
1576        // Lowercase hex digits, as Hikrobot writes them.
1577        assert_eq!(eval_int("PF = 0x0110000c", &[("PF", 0x0110000C)]), 1);
1578    }
1579
1580    #[test]
1581    fn power_operator() {
1582        assert!((eval_expr("2 ** 3", &[]) - 8.0).abs() < 1e-6);
1583        assert!((eval_expr("2 ** 3 ** 2", &[]) - 512.0).abs() < 1e-6); // Right-associative: 2^(3^2) = 2^9
1584    }
1585
1586    #[test]
1587    fn modulo_operator() {
1588        assert!((eval_expr("10 % 3", &[]) - 1.0).abs() < 1e-6);
1589        assert!((eval_expr("17 % 5", &[]) - 2.0).abs() < 1e-6);
1590    }
1591
1592    #[test]
1593    fn functions() {
1594        assert!((eval_expr("abs(-5)", &[]) - 5.0).abs() < 1e-6);
1595        assert!((eval_expr("sqrt(16)", &[]) - 4.0).abs() < 1e-6);
1596        assert!((eval_expr("min(3, 7)", &[]) - 3.0).abs() < 1e-6);
1597        assert!((eval_expr("max(3, 7)", &[]) - 7.0).abs() < 1e-6);
1598        assert!((eval_expr("pow(2, 10)", &[]) - 1024.0).abs() < 1e-6);
1599        assert!((eval_expr("floor(3.7)", &[]) - 3.0).abs() < 1e-6);
1600        assert!((eval_expr("ceil(3.2)", &[]) - 4.0).abs() < 1e-6);
1601        assert!((eval_expr("round(3.5)", &[]) - 4.0).abs() < 1e-6);
1602        assert!((eval_expr("sgn(-5)", &[]) - -1.0).abs() < 1e-6);
1603        assert!((eval_expr("sgn(5)", &[]) - 1.0).abs() < 1e-6);
1604        assert!((eval_expr("sgn(0)", &[]) - 0.0).abs() < 1e-6);
1605    }
1606
1607    /// `LG` is base-10 log. Baumer TXG descriptions use it for a dB scale.
1608    #[test]
1609    fn genapi_standard_functions() {
1610        assert!((eval_expr("LG(1000)", &[]) - 3.0).abs() < 1e-9);
1611        assert!((eval_expr("(20 * (LG(TO/1024)))", &[("TO", 10240.0)]) - 20.0).abs() < 1e-9);
1612        assert!((eval_expr("LN(1)", &[]) - 0.0).abs() < 1e-9);
1613        assert!((eval_expr("TRUNC(3.9)", &[]) - 3.0).abs() < 1e-9);
1614        assert!((eval_expr("NEG(4)", &[]) + 4.0).abs() < 1e-9);
1615        // Names are case-insensitive.
1616        assert!((eval_expr("Sqrt(9)", &[]) - 3.0).abs() < 1e-9);
1617    }
1618
1619    #[test]
1620    fn builtin_constants() {
1621        assert!((eval_expr("PI", &[]) - std::f64::consts::PI).abs() < 1e-12);
1622        assert!((eval_expr("E", &[]) - std::f64::consts::E).abs() < 1e-12);
1623        assert!((eval_expr("2 * PI", &[]) - std::f64::consts::TAU).abs() < 1e-12);
1624        // A declared variable shadows the constant.
1625        assert_eq!(eval_expr("E", &[("E", 7.0)]), 7.0);
1626        assert!(is_builtin_constant("pi"));
1627        assert!(!is_builtin_constant("EXPMODE"));
1628    }
1629
1630    #[test]
1631    fn scientific_notation() {
1632        assert!((eval_expr("1e3", &[]) - 1000.0).abs() < 1e-6);
1633        assert!((eval_expr("1.5e-2", &[]) - 0.015).abs() < 1e-9);
1634        assert!((eval_expr("2.5E+3", &[]) - 2500.0).abs() < 1e-6);
1635    }
1636
1637    #[test]
1638    fn division_by_zero_error() {
1639        let ast = parse_expression("A / B").expect("parse");
1640        let mut vars = |name: &str| match name {
1641            "A" => Ok(Value::Float(5.0)),
1642            "B" => Ok(Value::Float(0.0)),
1643            _ => Err(EvalError::UnknownVariable(name.to_string())),
1644        };
1645        let err = evaluate(&ast, &mut vars, EvalMode::Float).expect_err("division by zero");
1646        assert!(matches!(err, EvalError::DivisionByZero));
1647    }
1648
1649    #[test]
1650    fn complex_basler_style_expression() {
1651        // Basler cameras often use expressions like this for exposure time conversion
1652        let expr = "RawValue < 0 ? 0 : RawValue * 1000 / TickFreq";
1653        assert!(
1654            (eval_expr(expr, &[("RawValue", 500.0), ("TickFreq", 1000.0)]) - 500.0).abs() < 1e-6
1655        );
1656        assert_eq!(
1657            eval_expr(expr, &[("RawValue", -10.0), ("TickFreq", 1000.0)]),
1658            0.0
1659        );
1660    }
1661
1662    /// A representative selection of the shapes seen across the vendor corpus
1663    /// and in the reporter's Hikrobot dump: multi-line formulas, chained
1664    /// ternaries, `=`/`<>` mixed with bitwise masks.
1665    #[test]
1666    fn vendor_formula_shapes_parse() {
1667        let formulas = [
1668            "( ( PINPRES = 1 ) && ( MODE = 0 ) && (SEL <> 2) ) ? 1 : 0",
1669            "((CTRL_REG & 0x03000000)=0x03000000)?1:0",
1670            "((CTRL_REG | 0xFDFFFFFF)=0xFFFFFFFF)?0:1",
1671            "ADDROFFSET = 0 ? 0 : ADDROFFSET * 0x80",
1672            "(FEAT<32)?((GEVOPT>>FEAT)&0x1):((FEAT<64)?((IPOPT>>(FEAT-32))&0x1) : ((FEAT=66)?SCCB:0))",
1673            "(   ((TM = 0) && (LINE1 = 1)) \n || ((TL = 1) && (REVERSE = 0)) \n || (DS <> 0)) ? 1 : 0",
1674            "((TYPE = 0x011a) || (TYPE = 0x011b)) ? (0.4232 * DKELVIN - 334.83) : (DKELVIN /100)",
1675            "(SHUTTERMODE = 0) && (ROLLING = 1)",
1676            "INDEX = 0",
1677            "( MAX % UNIT ) ? ( MAX - (  MAX) % UNIT  ) : ( MAX)",
1678            "V1.Min",
1679            "V1.Max",
1680        ];
1681        for formula in formulas {
1682            parse_expression(formula)
1683                .unwrap_or_else(|err| panic!("failed to parse {formula:?}: {err}"));
1684        }
1685    }
1686
1687    /// GA-29: `.` is admitted into identifiers for `V1.Min`, and must not take
1688    /// number literals with it.
1689    #[test]
1690    fn qualified_identifiers_and_decimal_literals_lex_apart() {
1691        let ast = parse_expression("V1.Max - 1.5 + .5").expect("parse");
1692        let mut ids = HashSet::new();
1693        collect_identifiers(&ast, &mut ids);
1694        assert_eq!(ids, HashSet::from(["V1.Max".to_string()]));
1695
1696        let value = evaluate(
1697            &ast,
1698            &mut |name| match name {
1699                "V1.Max" => Ok(Value::Int(10)),
1700                other => Err(EvalError::UnknownVariable(other.to_string())),
1701            },
1702            EvalMode::Float,
1703        )
1704        .expect("evaluate");
1705        assert_eq!(value, Value::Float(9.0));
1706        assert!(matches!(
1707            parse_expression("1.5").expect("parse"),
1708            AstNode::Literal(Value::Float(v)) if v == 1.5
1709        ));
1710    }
1711
1712    #[test]
1713    fn var_attr_parses_the_standard_extensions_only() {
1714        assert_eq!(VarAttr::parse("Value"), Some(VarAttr::Value));
1715        assert_eq!(VarAttr::parse("Min"), Some(VarAttr::Min));
1716        assert_eq!(VarAttr::parse("MAX"), Some(VarAttr::Max));
1717        assert_eq!(VarAttr::parse("inc"), Some(VarAttr::Inc));
1718        assert_eq!(
1719            VarAttr::parse("Entry.Continuous"),
1720            Some(VarAttr::Entry("Continuous".into()))
1721        );
1722        for bad in [
1723            "",
1724            "Minimum",
1725            "Entry",
1726            "Entry.",
1727            "Entry.A.B",
1728            "Min.Max",
1729            "Value.X",
1730        ] {
1731            assert_eq!(VarAttr::parse(bad), None, "{bad:?}");
1732        }
1733        assert_eq!(split_qualified("V1.Min"), Some(("V1", "Min")));
1734        assert_eq!(split_qualified("V1"), None);
1735    }
1736
1737    #[test]
1738    fn parse_error_reports_offset() {
1739        let err = parse_expression("A + ").expect_err("incomplete expression");
1740        assert!(err.offset() > 0, "offset should point past the operator");
1741        assert!(err.to_string().contains("at offset"));
1742    }
1743
1744    #[test]
1745    fn collect_identifiers_with_ternary() {
1746        let ast = parse_expression("A > B ? C + D : E * F").expect("parse");
1747        let mut ids = HashSet::new();
1748        collect_identifiers(&ast, &mut ids);
1749        assert!(ids.contains("A"));
1750        assert!(ids.contains("B"));
1751        assert!(ids.contains("C"));
1752        assert!(ids.contains("D"));
1753        assert!(ids.contains("E"));
1754        assert!(ids.contains("F"));
1755        assert_eq!(ids.len(), 6);
1756    }
1757
1758    #[test]
1759    fn collect_identifiers_with_functions() {
1760        let ast = parse_expression("max(A, min(B, C))").expect("parse");
1761        let mut ids = HashSet::new();
1762        collect_identifiers(&ast, &mut ids);
1763        assert!(ids.contains("A"));
1764        assert!(ids.contains("B"));
1765        assert!(ids.contains("C"));
1766        assert_eq!(ids.len(), 3);
1767    }
1768}