Skip to main content

aylis_data/
expr.rs

1//! Expressões sobre os campos de um registro: o `filter` do dataset e os campos
2//! calculados (`expression` do [`Field`](crate::Field)).
3//!
4//! ```text
5//! cidade = 'São Paulo' and limite >= 1000
6//! nome like 'mar%' or not ativo
7//! uf in ('SP', 'RJ') and data_cadastro >= '2024-01-01'
8//! quantidade * preco_unitario            (campo calculado)
9//! upper(nome) + ' (' + uf + ')'
10//! iif(limite > 5000, 'VIP', 'Normal')
11//! ```
12//!
13//! - comparações: `=`, `<>` (ou `!=`), `<`, `<=`, `>`, `>=`, `like` (com `%` e `_`,
14//!   sem diferenciar maiúsculas), `in (...)`, `is null`, `is not null`;
15//! - texto compara sem diferenciar maiúsculas e minúsculas;
16//! - lógicos: `and`, `or`, `not`; contas: `+ - * / %` (`+` junta textos);
17//! - funções: `upper`, `lower`, `fold` (sem acento e sem maiúscula), `trim`, `len`, `substr(t, início, tamanho)`, `round(x, casas, modo)`,
18//!   `abs`, `coalesce(a, b)`, `iif(condição, a, b)`, `year`, `month`, `day`, `today()` e
19//!   `now()` (no horário local da tela);
20//! - nomes de campo com espaço ou acento: `[Data de cadastro]`.
21
22use std::cmp::Ordering;
23
24use crate::value::{Date, Decimal, Rounding, Value};
25
26/// Uma expressão já lida (lida uma vez, avaliada em cada registro).
27#[derive(Clone, Debug, PartialEq)]
28pub struct Expr(Node);
29
30#[derive(Clone, Debug, PartialEq)]
31enum Node {
32    Const(Value),
33    Field(String),
34    Unary(char, Box<Node>),
35    Binary(Op, Box<Node>, Box<Node>),
36    Not(Box<Node>),
37    And(Box<Node>, Box<Node>),
38    Or(Box<Node>, Box<Node>),
39    Like(Box<Node>, Box<Node>, bool),
40    In(Box<Node>, Vec<Node>, bool),
41    IsNull(Box<Node>, bool),
42    Call(String, Vec<Node>),
43}
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46enum Op {
47    Eq,
48    Ne,
49    Lt,
50    Le,
51    Gt,
52    Ge,
53    Add,
54    Sub,
55    Mul,
56    Div,
57    Mod,
58}
59
60impl Expr {
61    /// Lê a expressão. O erro diz onde está o problema.
62    pub fn parse(text: &str) -> Result<Expr, String> {
63        if text.len() > MAX_TEXT {
64            return Err(format!("expressão longa demais ({} KB; o máximo é {} KB)", text.len() / 1024, MAX_TEXT / 1024));
65        }
66        let tokens = tokenize(text)?;
67        let mut p = Parser { tokens, pos: 0, depth: 0, nesting: 0 };
68        let node = p.or()?;
69        if p.pos < p.tokens.len() {
70            return Err(format!("sobrou '{}' no fim da expressão", p.tokens[p.pos].text()));
71        }
72        Ok(Expr(node))
73    }
74
75    /// Nomes de campo usados (para conferir que existem); os parâmetros ficam de fora.
76    pub fn fields(&self) -> Vec<String> {
77        self.names().into_iter().filter(|n| !n.starts_with(':')).collect()
78    }
79
80    /// Parâmetros usados (`:minimo` → `minimo`).
81    pub fn params(&self) -> Vec<String> {
82        self.names().into_iter().filter_map(|n| n.strip_prefix(':').map(str::to_string)).collect()
83    }
84
85    fn names(&self) -> Vec<String> {
86        fn walk(n: &Node, out: &mut Vec<String>) {
87            match n {
88                Node::Field(f) => {
89                    if !out.iter().any(|o: &String| o.eq_ignore_ascii_case(f)) {
90                        out.push(f.clone());
91                    }
92                }
93                Node::Unary(_, a) | Node::Not(a) | Node::IsNull(a, _) => walk(a, out),
94                Node::Binary(_, a, b) | Node::And(a, b) | Node::Or(a, b) | Node::Like(a, b, _) => {
95                    walk(a, out);
96                    walk(b, out);
97                }
98                Node::In(a, list, _) => {
99                    walk(a, out);
100                    list.iter().for_each(|x| walk(x, out));
101                }
102                Node::Call(_, args) => args.iter().for_each(|x| walk(x, out)),
103                Node::Const(_) => {}
104            }
105        }
106        let mut out = Vec::new();
107        walk(&self.0, &mut out);
108        out
109    }
110
111    /// Avalia com os valores do registro (`get` devolve o valor de um campo pelo nome).
112    pub fn eval(&self, get: &dyn Fn(&str) -> Option<Value>) -> Result<Value, String> {
113        eval(&self.0, get)
114    }
115
116    /// Avalia como condição (filtro): `Null` e erros contam como falso.
117    pub fn matches(&self, get: &dyn Fn(&str) -> Option<Value>) -> bool {
118        matches!(self.eval(get), Ok(Value::Bool(true)))
119    }
120}
121
122// ---------------------------------------------------------------------------
123// Tokens
124
125#[derive(Clone, Debug, PartialEq)]
126enum Tok {
127    Num(String),
128    Str(String),
129    Ident(String),
130    Sym(&'static str),
131}
132
133impl Tok {
134    fn text(&self) -> String {
135        match self {
136            Tok::Num(s) | Tok::Ident(s) => s.clone(),
137            Tok::Str(s) => format!("'{s}'"),
138            Tok::Sym(s) => s.to_string(),
139        }
140    }
141
142    fn is_word(&self, word: &str) -> bool {
143        matches!(self, Tok::Ident(s) if s.eq_ignore_ascii_case(word))
144    }
145}
146
147fn tokenize(text: &str) -> Result<Vec<Tok>, String> {
148    let chars: Vec<char> = text.chars().collect();
149    let mut out = Vec::new();
150    let mut i = 0;
151    while i < chars.len() {
152        let c = chars[i];
153        if c.is_whitespace() {
154            i += 1;
155        } else if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(char::is_ascii_digit)) {
156            let start = i;
157            while i < chars.len() && (chars[i].is_ascii_digit() || chars[i] == '.') {
158                i += 1;
159            }
160            out.push(Tok::Num(chars[start..i].iter().collect()));
161        } else if c == '\'' || c == '"' {
162            let quote = c;
163            let mut s = String::new();
164            i += 1;
165            loop {
166                match chars.get(i) {
167                    None => return Err("texto sem a aspa de fechamento".into()),
168                    Some(&q) if q == quote && chars.get(i + 1) == Some(&quote) => {
169                        s.push(quote);
170                        i += 2;
171                    }
172                    Some(&q) if q == quote => {
173                        i += 1;
174                        break;
175                    }
176                    Some(&ch) => {
177                        s.push(ch);
178                        i += 1;
179                    }
180                }
181            }
182            out.push(Tok::Str(s));
183        } else if c == '[' {
184            let end = chars[i..].iter().position(|&x| x == ']').ok_or("nome de campo sem ']'")?;
185            out.push(Tok::Ident(chars[i + 1..i + end].iter().collect()));
186            i += end + 1;
187        } else if c == ':' && chars.get(i + 1).is_some_and(|n| n.is_alphabetic() || *n == '_') {
188            // Parâmetro (`:minimo`): lido como um campo de nome ":minimo"; quem avalia
189            // entrega o valor.
190            let start = i;
191            i += 1;
192            while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
193                i += 1;
194            }
195            out.push(Tok::Ident(chars[start..i].iter().collect()));
196        } else if c.is_alphabetic() || c == '_' {
197            let start = i;
198            while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_' || chars[i] == '.') {
199                i += 1;
200            }
201            out.push(Tok::Ident(chars[start..i].iter().collect()));
202        } else {
203            let two: String = chars[i..(i + 2).min(chars.len())].iter().collect();
204            let sym = match two.as_str() {
205                "<>" | "!=" => Some("<>"),
206                "<=" => Some("<="),
207                ">=" => Some(">="),
208                "==" => Some("="),
209                "&&" => Some("and"),
210                "||" => Some("or"),
211                _ => None,
212            };
213            if let Some(s) = sym {
214                out.push(Tok::Sym(s));
215                i += 2;
216                continue;
217            }
218            let one = match c {
219                '=' => "=",
220                '<' => "<",
221                '>' => ">",
222                '+' => "+",
223                '-' => "-",
224                '*' => "*",
225                '/' => "/",
226                '%' => "%",
227                '(' => "(",
228                ')' => ")",
229                ',' => ",",
230                '!' => "not",
231                _ => return Err(format!("caractere inesperado '{c}'")),
232            };
233            out.push(Tok::Sym(one));
234            i += 1;
235        }
236    }
237    Ok(out)
238}
239
240// ---------------------------------------------------------------------------
241// Leitura (descida recursiva)
242
243/// Profundidade máxima da árvore: a avaliação e o descarte são recursivos, e um texto como
244/// `((((…` ou `a + a + a…` com milhares de termos estouraria a pilha, o que encerra o processo
245/// sem chance de tratar. Conferida enquanto a árvore é montada (montada inteira, ela já
246/// estouraria ao ser descartada).
247const MAX_DEPTH: usize = 256;
248/// Tamanho máximo do texto de uma expressão.
249const MAX_TEXT: usize = 64 * 1024;
250
251fn too_deep() -> String {
252    format!("expressão aninhada demais (o máximo é {MAX_DEPTH} níveis)")
253}
254
255struct Parser {
256    tokens: Vec<Tok>,
257    pos: usize,
258    /// Profundidade do último nó devolvido.
259    depth: usize,
260    /// Leituras aninhadas abertas (parênteses, sinais, `not`): limitam a recursão da própria
261    /// leitura, que em `((((a))))` não aumenta a profundidade da árvore.
262    nesting: usize,
263}
264
265impl Parser {
266    /// Um nó acima de filhos com profundidade `below`.
267    fn node(&mut self, node: Node, below: usize) -> Result<Node, String> {
268        self.depth = below + 1;
269        if self.depth > MAX_DEPTH {
270            return Err(too_deep());
271        }
272        Ok(node)
273    }
274
275    fn enter(&mut self) -> Result<(), String> {
276        self.nesting += 1;
277        if self.nesting > MAX_DEPTH { Err(too_deep()) } else { Ok(()) }
278    }
279
280    fn leave(&mut self) {
281        self.nesting -= 1;
282    }
283
284    fn peek(&self) -> Option<&Tok> {
285        self.tokens.get(self.pos)
286    }
287
288    fn eat_sym(&mut self, s: &str) -> bool {
289        if matches!(self.peek(), Some(Tok::Sym(x)) if *x == s) {
290            self.pos += 1;
291            true
292        } else {
293            false
294        }
295    }
296
297    fn eat_word(&mut self, w: &str) -> bool {
298        if self.peek().is_some_and(|t| t.is_word(w)) || (matches!(self.peek(), Some(Tok::Sym(x)) if *x == w)) {
299            self.pos += 1;
300            true
301        } else {
302            false
303        }
304    }
305
306    fn expect(&mut self, s: &str) -> Result<(), String> {
307        if self.eat_sym(s) {
308            Ok(())
309        } else {
310            Err(format!("esperava '{s}'{}", self.peek().map(|t| format!(" e veio '{}'", t.text())).unwrap_or_default()))
311        }
312    }
313
314    fn or(&mut self) -> Result<Node, String> {
315        let mut left = self.and()?;
316        let mut depth = self.depth;
317        while self.eat_word("or") {
318            let right = self.and()?;
319            left = self.node(Node::Or(Box::new(left), Box::new(right)), depth.max(self.depth))?;
320            depth = self.depth;
321        }
322        self.depth = depth;
323        Ok(left)
324    }
325
326    fn and(&mut self) -> Result<Node, String> {
327        let mut left = self.not()?;
328        let mut depth = self.depth;
329        while self.eat_word("and") {
330            let right = self.not()?;
331            left = self.node(Node::And(Box::new(left), Box::new(right)), depth.max(self.depth))?;
332            depth = self.depth;
333        }
334        self.depth = depth;
335        Ok(left)
336    }
337
338    fn not(&mut self) -> Result<Node, String> {
339        if self.eat_word("not") {
340            self.enter()?;
341            let inner = self.not()?;
342            self.leave();
343            let below = self.depth;
344            return self.node(Node::Not(Box::new(inner)), below);
345        }
346        self.compare()
347    }
348
349    fn compare(&mut self) -> Result<Node, String> {
350        let left = self.add()?;
351        let below = self.depth;
352        let op = match self.peek() {
353            Some(Tok::Sym("=")) => Some(Op::Eq),
354            Some(Tok::Sym("<>")) => Some(Op::Ne),
355            Some(Tok::Sym("<")) => Some(Op::Lt),
356            Some(Tok::Sym("<=")) => Some(Op::Le),
357            Some(Tok::Sym(">")) => Some(Op::Gt),
358            Some(Tok::Sym(">=")) => Some(Op::Ge),
359            _ => None,
360        };
361        if let Some(op) = op {
362            self.pos += 1;
363            let right = self.add()?;
364            let below = below.max(self.depth);
365            return self.node(Node::Binary(op, Box::new(left), Box::new(right)), below);
366        }
367        let negated = self.peek().is_some_and(|t| t.is_word("not"))
368            && self.tokens.get(self.pos + 1).is_some_and(|t| t.is_word("like") || t.is_word("in"));
369        if negated {
370            self.pos += 1;
371        }
372        if self.eat_word("like") {
373            let pattern = self.add()?;
374            let below = below.max(self.depth);
375            return self.node(Node::Like(Box::new(left), Box::new(pattern), negated), below);
376        }
377        if self.eat_word("in") {
378            self.expect("(")?;
379            let mut list = vec![self.add()?];
380            let mut below = below.max(self.depth);
381            while self.eat_sym(",") {
382                list.push(self.add()?);
383                below = below.max(self.depth);
384            }
385            self.expect(")")?;
386            return self.node(Node::In(Box::new(left), list, negated), below);
387        }
388        if self.eat_word("is") {
389            let not = self.eat_word("not");
390            if !self.eat_word("null") {
391                return Err("esperava 'null' depois de 'is'".into());
392            }
393            return self.node(Node::IsNull(Box::new(left), not), below);
394        }
395        self.depth = below;
396        Ok(left)
397    }
398
399    fn add(&mut self) -> Result<Node, String> {
400        let mut left = self.mul()?;
401        let mut depth = self.depth;
402        loop {
403            let op = if self.eat_sym("+") {
404                Op::Add
405            } else if self.eat_sym("-") {
406                Op::Sub
407            } else {
408                self.depth = depth;
409                return Ok(left);
410            };
411            let right = self.mul()?;
412            left = self.node(Node::Binary(op, Box::new(left), Box::new(right)), depth.max(self.depth))?;
413            depth = self.depth;
414        }
415    }
416
417    fn mul(&mut self) -> Result<Node, String> {
418        let mut left = self.unary()?;
419        let mut depth = self.depth;
420        loop {
421            let op = if self.eat_sym("*") {
422                Op::Mul
423            } else if self.eat_sym("/") {
424                Op::Div
425            } else if self.eat_sym("%") {
426                Op::Mod
427            } else {
428                self.depth = depth;
429                return Ok(left);
430            };
431            let right = self.unary()?;
432            left = self.node(Node::Binary(op, Box::new(left), Box::new(right)), depth.max(self.depth))?;
433            depth = self.depth;
434        }
435    }
436
437    fn unary(&mut self) -> Result<Node, String> {
438        if self.eat_sym("-") {
439            self.enter()?;
440            let inner = self.unary()?;
441            self.leave();
442            let below = self.depth;
443            return self.node(Node::Unary('-', Box::new(inner)), below);
444        }
445        if self.eat_sym("+") {
446            self.enter()?;
447            let inner = self.unary()?;
448            self.leave();
449            return Ok(inner);
450        }
451        self.primary()
452    }
453
454    fn primary(&mut self) -> Result<Node, String> {
455        let tok = self.peek().cloned().ok_or("expressão incompleta")?;
456        self.pos += 1;
457        // Folhas; os parênteses devolvem a profundidade do que está dentro.
458        self.depth = 1;
459        match tok {
460            Tok::Num(n) => {
461                if n.contains('.') {
462                    Decimal::parse(&n).map(|d| Node::Const(Value::Decimal(d))).ok_or_else(|| format!("número inválido '{n}'"))
463                } else {
464                    n.parse::<i64>().map(|v| Node::Const(Value::Int(v))).map_err(|_| format!("número inválido '{n}'"))
465                }
466            }
467            Tok::Str(s) => Ok(Node::Const(Value::String(s))),
468            Tok::Sym("(") => {
469                self.enter()?;
470                let inner = self.or()?;
471                self.expect(")")?;
472                self.leave();
473                Ok(inner)
474            }
475            Tok::Ident(name) => {
476                match name.to_lowercase().as_str() {
477                    "true" | "verdadeiro" => return Ok(Node::Const(Value::Bool(true))),
478                    "false" | "falso" => return Ok(Node::Const(Value::Bool(false))),
479                    "null" => return Ok(Node::Const(Value::Null)),
480                    _ => {}
481                }
482                if self.eat_sym("(") {
483                    self.enter()?;
484                    let mut args = Vec::new();
485                    let mut below = 0;
486                    if !self.eat_sym(")") {
487                        args.push(self.or()?);
488                        below = self.depth;
489                        while self.eat_sym(",") {
490                            args.push(self.or()?);
491                            below = below.max(self.depth);
492                        }
493                        self.expect(")")?;
494                    }
495                    self.leave();
496                    return self.node(Node::Call(name.to_lowercase(), args), below);
497                }
498                Ok(Node::Field(name))
499            }
500            Tok::Sym(s) => Err(format!("'{s}' fora do lugar")),
501        }
502    }
503}
504
505// ---------------------------------------------------------------------------
506// Avaliação
507
508fn eval(node: &Node, get: &dyn Fn(&str) -> Option<Value>) -> Result<Value, String> {
509    Ok(match node {
510        Node::Const(v) => v.clone(),
511        Node::Field(name) => get(name).ok_or_else(|| format!("campo '{name}' não existe"))?,
512        Node::Unary(_, a) => match eval(a, get)? {
513            Value::Null => Value::Null,
514            Value::Int(i) => Value::Int(-i),
515            Value::Float(f) => Value::Float(-f),
516            Value::Decimal(d) => Value::Decimal(Decimal::new(-d.mantissa(), d.scale())),
517            v => return Err(format!("não dá para negar {}", v.kind_name())),
518        },
519        Node::Not(a) => match truth(&eval(a, get)?) {
520            Some(b) => Value::Bool(!b),
521            None => Value::Null,
522        },
523        Node::And(a, b) => {
524            let left = truth(&eval(a, get)?);
525            if left == Some(false) {
526                return Ok(Value::Bool(false));
527            }
528            match (left, truth(&eval(b, get)?)) {
529                (_, Some(false)) => Value::Bool(false),
530                (Some(true), Some(true)) => Value::Bool(true),
531                _ => Value::Null,
532            }
533        }
534        Node::Or(a, b) => {
535            let left = truth(&eval(a, get)?);
536            if left == Some(true) {
537                return Ok(Value::Bool(true));
538            }
539            match (left, truth(&eval(b, get)?)) {
540                (_, Some(true)) => Value::Bool(true),
541                (Some(false), Some(false)) => Value::Bool(false),
542                _ => Value::Null,
543            }
544        }
545        Node::IsNull(a, not) => Value::Bool(eval(a, get)?.is_null() != *not),
546        Node::Like(a, pattern, negated) => {
547            let (v, p) = (eval(a, get)?, eval(pattern, get)?);
548            if v.is_null() || p.is_null() {
549                return Ok(Value::Null);
550            }
551            Value::Bool(like(&v.to_string().to_lowercase(), &p.to_string().to_lowercase()) != *negated)
552        }
553        Node::In(a, list, negated) => {
554            let v = eval(a, get)?;
555            if v.is_null() {
556                return Ok(Value::Null);
557            }
558            let mut found = false;
559            for item in list {
560                if compare(&v, &eval(item, get)?) == Some(Ordering::Equal) {
561                    found = true;
562                    break;
563                }
564            }
565            Value::Bool(found != *negated)
566        }
567        Node::Binary(op, a, b) => binary(*op, eval(a, get)?, eval(b, get)?)?,
568        Node::Call(name, args) => call(name, args, get)?,
569    })
570}
571
572fn truth(v: &Value) -> Option<bool> {
573    match v {
574        Value::Null => None,
575        Value::Bool(b) => Some(*b),
576        Value::Int(i) => Some(*i != 0),
577        other => Some(!other.to_string().is_empty()),
578    }
579}
580
581/// Compara dois valores (texto sem diferenciar maiúsculas; números de tipos diferentes
582/// entre si; datas com texto ISO). `None` se não forem comparáveis ou um for `Null`.
583pub fn compare(a: &Value, b: &Value) -> Option<Ordering> {
584    use Value::*;
585    match (a, b) {
586        (Null, _) | (_, Null) => None,
587        (String(x), String(y)) => Some(x.to_lowercase().cmp(&y.to_lowercase())),
588        (Bool(x), Bool(y)) => Some(x.cmp(y)),
589        (Date(x), Date(y)) => Some(x.cmp(y)),
590        (Time(x), Time(y)) => Some(x.cmp(y)),
591        (DateTime(x), DateTime(y)) => Some(x.cmp(y)),
592        (Date(x), DateTime(y)) => Some(x.cmp(&y.date)),
593        (DateTime(x), Date(y)) => Some(x.date.cmp(y)),
594        (Timestamp(x), Timestamp(y)) => Some(x.cmp(y)),
595        // Com uma data e hora sem fuso (ou uma data), compara no horário local.
596        (Timestamp(x), DateTime(y)) => Some(x.to_local().cmp(y)),
597        (DateTime(x), Timestamp(y)) => Some(x.cmp(&y.to_local())),
598        (Timestamp(x), Date(y)) => Some(x.to_local().date.cmp(y)),
599        (Date(x), Timestamp(y)) => Some(x.cmp(&y.to_local().date)),
600        (Date(x), String(s)) => crate::value::Date::parse_iso(s).map(|y| x.cmp(&y)),
601        (String(s), Date(y)) => crate::value::Date::parse_iso(s).map(|x| x.cmp(y)),
602        (Decimal(x), Decimal(y)) => Some(x.cmp(y)),
603        (Int(x), Int(y)) => Some(x.cmp(y)),
604        _ => match (a.as_f64(), b.as_f64()) {
605            (Some(x), Some(y)) => x.partial_cmp(&y),
606            _ => Some(a.to_string().to_lowercase().cmp(&b.to_string().to_lowercase())),
607        },
608    }
609}
610
611/// Ordem para o índice: `Null` antes de tudo.
612pub fn sort_order(a: &Value, b: &Value) -> Ordering {
613    match (a.is_null(), b.is_null()) {
614        (true, true) => Ordering::Equal,
615        (true, false) => Ordering::Less,
616        (false, true) => Ordering::Greater,
617        _ => compare(a, b).unwrap_or(Ordering::Equal),
618    }
619}
620
621fn binary(op: Op, a: Value, b: Value) -> Result<Value, String> {
622    let cmp = |want: fn(Ordering) -> bool| Ok(compare(&a, &b).map_or(Value::Null, |o| Value::Bool(want(o))));
623    match op {
624        Op::Eq => cmp(|o| o == Ordering::Equal),
625        Op::Ne => cmp(|o| o != Ordering::Equal),
626        Op::Lt => cmp(|o| o == Ordering::Less),
627        Op::Le => cmp(|o| o != Ordering::Greater),
628        Op::Gt => cmp(|o| o == Ordering::Greater),
629        Op::Ge => cmp(|o| o != Ordering::Less),
630        _ if a.is_null() || b.is_null() => Ok(Value::Null),
631        Op::Add if matches!(a, Value::String(_)) || matches!(b, Value::String(_)) => Ok(Value::String(format!("{a}{b}"))),
632        Op::Add | Op::Sub if matches!(a, Value::Date(_)) => {
633            let days = b.as_i64().ok_or("só dá para somar dias (inteiros) a uma data")?;
634            let Value::Date(d) = a else { unreachable!() };
635            Ok(Value::Date(add_days(d, if op == Op::Add { days } else { -days })))
636        }
637        _ => arithmetic(op, &a, &b),
638    }
639}
640
641fn add_days(d: Date, days: i64) -> Date {
642    Date::from_days(d.to_days() + days).unwrap_or(d)
643}
644
645fn op_symbol(op: Op) -> &'static str {
646    match op {
647        Op::Add => "+",
648        Op::Sub => "-",
649        Op::Mul => "*",
650        Op::Div => "/",
651        Op::Mod => "%",
652        Op::Eq => "=",
653        Op::Ne => "<>",
654        Op::Lt => "<",
655        Op::Le => "<=",
656        Op::Gt => ">",
657        Op::Ge => ">=",
658    }
659}
660
661/// Contas: inteiros ficam inteiros (a divisão vira decimal), decimais ficam exatos (a divisão
662/// também), e estouro é erro, nunca um valor errado.
663fn arithmetic(op: Op, a: &Value, b: &Value) -> Result<Value, String> {
664    let not_number = |v: &Value| format!("'{v}' não é número");
665    let overflow = || format!("estouro: {a} {} {b} não cabe", op_symbol(op));
666    if let (Value::Int(x), Value::Int(y)) = (a, b) {
667        return match op {
668            Op::Add => x.checked_add(*y).map(Value::Int).ok_or_else(overflow),
669            Op::Sub => x.checked_sub(*y).map(Value::Int).ok_or_else(overflow),
670            Op::Mul => x.checked_mul(*y).map(Value::Int).ok_or_else(overflow),
671            Op::Mod if *y != 0 => Ok(Value::Int(x % y)),
672            // Inteiros são exatos: a divisão também (7 / 2 = 3,5000), sem passar por f64.
673            Op::Div if *y != 0 => {
674                let (x, y) = (Decimal::from(*x), Decimal::from(*y));
675                x.checked_div(&y, x.default_div_scale(&y), Rounding::HalfUp).map(Value::Decimal).ok_or_else(overflow)
676            }
677            _ => Ok(Value::Null), // divisão por zero
678        };
679    }
680    let decimal = matches!(a, Value::Decimal(_)) || matches!(b, Value::Decimal(_));
681    let floaty = matches!(a, Value::Float(_)) || matches!(b, Value::Float(_));
682    if decimal && !floaty && op != Op::Mod {
683        let (x, y) = (a.as_decimal().ok_or_else(|| not_number(a))?, b.as_decimal().ok_or_else(|| not_number(b))?);
684        let result = match op {
685            Op::Add => x.checked_add(&y),
686            Op::Sub => x.checked_sub(&y),
687            // O produto com as casas do maior mais 2 (2,5 × 1,333 = 3,33250), como antes.
688            Op::Mul => x.checked_mul(&y).and_then(|p| p.round(p.scale().min(x.scale().max(y.scale()).max(2) + 2), Rounding::HalfUp)),
689            // Exata, sem f64 (0,30 / 0,10 = 3): o campo da expressão depois arredonda para as
690            // casas e o modo dele.
691            Op::Div if y.mantissa() == 0 => return Ok(Value::Null),
692            _ => x.checked_div(&y, x.default_div_scale(&y), Rounding::HalfUp),
693        };
694        return result.map(Value::Decimal).ok_or_else(overflow);
695    }
696    let (x, y) = (a.as_f64().ok_or_else(|| not_number(a))?, b.as_f64().ok_or_else(|| not_number(b))?);
697    let r = match op {
698        Op::Add => x + y,
699        Op::Sub => x - y,
700        Op::Mul => x * y,
701        Op::Div if y != 0.0 => x / y,
702        Op::Mod if y != 0.0 => x % y,
703        _ => return Ok(Value::Null),
704    };
705    Ok(Value::Float(r))
706}
707
708/// `%` = qualquer sequência, `_` = um caractere.
709fn like(text: &str, pattern: &str) -> bool {
710    let t: Vec<char> = text.chars().collect();
711    let p: Vec<char> = pattern.chars().collect();
712    let (mut ti, mut pi) = (0, 0);
713    let (mut star, mut mark) = (None, 0);
714    while ti < t.len() {
715        if pi < p.len() && (p[pi] == '_' || p[pi] == t[ti]) {
716            ti += 1;
717            pi += 1;
718        } else if pi < p.len() && p[pi] == '%' {
719            star = Some(pi);
720            mark = ti;
721            pi += 1;
722        } else if let Some(s) = star {
723            pi = s + 1;
724            mark += 1;
725            ti = mark;
726        } else {
727            return false;
728        }
729    }
730    while pi < p.len() && p[pi] == '%' {
731        pi += 1;
732    }
733    pi == p.len()
734}
735
736fn call(name: &str, args: &[Node], get: &dyn Fn(&str) -> Option<Value>) -> Result<Value, String> {
737    let values: Vec<Value> = if name == "iif" { Vec::new() } else { args.iter().map(|a| eval(a, get)).collect::<Result<_, _>>()? };
738    let arg = |i: usize| values.get(i).cloned().unwrap_or(Value::Null);
739    let need = |n: usize| if args.len() < n { Err(format!("{name} precisa de {n} argumento(s)")) } else { Ok(()) };
740    let text = |v: &Value| v.to_string();
741    Ok(match name {
742        "upper" => {
743            need(1)?;
744            if arg(0).is_null() { Value::Null } else { Value::String(text(&arg(0)).to_uppercase()) }
745        }
746        "lower" => {
747            need(1)?;
748            if arg(0).is_null() { Value::Null } else { Value::String(text(&arg(0)).to_lowercase()) }
749        }
750        // Sem acento e sem maiúscula (o `aylis_core::text::fold`): `fold(nome) like '%sao%'`
751        // acha "São Paulo".
752        "fold" => {
753            need(1)?;
754            if arg(0).is_null() { Value::Null } else { Value::String(aylis_core::text::fold(&text(&arg(0)))) }
755        }
756        "trim" => {
757            need(1)?;
758            if arg(0).is_null() { Value::Null } else { Value::String(text(&arg(0)).trim().to_string()) }
759        }
760        "len" | "length" => {
761            need(1)?;
762            Value::Int(if arg(0).is_null() { 0 } else { text(&arg(0)).chars().count() as i64 })
763        }
764        "substr" | "substring" => {
765            need(2)?;
766            let s = text(&arg(0));
767            let start = arg(1).as_i64().unwrap_or(1).max(1) as usize - 1;
768            let len = values.get(2).and_then(Value::as_i64).map_or(usize::MAX, |l| l.max(0) as usize);
769            Value::String(s.chars().skip(start).take(len).collect())
770        }
771        "abs" => {
772            need(1)?;
773            match arg(0) {
774                Value::Int(i) => Value::Int(i.abs()),
775                Value::Decimal(d) => Value::Decimal(Decimal::new(d.mantissa().abs(), d.scale())),
776                v => v.as_f64().map_or(Value::Null, |f| Value::Float(f.abs())),
777            }
778        }
779        "round" => {
780            need(1)?;
781            let places = values.get(1).and_then(Value::as_i64).unwrap_or(0).clamp(0, 12) as u8;
782            // round(x, casas, 'half_even'): o modo (half_up, o padrão; half_even, o bancário;
783            // truncate; up).
784            let mode = match values.get(2) {
785                None | Some(Value::Null) => Rounding::HalfUp,
786                Some(m) => {
787                    let name = m.to_string();
788                    Rounding::from_name(&name).ok_or_else(|| format!("arredondamento '{name}' desconhecido (half_up, half_even, truncate, up)"))?
789                }
790            };
791            match arg(0) {
792                Value::Null => Value::Null,
793                Value::Decimal(d) => Value::Decimal(d.round(places, mode).ok_or_else(|| format!("estouro: round({d}, {places})"))?),
794                Value::Int(i) => Value::Int(i),
795                v => {
796                    let f = v.as_f64().ok_or("round precisa de número")?;
797                    let factor = 10f64.powi(places as i32);
798                    let r = (f * factor).round() / factor;
799                    if places == 0 { Value::Int(r as i64) } else { Value::Float(r) }
800                }
801            }
802        }
803        "coalesce" | "ifnull" => values.into_iter().find(|v| !v.is_null()).unwrap_or(Value::Null),
804        "iif" | "if" => {
805            need(3)?;
806            if truth(&eval(&args[0], get)?) == Some(true) { eval(&args[1], get)? } else { eval(&args[2], get)? }
807        }
808        "year" | "month" | "day" => {
809            need(1)?;
810            match arg(0).as_date() {
811                Some(d) => Value::Int(match name {
812                    "year" => d.year() as i64,
813                    "month" => d.month() as i64,
814                    _ => d.day() as i64,
815                }),
816                None => Value::Null,
817            }
818        }
819        // No horário local da tela (antes era o dia em UTC: em Brasília, depois das 21h, já
820        // era amanhã).
821        "today" => Value::Date(Date::today()),
822        "now" => Value::DateTime(crate::value::DateTime::now()),
823        other => return Err(format!("função desconhecida '{other}'")),
824    })
825}