fv-value-datafusion 0.1.1

The fv-value expression dialect as DataFusion expressions: exact translation for pushdown and vectorized evaluation, with a per-row UDF fallback.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! `fv_value::Expr` → `datafusion::logical_expr::Expr`, exact or not at all.
//!
//! Every emitted expression reproduces the dialect's answer for every row, including its null,
//! NaN, `-0.0`, strict-boolean and error semantics. Where that cannot be done — an unmapped
//! function, an unsupported column type, an operation whose result kind is not statically known —
//! the sub-expression is left to the per-row fallback ([`crate::udf::EvalUdf`]) or refused.
//!
//! Two relaxations are available to the integrator, both sound within their stated scope:
//! predicate mode ([`Translator::translate_predicate`]), where a filter's NULL means false, and
//! [`Options::assume_no_nan`] for sources that cannot hold NaN. Together they turn
//! `status == 'ACTIVE' && speed > 40` into the plain `status = 'ACTIVE' AND speed > 40` that a
//! source's pushdown recognises.

use std::fmt;

use datafusion::arrow::datatypes::{DataType, SchemaRef};
use datafusion::common::Column;
use datafusion::config::ConfigOptions;
use datafusion::functions::{core, datetime, math, regex, string, unicode};
use datafusion::logical_expr::{cast, lit, when, BinaryExpr, Expr as DfExpr, Operator, ScalarUDF};
use datafusion::scalar::ScalarValue;
use fv_value::{Ast, BinaryOp, Expr, UnaryOp, Value};

use crate::convert::{data_type_for, Kind};
use crate::udf::{fallback, ErrorUdf};

/// Why an expression (or part of it) could not be translated exactly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unsupported {
    /// What stood in the way.
    pub reason: String,
}

impl fmt::Display for Unsupported {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "not translatable: {}", self.reason)
    }
}

impl std::error::Error for Unsupported {}

fn no<T>(reason: impl Into<String>) -> Result<T, Unsupported> {
    Err(Unsupported { reason: reason.into() })
}

/// A translated expression.
#[derive(Debug, Clone)]
pub struct Translation {
    /// The DataFusion expression.
    pub expr: DfExpr,
    /// The kind of value it produces.
    pub kind: Kind,
    /// `true` when no per-row fallback was needed anywhere in the tree.
    pub exact: bool,
}

/// What the integrator knows about the rows, which lets the translator drop guards it would
/// otherwise need. Every option defaults to the strict setting.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Options {
    /// The numbers in the rows are never NaN — true for any JSON-derived source (OpenSearch, most
    /// connectors), since JSON cannot express NaN. Drops the `isnan` guards, so comparisons on
    /// columns become plain `x > 5` that a source can push down. Only expressions that themselves
    /// produce NaN (`pow` of a negative base with a fractional exponent, `inf - inf`) could then
    /// diverge from the dialect, and only in their ordering.
    pub assume_no_nan: bool,
}

/// Translates compiled dialect expressions against a schema (column types decide what is exact).
#[derive(Debug, Clone)]
pub struct Translator {
    schema: SchemaRef,
    options: Options,
}

/// A translated node with the facts the parent needs to keep the translation exact.
#[derive(Debug, Clone)]
struct Node {
    expr: DfExpr,
    kind: Kind,
    /// Can evaluate to NULL.
    nullable: bool,
    /// Can evaluate to NaN (floats from columns or arithmetic; never literals or integers).
    maybe_nan: bool,
    /// Can fail at run time (a division, a domain check, a strict-boolean check, a fallback).
    may_error: bool,
    exact: bool,
}

impl Node {
    fn new(expr: DfExpr, kind: Kind) -> Self {
        Node {
            expr,
            kind,
            nullable: true,
            maybe_nan: kind == Kind::Num,
            may_error: false,
            exact: true,
        }
    }
    fn certain(mut self) -> Self {
        self.nullable = false;
        self
    }
    fn finite(mut self) -> Self {
        self.maybe_nan = false;
        self
    }
    fn fallible(mut self) -> Self {
        self.may_error = true;
        self
    }
    fn null(kind: Kind) -> Self {
        Node::new(null_of(kind), kind).finite()
    }
}

fn f64_lit(x: f64) -> DfExpr {
    DfExpr::Literal(ScalarValue::Float64(Some(x)), None)
}

fn null_of(kind: Kind) -> DfExpr {
    DfExpr::Literal(
        match kind {
            Kind::Num => ScalarValue::Float64(None),
            Kind::Str => ScalarValue::Utf8(None),
            Kind::Bool => ScalarValue::Boolean(None),
            Kind::Null => ScalarValue::Null,
        },
        None,
    )
}

fn binary(l: DfExpr, op: Operator, r: DfExpr) -> DfExpr {
    DfExpr::BinaryExpr(BinaryExpr::new(Box::new(l), op, Box::new(r)))
}

/// `x IS NULL [OR y IS NULL]` over the operands that can actually be null, if any.
fn any_null(nodes: &[&Node]) -> Option<DfExpr> {
    let checks: Vec<DfExpr> = nodes
        .iter()
        .filter(|n| n.nullable)
        .map(|n| n.expr.clone().is_null())
        .collect();
    (!checks.is_empty()).then(|| or_all(checks))
}

/// `isnan(x) [OR isnan(y)]` over the operands that can actually be NaN, if any.
fn any_nan(nodes: &[&Node]) -> Option<DfExpr> {
    let checks: Vec<DfExpr> = nodes
        .iter()
        .filter(|n| n.maybe_nan)
        .map(|n| isnan(n.expr.clone()))
        .collect();
    (!checks.is_empty()).then(|| or_all(checks))
}

fn or_all(mut items: Vec<DfExpr>) -> DfExpr {
    let first = items.remove(0);
    items.into_iter().fold(first, |acc, e| binary(acc, Operator::Or, e))
}

/// `CASE WHEN c1 THEN t1 [WHEN …] ELSE e END`.
fn case(clauses: Vec<(DfExpr, DfExpr)>, otherwise: DfExpr) -> DfExpr {
    let mut it = clauses.into_iter();
    let (c, t) = it.next().expect("at least one WHEN");
    let mut b = when(c, t);
    for (c, t) in it {
        b = b.when(c, t);
    }
    b.otherwise(otherwise).expect("a CASE with clauses is well-formed")
}

/// A `CASE` whose branches are booleans, encoded numerically: `CASE … THEN CAST(b AS DOUBLE) … END = 1.0`.
/// DataFusion's simplifier rewrites a *boolean-valued* `CASE` with one or two clauses into `AND`/`OR`
/// form, which evaluates every branch eagerly; a Float64-valued `CASE` keeps its branches lazy, so
/// errors and expensive sub-expressions only run for the rows that select them. Nulls survive:
/// `CAST(NULL AS DOUBLE) = 1.0` is NULL.
fn lazy_bool_case(clauses: Vec<(DfExpr, DfExpr)>, otherwise: DfExpr) -> DfExpr {
    let num = |b: DfExpr| match b {
        DfExpr::Literal(ScalarValue::Boolean(Some(true)), _) => f64_lit(1.0),
        DfExpr::Literal(ScalarValue::Boolean(Some(false)), _) => f64_lit(0.0),
        other => cast(other, DataType::Float64),
    };
    let clauses = clauses.into_iter().map(|(c, t)| (c, num(t))).collect();
    binary(case(clauses, num(otherwise)), Operator::Eq, f64_lit(1.0))
}

fn error(kind: Kind, message: &str) -> DfExpr {
    ErrorUdf::call_expr(data_type_for(kind), message)
}

fn isnan(e: DfExpr) -> DfExpr {
    math::isnan().call(vec![e])
}

fn to_f64(e: DfExpr) -> DfExpr {
    cast(e, DataType::Float64)
}

fn is_nonzero_literal(e: &DfExpr) -> bool {
    matches!(e, DfExpr::Literal(ScalarValue::Float64(Some(x)), _) if *x != 0.0)
}

/// A `null` literal of the untyped kind, retyped to sit beside `kind` in a CASE / coalesce.
fn retype(expr: DfExpr, from: Kind, to: Kind) -> DfExpr {
    if from == Kind::Null && to != Kind::Null {
        null_of(to)
    } else {
        expr
    }
}

/// The one non-null kind among `kinds` (nulls are compatible with anything), if consistent.
fn common_kind(kinds: impl Iterator<Item = Option<Kind>>) -> Option<Kind> {
    let mut found: Option<Kind> = None;
    for k in kinds {
        match k? {
            Kind::Null => {}
            k => match found {
                None => found = Some(k),
                Some(f) if f == k => {}
                Some(_) => return None,
            },
        }
    }
    Some(found.unwrap_or(Kind::Null))
}

/// The static result kind of a standard builtin, for typing the fallback of an unmapped call.
fn builtin_kind(name: &str, args: &[Option<Kind>]) -> Option<Kind> {
    const NUM: &[&str] = &[
        "abs",
        "floor",
        "ceil",
        "trunc",
        "round",
        "exp",
        "sqrt",
        "ln",
        "log10",
        "log2",
        "cbrt",
        "sign",
        "pow",
        "hypot",
        "degToRad",
        "radToDeg",
        "min",
        "max",
        "clamp",
        "roundTo",
        "toNumber",
        "sin",
        "cos",
        "tan",
        "asin",
        "acos",
        "atan",
        "atan2",
        "sinh",
        "cosh",
        "tanh",
        "log",
        "pi",
        "factorial",
        "gcd",
        "lcm",
        "length",
        "indexOf",
        "ascii",
        "epochMs",
        "yearOf",
        "monthOf",
        "dayOf",
        "hourOf",
        "minuteOf",
        "dayOfWeekOf",
        "dayOfYear",
        "arraySum",
        "arrayMin",
        "arrayMax",
        "haversineKm",
        "bearingDeg",
        "distance3dM",
    ];
    const STR: &[&str] = &[
        "upper",
        "lower",
        "trim",
        "trimStart",
        "trimEnd",
        "capitalize",
        "reverse",
        "concat",
        "replace",
        "repeat",
        "substr",
        "left",
        "right",
        "splitPart",
        "concatWs",
        "chr",
        "toHex",
        "regexReplace",
        "substring",
        "padStart",
        "padEnd",
        "toString",
        "regexExtract",
        "arrayJoin",
        "epochToIso",
        "typeOf",
        "groundStrike",
    ];
    const BOOL: &[&str] = &[
        "contains",
        "startsWith",
        "endsWith",
        "regexMatch",
        "isNull",
        "isNumber",
        "isString",
        "isBoolean",
        "arrayContains",
        "geoContains",
        "geoWithin",
        "geoIntersects",
        "altitudeBetween",
        "geoWithinVolume",
    ];
    if NUM.contains(&name) {
        Some(Kind::Num)
    } else if STR.contains(&name) {
        Some(Kind::Str)
    } else if BOOL.contains(&name) {
        Some(Kind::Bool)
    } else if name == "coalesce" || name == "nullIf" {
        common_kind(args.iter().copied())
    } else {
        None
    }
}

/// The dialect's domain checks on numeric functions that DataFusion would let through as NaN/±inf.
#[derive(Clone, Copy)]
enum Guard {
    NonNegative,
    Positive,
    UnitInterval,
}

/// Wrap a mapped numeric function so out-of-domain inputs raise the dialect's error instead of
/// producing NaN or infinity. Nulls pass through (the function propagates them).
fn guarded(node: Node, arg: &Node, guard: Guard, message: &str) -> Node {
    if arg.kind != Kind::Num {
        return node;
    }
    let x = arg.expr.clone();
    let out_of_domain = match guard {
        Guard::NonNegative => binary(x, Operator::Lt, f64_lit(0.0)),
        Guard::Positive => binary(x, Operator::LtEq, f64_lit(0.0)),
        Guard::UnitInterval => binary(
            binary(x.clone(), Operator::Lt, f64_lit(-1.0)),
            Operator::Or,
            binary(x, Operator::Gt, f64_lit(1.0)),
        ),
    };
    let mut clauses = Vec::new();
    if arg.nullable {
        clauses.push((arg.expr.clone().is_null(), null_of(Kind::Num)));
    }
    clauses.push((out_of_domain, error(Kind::Num, message)));
    Node {
        expr: case(clauses, node.expr),
        may_error: true,
        ..node
    }
}

type Udf = fn() -> std::sync::Arc<ScalarUDF>;

impl Translator {
    /// A translator for expressions evaluated against rows of `schema`, with strict [`Options`].
    pub fn new(schema: SchemaRef) -> Self {
        Translator {
            schema,
            options: Options::default(),
        }
    }

    /// Set the [`Options`].
    pub fn with_options(mut self, options: Options) -> Self {
        self.options = options;
        self
    }

    /// Translate exactly, or refuse. Nothing in the result needs a per-row fallback.
    pub fn translate(&self, expr: &Expr) -> Result<Translation, Unsupported> {
        let n = self.node(expr.ast(), false, false)?;
        Ok(Translation {
            expr: n.expr,
            kind: n.kind,
            exact: true,
        })
    }

    /// Translate exactly where possible; sub-expressions that cannot be translated become per-row
    /// UDF calls over their columns, so the rest of the expression still pushes down. Fails only
    /// when the result kind of some untranslatable part cannot be determined statically.
    pub fn translate_or_fallback(&self, expr: &Expr) -> Result<Translation, Unsupported> {
        let n = self.node(expr.ast(), true, false)?;
        Ok(Translation {
            expr: n.expr,
            kind: n.kind,
            exact: n.exact,
        })
    }

    /// Translate a boolean expression for use as a **filter**, where DataFusion treats a NULL
    /// result as false — exactly what the dialect returns for a comparison involving null. That
    /// equivalence lets comparisons and `&&`/`||` chains be emitted plainly (`x > 5 AND s = 'a'`),
    /// which is what a source's pushdown recognises; the guards are kept wherever the value could
    /// flow somewhere NULL and false differ (`!`, `?:`, `==` on the result, `!=`) or where a side
    /// can fail. Refuses non-boolean expressions.
    pub fn translate_predicate(&self, expr: &Expr) -> Result<Translation, Unsupported> {
        let n = self.node(expr.ast(), false, true)?;
        if n.kind != Kind::Bool {
            return no(format!("a filter must be a boolean, this is a {:?}", n.kind));
        }
        Ok(Translation {
            expr: n.expr,
            kind: n.kind,
            exact: true,
        })
    }

    /// [`translate_predicate`](Self::translate_predicate) with the per-row fallback for what
    /// cannot be translated. DataFusion splits `AND`s into separate filters, so the translatable
    /// conjuncts still push down when one needs the fallback.
    pub fn translate_predicate_or_fallback(&self, expr: &Expr) -> Result<Translation, Unsupported> {
        let n = self.node(expr.ast(), true, true)?;
        if n.kind != Kind::Bool {
            return no(format!("a filter must be a boolean, this is a {:?}", n.kind));
        }
        Ok(Translation {
            expr: n.expr,
            kind: n.kind,
            exact: n.exact,
        })
    }

    /// The static kind of an expression's result, if it can be known from the schema alone.
    pub fn kind_of(&self, expr: &Expr) -> Option<Kind> {
        self.kind(expr.ast())
    }

    fn column_kind(&self, name: &str) -> Option<Kind> {
        self.schema
            .field_with_name(name)
            .ok()
            .and_then(|f| Kind::of_data_type(f.data_type()))
    }

    fn kind(&self, ast: &Ast) -> Option<Kind> {
        Some(match ast {
            Ast::Lit(v) => match v {
                Value::Null => Kind::Null,
                Value::Bool(_) => Kind::Bool,
                Value::Num(_) => Kind::Num,
                Value::Str(_) => Kind::Str,
                _ => return None,
            },
            Ast::Id(name) => match self.schema.field_with_name(name) {
                Ok(_) => self.column_kind(name)?,
                Err(_) => Kind::Null, // no such column: the dialect reads it as null
            },
            Ast::Member(..) | Ast::Index(..) | Ast::List(_) => return None,
            Ast::Unary(UnaryOp::Not, _) => Kind::Bool,
            Ast::Unary(UnaryOp::Neg, _) => Kind::Num,
            Ast::Binary(op, l, r) => match op {
                BinaryOp::Or
                | BinaryOp::And
                | BinaryOp::Eq
                | BinaryOp::Ne
                | BinaryOp::In
                | BinaryOp::Lt
                | BinaryOp::Le
                | BinaryOp::Gt
                | BinaryOp::Ge => Kind::Bool,
                BinaryOp::Add => common_kind([self.kind(l), self.kind(r)].into_iter())?,
                BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Rem => Kind::Num,
                _ => return None,
            },
            Ast::Ternary(_, t, e) => common_kind([self.kind(t), self.kind(e)].into_iter())?,
            Ast::Call(f, args) => {
                let kinds: Vec<Option<Kind>> = args.iter().map(|a| self.kind(a)).collect();
                builtin_kind(f.name(), &kinds)?
            }
            _ => return None,
        })
    }

    /// Translate a subtree; with `fb`, an untranslatable subtree of known kind becomes a fallback;
    /// with `pred`, the subtree's boolean result feeds a filter (NULL ≡ false), which `&&`/`||`
    /// pass down and every other node resets.
    fn node(&self, ast: &Ast, fb: bool, pred: bool) -> Result<Node, Unsupported> {
        match self.node_inner(ast, fb, pred) {
            Ok(n) => Ok(n),
            Err(u) if fb => match self.kind(ast) {
                Some(kind) => {
                    let expr = Expr::from_ast(ast.clone());
                    let mut n = Node::new(fallback(&expr, data_type_for(kind), &self.schema), kind).fallible();
                    n.exact = false;
                    Ok(n)
                }
                None => Err(u),
            },
            Err(u) => Err(u),
        }
    }

    fn node_inner(&self, ast: &Ast, fb: bool, pred: bool) -> Result<Node, Unsupported> {
        // A subtree that reads no columns is a constant: evaluate it here, once, exactly.
        if !matches!(ast, Ast::Lit(_)) && ast.identifiers().is_empty() {
            return self.constant(ast);
        }
        match ast {
            Ast::Lit(v) => Ok(match v {
                Value::Null => Node::null(Kind::Null),
                Value::Bool(b) => Node::new(lit(*b), Kind::Bool).certain().finite(),
                Value::Num(n) => {
                    let node = Node::new(f64_lit(*n), Kind::Num).certain();
                    if n.is_nan() {
                        node
                    } else {
                        node.finite()
                    }
                }
                Value::Str(s) => Node::new(lit(s.as_str()), Kind::Str).certain().finite(),
                Value::List(_) | Value::Obj(_) => return no("list and object literals"),
            }),
            Ast::Id(name) => {
                let Ok(field) = self.schema.field_with_name(name) else {
                    // No such column: the dialect reads a missing identifier as null.
                    return Ok(Node::null(Kind::Null));
                };
                let kind = Kind::of_data_type(field.data_type()).ok_or_else(|| Unsupported {
                    reason: format!("column '{name}' has type {}", field.data_type()),
                })?;
                let column = DfExpr::Column(Column::from_name(name));
                let expr = match (kind, field.data_type()) {
                    (Kind::Num, DataType::Float64) => column,
                    (Kind::Num, _) => to_f64(column),
                    _ => column,
                };
                let mut n = Node::new(expr, kind);
                n.nullable = field.is_nullable();
                n.maybe_nan =
                    !self.options.assume_no_nan && matches!(field.data_type(), DataType::Float32 | DataType::Float64);
                Ok(n)
            }
            Ast::Member(..) => no("member access on objects"),
            Ast::Index(..) => no("indexing"),
            Ast::List(_) => no("list values"),
            Ast::Unary(UnaryOp::Not, a) => {
                let a = self.must_bool(self.node(a, fb, false)?, "'!'")?;
                Ok(Node {
                    expr: DfExpr::Not(Box::new(a.expr)),
                    kind: Kind::Bool,
                    nullable: false,
                    maybe_nan: false,
                    may_error: a.may_error,
                    exact: a.exact,
                })
            }
            Ast::Unary(UnaryOp::Neg, a) => {
                let a = self.node(a, fb, false)?;
                match a.kind {
                    Kind::Null => Ok(Node::null(Kind::Num)),
                    Kind::Num => Ok(Node {
                        expr: DfExpr::Negative(Box::new(a.expr)),
                        ..a
                    }),
                    k => no(format!("unary '-' on a {k:?}")),
                }
            }
            Ast::Ternary(c, t, e) => {
                let c = self.must_bool(self.node(c, fb, false)?, "'?:' condition")?;
                let t = self.node(t, fb, false)?;
                let e = self.node(e, fb, false)?;
                let kind = common_kind([Some(t.kind), Some(e.kind)].into_iter()).ok_or_else(|| Unsupported {
                    reason: "'?:' branches of different kinds".into(),
                })?;
                let (te, ee) = (retype(t.expr, t.kind, kind), retype(e.expr, e.kind, kind));
                let expr = if kind == Kind::Bool {
                    lazy_bool_case(vec![(c.expr, te)], ee)
                } else {
                    case(vec![(c.expr, te)], ee)
                };
                Ok(Node {
                    expr,
                    kind,
                    nullable: t.nullable || e.nullable,
                    maybe_nan: t.maybe_nan || e.maybe_nan,
                    may_error: c.may_error || t.may_error || e.may_error,
                    exact: c.exact && t.exact && e.exact,
                })
            }
            Ast::Binary(op, l, r) => self.binary_node(*op, l, r, fb, pred),
            Ast::Call(f, args) => {
                let nodes = args
                    .iter()
                    .map(|a| self.node(a, fb, false))
                    .collect::<Result<Vec<_>, _>>()?;
                self.call(f.name(), nodes)
            }
            _ => no("unknown node"),
        }
    }

    /// A constant subtree, folded natively: its value as a literal, or its error as an error call.
    fn constant(&self, ast: &Ast) -> Result<Node, Unsupported> {
        let expr = Expr::from_ast(ast.clone());
        match expr.eval(&fv_value::Empty) {
            Ok(Value::Null) => Ok(Node::null(Kind::Null)),
            Ok(Value::Bool(b)) => Ok(Node::new(lit(b), Kind::Bool).certain().finite()),
            Ok(Value::Num(n)) => {
                let node = Node::new(f64_lit(n), Kind::Num).certain();
                Ok(if n.is_nan() { node } else { node.finite() })
            }
            Ok(Value::Str(s)) => Ok(Node::new(lit(s.as_str()), Kind::Str).certain().finite()),
            Ok(other) => no(format!("constant {} values", other.type_name())),
            Err(e) => match self.kind(ast) {
                Some(kind) if kind != Kind::Null => Ok(Node::new(error(kind, &e.to_string()), kind)
                    .certain()
                    .finite()
                    .fallible()),
                _ => no(format!("a constant that errors ({e}) with no known kind")),
            },
        }
    }

    /// A boolean operand as the dialect wants it: a NULL is a run-time error, anything non-boolean
    /// is untranslatable (the fallback reproduces the type error).
    fn must_bool(&self, n: Node, where_: &str) -> Result<Node, Unsupported> {
        match n.kind {
            Kind::Bool if !n.nullable => Ok(n),
            Kind::Bool => Ok(Node {
                expr: lazy_bool_case(
                    vec![(
                        n.expr.clone().is_null(),
                        error(Kind::Bool, &format!("{where_}: expected a boolean, got null")),
                    )],
                    n.expr,
                ),
                nullable: false,
                may_error: true,
                ..n
            }),
            k => no(format!("{where_} on a {k:?}")),
        }
    }

    fn binary_node(&self, op: BinaryOp, l: &Ast, r: &Ast, fb: bool, pred: bool) -> Result<Node, Unsupported> {
        match op {
            BinaryOp::And | BinaryOp::Or => {
                let a = self.must_bool(self.node(l, fb, pred)?, op.symbol())?;
                let b = self.must_bool(self.node(r, fb, pred)?, op.symbol())?;
                let may_error = a.may_error || b.may_error;
                // Short-circuit matters only when the right side can fail: then it must be
                // evaluated only on the rows the left side does not decide. Otherwise a plain
                // AND/OR is exact (both sides are non-null booleans) and pushes down.
                let expr = match (op, b.may_error) {
                    (BinaryOp::And, false) => binary(a.expr, Operator::And, b.expr),
                    (BinaryOp::And, true) => lazy_bool_case(vec![(a.expr, b.expr)], lit(false)),
                    (_, false) => binary(a.expr, Operator::Or, b.expr),
                    (_, true) => lazy_bool_case(vec![(a.expr, lit(true))], b.expr),
                };
                Ok(Node {
                    expr,
                    kind: Kind::Bool,
                    nullable: false,
                    maybe_nan: false,
                    may_error,
                    exact: a.exact && b.exact,
                })
            }
            BinaryOp::In => {
                let a = self.node(l, fb, false)?;
                let Ast::List(items) = r else {
                    return no("'in' with a non-literal list");
                };
                if items.is_empty() {
                    return Ok(Node::new(lit(false), Kind::Bool).certain().finite());
                }
                let mut exact = a.exact;
                let mut may_error = a.may_error;
                let mut clauses = Vec::with_capacity(items.len());
                for it in items {
                    let b = self.node(it, fb, false)?;
                    exact &= b.exact;
                    may_error |= b.may_error;
                    clauses.push(self.eq(&a, &b, pred));
                }
                Ok(Node {
                    expr: or_all(clauses),
                    kind: Kind::Bool,
                    nullable: false,
                    maybe_nan: false,
                    may_error,
                    exact,
                })
            }
            _ => {
                let a = self.node(l, fb, false)?;
                let b = self.node(r, fb, false)?;
                let exact = a.exact && b.exact;
                let may_error = a.may_error || b.may_error;
                let mut n = match op {
                    BinaryOp::Eq => Node::new(self.eq(&a, &b, pred), Kind::Bool).certain().finite(),
                    // `!=` must stay null-safe even in a filter: the dialect keeps a row whose
                    // column is null (`null != 'a'` is true); a plain `<>` would drop it.
                    BinaryOp::Ne => Node::new(DfExpr::Not(Box::new(self.eq(&a, &b, false))), Kind::Bool)
                        .certain()
                        .finite(),
                    BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge => self.ordered(op, &a, &b, pred)?,
                    BinaryOp::Add => self.add(&a, &b)?,
                    BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Rem => self.arith(op, &a, &b)?,
                    BinaryOp::And | BinaryOp::Or | BinaryOp::In => unreachable!(),
                    _ => return no("unknown operator"),
                };
                n.exact = exact;
                n.may_error |= may_error;
                Ok(n)
            }
        }
    }

    /// The dialect's `==` as a boolean expression: never null, or — in a filter (`pred`) — null
    /// exactly where the dialect gives false, which lets it be a plain `=` a source can push down.
    fn eq(&self, a: &Node, b: &Node, pred: bool) -> DfExpr {
        let both_null = binary(a.expr.clone().is_null(), Operator::And, b.expr.clone().is_null());
        match (a.kind, b.kind) {
            (Kind::Null, Kind::Null) => lit(true),
            (Kind::Null, _) => b.expr.clone().is_null(),
            (_, Kind::Null) => a.expr.clone().is_null(),
            (x, y) if x != y => {
                // Different kinds are never equal — unless both are null.
                if a.nullable && b.nullable {
                    both_null
                } else {
                    lit(false)
                }
            }
            (Kind::Num, Kind::Num) => {
                // Arrow compares floats bitwise (NaN == NaN, -0.0 != 0.0); the dialect does the
                // opposite on both counts. Comparing against a nonzero literal cannot meet -0.0.
                let (x, y) = (a.expr.clone(), b.expr.clone());
                let mut clauses = Vec::new();
                if !pred {
                    if a.nullable && b.nullable {
                        clauses.push((both_null, lit(true)));
                    }
                    if let Some(null) = any_null(&[a, b]) {
                        clauses.push((null, lit(false)));
                    }
                }
                if let Some(nan) = any_nan(&[a, b]) {
                    clauses.push((nan, lit(false)));
                }
                let plain = if is_nonzero_literal(&x) || is_nonzero_literal(&y) {
                    binary(x, Operator::Eq, y)
                } else {
                    binary(
                        binary(x, Operator::Plus, f64_lit(0.0)),
                        Operator::Eq,
                        binary(y, Operator::Plus, f64_lit(0.0)),
                    )
                };
                if clauses.is_empty() {
                    plain
                } else {
                    case(clauses, plain)
                }
            }
            _ => {
                if pred && (!a.nullable || !b.nullable) {
                    binary(a.expr.clone(), Operator::Eq, b.expr.clone())
                } else {
                    binary(a.expr.clone(), Operator::IsNotDistinctFrom, b.expr.clone())
                }
            }
        }
    }

    fn ordered(&self, op: BinaryOp, a: &Node, b: &Node, pred: bool) -> Result<Node, Unsupported> {
        let dfop = match op {
            BinaryOp::Lt => Operator::Lt,
            BinaryOp::Le => Operator::LtEq,
            BinaryOp::Gt => Operator::Gt,
            _ => Operator::GtEq,
        };
        match (a.kind, b.kind) {
            (Kind::Null, _) | (_, Kind::Null) => Ok(Node::new(lit(false), Kind::Bool).certain().finite()),
            (Kind::Num, Kind::Num) | (Kind::Str, Kind::Str) => {
                let (x, y) = (a.expr.clone(), b.expr.clone());
                let mut clauses = Vec::new();
                if !pred {
                    if let Some(null) = any_null(&[a, b]) {
                        clauses.push((null, lit(false)));
                    }
                }
                if a.kind == Kind::Num {
                    if let Some(nan) = any_nan(&[a, b]) {
                        clauses.push((nan, lit(false)));
                    }
                }
                let plain = binary(x, dfop, y);
                let expr = if clauses.is_empty() {
                    plain
                } else {
                    case(clauses, plain)
                };
                Ok(Node::new(expr, Kind::Bool).certain().finite())
            }
            (x, y) => no(format!("'{}' between a {x:?} and a {y:?}", op.symbol())),
        }
    }

    fn add(&self, a: &Node, b: &Node) -> Result<Node, Unsupported> {
        match (a.kind, b.kind) {
            (Kind::Null, Kind::Null) => Ok(Node::null(Kind::Null)),
            (Kind::Null, k) | (k, Kind::Null) if matches!(k, Kind::Num | Kind::Str) => Ok(Node::null(k)),
            (Kind::Num, Kind::Num) => Ok(Node {
                expr: binary(a.expr.clone(), Operator::Plus, b.expr.clone()),
                kind: Kind::Num,
                nullable: a.nullable || b.nullable,
                maybe_nan: true,
                may_error: false,
                exact: true,
            }),
            (Kind::Str, Kind::Str) => Ok(Node {
                expr: binary(a.expr.clone(), Operator::StringConcat, b.expr.clone()),
                kind: Kind::Str,
                nullable: a.nullable || b.nullable,
                maybe_nan: false,
                may_error: false,
                exact: true,
            }),
            (x, y) => no(format!("'+' between a {x:?} and a {y:?}")),
        }
    }

    fn arith(&self, op: BinaryOp, a: &Node, b: &Node) -> Result<Node, Unsupported> {
        match (a.kind, b.kind) {
            (Kind::Null, _) | (_, Kind::Null)
                if matches!(a.kind, Kind::Null | Kind::Num) && matches!(b.kind, Kind::Null | Kind::Num) =>
            {
                Ok(Node::null(Kind::Num))
            }
            (Kind::Num, Kind::Num) => {
                let (x, y) = (a.expr.clone(), b.expr.clone());
                let dfop = match op {
                    BinaryOp::Sub => Operator::Minus,
                    BinaryOp::Mul => Operator::Multiply,
                    BinaryOp::Div => Operator::Divide,
                    _ => Operator::Modulo,
                };
                let guarded = matches!(op, BinaryOp::Div | BinaryOp::Rem) && !is_nonzero_literal(&b.expr);
                let plain = binary(x, dfop, y.clone());
                let expr = if guarded {
                    let mut clauses = Vec::new();
                    if let Some(null) = any_null(&[a, b]) {
                        clauses.push((null, null_of(Kind::Num)));
                    }
                    clauses.push((
                        binary(y, Operator::Eq, f64_lit(0.0)),
                        error(Kind::Num, "division by zero"),
                    ));
                    case(clauses, plain)
                } else {
                    plain
                };
                Ok(Node {
                    expr,
                    kind: Kind::Num,
                    nullable: a.nullable || b.nullable,
                    maybe_nan: true,
                    may_error: guarded,
                    exact: true,
                })
            }
            (x, y) => no(format!("'{}' between a {x:?} and a {y:?}", op.symbol())),
        }
    }

    fn call(&self, name: &str, args: Vec<Node>) -> Result<Node, Unsupported> {
        let exact = args.iter().all(|a| a.exact);
        let nullable = args.iter().any(|a| a.nullable);
        let may_error = args.iter().any(|a| a.may_error);
        let num = |expr: DfExpr, nullable: bool| Node {
            expr,
            kind: Kind::Num,
            nullable,
            maybe_nan: true,
            may_error,
            exact,
        };
        let num1 = |f: Udf, a: &Node| -> Result<Node, Unsupported> {
            match a.kind {
                Kind::Num => Ok(num(f().call(vec![a.expr.clone()]), a.nullable)),
                Kind::Null => Ok(Node::null(Kind::Num)),
                k => no(format!("{name} on a {k:?}")),
            }
        };
        let str1 = |f: Udf, a: &Node, kind: Kind| -> Result<Node, Unsupported> {
            match a.kind {
                Kind::Str => Ok(Node {
                    expr: f().call(vec![a.expr.clone()]),
                    kind,
                    nullable: a.nullable,
                    maybe_nan: false,
                    may_error,
                    exact,
                }),
                Kind::Null => Ok(Node::null(kind)),
                k => no(format!("{name} on a {k:?}")),
            }
        };
        let all_num = |args: &[Node]| args.iter().all(|a| a.kind == Kind::Num);
        let all_str = |args: &[Node]| args.iter().all(|a| a.kind == Kind::Str);
        let any_null_kind = |args: &[Node]| args.iter().any(|a| a.kind == Kind::Null);
        let all_num_or_null = |args: &[Node]| args.iter().all(|a| matches!(a.kind, Kind::Num | Kind::Null));
        let all_str_or_null = |args: &[Node]| args.iter().all(|a| matches!(a.kind, Kind::Str | Kind::Null));
        match (name, args.as_slice()) {
            ("abs", [a]) => num1(math::abs, a),
            ("floor", [a]) => num1(math::floor, a),
            ("ceil", [a]) => num1(math::ceil, a),
            ("trunc", [a]) => num1(math::trunc, a),
            ("exp", [a]) => num1(math::exp, a),
            ("cbrt", [a]) => num1(math::cbrt, a),
            ("sin", [a]) => num1(math::sin, a),
            ("cos", [a]) => num1(math::cos, a),
            ("tan", [a]) => num1(math::tan, a),
            ("atan", [a]) => num1(math::atan, a),
            ("sinh", [a]) => num1(math::sinh, a),
            ("cosh", [a]) => num1(math::cosh, a),
            ("tanh", [a]) => num1(math::tanh, a),
            ("degToRad", [a]) => num1(math::radians, a),
            ("radToDeg", [a]) => num1(math::degrees, a),
            ("sqrt", [a]) => Ok(guarded(
                num1(math::sqrt, a)?,
                a,
                Guard::NonNegative,
                "sqrt: negative argument",
            )),
            ("ln", [a]) => Ok(guarded(
                num1(math::ln, a)?,
                a,
                Guard::Positive,
                "ln: argument must be positive",
            )),
            ("log10", [a]) => Ok(guarded(
                num1(math::log10, a)?,
                a,
                Guard::Positive,
                "log10: argument must be positive",
            )),
            ("log2", [a]) => Ok(guarded(
                num1(math::log2, a)?,
                a,
                Guard::Positive,
                "log2: argument must be positive",
            )),
            ("asin", [a]) => Ok(guarded(
                num1(math::asin, a)?,
                a,
                Guard::UnitInterval,
                "asin: argument must be in [-1, 1]",
            )),
            ("acos", [a]) => Ok(guarded(
                num1(math::acos, a)?,
                a,
                Guard::UnitInterval,
                "acos: argument must be in [-1, 1]",
            )),
            ("round", [a]) => match a.kind {
                // The dialect rounds half up; DataFusion's round is half away from zero.
                Kind::Num => Ok(num(
                    math::floor().call(vec![binary(a.expr.clone(), Operator::Plus, f64_lit(0.5))]),
                    a.nullable,
                )),
                Kind::Null => Ok(Node::null(Kind::Num)),
                k => no(format!("round on a {k:?}")),
            },
            ("roundTo" | "pow" | "atan2", _) if any_null_kind(&args) && all_num_or_null(&args) => {
                Ok(Node::null(Kind::Num))
            }
            ("roundTo", [a, n]) if all_num(&args) => {
                let f = math::power().call(vec![f64_lit(10.0), math::trunc().call(vec![n.expr.clone()])]);
                let scaled = binary(
                    binary(a.expr.clone(), Operator::Multiply, f.clone()),
                    Operator::Plus,
                    f64_lit(0.5),
                );
                Ok(num(
                    binary(math::floor().call(vec![scaled]), Operator::Divide, f),
                    nullable,
                ))
            }
            ("pow", [a, b]) if all_num(&args) => {
                Ok(num(math::power().call(vec![a.expr.clone(), b.expr.clone()]), nullable))
            }
            ("atan2", [a, b]) if all_num(&args) => {
                Ok(num(math::atan2().call(vec![a.expr.clone(), b.expr.clone()]), nullable))
            }
            ("pi", []) => Ok(Node::new(f64_lit(std::f64::consts::PI), Kind::Num).certain().finite()),
            ("sign", [a]) => match a.kind {
                Kind::Num => {
                    let x = a.expr.clone();
                    let mut clauses = Vec::new();
                    if a.nullable {
                        clauses.push((x.clone().is_null(), null_of(Kind::Num)));
                    }
                    clauses.push((binary(x.clone(), Operator::Gt, f64_lit(0.0)), f64_lit(1.0)));
                    clauses.push((binary(x, Operator::Lt, f64_lit(0.0)), f64_lit(-1.0)));
                    Ok(Node {
                        expr: case(clauses, f64_lit(0.0)),
                        kind: Kind::Num,
                        nullable: a.nullable,
                        maybe_nan: false,
                        may_error,
                        exact,
                    })
                }
                Kind::Null => Ok(Node::null(Kind::Num)),
                k => no(format!("sign on a {k:?}")),
            },
            ("coalesce", _) => {
                let kind = common_kind(args.iter().map(|a| Some(a.kind))).ok_or_else(|| Unsupported {
                    reason: "coalesce over mixed kinds".into(),
                })?;
                let exprs: Vec<DfExpr> = args.iter().map(|a| retype(a.expr.clone(), a.kind, kind)).collect();
                Ok(Node {
                    expr: core::coalesce().call(exprs),
                    kind,
                    nullable: args.iter().all(|a| a.nullable),
                    maybe_nan: args.iter().any(|a| a.maybe_nan),
                    may_error,
                    exact,
                })
            }
            ("isNull", [a]) => Ok(Node {
                expr: a.expr.clone().is_null(),
                kind: Kind::Bool,
                nullable: false,
                maybe_nan: false,
                may_error,
                exact,
            }),
            ("isNumber" | "isString" | "isBoolean", [a]) => {
                let want = match name {
                    "isNumber" => Kind::Num,
                    "isString" => Kind::Str,
                    _ => Kind::Bool,
                };
                let expr = if a.kind == want {
                    a.expr.clone().is_not_null()
                } else {
                    lit(false)
                };
                Ok(Node {
                    expr,
                    kind: Kind::Bool,
                    nullable: false,
                    maybe_nan: false,
                    may_error,
                    exact,
                })
            }
            ("typeOf", [a]) => {
                let type_name = match a.kind {
                    Kind::Num => "number",
                    Kind::Str => "string",
                    Kind::Bool => "boolean",
                    Kind::Null => "null",
                };
                let expr = if a.nullable && a.kind != Kind::Null {
                    case(vec![(a.expr.clone().is_null(), lit("null"))], lit(type_name))
                } else {
                    lit(type_name)
                };
                Ok(Node {
                    expr,
                    kind: Kind::Str,
                    nullable: false,
                    maybe_nan: false,
                    may_error,
                    exact,
                })
            }
            ("nullIf", [a, b]) => {
                let kind = common_kind([Some(a.kind), Some(b.kind)].into_iter()).ok_or_else(|| Unsupported {
                    reason: "nullIf over mixed kinds".into(),
                })?;
                Ok(Node {
                    expr: case(
                        vec![(self.eq(a, b, false), null_of(kind))],
                        retype(a.expr.clone(), a.kind, kind),
                    ),
                    kind,
                    nullable: true,
                    maybe_nan: a.maybe_nan,
                    may_error,
                    exact,
                })
            }
            ("upper", [a]) => str1(string::upper, a, Kind::Str),
            ("lower", [a]) => str1(string::lower, a, Kind::Str),
            ("reverse", [a]) => str1(unicode::reverse, a, Kind::Str),
            ("length", [a]) => match a.kind {
                Kind::Str => Ok(Node {
                    expr: to_f64(unicode::character_length().call(vec![a.expr.clone()])),
                    kind: Kind::Num,
                    nullable: a.nullable,
                    maybe_nan: false,
                    may_error,
                    exact,
                }),
                Kind::Null => Ok(Node::null(Kind::Num)),
                k => no(format!("length on a {k:?}")),
            },
            ("startsWith" | "endsWith" | "contains" | "regexMatch", _)
                if any_null_kind(&args) && all_str_or_null(&args) =>
            {
                Ok(Node::null(Kind::Bool))
            }
            ("startsWith" | "endsWith" | "contains", [a, b]) if all_str(&args) => {
                let f = match name {
                    "startsWith" => string::starts_with(),
                    "endsWith" => string::ends_with(),
                    _ => string::contains(),
                };
                Ok(Node {
                    expr: f.call(vec![a.expr.clone(), b.expr.clone()]),
                    kind: Kind::Bool,
                    nullable,
                    maybe_nan: false,
                    may_error,
                    exact,
                })
            }
            ("regexMatch", [a, b]) if all_str(&args) => Ok(Node {
                expr: regex::regexp_like().call(vec![a.expr.clone(), b.expr.clone()]),
                kind: Kind::Bool,
                nullable,
                maybe_nan: false,
                may_error: true, // an invalid pattern fails, in both
                exact,
            }),
            ("replace" | "indexOf", _) if any_null_kind(&args) && all_str_or_null(&args) => {
                Ok(Node::null(if name == "replace" { Kind::Str } else { Kind::Num }))
            }
            ("replace", [a, b, c]) if all_str(&args) => Ok(Node {
                expr: string::replace().call(vec![a.expr.clone(), b.expr.clone(), c.expr.clone()]),
                kind: Kind::Str,
                nullable,
                maybe_nan: false,
                may_error,
                exact,
            }),
            ("indexOf", [a, b]) if all_str(&args) => {
                let pos = to_f64(unicode::strpos().call(vec![a.expr.clone(), b.expr.clone()]));
                let mut clauses = Vec::new();
                if let Some(null) = any_null(&[a, b]) {
                    clauses.push((null, null_of(Kind::Num)));
                }
                clauses.push((binary(pos.clone(), Operator::Eq, f64_lit(0.0)), f64_lit(-1.0)));
                Ok(Node {
                    expr: case(clauses, binary(pos, Operator::Minus, f64_lit(1.0))),
                    kind: Kind::Num,
                    nullable,
                    maybe_nan: false,
                    may_error,
                    exact,
                })
            }
            ("yearOf" | "monthOf" | "dayOf" | "hourOf" | "minuteOf" | "dayOfWeekOf" | "dayOfYear", [a]) => match a.kind
            {
                Kind::Num => {
                    // The dialect reads whole seconds of UTC from epoch milliseconds.
                    let secs = math::floor().call(vec![binary(a.expr.clone(), Operator::Divide, f64_lit(1000.0))]);
                    let ts = datetime::to_timestamp_seconds(&ConfigOptions::default())
                        .call(vec![cast(secs, DataType::Int64)]);
                    let part = |p: &str| to_f64(datetime::date_part().call(vec![lit(p), ts.clone()]));
                    let expr = match name {
                        "yearOf" => part("year"),
                        "monthOf" => part("month"),
                        "dayOf" => part("day"),
                        "hourOf" => part("hour"),
                        "minuteOf" => part("minute"),
                        "dayOfYear" => part("doy"),
                        _ => {
                            // ISO weekday: Monday = 1 … Sunday = 7; DataFusion's dow is Sunday = 0.
                            let dow = part("dow");
                            case(
                                vec![(binary(dow.clone(), Operator::Eq, f64_lit(0.0)), f64_lit(7.0))],
                                dow,
                            )
                        }
                    };
                    Ok(Node {
                        expr,
                        kind: Kind::Num,
                        nullable: a.nullable,
                        maybe_nan: false,
                        may_error,
                        exact,
                    })
                }
                Kind::Null => Ok(Node::null(Kind::Num)),
                k => no(format!("{name} on a {k:?}")),
            },
            _ => no(format!("function {name}")),
        }
    }
}