Skip to main content

agentmux_srv/drone/transform/
expr.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Transform expression language: the tokenizer, the parser and the
5//! evaluator (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.9).
6
7use std::cmp::Ordering;
8
9use regex::{Regex, RegexBuilder};
10use serde_json::{Number, Value};
11
12use super::{expr_step, op_step, BoundKind, TransformError, MAX_OPERATIONS, MAX_REGEX_BYTES};
13
14/// An expression's source may be at most this long. The grammar is small, and
15/// a bound keeps the tokenizer and parser work finite; the size of a `matches`
16/// pattern is bounded separately, where the pattern is compiled.
17const MAX_EXPRESSION_BYTES: usize = 64 * 1024;
18/// How deeply a source may nest `(`, `[`, `!` and `-`. The parser is
19/// recursive, so a source nested further is an expression error rather than a
20/// stack overflow.
21const MAX_NESTING_DEPTH: usize = 64;
22/// How deep an expression tree may be before evaluation stops: a chain such as
23/// `1 + 1 + ...` is not nested in the source but is deep in the tree.
24const MAX_EVAL_DEPTH: usize = 256;
25/// How many binary operators one expression may hold. A chain is built by a
26/// loop, so it is neither nested in the source nor limited by the nesting
27/// depth, but dropping its tree recurses once per node.
28const MAX_OPERATORS: usize = 1024;
29
30/// What one node's evaluation carries between elements: the budget it has
31/// spent.
32#[derive(Default)]
33pub(super) struct State {
34    budget: u64,
35}
36
37/// One unit of the evaluation budget; the total may not pass
38/// [`MAX_OPERATIONS`].
39pub(super) fn charge(state: &mut State) -> Result<(), TransformError> {
40    state.budget += 1;
41    if state.budget > MAX_OPERATIONS {
42        Err(TransformError::Bound {
43            kind: BoundKind::Operations,
44            limit: MAX_OPERATIONS,
45        })
46    } else {
47        Ok(())
48    }
49}
50
51// ---------------------------------------------------------------------------
52// The tokenizer
53// ---------------------------------------------------------------------------
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub(super) enum Op {
57    Plus,
58    Minus,
59    Star,
60    Slash,
61    Percent,
62    Bang,
63    Eq,
64    Ne,
65    Lt,
66    Le,
67    Gt,
68    Ge,
69    And,
70    Or,
71    Contains,
72    Matches,
73    InSet,
74    LParen,
75    RParen,
76    LBracket,
77    RBracket,
78    Comma,
79    Dot,
80}
81
82#[derive(Debug, Clone, PartialEq)]
83enum Token {
84    Number(Number),
85    Text(String),
86    Name(String),
87    Op(Op),
88}
89
90fn tokenize(source: &str) -> Result<Vec<Token>, String> {
91    let chars: Vec<char> = source.chars().collect();
92    let mut tokens = Vec::new();
93    let mut i = 0;
94    while i < chars.len() {
95        let c = chars[i];
96        if c.is_whitespace() {
97            i += 1;
98        } else if c.is_ascii_digit() {
99            let (number, next) = number_at(&chars, i)?;
100            tokens.push(Token::Number(number));
101            i = next;
102        } else if c == '\'' || c == '"' {
103            let (text, next) = text_at(&chars, i, c)?;
104            tokens.push(Token::Text(text));
105            i = next;
106        } else if c.is_alphabetic() || c == '_' {
107            let start = i;
108            while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
109                i += 1;
110            }
111            tokens.push(Token::Name(chars[start..i].iter().collect()));
112        } else {
113            let (op, width) = operator_at(&chars, i)?;
114            tokens.push(Token::Op(op));
115            i += width;
116        }
117    }
118    Ok(tokens)
119}
120
121fn operator_at(chars: &[char], i: usize) -> Result<(Op, usize), String> {
122    let next = chars.get(i + 1).copied();
123    match (chars[i], next) {
124        ('=', Some('=')) => Ok((Op::Eq, 2)),
125        ('!', Some('=')) => Ok((Op::Ne, 2)),
126        ('<', Some('=')) => Ok((Op::Le, 2)),
127        ('>', Some('=')) => Ok((Op::Ge, 2)),
128        ('&', Some('&')) => Ok((Op::And, 2)),
129        ('|', Some('|')) => Ok((Op::Or, 2)),
130        ('+', _) => Ok((Op::Plus, 1)),
131        ('-', _) => Ok((Op::Minus, 1)),
132        ('*', _) => Ok((Op::Star, 1)),
133        ('/', _) => Ok((Op::Slash, 1)),
134        ('%', _) => Ok((Op::Percent, 1)),
135        ('!', _) => Ok((Op::Bang, 1)),
136        ('<', _) => Ok((Op::Lt, 1)),
137        ('>', _) => Ok((Op::Gt, 1)),
138        ('(', _) => Ok((Op::LParen, 1)),
139        (')', _) => Ok((Op::RParen, 1)),
140        ('[', _) => Ok((Op::LBracket, 1)),
141        (']', _) => Ok((Op::RBracket, 1)),
142        (',', _) => Ok((Op::Comma, 1)),
143        ('.', _) => Ok((Op::Dot, 1)),
144        (other, _) => Err(format!("unexpected character {other:?}")),
145    }
146}
147
148fn number_at(chars: &[char], start: usize) -> Result<(Number, usize), String> {
149    let mut i = start;
150    while i < chars.len() && chars[i].is_ascii_digit() {
151        i += 1;
152    }
153    let mut float = false;
154    if i < chars.len() && chars[i] == '.' {
155        float = true;
156        i += 1;
157        while i < chars.len() && chars[i].is_ascii_digit() {
158            i += 1;
159        }
160    }
161    if i < chars.len() && (chars[i] == 'e' || chars[i] == 'E') {
162        float = true;
163        i += 1;
164        if i < chars.len() && (chars[i] == '+' || chars[i] == '-') {
165            i += 1;
166        }
167        let digits = i;
168        while i < chars.len() && chars[i].is_ascii_digit() {
169            i += 1;
170        }
171        if i == digits {
172            return Err("an exponent needs digits".to_string());
173        }
174    }
175    let text: String = chars[start..i].iter().collect();
176    if !float {
177        if let Ok(value) = text.parse::<i64>() {
178            return Ok((Number::from(value), i));
179        }
180    }
181    let value: f64 = text
182        .parse()
183        .map_err(|_| format!("{text:?} is not a number"))?;
184    let number = Number::from_f64(value).ok_or_else(|| format!("{text:?} is not finite"))?;
185    Ok((number, i))
186}
187
188fn text_at(chars: &[char], start: usize, quote: char) -> Result<(String, usize), String> {
189    let mut text = String::new();
190    let mut i = start + 1;
191    while i < chars.len() {
192        let c = chars[i];
193        if c == quote {
194            return Ok((text, i + 1));
195        }
196        if c == '\\' {
197            i += 1;
198            let escaped = *chars
199                .get(i)
200                .ok_or_else(|| "a string ended after a backslash".to_string())?;
201            match escaped {
202                '\\' => text.push('\\'),
203                '\'' => text.push('\''),
204                '"' => text.push('"'),
205                other => return Err(format!("unknown escape \\{other}")),
206            }
207            i += 1;
208            continue;
209        }
210        text.push(c);
211        i += 1;
212    }
213    Err("a string is not closed".to_string())
214}
215
216// ---------------------------------------------------------------------------
217// The parser
218// ---------------------------------------------------------------------------
219
220#[derive(Debug, Clone)]
221pub(super) enum Expr {
222    Literal(Value),
223    Path(Vec<String>),
224    List(Vec<Expr>),
225    Call {
226        name: String,
227        args: Vec<Expr>,
228    },
229    Not(Box<Expr>),
230    Negate(Box<Expr>),
231    /// `value matches 'pattern'`, with the pattern compiled when the chain was
232    /// parsed so no element ever pays for a compile.
233    Matches {
234        value: Box<Expr>,
235        regex: Regex,
236    },
237    Binary {
238        op: Op,
239        left: Box<Expr>,
240        right: Box<Expr>,
241    },
242}
243
244/// How many arguments each function name takes; anything else is unknown.
245fn function_arity(name: &str) -> Option<usize> {
246    match name {
247        "lower" | "exists" => Some(1),
248        "trunc" | "default" => Some(2),
249        _ => None,
250    }
251}
252
253struct Parser {
254    tokens: Vec<Token>,
255    pos: usize,
256    depth: usize,
257    operators: usize,
258}
259
260impl Parser {
261    fn parse(source: &str) -> Result<Expr, String> {
262        if source.len() > MAX_EXPRESSION_BYTES {
263            return Err(format!(
264                "an expression may be at most {MAX_EXPRESSION_BYTES} bytes"
265            ));
266        }
267        let mut parser = Self {
268            tokens: tokenize(source)?,
269            pos: 0,
270            depth: 0,
271            operators: 0,
272        };
273        let expr = parser.expression()?;
274        if parser.pos < parser.tokens.len() {
275            return Err("a token is left over after the expression".to_string());
276        }
277        Ok(expr)
278    }
279
280    /// Count one level of nesting; past the limit the source is refused rather
281    /// than parsed until the stack runs out. An error abandons the parse, so a
282    /// depth is not given back on that path.
283    fn enter(&mut self) -> Result<(), String> {
284        self.depth += 1;
285        if self.depth > MAX_NESTING_DEPTH {
286            return Err(format!(
287                "an expression may nest at most {MAX_NESTING_DEPTH} levels"
288            ));
289        }
290        Ok(())
291    }
292
293    fn leave(&mut self) {
294        self.depth = self.depth.saturating_sub(1);
295    }
296
297    fn peek(&self) -> Option<&Token> {
298        self.tokens.get(self.pos)
299    }
300
301    fn bump(&mut self) -> Option<Token> {
302        let token = self.tokens.get(self.pos).cloned();
303        if token.is_some() {
304            self.pos += 1;
305        }
306        token
307    }
308
309    fn eat(&mut self, op: Op) -> bool {
310        if self.peek() == Some(&Token::Op(op)) {
311            self.pos += 1;
312            true
313        } else {
314            false
315        }
316    }
317
318    fn expect(&mut self, op: Op, what: &str) -> Result<(), String> {
319        if self.eat(op) {
320            Ok(())
321        } else {
322            Err(format!("{what} is expected"))
323        }
324    }
325
326    /// Join two operands, counting the operator against [`MAX_OPERATORS`].
327    fn join(&mut self, op: Op, left: Expr, right: Expr) -> Result<Expr, String> {
328        self.operators += 1;
329        if self.operators > MAX_OPERATORS {
330            return Err(format!(
331                "an expression may hold at most {MAX_OPERATORS} operators"
332            ));
333        }
334        Ok(binary(op, left, right))
335    }
336
337    fn expression(&mut self) -> Result<Expr, String> {
338        self.enter()?;
339        let expr = self.or()?;
340        self.leave();
341        Ok(expr)
342    }
343
344    fn or(&mut self) -> Result<Expr, String> {
345        let mut expr = self.and()?;
346        while self.eat(Op::Or) {
347            let right = self.and()?;
348            expr = self.join(Op::Or, expr, right)?;
349        }
350        Ok(expr)
351    }
352
353    fn and(&mut self) -> Result<Expr, String> {
354        let mut expr = self.not()?;
355        while self.eat(Op::And) {
356            let right = self.not()?;
357            expr = self.join(Op::And, expr, right)?;
358        }
359        Ok(expr)
360    }
361
362    fn not(&mut self) -> Result<Expr, String> {
363        if self.eat(Op::Bang) {
364            self.enter()?;
365            let inner = self.not();
366            self.leave();
367            Ok(Expr::Not(Box::new(inner?)))
368        } else {
369            self.comparison()
370        }
371    }
372
373    fn comparison(&mut self) -> Result<Expr, String> {
374        let left = self.sum()?;
375        let op = match self.peek() {
376            Some(Token::Op(op @ (Op::Eq | Op::Ne | Op::Lt | Op::Le | Op::Gt | Op::Ge))) => *op,
377            Some(Token::Name(name)) => match name.as_str() {
378                "contains" => Op::Contains,
379                "matches" => Op::Matches,
380                "in_set" => Op::InSet,
381                _ => return Ok(left),
382            },
383            _ => return Ok(left),
384        };
385        self.pos += 1;
386        let right = self.sum()?;
387        if op == Op::Matches {
388            return self.matches(left, right);
389        }
390        self.join(op, left, right)
391    }
392
393    /// `a matches 'pattern'`: the pattern is a string literal, compiled here
394    /// once, so a chain over many elements never compiles one per element and
395    /// a hostile pattern cannot buy compile work with element count.
396    fn matches(&mut self, value: Expr, pattern: Expr) -> Result<Expr, String> {
397        let Expr::Literal(Value::String(pattern)) = pattern else {
398            return Err("matches needs a string literal pattern".to_string());
399        };
400        let regex = RegexBuilder::new(&pattern)
401            .size_limit(MAX_REGEX_BYTES)
402            .build()
403            .map_err(|error| format!("bad regular expression: {error}"))?;
404        Ok(Expr::Matches {
405            value: Box::new(value),
406            regex,
407        })
408    }
409
410    fn sum(&mut self) -> Result<Expr, String> {
411        let mut expr = self.product()?;
412        loop {
413            let op = if self.eat(Op::Plus) {
414                Op::Plus
415            } else if self.eat(Op::Minus) {
416                Op::Minus
417            } else {
418                return Ok(expr);
419            };
420            let right = self.product()?;
421            expr = self.join(op, expr, right)?;
422        }
423    }
424
425    fn product(&mut self) -> Result<Expr, String> {
426        let mut expr = self.unary()?;
427        loop {
428            let op = if self.eat(Op::Star) {
429                Op::Star
430            } else if self.eat(Op::Slash) {
431                Op::Slash
432            } else if self.eat(Op::Percent) {
433                Op::Percent
434            } else {
435                return Ok(expr);
436            };
437            let right = self.unary()?;
438            expr = self.join(op, expr, right)?;
439        }
440    }
441
442    fn unary(&mut self) -> Result<Expr, String> {
443        if self.eat(Op::Minus) {
444            self.enter()?;
445            let inner = self.unary();
446            self.leave();
447            Ok(Expr::Negate(Box::new(inner?)))
448        } else {
449            self.atom()
450        }
451    }
452
453    fn atom(&mut self) -> Result<Expr, String> {
454        match self.bump() {
455            Some(Token::Number(number)) => Ok(Expr::Literal(Value::Number(number))),
456            Some(Token::Text(text)) => Ok(Expr::Literal(Value::String(text))),
457            Some(Token::Name(name)) => self.name(name),
458            Some(Token::Op(Op::LParen)) => {
459                let expr = self.expression()?;
460                self.expect(Op::RParen, "')'")?;
461                Ok(expr)
462            }
463            Some(Token::Op(Op::LBracket)) => self.list(),
464            Some(token) => Err(format!("{token:?} cannot start an expression")),
465            None => Err("the expression ended early".to_string()),
466        }
467    }
468
469    fn name(&mut self, name: String) -> Result<Expr, String> {
470        if self.eat(Op::LParen) {
471            return self.call(name);
472        }
473        match name.as_str() {
474            "true" => return Ok(Expr::Literal(Value::Bool(true))),
475            "false" => return Ok(Expr::Literal(Value::Bool(false))),
476            "null" => return Ok(Expr::Literal(Value::Null)),
477            _ => {}
478        }
479        let mut path = vec![name];
480        while self.eat(Op::Dot) {
481            match self.bump() {
482                Some(Token::Name(segment)) => path.push(segment),
483                _ => return Err("a field name is expected after '.'".to_string()),
484            }
485        }
486        Ok(Expr::Path(path))
487    }
488
489    fn call(&mut self, name: String) -> Result<Expr, String> {
490        let arity = function_arity(&name).ok_or_else(|| format!("unknown function {name:?}"))?;
491        let mut args = Vec::new();
492        if !self.eat(Op::RParen) {
493            loop {
494                args.push(self.expression()?);
495                if self.eat(Op::Comma) {
496                    continue;
497                }
498                self.expect(Op::RParen, "')'")?;
499                break;
500            }
501        }
502        if args.len() != arity {
503            return Err(format!(
504                "{name} takes {arity} argument(s), not {}",
505                args.len()
506            ));
507        }
508        Ok(Expr::Call { name, args })
509    }
510
511    fn list(&mut self) -> Result<Expr, String> {
512        let mut items = Vec::new();
513        if !self.eat(Op::RBracket) {
514            loop {
515                items.push(self.expression()?);
516                if self.eat(Op::Comma) {
517                    continue;
518                }
519                self.expect(Op::RBracket, "']'")?;
520                break;
521            }
522        }
523        Ok(Expr::List(items))
524    }
525}
526
527fn binary(op: Op, left: Expr, right: Expr) -> Expr {
528    Expr::Binary {
529        op,
530        left: Box::new(left),
531        right: Box::new(right),
532    }
533}
534
535/// A dotted path with no operators, for `exists` over an object.
536pub(super) fn parse_object_path(source: &str) -> Result<Vec<String>, String> {
537    let tokens = tokenize(source)?;
538    let mut segments = Vec::new();
539    let mut i = 0;
540    loop {
541        match tokens.get(i) {
542            Some(Token::Name(name)) => segments.push(name.clone()),
543            _ => return Err("a dotted path is expected".to_string()),
544        }
545        i += 1;
546        match tokens.get(i) {
547            Some(Token::Op(Op::Dot)) => i += 1,
548            Some(_) => return Err("only a dotted path is allowed here".to_string()),
549            None => return Ok(segments),
550        }
551    }
552}
553
554// ---------------------------------------------------------------------------
555// The evaluator
556// ---------------------------------------------------------------------------
557
558struct Eval<'a> {
559    item: &'a Value,
560    index: usize,
561    step: usize,
562    state: &'a mut State,
563    depth: usize,
564}
565
566impl<'a> Eval<'a> {
567    fn fail(&self, message: impl Into<String>) -> TransformError {
568        expr_step(self.step, message.into())
569    }
570
571    fn charge(&mut self) -> Result<(), TransformError> {
572        charge(self.state)
573    }
574
575    fn eval(&mut self, expr: &Expr) -> Result<Value, TransformError> {
576        self.charge()?;
577        self.depth += 1;
578        if self.depth > MAX_EVAL_DEPTH {
579            return Err(self.fail(format!(
580                "an expression may be evaluated at most {MAX_EVAL_DEPTH} levels deep"
581            )));
582        }
583        let answer = self.eval_node(expr);
584        self.depth -= 1;
585        answer
586    }
587
588    fn eval_node(&mut self, expr: &Expr) -> Result<Value, TransformError> {
589        match expr {
590            Expr::Literal(value) => Ok(value.clone()),
591            Expr::Path(path) => self.path(path),
592            Expr::List(items) => {
593                let mut out = Vec::with_capacity(items.len());
594                for item in items {
595                    out.push(self.eval(item)?);
596                }
597                Ok(Value::Array(out))
598            }
599            Expr::Call { name, args } => self.call(name, args),
600            Expr::Not(inner) => Ok(Value::Bool(!self.eval_bool(inner)?)),
601            Expr::Negate(inner) => {
602                let value = self.eval(inner)?;
603                negate(&value).map_err(|message| self.fail(message))
604            }
605            Expr::Binary { op, left, right } => self.binary(*op, left, right),
606            Expr::Matches { value, regex } => {
607                let value = self.eval(value)?;
608                let text = value
609                    .as_str()
610                    .ok_or_else(|| self.fail("matches needs a string"))?;
611                Ok(Value::Bool(regex.is_match(text)))
612            }
613        }
614    }
615
616    fn eval_bool(&mut self, expr: &Expr) -> Result<bool, TransformError> {
617        match self.eval(expr)? {
618            Value::Bool(value) => Ok(value),
619            other => Err(self.fail(format!("a true or false is expected, not {other}"))),
620        }
621    }
622
623    fn path(&mut self, path: &[String]) -> Result<Value, TransformError> {
624        let (root, rest) = path
625            .split_first()
626            .ok_or_else(|| self.fail("an empty path"))?;
627        let start = match root.as_str() {
628            "item" => self.item.clone(),
629            "index" => Value::Number(Number::from(self.index as u64)),
630            other => return Err(self.fail(format!("unknown name {other:?}"))),
631        };
632        Ok(lookup_path(&start, rest))
633    }
634
635    fn call(&mut self, name: &str, args: &[Expr]) -> Result<Value, TransformError> {
636        match name {
637            "lower" => {
638                let [arg] = args else {
639                    return Err(self.fail("lower takes one argument"));
640                };
641                let value = self.eval(arg)?;
642                let text = value
643                    .as_str()
644                    .ok_or_else(|| self.fail("lower needs a string"))?;
645                Ok(Value::String(text.to_lowercase()))
646            }
647            "trunc" => {
648                let [text, count] = args else {
649                    return Err(self.fail("trunc takes two arguments"));
650                };
651                let value = self.eval(text)?;
652                let text = value
653                    .as_str()
654                    .ok_or_else(|| self.fail("trunc needs a string"))?;
655                let count = self.eval(count)?;
656                let count = count
657                    .as_u64()
658                    .ok_or_else(|| self.fail("trunc needs a count of at least 0"))?;
659                Ok(Value::String(text.chars().take(count as usize).collect()))
660            }
661            "default" => {
662                let [value, fallback] = args else {
663                    return Err(self.fail("default takes two arguments"));
664                };
665                let value = self.eval(value)?;
666                if value.is_null() {
667                    self.eval(fallback)
668                } else {
669                    Ok(value)
670                }
671            }
672            "exists" => {
673                let [arg] = args else {
674                    return Err(self.fail("exists takes one argument"));
675                };
676                let value = self.eval(arg)?;
677                Ok(Value::Bool(!value.is_null()))
678            }
679            other => Err(self.fail(format!("unknown function {other:?}"))),
680        }
681    }
682
683    fn binary(&mut self, op: Op, left: &Expr, right: &Expr) -> Result<Value, TransformError> {
684        match op {
685            Op::And => {
686                if !self.eval_bool(left)? {
687                    return Ok(Value::Bool(false));
688                }
689                Ok(Value::Bool(self.eval_bool(right)?))
690            }
691            Op::Or => {
692                if self.eval_bool(left)? {
693                    return Ok(Value::Bool(true));
694                }
695                Ok(Value::Bool(self.eval_bool(right)?))
696            }
697            Op::Eq => {
698                let left = self.eval(left)?;
699                let right = self.eval(right)?;
700                Ok(Value::Bool(equal(&left, &right)))
701            }
702            Op::Ne => {
703                let left = self.eval(left)?;
704                let right = self.eval(right)?;
705                Ok(Value::Bool(!equal(&left, &right)))
706            }
707            Op::Lt | Op::Le | Op::Gt | Op::Ge => {
708                let left = self.eval(left)?;
709                let right = self.eval(right)?;
710                let ordering = compare(&left, &right).map_err(|message| self.fail(message))?;
711                let answer = match op {
712                    Op::Lt => ordering.is_lt(),
713                    Op::Le => ordering.is_le(),
714                    Op::Gt => ordering.is_gt(),
715                    _ => ordering.is_ge(),
716                };
717                Ok(Value::Bool(answer))
718            }
719            Op::Contains => {
720                let left = self.eval(left)?;
721                let right = self.eval(right)?;
722                contains(&left, &right)
723                    .map(Value::Bool)
724                    .map_err(|message| self.fail(message))
725            }
726            Op::InSet => {
727                let left = self.eval(left)?;
728                let right = self.eval(right)?;
729                in_set(&left, &right)
730                    .map(Value::Bool)
731                    .map_err(|message| self.fail(message))
732            }
733            Op::Plus | Op::Minus | Op::Star | Op::Slash | Op::Percent => {
734                let left = self.eval(left)?;
735                let right = self.eval(right)?;
736                arithmetic(op, &left, &right).map_err(|message| self.fail(message))
737            }
738            op => Err(self.fail(format!("{op:?} is not an infix operator"))),
739        }
740    }
741}
742
743pub(super) fn eval_at<'a>(
744    ast: &Expr,
745    item: &'a Value,
746    index: usize,
747    step: usize,
748    state: &'a mut State,
749) -> Result<Value, TransformError> {
750    Eval {
751        item,
752        index,
753        step,
754        state,
755        depth: 0,
756    }
757    .eval(ast)
758}
759
760fn lookup_path(root: &Value, segments: &[String]) -> Value {
761    let mut current = root;
762    for segment in segments {
763        match current.get(segment.as_str()) {
764            Some(next) => current = next,
765            None => return Value::Null,
766        }
767    }
768    current.clone()
769}
770
771fn negate(value: &Value) -> Result<Value, String> {
772    if let Some(integer) = value.as_i64() {
773        if let Some(negated) = integer.checked_neg() {
774            return Ok(Value::Number(Number::from(negated)));
775        }
776    }
777    let number = value
778        .as_f64()
779        .ok_or_else(|| "'-' needs a number".to_string())?;
780    Number::from_f64(-number)
781        .map(Value::Number)
782        .ok_or_else(|| "a number that is not finite".to_string())
783}
784
785fn arithmetic(op: Op, left: &Value, right: &Value) -> Result<Value, String> {
786    let (x, y) = match (left.as_f64(), right.as_f64()) {
787        (Some(x), Some(y)) => (x, y),
788        _ => return Err("arithmetic needs numbers".to_string()),
789    };
790    if matches!(op, Op::Slash | Op::Percent) && y == 0.0 {
791        return Err("division by zero".to_string());
792    }
793    if let (Some(a), Some(b)) = (left.as_i64(), right.as_i64()) {
794        // `i64::MIN / -1` and `i64::MIN % -1` overflow; checked division
795        // returns `None` for them and the float path below handles the value.
796        let integer = match op {
797            Op::Plus => a.checked_add(b),
798            Op::Minus => a.checked_sub(b),
799            Op::Star => a.checked_mul(b),
800            Op::Slash => match a.checked_rem(b) {
801                Some(0) => a.checked_div(b),
802                _ => None,
803            },
804            Op::Percent => a.checked_rem(b),
805            _ => None,
806        };
807        if let Some(value) = integer {
808            return Ok(Value::Number(Number::from(value)));
809        }
810    }
811    let result = match op {
812        Op::Plus => x + y,
813        Op::Minus => x - y,
814        Op::Star => x * y,
815        Op::Slash => x / y,
816        Op::Percent => x % y,
817        _ => return Err("unknown arithmetic".to_string()),
818    };
819    Number::from_f64(result)
820        .map(Value::Number)
821        .ok_or_else(|| "a number that is not finite".to_string())
822}
823
824fn equal(left: &Value, right: &Value) -> bool {
825    match (left, right) {
826        (Value::Number(_), Value::Number(_)) => match (left.as_f64(), right.as_f64()) {
827            (Some(x), Some(y)) => x == y,
828            _ => false,
829        },
830        _ => left == right,
831    }
832}
833
834fn compare(left: &Value, right: &Value) -> Result<Ordering, String> {
835    match (left, right) {
836        (Value::Number(_), Value::Number(_)) => {
837            let x = left.as_f64().ok_or_else(|| "a number".to_string())?;
838            let y = right.as_f64().ok_or_else(|| "a number".to_string())?;
839            x.partial_cmp(&y)
840                .ok_or_else(|| "two numbers that cannot be ordered".to_string())
841        }
842        (Value::String(x), Value::String(y)) => Ok(x.cmp(y)),
843        (Value::Bool(x), Value::Bool(y)) => Ok(x.cmp(y)),
844        _ => Err("ordering needs two numbers or two strings".to_string()),
845    }
846}
847
848fn contains(haystack: &Value, needle: &Value) -> Result<bool, String> {
849    match haystack {
850        Value::String(text) => {
851            let needle = needle
852                .as_str()
853                .ok_or_else(|| "contains on a string needs a string".to_string())?;
854            Ok(text.contains(needle))
855        }
856        Value::Array(items) => Ok(items.iter().any(|item| equal(item, needle))),
857        _ => Err("contains needs a string or a list".to_string()),
858    }
859}
860
861fn in_set(value: &Value, set: &Value) -> Result<bool, String> {
862    let items = set
863        .as_array()
864        .ok_or_else(|| "in_set needs a list after it".to_string())?;
865    Ok(items.iter().any(|item| equal(item, value)))
866}
867
868/// The type a sort key must share with every other key before ordering is
869/// defined; ordering across types is an expression error.
870pub(super) fn value_class(value: &Value) -> &'static str {
871    match value {
872        Value::Number(_) => "number",
873        Value::String(_) => "string",
874        Value::Bool(_) => "bool",
875        Value::Null => "null",
876        Value::Array(_) => "list",
877        Value::Object(_) => "object",
878    }
879}
880
881pub(super) fn cmp_same_class(left: &Value, right: &Value) -> Ordering {
882    match (left, right) {
883        (Value::Number(_), Value::Number(_)) => left
884            .as_f64()
885            .and_then(|x| right.as_f64().and_then(|y| x.partial_cmp(&y)))
886            .unwrap_or(Ordering::Equal),
887        (Value::String(x), Value::String(y)) => x.cmp(y),
888        (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
889        _ => Ordering::Equal,
890    }
891}
892
893pub(super) fn as_list<'a>(
894    input: &'a Value,
895    step: usize,
896    what: &str,
897) -> Result<&'a [Value], TransformError> {
898    input
899        .as_array()
900        .map(Vec::as_slice)
901        .ok_or_else(|| op_step(step, &format!("{what} needs a list")))
902}
903
904pub(super) fn parse_or(expr: &str, step: usize) -> Result<Expr, TransformError> {
905    Parser::parse(expr).map_err(|message| expr_step(step, message))
906}
907
908pub(super) fn parse_opt(by: Option<&str>, step: usize) -> Result<Option<Expr>, TransformError> {
909    match by {
910        Some(source) => Ok(Some(parse_or(source, step)?)),
911        None => Ok(None),
912    }
913}