fv-value-datafusion 0.2.0

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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
//! `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 — and a NaN or infinite computed number, which
//! the dialect makes an error. 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. A row the dialect rejects may
//! be handed to it so the error is its own (an epoch with no date); that never computes a value,
//! so the translation stays exact.
//!
//! 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_finite`] for rows known to hold no NaN or infinity. Together they turn
//! `status == 'ACTIVE' && speed > 40` into the plain `status = 'ACTIVE' AND speed > 40` that a
//! source's pushdown recognises; without the second, the comparison gains the NaN bound
//! `speed <= +inf`, still a range a source can prune on.

use std::fmt;

use datafusion::arrow::datatypes::{DataType, SchemaRef};
use datafusion::common::Column;
use datafusion::functions::{core, datetime, math, regex, string, unicode};
use datafusion::functions_nested::expr_fn::array_element;
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, FiniteUdf};

/// 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 float columns hold no NaN and no infinity. Comparisons on them then need no NaN bound
    /// and a computation that cannot overflow finite inputs needs no finiteness check, so the
    /// translation costs what DataFusion's bare kernels cost. Sound only when it is known: a source
    /// that cannot hold such values (OpenSearch documents), or a batch whose float columns
    /// [`crate::all_finite`] has just checked (one pass per column, about 0.15 ns a value).
    /// Arithmetic that can overflow is still checked.
    pub assume_finite: 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 or ±infinity — only a float column, or a value passed through from one:
    /// the dialect turns a non-finite *computed* number into an error, so a computed node is finite.
    maybe_nonfinite: 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_nonfinite: kind == Kind::Num,
            may_error: false,
            exact: true,
        }
    }
    fn certain(mut self) -> Self {
        self.nullable = false;
        self
    }
    fn finite(mut self) -> Self {
        self.maybe_nonfinite = 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))
}

/// `a op b` for two numbers (`op` an ordering), as the dialect orders them. Arrow orders floats by
/// IEEE totalOrder, the dialect by IEEE comparison, and the two differ in two places:
/// - zeros: totalOrder puts -0 below +0, the dialect has them equal. Against a zero literal its
///   sign is chosen so either zero lands where the dialect puts it (`x < 0` is `x < -0.0`,
///   `x <= 0` is `x <= +0.0`); between two non-literals both are normalised by adding +0.0.
/// - NaN: totalOrder puts a positive NaN above +inf and a negative one below -inf, the dialect
///   orders it against nothing. A side that may be NaN is bounded on the side it would wrongly
///   win (`x > c` gains `x <= +inf`), a conjunct that still lets a source prune on `x > c`.
fn ordered_numbers(op: Operator, a: &Node, b: &Node) -> DfExpr {
    let greater = matches!(op, Operator::Gt | Operator::GtEq);
    let inclusive = matches!(op, Operator::LtEq | Operator::GtEq);
    // the zero literal for each side: on the right, `<` and `>=` take -0.0 and `<=` and `>` take
    // +0.0; on the left the reverse
    let zero = |right: bool| if (inclusive == greater) == right { -0.0 } else { 0.0 };
    let side = |n: &Node, right: bool, other: &Node| match f64_literal(&n.expr) {
        Some(0.0) => f64_lit(zero(right)),
        Some(_) => n.expr.clone(),
        None if f64_literal(&other.expr).is_some() => n.expr.clone(),
        None => binary(n.expr.clone(), Operator::Plus, f64_lit(0.0)),
    };
    let mut conj = binary(side(a, false, b), op, side(b, true, a));
    // the side that would wrongly win with a NaN: a greater-than's left and a less-than's right
    // must not be a NaN above +inf; the other side must not be one below -inf
    let (high, low) = if greater { (a, b) } else { (b, a) };
    if high.maybe_nonfinite {
        conj = binary(
            conj,
            Operator::And,
            binary(high.expr.clone(), Operator::LtEq, f64_lit(f64::INFINITY)),
        );
    }
    if low.maybe_nonfinite {
        conj = binary(
            conj,
            Operator::And,
            binary(low.expr.clone(), Operator::GtEq, f64_lit(f64::NEG_INFINITY)),
        );
    }
    conj
}

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])
}

/// A number literal at or above zero (a count the dialect and DataFusion treat alike).
fn non_negative_literal(e: &DfExpr) -> bool {
    matches!(e, DfExpr::Literal(ScalarValue::Float64(Some(n)), _) if *n >= 0.0 && n.fract() == 0.0)
}

/// 2^63: the first whole number past `i64::MAX`, and exactly a float.
const TWO_POW_63: f64 = 9_223_372_036_854_775_808.0;

/// A whole-number literal within the 64-bit range (a count or position both sides read alike).
fn whole_literal(e: &DfExpr) -> bool {
    f64_literal(e).is_some_and(|n| n.fract() == 0.0 && n.abs() < TWO_POW_63)
}

/// The magnitudes of a fraction for which Arrow's float text (`CAST(x AS Utf8)`) is the dialect's
/// `toString`: below it Arrow switches to scientific notation, and from 10^15 the two can choose a
/// different last digit. A test pins it against the dialect.
pub const PLAIN_FLOAT_TEXT: std::ops::Range<f64> = 1e-5..1e15;

/// An epoch in milliseconds as a timestamp: its whole milliseconds, truncated toward zero as the
/// dialect reads them (`CAST` to `Int64` truncates).
fn epoch_millis(a: &Node) -> DfExpr {
    datetime::expr_fn::to_timestamp_millis(vec![cast(a.expr.clone(), DataType::Int64)])
}

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

/// A number literal's value.
fn f64_literal(e: &DfExpr) -> Option<f64> {
    match e {
        DfExpr::Literal(ScalarValue::Float64(Some(x)), _) => Some(*x),
        _ => None,
    }
}

/// The dialect's rule for a computed number — NaN or ±infinity is an error naming `what` — applied
/// only where such a result is `possible`: an input may already be non-finite, or the operation can
/// overflow finite inputs. Everywhere else the result is known finite and carries no check, so the
/// common shapes (`price * 0.908`, `round(x)` over finite data) translate to the bare kernel.
fn finite_checked(mut node: Node, what: &str, possible: bool) -> Node {
    if node.kind == Kind::Num && possible {
        node.expr = FiniteUdf::call_expr(node.expr, what);
        node.may_error = true;
    }
    node.maybe_nonfinite = false;
    node
}

/// Whether a literal settles that `a op b` cannot overflow when both are finite: adding one below
/// 2^970 in magnitude cannot carry a finite number past the largest (the sum rounds back),
/// multiplying by one at most 1 in magnitude cannot grow it, dividing by one at least 1 cannot,
/// and a remainder is never larger than its dividend.
fn literal_rules_out_overflow(op: BinaryOp, a: &Node, b: &Node) -> bool {
    let lit = |n: &Node| f64_literal(&n.expr).map(f64::abs);
    let small = |n: &Node| lit(n).is_some_and(|c| c < 2f64.powi(970));
    match op {
        BinaryOp::Add | BinaryOp::Sub => small(a) || small(b),
        BinaryOp::Mul => lit(a).is_some_and(|c| c <= 1.0) || lit(b).is_some_and(|c| c <= 1.0),
        BinaryOp::Div => lit(b).is_some_and(|c| c >= 1.0),
        _ => true,
    }
}

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();
    // Arrow orders floats by IEEE totalOrder, the dialect by IEEE comparison: -0 sorts below +0
    // and a negative NaN below everything. Comparing against -0.0 / +0.0 picks the zeros the
    // dialect picks, and `x >= -inf` keeps a NaN out (it fails no domain check in the dialect).
    let below = |op: Operator, bound: f64| {
        let c = binary(x.clone(), op, f64_lit(bound));
        if arg.maybe_nonfinite {
            binary(
                c,
                Operator::And,
                binary(x.clone(), Operator::GtEq, f64_lit(f64::NEG_INFINITY)),
            )
        } else {
            c
        }
    };
    let out_of_domain = match guard {
        Guard::NonNegative => below(Operator::Lt, -0.0),
        Guard::Positive => below(Operator::LtEq, 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
    }
}

/// The largest `x ≥ 0` whose product with the positive, finite `factor` is finite. Non-negative
/// floats order as their bit patterns do, so a bisection over the bits finds it exactly.
fn largest_finite_multiplicand(factor: f64) -> f64 {
    if (f64::MAX * factor).is_finite() {
        return f64::MAX;
    }
    // `lo` times the factor is finite, `hi` times it is not
    let (mut lo, mut hi) = (0u64, f64::MAX.to_bits());
    while hi - lo > 1 {
        let mid = lo + (hi - lo) / 2;
        if (f64::from_bits(mid) * factor).is_finite() {
            lo = mid;
        } else {
            hi = mid;
        }
    }
    f64::from_bits(lo)
}

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)?;
        if !n.exact {
            return no("some rows need the dialect's own evaluation");
        }
        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));
        }
        if !n.exact {
            return no("some rows need the dialect's own evaluation");
        }
        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),
                    // a dictionary column reads as its values
                    (_, DataType::Dictionary(_, values)) => cast(column, values.as_ref().clone()),
                    _ => column,
                };
                let mut n = Node::new(expr, kind);
                n.nullable = field.is_nullable();
                n.maybe_nonfinite =
                    !self.options.assume_finite && 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_nonfinite: 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 => {
                        // negation never overflows: only a non-finite input can give a non-finite result
                        let possible = a.maybe_nonfinite;
                        Ok(finite_checked(
                            Node {
                                expr: DfExpr::Negative(Box::new(a.expr)),
                                ..a
                            },
                            "'-'",
                            possible,
                        ))
                    }
                    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_nonfinite: t.maybe_nonfinite || e.maybe_nonfinite,
                    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, ast)
            }
            _ => 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_nonfinite: 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_nonfinite: 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, l, r)?,
                    BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Rem => self.arith(op, &a, &b, l, r)?,
                    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();
                // `null == null` is true even in a filter, where a NULL could otherwise stand in
                // for false
                if a.nullable && b.nullable {
                    clauses.push((both_null, lit(true)));
                }
                if !pred {
                    if let Some(null) = any_null(&[a, b]) {
                        clauses.push((null, lit(false)));
                    }
                }
                // A NaN equals no number, but Arrow's total order makes a NaN equal to a NaN with
                // the same bits: only when both sides may be NaN does one need ruling out.
                if a.maybe_nonfinite && b.maybe_nonfinite {
                    clauses.push((isnan(x.clone()), 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 mut clauses = Vec::new();
                if !pred {
                    if let Some(null) = any_null(&[a, b]) {
                        clauses.push((null, lit(false)));
                    }
                }
                let plain = if a.kind == Kind::Num {
                    ordered_numbers(dfop, a, b)
                } else {
                    binary(a.expr.clone(), dfop, b.expr.clone())
                };
                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, l: &Ast, r: &Ast) -> 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(finite_checked(
                Node {
                    expr: binary(a.expr.clone(), Operator::Plus, b.expr.clone()),
                    kind: Kind::Num,
                    nullable: a.nullable || b.nullable,
                    maybe_nonfinite: true,
                    may_error: false,
                    exact: true,
                },
                "'+'",
                a.maybe_nonfinite || b.maybe_nonfinite || self.can_overflow(BinaryOp::Add, a, b, l, r),
            )),
            (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_nonfinite: 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, l: &Ast, r: &Ast) -> 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)));
                    }
                    // `abs` so -0 is zero too: Arrow's total order has -0 != 0
                    clauses.push((
                        binary(math::abs().call(vec![y]), Operator::Eq, f64_lit(0.0)),
                        error(Kind::Num, "division by zero"),
                    ));
                    case(clauses, plain)
                } else {
                    plain
                };
                let node = Node {
                    expr,
                    kind: Kind::Num,
                    nullable: a.nullable || b.nullable,
                    maybe_nonfinite: true,
                    may_error: guarded,
                    exact: true,
                };
                let possible = a.maybe_nonfinite || b.maybe_nonfinite || self.can_overflow(op, a, b, l, r);
                Ok(finite_checked(node, &format!("'{}'", op.symbol()), possible))
            }
            (x, y) => no(format!("'{}' between a {x:?} and a {y:?}", op.symbol())),
        }
    }

    /// Whether `l op r` (translated as `a`, `b`) can overflow when both are finite. Not when a
    /// literal settles it ([`literal_rules_out_overflow`]), nor when the operands' magnitude bounds
    /// keep the result below the largest number: arithmetic over integer columns (|x| ≤ 2^64) needs
    /// many steps to get there, so it carries no check.
    fn can_overflow(&self, op: BinaryOp, a: &Node, b: &Node, l: &Ast, r: &Ast) -> bool {
        if literal_rules_out_overflow(op, a, b) {
            return false;
        }
        let (x, y) = (self.bound(l), self.bound(r));
        let worst = match op {
            BinaryOp::Add | BinaryOp::Sub => x + y,
            BinaryOp::Mul => x * y,
            BinaryOp::Div => match f64_literal(&b.expr) {
                Some(c) if c != 0.0 => x / c.abs(),
                _ => f64::INFINITY,
            },
            _ => return false,
        };
        // the bound is itself computed in floats: half the largest number leaves room for its rounding
        worst >= f64::MAX / 2.0
    }

    /// An upper bound on the magnitude of `ast`'s value, from the column types and the literals:
    /// `f64::INFINITY` where it is not known (a float column, a string function). Every arm is at
    /// least the true magnitude, so a check it leaves out can never be needed.
    fn bound(&self, ast: &Ast) -> f64 {
        match ast {
            Ast::Lit(Value::Num(n)) => n.abs(),
            Ast::Id(name) => match self.schema.field_with_name(name).map(|f| f.data_type()) {
                Ok(DataType::Int8 | DataType::UInt8) => 256.0,
                Ok(DataType::Int16 | DataType::UInt16) => 65_536.0,
                Ok(DataType::Int32 | DataType::UInt32) => 4_294_967_296.0,
                Ok(DataType::Int64 | DataType::UInt64) => 18_446_744_073_709_551_616.0,
                _ => f64::INFINITY,
            },
            Ast::Unary(UnaryOp::Neg, e) => self.bound(e),
            Ast::Binary(op, l, r) => {
                let (x, y) = (self.bound(l), self.bound(r));
                match op {
                    BinaryOp::Add | BinaryOp::Sub => x + y,
                    BinaryOp::Mul => x * y,
                    BinaryOp::Rem => x,
                    BinaryOp::Div => match r.as_ref() {
                        Ast::Lit(Value::Num(c)) if *c != 0.0 => x / c.abs(),
                        _ => f64::INFINITY,
                    },
                    _ => f64::INFINITY,
                }
            }
            Ast::Ternary(_, t, e) => self.bound(t).max(self.bound(e)),
            Ast::Call(f, args) => match (f.name(), args.as_slice()) {
                // rounding can move a value by at most one
                ("abs" | "floor" | "ceil" | "trunc" | "round", [a]) => self.bound(a) + 1.0,
                ("sign" | "sin" | "cos" | "tanh", _) => 1.0,
                ("atan" | "atan2", _) => std::f64::consts::PI,
                ("min" | "max" | "coalesce", args) => args.iter().map(|a| self.bound(a)).fold(0.0, f64::max),
                _ => f64::INFINITY,
            },
            _ => f64::INFINITY,
        }
    }

    /// `min` / `max`: DataFusion's `least` / `greatest`, as the dialect's — null arguments skipped,
    /// the result null only when every argument is, numbers in the IEEE total order both use.
    fn extreme(&self, name: &str, args: &[Node]) -> Result<Node, Unsupported> {
        let mut exprs: Vec<DfExpr> = args
            .iter()
            .filter(|a| a.kind != Kind::Null)
            .map(|a| a.expr.clone())
            .collect();
        let expr = if exprs.len() == 1 {
            exprs.remove(0)
        } else if name == "min" {
            core::least().call(exprs)
        } else {
            core::greatest().call(exprs)
        };
        let node = Node {
            expr,
            kind: Kind::Num,
            nullable: args.iter().all(|a| a.nullable),
            maybe_nonfinite: true,
            may_error: args.iter().any(|a| a.may_error),
            exact: args.iter().all(|a| a.exact),
        };
        Ok(finite_checked(node, name, args.iter().any(|a| a.maybe_nonfinite)))
    }

    /// `roundTo(x, d)` for a whole-number literal `d`: DataFusion's `round(x * 10^d) / 10^d`, the
    /// factor computed here exactly as the dialect computes it. The two cases that formula gets
    /// wrong are settled by the factor, once: a place beyond any finite number rounds every `x` to
    /// zero, and a place further out than any digit of `x` leaves it unchanged — every `|x|` above
    /// the largest whose scaled value is finite.
    fn round_to(&self, a: &Node, d: &Node) -> Result<Node, Unsupported> {
        let Some(d) = f64_literal(&d.expr).filter(|d| d.fract() == 0.0) else {
            return no("roundTo with digits that are not a whole-number literal");
        };
        // `as` saturates a huge `d`, as the dialect's own conversion does
        let factor = 10_f64.powi(d as i32);
        let x = a.expr.clone();
        // above `limit` the scaled value would overflow: such an `x` has no digit at this place
        let limit = if factor.is_finite() && factor != 0.0 {
            largest_finite_multiplicand(factor)
        } else {
            f64::MAX
        };
        let expr = if factor == 0.0 {
            if a.nullable {
                case(vec![(x.is_null(), null_of(Kind::Num))], f64_lit(0.0))
            } else {
                f64_lit(0.0)
            }
        } else if factor.is_infinite() {
            x
        } else {
            let scaled = binary(x.clone(), Operator::Multiply, f64_lit(factor));
            let rounded = binary(math::round().call(vec![scaled]), Operator::Divide, f64_lit(factor));
            match limit {
                f64::MAX => rounded,
                limit => case(
                    vec![(
                        binary(math::abs().call(vec![x.clone()]), Operator::Gt, f64_lit(limit)),
                        x,
                    )],
                    rounded,
                ),
            }
        };
        // the largest result is that of the largest `x` rounded: past the largest number only for
        // a factor below about 1e-307 (a place left of every digit, rounding up)
        let overflow = factor.is_finite() && factor != 0.0 && !((limit * factor).round() / factor).is_finite();
        let node = Node {
            expr,
            kind: Kind::Num,
            nullable: a.nullable,
            maybe_nonfinite: true,
            may_error: a.may_error,
            exact: a.exact,
        };
        Ok(finite_checked(
            node,
            "roundTo",
            factor != 0.0 && (a.maybe_nonfinite || overflow),
        ))
    }

    /// `expr`, a function of the epoch `a`, for an epoch that has a date; the dialect itself for
    /// one that does not (outside chrono's years, or not finite), whose error names the function
    /// and the value. The dialect reads an epoch as its whole milliseconds, truncated toward zero,
    /// so the bounds are exclusive by one.
    fn within_dates(&self, a: &Node, expr: DfExpr, ast: &Ast, kind: Kind) -> Result<DfExpr, Unsupported> {
        use chrono::{DateTime, Utc};
        let (min, max) = (
            DateTime::<Utc>::MIN_UTC.timestamp_millis() as f64,
            DateTime::<Utc>::MAX_UTC.timestamp_millis() as f64,
        );
        let x = a.expr.clone();
        let has_date = binary(
            binary(x.clone(), Operator::Gt, f64_lit(min - 1.0)),
            Operator::And,
            binary(x.clone(), Operator::Lt, f64_lit(max + 1.0)),
        );
        let mut clauses = Vec::new();
        if a.nullable {
            clauses.push((x.is_null(), null_of(kind)));
        }
        clauses.push((has_date, expr));
        Ok(case(clauses, self.native(ast, kind)?))
    }

    /// Whether the call's one argument is a column of a signed integer type (or an unsigned one of
    /// 32 bits or fewer), whose every value is a whole number within ±2^63.
    fn integer_argument(&self, ast: &Ast) -> bool {
        let Ast::Call(_, args) = ast else { return false };
        let [Ast::Id(name)] = args.as_slice() else { return false };
        self.schema.field_with_name(name).is_ok_and(|f| {
            matches!(
                f.data_type(),
                DataType::Int8
                    | DataType::Int16
                    | DataType::Int32
                    | DataType::Int64
                    | DataType::UInt8
                    | DataType::UInt16
                    | DataType::UInt32
            )
        })
    }

    /// The dialect's own evaluation of `ast`, per row: for the rows a translation leaves to it.
    fn native(&self, ast: &Ast, kind: Kind) -> Result<DfExpr, Unsupported> {
        fallback(&Expr::from_ast(ast.clone()), data_type_for(kind), &self.schema)
    }

    fn call(&self, name: &str, args: Vec<Node>, ast: &Ast) -> 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_nonfinite: 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_nonfinite: false,
                    may_error,
                    exact,
                }),
                Kind::Null => Ok(Node::null(kind)),
                k => no(format!("{name} on a {k:?}")),
            }
        };
        let keeps = |n: Node, a: &Node| finite_checked(n, name, a.maybe_nonfinite);
        let grows = |n: Node| finite_checked(n, name, true);
        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()) {
            // A function that keeps a finite input finite is checked only for an input that may
            // already be non-finite; one that can overflow finite inputs is always checked.
            ("abs", [a]) => Ok(keeps(num1(math::abs, a)?, a)),
            ("floor", [a]) => Ok(keeps(num1(math::floor, a)?, a)),
            ("ceil", [a]) => Ok(keeps(num1(math::ceil, a)?, a)),
            ("trunc", [a]) => Ok(keeps(num1(math::trunc, a)?, a)),
            // DataFusion's round is the dialect's: half away from zero
            ("round", [a]) => Ok(keeps(num1(math::round, a)?, a)),
            // DataFusion's signum is the dialect's sign: 0 for either zero, NaN for NaN
            ("sign", [a]) => Ok(keeps(num1(math::signum, a)?, a)),
            ("cbrt", [a]) => Ok(keeps(num1(math::cbrt, a)?, a)),
            ("sin", [a]) => Ok(keeps(num1(math::sin, a)?, a)),
            ("cos", [a]) => Ok(keeps(num1(math::cos, a)?, a)),
            ("tan", [a]) => Ok(keeps(num1(math::tan, a)?, a)),
            ("atan", [a]) => Ok(keeps(num1(math::atan, a)?, a)),
            ("tanh", [a]) => Ok(keeps(num1(math::tanh, a)?, a)),
            ("degToRad", [a]) => Ok(keeps(num1(math::radians, a)?, a)),
            ("exp", [a]) => Ok(grows(num1(math::exp, a)?)),
            ("sinh", [a]) => Ok(grows(num1(math::sinh, a)?)),
            ("cosh", [a]) => Ok(grows(num1(math::cosh, a)?)),
            ("radToDeg", [a]) => Ok(grows(num1(math::degrees, a)?)),
            ("sqrt", [a]) => Ok(keeps(
                guarded(num1(math::sqrt, a)?, a, Guard::NonNegative, "sqrt: negative argument"),
                a,
            )),
            ("ln", [a]) => Ok(keeps(
                guarded(num1(math::ln, a)?, a, Guard::Positive, "ln: argument must be positive"),
                a,
            )),
            ("log10", [a]) => Ok(keeps(
                guarded(
                    num1(math::log10, a)?,
                    a,
                    Guard::Positive,
                    "log10: argument must be positive",
                ),
                a,
            )),
            ("log2", [a]) => Ok(keeps(
                guarded(
                    num1(math::log2, a)?,
                    a,
                    Guard::Positive,
                    "log2: argument must be positive",
                ),
                a,
            )),
            ("asin", [a]) => Ok(keeps(
                guarded(
                    num1(math::asin, a)?,
                    a,
                    Guard::UnitInterval,
                    "asin: argument must be in [-1, 1]",
                ),
                a,
            )),
            ("acos", [a]) => Ok(keeps(
                guarded(
                    num1(math::acos, a)?,
                    a,
                    Guard::UnitInterval,
                    "acos: argument must be in [-1, 1]",
                ),
                a,
            )),
            ("roundTo" | "pow" | "atan2" | "min" | "max", _) if any_null_kind(&args) && all_num_or_null(&args) => {
                match name {
                    // least / greatest skip nulls: the result is null only when every argument is
                    "min" | "max" if !args.iter().all(|a| a.kind == Kind::Null) => self.extreme(name, &args),
                    _ => Ok(Node::null(Kind::Num)),
                }
            }
            ("roundTo", [a, d]) if all_num(&args) => self.round_to(a, d),
            ("pow", [a, b]) if all_num(&args) => {
                // DataFusion's power raises PostgreSQL's own error for zero to a negative power;
                // those rows are decided first so the error is the dialect's. `abs` folds -0 into
                // the zero test and `< -0.0` keeps a -0 exponent out, as IEEE comparison would.
                let zero_to_negative = binary(
                    binary(math::abs().call(vec![a.expr.clone()]), Operator::Eq, f64_lit(0.0)),
                    Operator::And,
                    binary(b.expr.clone(), Operator::Lt, f64_lit(-0.0)),
                );
                let power = math::power().call(vec![a.expr.clone(), b.expr.clone()]);
                Ok(grows(num(
                    case(
                        vec![(zero_to_negative, error(Kind::Num, "pow: result is not a finite number"))],
                        power,
                    ),
                    nullable,
                )))
            }
            ("atan2", [a, b]) if all_num(&args) => Ok(finite_checked(
                num(math::atan2().call(vec![a.expr.clone(), b.expr.clone()]), nullable),
                name,
                a.maybe_nonfinite || b.maybe_nonfinite,
            )),
            ("min" | "max", _) if !args.is_empty() && all_num(&args) => self.extreme(name, &args),
            ("pi", []) => Ok(Node::new(f64_lit(std::f64::consts::PI), Kind::Num).certain().finite()),
            ("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_nonfinite: args.iter().any(|a| a.maybe_nonfinite),
                    may_error,
                    exact,
                })
            }
            ("isNull", [a]) => Ok(Node {
                expr: a.expr.clone().is_null(),
                kind: Kind::Bool,
                nullable: false,
                maybe_nonfinite: 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_nonfinite: 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_nonfinite: 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_nonfinite: a.maybe_nonfinite,
                    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_nonfinite: 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_nonfinite: false,
                    may_error,
                    exact,
                })
            }
            ("regexMatch", [a, b]) if a.kind == Kind::Str && valid_pattern(&b.expr) => Ok(Node {
                expr: regex::regexp_like().call(vec![a.expr.clone(), b.expr.clone()]),
                kind: Kind::Bool,
                nullable,
                maybe_nonfinite: false,
                may_error,
                exact,
            }),
            ("replace" | "indexOf", _) if any_null_kind(&args) && all_str_or_null(&args) => {
                Ok(Node::null(if name == "replace" { Kind::Str } else { Kind::Num }))
            }
            // ── The string family that ran per row until 2026-09-16 (found by Nexmark q21 at
            // 20k events/s per core): each maps to DataFusion's vectorised function only where the
            // two agree exactly; anything else stays a per-row fallback. ──
            // A literal position, whole and not zero: the two read it alike (from the end when
            // negative). Position zero, or one from a column, stays with the dialect, whose error
            // names the function.
            ("splitPart", [a, b, c])
                if a.kind == Kind::Str
                    && b.kind == Kind::Str
                    && f64_literal(&c.expr).is_some_and(|n| n != 0.0 && n.abs() < TWO_POW_63) =>
            {
                Ok(Node {
                    expr: string::split_part().call(vec![
                        a.expr.clone(),
                        b.expr.clone(),
                        cast(c.expr.clone(), DataType::Int64),
                    ]),
                    kind: Kind::Str,
                    nullable,
                    maybe_nonfinite: false,
                    may_error,
                    exact,
                })
            }
            ("left" | "right", [a, b]) if a.kind == Kind::Str && whole_literal(&b.expr) => Ok(Node {
                expr: (if name == "left" {
                    unicode::left()
                } else {
                    unicode::right()
                })
                .call(vec![a.expr.clone(), cast(b.expr.clone(), DataType::Int64)]),
                kind: Kind::Str,
                nullable,
                maybe_nonfinite: false,
                may_error,
                exact,
            }),
            ("substr" | "substring", [a, b]) if a.kind == Kind::Str && whole_literal(&b.expr) => Ok(Node {
                expr: unicode::substr().call(vec![a.expr.clone(), cast(b.expr.clone(), DataType::Int64)]),
                kind: Kind::Str,
                nullable,
                maybe_nonfinite: false,
                may_error,
                exact,
            }),
            ("substr" | "substring", [a, b, c])
                if a.kind == Kind::Str && whole_literal(&b.expr) && non_negative_literal(&c.expr) =>
            {
                Ok(Node {
                    expr: unicode::substr().call(vec![
                        a.expr.clone(),
                        cast(b.expr.clone(), DataType::Int64),
                        cast(c.expr.clone(), DataType::Int64),
                    ]),
                    kind: Kind::Str,
                    nullable,
                    maybe_nonfinite: false,
                    may_error,
                    exact,
                })
            }
            // A literal length small enough that no result can pass the dialect's 10 MiB cap (a
            // character is at most 4 bytes); a longer one, or one from a column, stays with the
            // dialect, which checks the cap.
            ("padStart" | "padEnd", [a, b, c])
                if a.kind == Kind::Str
                    && f64_literal(&b.expr)
                        .is_some_and(|n| n.trunc().abs() <= (fv_value::MAX_BUILT_BYTES / 4) as f64)
                    && c.kind == Kind::Str =>
            {
                // the dialect never truncates and leaves the string alone for an empty pad; lpad /
                // rpad truncate and error — the two cases are decided before the call.
                let pad = (if name == "padStart" {
                    unicode::lpad()
                } else {
                    unicode::rpad()
                })
                .call(vec![
                    a.expr.clone(),
                    cast(b.expr.clone(), DataType::Int64),
                    c.expr.clone(),
                ]);
                let too_short = unicode::character_length()
                    .call(vec![a.expr.clone()])
                    .lt(cast(b.expr.clone(), DataType::Int32));
                let has_pad = unicode::character_length().call(vec![c.expr.clone()]).gt(lit(0i32));
                Ok(Node {
                    expr: when(too_short.and(has_pad), pad)
                        .otherwise(a.expr.clone())
                        .expect("case"),
                    kind: Kind::Str,
                    nullable,
                    maybe_nonfinite: false,
                    may_error,
                    exact,
                })
            }
            ("regexExtract", [a, b]) if a.kind == Kind::Str && valid_pattern(&b.expr) => Ok(Node {
                // regexp_match's first element is the first capture group when the pattern has
                // one and the whole match when it has none — PostgreSQL's substring(s from p),
                // which the dialect's regexExtract is.
                expr: array_element(
                    regex::regexp_match().call(vec![a.expr.clone(), b.expr.clone()]),
                    lit(1i64),
                ),
                kind: Kind::Str,
                nullable: true,
                maybe_nonfinite: false,
                may_error,
                exact,
            }),
            ("epochToIso", [a]) if a.kind == Kind::Num => Ok(Node {
                // `YYYY-MM-DDTHH:MM:SS.mmmZ` from epoch milliseconds, the integer part of the number.
                expr: self.within_dates(
                    a,
                    datetime::expr_fn::to_char(epoch_millis(a), lit("%Y-%m-%dT%H:%M:%S%.3fZ")),
                    ast,
                    Kind::Str,
                )?,
                kind: Kind::Str,
                nullable,
                maybe_nonfinite: false,
                may_error: true,
                exact,
            }),
            ("toString", [a]) if a.kind == Kind::Str => Ok(a.clone()),
            ("toString", [a]) if a.kind == Kind::Bool => Ok(Node {
                expr: when(a.expr.clone(), lit("true")).otherwise(lit("false")).expect("case"),
                kind: Kind::Str,
                nullable,
                maybe_nonfinite: false,
                may_error,
                exact,
            }),
            // An integer column: every value is a whole number the 64-bit cast carries — but one
            // near i64::MAX, which as a number rounds to 2^63, one past the range
            ("toString", [a]) if a.kind == Kind::Num && self.integer_argument(ast) => {
                let x = a.expr.clone();
                Ok(Node {
                    expr: case(
                        vec![(
                            binary(x.clone(), Operator::Eq, f64_lit(TWO_POW_63)),
                            lit("9223372036854775808"),
                        )],
                        cast(cast(x, DataType::Int64), DataType::Utf8),
                    ),
                    kind: Kind::Str,
                    nullable,
                    maybe_nonfinite: false,
                    may_error,
                    exact,
                })
            }
            ("toString", [a]) if a.kind == Kind::Num => {
                // Vectorised wherever Arrow writes what the dialect writes: a whole number within
                // the 64-bit range as that integer, a fraction within PLAIN_FLOAT_TEXT as Arrow's
                // float text. Anything else — a tiny or huge fraction (Arrow writes `1.6e-6` where
                // the dialect writes `0.0000016`), a whole number past 2^63, NaN or infinity —
                // prints as the dialect prints it, per row.
                let x = a.expr.clone();
                let magnitude = math::abs().call(vec![x.clone()]);
                let whole = binary(
                    binary(math::floor().call(vec![x.clone()]), Operator::Eq, x.clone()),
                    Operator::And,
                    binary(magnitude.clone(), Operator::Lt, f64_lit(TWO_POW_63)),
                );
                let plain = binary(
                    binary(magnitude.clone(), Operator::GtEq, f64_lit(PLAIN_FLOAT_TEXT.start)),
                    Operator::And,
                    binary(magnitude, Operator::Lt, f64_lit(PLAIN_FLOAT_TEXT.end)),
                );
                let mut clauses = Vec::new();
                if a.nullable {
                    clauses.push((x.clone().is_null(), null_of(Kind::Str)));
                }
                clauses.push((whole, cast(cast(x.clone(), DataType::Int64), DataType::Utf8)));
                clauses.push((plain, cast(x, DataType::Utf8)));
                Ok(Node {
                    expr: case(clauses, self.native(ast, Kind::Str)?),
                    kind: Kind::Str,
                    nullable,
                    maybe_nonfinite: false,
                    may_error,
                    exact: false,
                })
            }
            ("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_nonfinite: 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_nonfinite: false,
                    may_error,
                    exact,
                })
            }
            ("yearOf" | "monthOf" | "dayOf" | "hourOf" | "minuteOf" | "dayOfWeekOf" | "dayOfYear", [a]) => match a.kind
            {
                Kind::Num => {
                    let ts = epoch_millis(a);
                    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: self.within_dates(a, expr, ast, Kind::Num)?,
                        kind: Kind::Num,
                        nullable: a.nullable,
                        maybe_nonfinite: false,
                        may_error: true,
                        exact,
                    })
                }
                Kind::Null => Ok(Node::null(Kind::Num)),
                k => no(format!("{name} on a {k:?}")),
            },
            ("concat", _) if any_null_kind(&args) && all_str_or_null(&args) => Ok(Node::null(Kind::Str)),
            ("concatWs" | "trim" | "trimStart" | "trimEnd" | "repeat" | "regexReplace", [first, ..])
                if first.kind == Kind::Null =>
            {
                Ok(Node::null(Kind::Str))
            }
            // the dialect's concat is null when any part is: `||`, not DataFusion's concat, which
            // reads a null part as empty
            ("concat", [first, rest @ ..]) if all_str(&args) => Ok(Node {
                expr: rest.iter().fold(first.expr.clone(), |l, r| {
                    binary(l, Operator::StringConcat, r.expr.clone())
                }),
                kind: Kind::Str,
                nullable,
                maybe_nonfinite: false,
                may_error,
                exact,
            }),
            // both skip a null part and give null for a null separator
            ("concatWs", [sep, parts @ ..])
                if sep.kind == Kind::Str
                    && !parts.is_empty()
                    && parts.iter().all(|a| matches!(a.kind, Kind::Str | Kind::Null)) =>
            {
                let mut exprs = vec![sep.expr.clone()];
                exprs.extend(parts.iter().map(|a| retype(a.expr.clone(), a.kind, Kind::Str)));
                Ok(Node {
                    expr: string::concat_ws().call(exprs),
                    kind: Kind::Str,
                    nullable: sep.nullable,
                    maybe_nonfinite: false,
                    may_error,
                    exact,
                })
            }
            // the dialect trims Unicode whitespace, DataFusion's one-argument trims only spaces:
            // given the whitespace set itself, they trim alike
            ("trim" | "trimStart" | "trimEnd", [a]) if a.kind == Kind::Str => Ok(Node {
                expr: match name {
                    "trim" => string::btrim(),
                    "trimStart" => string::ltrim(),
                    _ => string::rtrim(),
                }
                .call(vec![a.expr.clone(), lit(unicode_whitespace())]),
                kind: Kind::Str,
                nullable: a.nullable,
                maybe_nonfinite: false,
                may_error,
                exact,
            }),
            // A literal count: a negative one repeats nothing in both. A row whose result would
            // pass the dialect's 10 MiB limit goes to the dialect, which refuses it.
            ("repeat", [a, n])
                if a.kind == Kind::Str
                    && f64_literal(&n.expr).is_some_and(|c| c.trunc() <= fv_value::MAX_BUILT_BYTES as f64) =>
            {
                let count = f64_literal(&n.expr).unwrap_or(0.0).trunc().max(0.0);
                let bytes = binary(
                    to_f64(string::octet_length().call(vec![a.expr.clone()])),
                    Operator::Multiply,
                    f64_lit(count),
                );
                Ok(Node {
                    expr: case(
                        vec![(
                            binary(bytes, Operator::Gt, f64_lit(fv_value::MAX_BUILT_BYTES as f64)),
                            self.native(ast, Kind::Str)?,
                        )],
                        string::repeat().call(vec![a.expr.clone(), lit(count as i64)]),
                    ),
                    kind: Kind::Str,
                    nullable: a.nullable,
                    maybe_nonfinite: false,
                    may_error: true,
                    exact,
                })
            }
            // DataFusion rewrites `\N` to `${N}` and hands the rest to the same regex crate: given
            // the dialect's own rewrite of the replacement (`$1x` is group 1, then x) and no
            // backslash for DataFusion to reinterpret, with `g` both replace every match alike.
            ("regexReplace", [a, p, r]) if a.kind == Kind::Str && valid_pattern(&p.expr) => {
                let DfExpr::Literal(ScalarValue::Utf8(Some(rep)), _) = &r.expr else {
                    return no("regexReplace with a replacement that is not a literal");
                };
                let rep = fv_value::regex_replacement(rep);
                if rep.contains('\\') {
                    return no("regexReplace with a backslash in the replacement");
                }
                Ok(Node {
                    expr: regex::regexp_replace().call(vec![
                        a.expr.clone(),
                        p.expr.clone(),
                        lit(rep.into_owned()),
                        lit("g"),
                    ]),
                    kind: Kind::Str,
                    nullable: a.nullable,
                    maybe_nonfinite: false,
                    may_error,
                    exact,
                })
            }
            // Literal bounds: `lo > hi` is the dialect's error for any non-null `x`; otherwise
            // greatest-then-least, except that the dialect's `max` passes over a NaN `x` to `lo`.
            ("clamp", [x, lo, hi]) if all_num(&args) => {
                let (Some(l), Some(h)) = (f64_literal(&lo.expr), f64_literal(&hi.expr)) else {
                    return no("clamp with bounds that are not literals");
                };
                let mut clauses = Vec::new();
                if x.nullable {
                    clauses.push((x.expr.clone().is_null(), null_of(Kind::Num)));
                }
                let otherwise = if l > h {
                    error(Kind::Num, "clamp: lo must not be greater than hi")
                } else {
                    if x.maybe_nonfinite {
                        clauses.push((isnan(x.expr.clone()), f64_lit(l)));
                    }
                    core::least().call(vec![
                        core::greatest().call(vec![x.expr.clone(), f64_lit(l)]),
                        f64_lit(h),
                    ])
                };
                Ok(Node {
                    expr: if clauses.is_empty() {
                        otherwise
                    } else {
                        case(clauses, otherwise)
                    },
                    kind: Kind::Num,
                    nullable: x.nullable,
                    maybe_nonfinite: false,
                    may_error: may_error || l > h,
                    exact,
                })
            }
            _ => no(format!("function {name}")),
        }
    }
}

/// Every character Rust's `str::trim` removes (Unicode `White_Space`), as one string.
fn unicode_whitespace() -> &'static str {
    static WS: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
        (0..=0x10FFFF)
            .filter_map(char::from_u32)
            .filter(|c| c.is_whitespace())
            .collect()
    });
    &WS
}

/// A pattern literal the regex crate compiles: DataFusion and the dialect then match it alike,
/// and an invalid one is left to the dialect, whose error names the function.
fn valid_pattern(e: &DfExpr) -> bool {
    matches!(e, DfExpr::Literal(ScalarValue::Utf8(Some(p)), _) if ::regex::Regex::new(p).is_ok())
}