aura-lang 0.2.0

Aura configuration language: deterministic, capability-secured, schema-validated configs — embeddable library + the `aura` CLI
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
//! Method registry (SPEC §4.4). Dispatch by (receiver TypeTag, method name).
//! Registration via fn pointers: a new method = a function + `register`, the parser stays unchanged.

use indexmap::IndexMap;
use std::collections::HashMap;
use std::sync::Arc;

use super::value::{TypeTag, Value};
use super::{Interpreter, TextCtx};
use crate::error::Diagnostic;
use crate::span::Span;

pub type MethodFn<'a> =
    fn(&mut Interpreter<'a>, &Value<'a>, &[Value<'a>], Span) -> Result<Value<'a>, Diagnostic>;

pub struct MethodRegistry<'a> {
    table: HashMap<(TypeTag, &'static str), MethodFn<'a>>,
}

impl<'a> MethodRegistry<'a> {
    pub fn new() -> Self {
        MethodRegistry {
            table: HashMap::new(),
        }
    }

    pub fn register(&mut self, tag: TypeTag, name: &'static str, f: MethodFn<'a>) {
        self.table.insert((tag, name), f);
    }

    pub fn get(&self, tag: TypeTag, name: &str) -> Option<MethodFn<'a>> {
        self.table.get(&(tag, name)).copied()
    }

    /// Every registered `(receiver, method)` pair. Lets tooling (the LSP) check
    /// its stdlib manifest against the real registry so the two cannot drift.
    pub fn entries(&self) -> Vec<(TypeTag, &'static str)> {
        self.table.keys().copied().collect()
    }

    pub fn builtin() -> Self {
        let mut r = Self::new();
        r.register(TypeTag::Str, "upper", m_str_upper);
        r.register(TypeTag::Str, "lower", m_str_lower);
        r.register(TypeTag::Str, "len", m_len);
        r.register(TypeTag::Str, "parse_toml", m_parse_toml);
        r.register(TypeTag::Str, "parse_duration", m_parse_duration);
        r.register(TypeTag::Str, "parse_datetime", m_parse_datetime);
        r.register(TypeTag::Int, "format_duration", m_format_duration);
        r.register(TypeTag::Int, "format_datetime", m_format_datetime);
        r.register(TypeTag::Str, "parse_json", m_parse_json);
        r.register(TypeTag::Str, "parse_yaml", m_parse_yaml);
        r.register(TypeTag::List, "len", m_len);
        r.register(TypeTag::List, "compact", m_list_compact);
        r.register(TypeTag::List, "uniq", m_list_uniq);
        r.register(TypeTag::List, "map", m_list_map);
        r.register(TypeTag::List, "filter", m_list_filter);
        r.register(TypeTag::List, "get", m_get);
        r.register(TypeTag::List, "contains", m_contains);
        r.register(TypeTag::List, "join", m_list_join);
        r.register(TypeTag::Str, "contains", m_contains);
        r.register(TypeTag::Object, "keys", m_obj_keys);
        r.register(TypeTag::Object, "values", m_obj_values);
        r.register(TypeTag::Object, "contains", m_contains);
        r.register(TypeTag::List, "first", m_list_first);
        r.register(TypeTag::List, "last", m_list_last);
        r.register(TypeTag::Object, "len", m_len);
        r.register(TypeTag::List, "reduce", m_list_reduce);
        r.register(TypeTag::List, "any", m_list_any);
        r.register(TypeTag::List, "all", m_list_all);
        r.register(TypeTag::List, "find", m_list_find);
        r.register(TypeTag::List, "index_of", m_list_index_of);
        r.register(TypeTag::Object, "entries", m_obj_entries);
        r.register(TypeTag::List, "to_object", m_list_to_object);
        r.register(TypeTag::Object, "merge", m_obj_merge);
        r.register(TypeTag::Object, "get", m_get);
        for tag in [TypeTag::Object, TypeTag::List] {
            r.register(tag, "to_json", m_to_json);
            r.register(tag, "to_yaml", m_to_yaml);
            r.register(tag, "to_toml", m_to_toml);
            r.register(tag, "to_json_pretty", m_to_json_pretty);
            r.register(tag, "to_yaml_pretty", m_to_yaml_pretty);
            r.register(tag, "to_toml_pretty", m_to_toml_pretty);
        }
        // stdlib extension: String
        r.register(TypeTag::Str, "trim", m_str_trim);
        r.register(TypeTag::Str, "split", m_str_split);
        r.register(TypeTag::Str, "replace", m_str_replace);
        r.register(TypeTag::Str, "starts_with", m_str_starts_with);
        r.register(TypeTag::Str, "ends_with", m_str_ends_with);
        r.register(TypeTag::Str, "to_int", m_str_to_int);
        r.register(TypeTag::Str, "to_float", m_str_to_float);
        // Pure, deterministic digests/codecs (no I/O): safe under D1/D13.
        r.register(TypeTag::Str, "sha256", m_str_sha256);
        r.register(TypeTag::Str, "base64", m_str_base64);
        r.register(TypeTag::Str, "base64_decode", m_str_base64_decode);
        // stdlib extension: List
        r.register(TypeTag::List, "sort", m_list_sort);
        r.register(TypeTag::List, "reverse", m_list_reverse);
        r.register(TypeTag::List, "sum", m_list_sum);
        r.register(TypeTag::List, "min", m_list_min);
        r.register(TypeTag::List, "max", m_list_max);
        r.register(TypeTag::List, "flatten", m_list_flatten);
        r.register(TypeTag::List, "slice", m_list_slice);
        r.register(TypeTag::Str, "slice", m_str_slice);
        // Widening only: Int -> Float loses nothing, and there is deliberately
        // no Float -> Int, which would have to choose a rounding nobody asked
        // for and would make a lossy conversion look like a spelling change.
        r.register(TypeTag::Int, "to_float", m_int_to_float);
        // stdlib extension: numeric + universal to_str
        r.register(TypeTag::Int, "abs", m_num_abs);
        r.register(TypeTag::Float, "abs", m_num_abs);
        for tag in [TypeTag::Int, TypeTag::Float, TypeTag::Bool, TypeTag::Str] {
            r.register(tag, "to_str", m_to_str);
        }
        r
    }
}

impl Default for MethodRegistry<'_> {
    fn default() -> Self {
        Self::builtin()
    }
}

fn rt(code: &'static str, msg: impl Into<String>, span: Span) -> Diagnostic {
    Diagnostic::error(code, msg, span, "in this method call")
}

fn m_str_upper<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    Ok(Value::str(s.to_uppercase()))
}

fn m_str_lower<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    Ok(Value::str(s.to_lowercase()))
}

fn m_len<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let n = match recv {
        Value::Str(s) => s.chars().count(),
        Value::List(xs) => xs.len(),
        Value::Object(m) => m.len(),
        _ => unreachable!(),
    };
    Ok(Value::Int(n as i64))
}

/// `.compact()` — removes Null while preserving order (SPEC §4.4).
fn m_list_compact<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    Ok(Value::list(
        xs.iter()
            .filter(|v| !matches!(v, Value::Null))
            .cloned()
            .collect(),
    ))
}

/// `.uniq()` — deduplication keeping the first occurrence.
fn m_list_uniq<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let mut out: Vec<Value<'a>> = Vec::with_capacity(xs.len());
    for v in xs.iter() {
        if !out.contains(v) {
            out.push(v.clone());
        }
    }
    Ok(Value::list(out))
}

fn expect_lambda<'a, 'b>(
    args: &'b [Value<'a>],
    name: &str,
    sp: Span,
) -> Result<&'b Value<'a>, Diagnostic> {
    match args.last() {
        Some(f @ Value::Function(_)) => Ok(f),
        _ => Err(rt(
            "E0315",
            format!("`{name}` requires a lambda argument"),
            sp,
        )),
    }
}

/// `.map (elem, index) -> ... end` — the callback receives the element and its index.
fn m_list_map<'a>(
    it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let f = expect_lambda(args, "map", sp)?.clone();
    let mut out = Vec::with_capacity(xs.len());
    for (i, v) in xs.iter().enumerate() {
        out.push(it.call_value(&f, &[v.clone(), Value::Int(i as i64)], sp)?);
    }
    Ok(Value::list(out))
}

fn m_list_filter<'a>(
    it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let f = expect_lambda(args, "filter", sp)?.clone();
    let mut out = Vec::new();
    for (i, v) in xs.iter().enumerate() {
        match it.call_value(&f, &[v.clone(), Value::Int(i as i64)], sp)? {
            Value::Bool(true) => out.push(v.clone()),
            Value::Bool(false) => {}
            other => {
                return Err(rt(
                    "E0306",
                    format!("filter lambda must return Bool, got {}", other.type_name()),
                    sp,
                ))
            }
        }
    }
    Ok(Value::list(out))
}

/// Calls a predicate lambda and insists on a Bool, as `filter` does.
fn predicate<'a>(
    it: &mut Interpreter<'a>,
    f: &Value<'a>,
    v: &Value<'a>,
    i: usize,
    name: &str,
    sp: Span,
) -> Result<bool, Diagnostic> {
    match it.call_value(f, &[v.clone(), Value::Int(i as i64)], sp)? {
        Value::Bool(b) => Ok(b),
        other => {
            let mut d = rt(
                "E0306",
                format!("{name} lambda must return Bool, got {}", other.type_name()),
                sp,
            );
            d.help = Some(format!(
                "the body has to be a comparison: xs.{name} (x, i) -> x > 0 end"
            ));
            Err(d)
        }
    }
}

/// The argument a method needs before its trailing lambda (`reduce`'s initial
/// value, `find`'s fallback). `args` ends with the lambda, so the value is
/// everything before it.
fn leading_arg<'a, 'b>(
    args: &'b [Value<'a>],
    name: &str,
    what: &str,
    example: &str,
    sp: Span,
) -> Result<&'b Value<'a>, Diagnostic> {
    if args.len() < 2 {
        let mut d = rt(
            "E0306",
            format!("`{name}` needs {what} before the lambda"),
            sp,
        );
        d.help = Some(format!("write it as: {example}"));
        return Err(d);
    }
    Ok(&args[0])
}

/// `.reduce(init) (acc, elem) -> ... end` — left fold.
///
/// The initial value is required rather than defaulting to the first element:
/// an empty list would otherwise have no answer, and `first()` already shows
/// that this language errors instead of inventing one.
fn m_list_reduce<'a>(
    it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let f = expect_lambda(args, "reduce", sp)?.clone();
    let mut acc = leading_arg(
        args,
        "reduce",
        "an initial value",
        "xs.reduce(0) (acc, x) -> acc + x end",
        sp,
    )?
    .clone();
    for (i, v) in xs.iter().enumerate() {
        acc = it.call_value(&f, &[acc, v.clone(), Value::Int(i as i64)], sp)?;
    }
    Ok(acc)
}

/// `.any (elem, i) -> Bool end` — true if the predicate holds for some element.
/// Empty list: false. Stops at the first match.
fn m_list_any<'a>(
    it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let f = expect_lambda(args, "any", sp)?.clone();
    for (i, v) in xs.iter().enumerate() {
        if predicate(it, &f, v, i, "any", sp)? {
            return Ok(Value::Bool(true));
        }
    }
    Ok(Value::Bool(false))
}

/// `.all (elem, i) -> Bool end` — true if the predicate holds for every element.
/// Empty list: true, the standard vacuous reading. Stops at the first failure.
fn m_list_all<'a>(
    it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let f = expect_lambda(args, "all", sp)?.clone();
    for (i, v) in xs.iter().enumerate() {
        if !predicate(it, &f, v, i, "all", sp)? {
            return Ok(Value::Bool(false));
        }
    }
    Ok(Value::Bool(true))
}

/// `.find(default) (elem, i) -> Bool end` — the first match, or the default.
///
/// The fallback is explicit for the same reason `get(i, default)` takes one:
/// "not found" is an ordinary outcome, and the alternative is either a silent
/// `Null` or a sentinel, both of which this language removes elsewhere.
fn m_list_find<'a>(
    it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let f = expect_lambda(args, "find", sp)?.clone();
    let default = leading_arg(
        args,
        "find",
        "a fallback value",
        "xs.find(0) (x, i) -> x > 9000 end",
        sp,
    )?
    .clone();
    for (i, v) in xs.iter().enumerate() {
        if predicate(it, &f, v, i, "find", sp)? {
            return Ok(v.clone());
        }
    }
    Ok(default)
}

/// `.index_of(value, default)` — the first index equal to `value`, or the default.
///
/// No `-1` sentinel: a magic number meaning "absent" is the implicit rule D4 and
/// D7 remove, and passing it on silently indexes from the end.
///
/// The fallback must itself be an `Int`, so the method returns an `Int` on every
/// path. Allowing any type would make one call site produce an index on one
/// branch and something else on another — the caller could not read the result
/// without knowing which branch ran.
fn m_list_index_of<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let [needle, default] = args else {
        let mut d = rt(
            "E0306",
            format!(
                "`index_of` takes a value and a fallback, got {} argument(s)",
                args.len()
            ),
            sp,
        );
        d.help = Some("name what an absent element means: index_of(x, -1)".into());
        return Err(d);
    };
    let Value::Int(_) = default else {
        let mut d = rt(
            "E0306",
            format!(
                "the fallback for `index_of` must be an Int, got {}",
                default.type_name()
            ),
            sp,
        );
        d.help = Some(
            "index_of returns an Int on every path, so the fallback is one too: \
             index_of(x, -1)"
                .into(),
        );
        return Err(d);
    };
    match xs.iter().position(|v| v == needle) {
        Some(i) => Ok(Value::Int(i as i64)),
        None => Ok(default.clone()),
    }
}

/// `.merge(other)` — the right-hand operand overrides the left-hand keys.
fn m_obj_merge<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Object(base) = recv else {
        unreachable!()
    };
    let Some(Value::Object(other)) = args.first() else {
        return Err(rt("E0306", "merge expects an Object argument", sp));
    };
    let mut out: IndexMap<String, Value<'a>> = (**base).clone();
    for (k, v) in other.iter() {
        out.insert(k.clone(), v.clone());
    }
    Ok(Value::object(out))
}

/// `.parse_toml()` — TOML integers → Int (D6).
fn m_parse_toml<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    read_toml(s, sp)
}

pub fn read_toml<'a>(s: &str, sp: Span) -> Result<Value<'a>, Diagnostic> {
    let parsed: toml::Value =
        toml::from_str(s).map_err(|e| rt("E0314", format!("invalid TOML: {e}"), sp))?;
    Ok(toml_to_value(parsed))
}

/// `.get(index_or_key, default)` — safe access: a miss returns default (or Null).
fn m_get<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let default = || args.get(1).cloned().unwrap_or(Value::Null);
    match (recv, args.first()) {
        (Value::List(xs), Some(Value::Int(i))) => Ok(usize::try_from(*i)
            .ok()
            .and_then(|i| xs.get(i))
            .cloned()
            .unwrap_or_else(default)),
        (Value::Object(m), Some(Value::Str(k))) => {
            Ok(m.get(k.as_ref()).cloned().unwrap_or_else(default))
        }
        (Value::List(_), _) => Err(rt("E0306", "List.get expects an Int index", sp)),
        _ => Err(rt("E0306", "Object.get expects a String key", sp)),
    }
}

fn m_list_first<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    xs.first().cloned().ok_or_else(|| {
        let mut d = rt("E0317", "first() on an empty list", sp);
        // The catalogue has carried this remedy since E0317 existed; it just
        // never reached the person who hit the error.
        d.help = Some("when the list may be empty: xs.get(0, \"none\")".into());
        d
    })
}

fn m_list_last<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    xs.last().cloned().ok_or_else(|| {
        let mut d = rt("E0317", "last() on an empty list", sp);
        // `get` takes no negative index, so the guard is the honest advice here.
        d.help = Some("when the list may be empty: xs.len() > 0 ? xs.last() : \"none\"".into());
        d
    })
}

fn m_parse_json<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    read_json(s, sp)
}

pub fn read_json<'a>(s: &str, sp: Span) -> Result<Value<'a>, Diagnostic> {
    let parsed: serde_json::Value =
        serde_json::from_str(s).map_err(|e| rt("E0314", format!("invalid JSON: {e}"), sp))?;
    Ok(json_to_value(parsed))
}

fn m_parse_yaml<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    read_yaml(s, sp)
}

/// The three readers, reachable without an interpreter so a fuzz target can
/// drive them on raw bytes. They are the only place Aura accepts input it did
/// not lex itself.
pub fn read_yaml<'a>(s: &str, sp: Span) -> Result<Value<'a>, Diagnostic> {
    let docs = yaml_rust2::YamlLoader::load_from_str(s)
        .map_err(|e| rt("E0314", format!("invalid YAML: {e}"), sp))?;
    // A stream with several documents is ambiguous as a single value (D13: one
    // input, one result), so require exactly one.
    let doc = match docs.len() {
        1 => &docs[0],
        0 => return Ok(Value::Null),
        n => {
            return Err(rt(
                "E0314",
                format!("invalid YAML: expected one document, found {n}"),
                sp,
            ))
        }
    };
    yaml_to_value(doc, sp)
}

/// YAML's merge key. Not an Aura concept — it belongs to the file being read,
/// and reading someone else's format means reading it as that format defines it.
const MERGE_KEY: &str = "<<";

/// Only scalar keys map onto an Aura object.
fn scalar_key(k: &yaml_rust2::Yaml, sp: Span) -> Result<String, Diagnostic> {
    use yaml_rust2::Yaml as Y;
    Ok(match k {
        Y::String(s) => s.clone(),
        Y::Integer(n) => n.to_string(),
        Y::Boolean(b) => b.to_string(),
        Y::Real(r) => r.clone(),
        _ => {
            return Err(rt(
                "E0314",
                "invalid YAML: only scalar keys are supported".to_string(),
                sp,
            ))
        }
    })
}

/// Expand one `<<` entry at the position it was written.
///
/// Two precedence rules, both from the YAML merge specification: a key written
/// out in the mapping beats a merged one, and in `<<: [a, b]` the earlier
/// source beats the later. Both fall out of refusing to overwrite: `explicit`
/// blocks the first, `contains_key` blocks the second.
fn merge_into<'a>(
    map: &mut indexmap::IndexMap<String, Value<'a>>,
    source: &yaml_rust2::Yaml,
    explicit: &std::collections::HashSet<String>,
    sp: Span,
) -> Result<(), Diagnostic> {
    use yaml_rust2::Yaml as Y;
    match source {
        Y::Hash(h) => {
            for (k, v) in h {
                let key = scalar_key(k, sp)?;
                if explicit.contains(&key) || map.contains_key(&key) {
                    continue;
                }
                map.insert(key, yaml_to_value(v, sp)?);
            }
            Ok(())
        }
        Y::Array(xs) => {
            for x in xs {
                merge_into(map, x, explicit, sp)?;
            }
            Ok(())
        }
        // Anything else would have to be guessed at, and a guess here silently
        // changes a configuration.
        _ => Err(rt(
            "E0314",
            "invalid YAML: `<<` merges a mapping, or a list of mappings".to_string(),
            sp,
        )),
    }
}

/// yaml-rust2's tree into an Aura value. Written out rather than routed through
/// serde so the type mapping is explicit: YAML's untyped scalars are where a
/// version string quietly becomes a float.
fn yaml_to_value<'a>(y: &yaml_rust2::Yaml, sp: Span) -> Result<Value<'a>, Diagnostic> {
    use yaml_rust2::Yaml as Y;
    Ok(match y {
        Y::Null => Value::Null,
        Y::Boolean(b) => Value::Bool(*b),
        Y::Integer(n) => Value::Int(*n),
        // Reals are kept as text by the parser and parsed on demand.
        Y::Real(r) => match r.parse::<f64>() {
            Ok(f) => Value::Float(f),
            Err(_) => Value::str(r.clone()),
        },
        Y::String(s) => Value::str(s.clone()),
        Y::Array(xs) => {
            let mut out = Vec::with_capacity(xs.len());
            for x in xs {
                out.push(yaml_to_value(x, sp)?);
            }
            Value::list(out)
        }
        Y::Hash(h) => {
            let mut map = indexmap::IndexMap::with_capacity(h.len());

            // `<<` is YAML's merge key, and the keys written out in this
            // mapping win over anything it pulls in. Which ones those are has
            // to be known before the merge is expanded, so they are collected
            // first rather than relying on insertion order.
            let mut explicit = std::collections::HashSet::new();
            for (k, _) in h {
                if !matches!(k, Y::String(s) if s == MERGE_KEY) {
                    explicit.insert(scalar_key(k, sp)?);
                }
            }

            for (k, v) in h {
                if matches!(k, Y::String(s) if s == MERGE_KEY) {
                    merge_into(&mut map, v, &explicit, sp)?;
                    continue;
                }
                map.insert(scalar_key(k, sp)?, yaml_to_value(v, sp)?);
            }
            Value::object(map)
        }
        Y::Alias(_) | Y::BadValue => {
            return Err(rt(
                "E0314",
                "invalid YAML: aliases are not supported".to_string(),
                sp,
            ))
        }
    })
}

fn m_to_json<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let json = crate::serialize::to_json(recv).map_err(|d| rt(d.code, d.message, sp))?;
    Ok(Value::str(
        serde_json::to_string(&json).expect("valid json"),
    ))
}

fn m_to_yaml<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    crate::serialize::to_yaml_compact_string(recv)
        .map(Value::str)
        .map_err(|d| rt(d.code, d.message, sp))
}

/// The three `_pretty` counterparts (D32). `to_*` gives the most compact form
/// the format allows, for a string being embedded somewhere; `to_*_pretty`
/// gives the form a person reads, for a file that lands in a repository, where
/// one line per document makes a diff useless.
fn m_to_json_pretty<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let json = crate::serialize::to_json(recv).map_err(|d| rt(d.code, d.message, sp))?;
    Ok(Value::str(
        serde_json::to_string_pretty(&json).expect("valid json"),
    ))
}

fn m_to_yaml_pretty<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    crate::serialize::to_yaml_string(recv)
        .map(Value::str)
        .map_err(|d| rt(d.code, d.message, sp))
}

fn m_to_toml_pretty<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    crate::serialize::to_toml_string(recv)
        .map(Value::str)
        .map_err(|d| rt(d.code, d.message, sp))
}

fn m_to_toml<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    crate::serialize::to_toml_compact_string(recv)
        .map(Value::str)
        .map_err(|d| rt(d.code, d.message, sp))
}

/// `.keys()` — object keys in declaration order.
fn m_obj_keys<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Object(m) = recv else {
        unreachable!()
    };
    Ok(Value::list(m.keys().map(Value::str).collect()))
}

fn m_obj_values<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Object(m) = recv else {
        unreachable!()
    };
    Ok(Value::list(m.values().cloned().collect()))
}

/// `.entries()`: Object -> List of `{ key, value }` objects, declaration order.
///
/// The pair is an object rather than a two-element list so a lambda reads
/// `e.key` instead of `e[0]`. It is also what `to_object()` consumes, so the
/// two are inverses and a round trip is written without reshaping.
fn m_obj_entries<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Object(m) = recv else {
        unreachable!()
    };
    let pairs = m
        .iter()
        .map(|(k, v)| {
            let mut pair = IndexMap::with_capacity(2);
            pair.insert("key".to_string(), Value::str(k));
            pair.insert("value".to_string(), v.clone());
            Value::object(pair)
        })
        .collect();
    Ok(Value::list(pairs))
}

/// `.to_object()`: List of `{ key, value }` objects -> Object.
///
/// The inverse of `entries()`, and the only way to build an object whose keys
/// are computed: a property key is a literal in the grammar, so before this a
/// list could be mapped but never indexed by a value it carried.
fn m_list_to_object<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(items) = recv else {
        unreachable!()
    };
    let mut out: IndexMap<String, Value<'a>> = IndexMap::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        let Value::Object(pair) = item else {
            return Err(rt(
                "E0306",
                format!(
                    "to_object() expects {{ key, value }} objects, but element {i} is {}",
                    item.type_name()
                ),
                sp,
            ));
        };
        let (Some(k), Some(v)) = (pair.get("key"), pair.get("value")) else {
            return Err(rt(
                "E0306",
                format!("element {i} needs both a 'key' and a 'value' field"),
                sp,
            ));
        };
        let Value::Str(k) = k else {
            return Err(rt(
                "E0306",
                format!(
                    "the 'key' of element {i} must be a String, got {}",
                    k.type_name()
                ),
                sp,
            ));
        };
        // A silent overwrite would make the result depend on element order in a
        // way nothing in the source shows, so a collision is an error instead.
        if let Some(first) = out.get_index_of(k.as_ref()) {
            return Err(rt(
                "E0323",
                format!("duplicate key \"{k}\": elements {first} and {i} both claim it",),
                sp,
            ));
        }
        out.insert(k.to_string(), v.clone());
    }
    Ok(Value::object(out))
}

/// `.contains(x)`: List — element; Object — key; Str — substring.
fn m_contains<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Some(needle) = args.first() else {
        return Err(rt("E0306", "contains() expects an argument", sp));
    };
    let found = match (recv, needle) {
        (Value::List(xs), n) => xs.contains(n),
        (Value::Object(m), Value::Str(k)) => m.contains_key(k.as_ref()),
        (Value::Str(s), Value::Str(sub)) => s.contains(sub.as_ref()),
        (Value::Object(_), n) => {
            return Err(rt(
                "E0306",
                format!(
                    "Object.contains expects a String key, got {}",
                    n.type_name()
                ),
                sp,
            ))
        }
        (Value::Str(_), n) => {
            return Err(rt(
                "E0306",
                format!("String.contains expects a String, got {}", n.type_name()),
                sp,
            ))
        }
        _ => unreachable!(),
    };
    Ok(Value::Bool(found))
}

/// `.join(sep)` — scalar elements joined by a separator (empty string if no argument).
fn m_list_join<'a>(
    it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let sep = match args.first() {
        Some(Value::Str(s)) => s.to_string(),
        None => String::new(),
        Some(other) => {
            return Err(rt(
                "E0306",
                format!(
                    "join() expects a String separator, got {}",
                    other.type_name()
                ),
                sp,
            ))
        }
    };
    let parts: Vec<String> = xs
        .iter()
        .map(|v| it.display(v, sp, TextCtx::Join))
        .collect::<Result<_, _>>()?;
    Ok(Value::str(parts.join(&sep)))
}

/// `"1h30m".parse_duration()` → seconds (Int). Units: d, h, m, s.
/// A deterministic alternative to timeout "magic numbers".
fn m_parse_duration<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    let err = || {
        rt(
            "E0319",
            format!("invalid duration '{s}': expected e.g. \"1h30m\", units d/h/m/s"),
            sp,
        )
    };
    let bytes = s.as_bytes();
    let mut i = 0;
    let mut total: i64 = 0;
    let mut components = 0;
    while i < bytes.len() {
        let start = i;
        while i < bytes.len() && bytes[i].is_ascii_digit() {
            i += 1;
        }
        if i == start || i == bytes.len() {
            return Err(err());
        }
        let n: i64 = s[start..i].parse().map_err(|_| err())?;
        let mult: i64 = match bytes[i] {
            b'd' => 86400,
            b'h' => 3600,
            b'm' => 60,
            b's' => 1,
            _ => return Err(err()),
        };
        i += 1;
        total = n
            .checked_mul(mult)
            .and_then(|x| total.checked_add(x))
            .ok_or_else(|| rt("E0304", "duration overflows i64 seconds", sp))?;
        components += 1;
    }
    if components == 0 {
        return Err(err());
    }
    Ok(Value::Int(total))
}

/// `5400.format_duration()` → "1h30m" (compact, no zero components).
fn m_format_duration<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Int(total) = recv else {
        unreachable!()
    };
    if *total < 0 {
        return Err(rt(
            "E0306",
            "format_duration expects a non-negative number of seconds",
            sp,
        ));
    }
    if *total == 0 {
        return Ok(Value::str("0s"));
    }
    let (mut rest, mut out) = (*total, String::new());
    for (unit, secs) in [("d", 86400), ("h", 3600), ("m", 60), ("s", 1)] {
        let n = rest / secs;
        if n > 0 {
            out.push_str(&format!("{n}{unit}"));
            rest %= secs;
        }
    }
    Ok(Value::str(out))
}

/// `"2026-07-18T12:00:00Z".parse_datetime()` → epoch seconds (Int, UTC).
/// Formats: `YYYY-MM-DD` (midnight UTC) and RFC3339 with `Z` or a `±HH:MM` offset.
fn m_parse_datetime<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    parse_rfc3339(s).map(Value::Int).ok_or_else(|| {
        rt(
            "E0320",
            format!("invalid datetime '{s}': expected RFC3339, e.g. \"2026-07-18T12:00:00Z\""),
            sp,
        )
    })
}

/// `epoch.format_datetime()` → an RFC3339 string in UTC.
fn m_format_datetime<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Int(epoch) = recv else {
        unreachable!()
    };
    let days = epoch.div_euclid(86400);
    let secs = epoch.rem_euclid(86400);
    let (y, m, d) = civil_from_days(days);
    Ok(Value::str(format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
        secs / 3600,
        (secs % 3600) / 60,
        secs % 60
    )))
}

fn parse_rfc3339(s: &str) -> Option<i64> {
    let num = |t: &str| -> Option<i64> {
        if t.bytes().all(|b| b.is_ascii_digit()) && !t.is_empty() {
            t.parse().ok()
        } else {
            None
        }
    };
    let (date, rest) = if s.len() > 10 {
        // split_at is byte-indexed: a multi-byte char across the boundary is not
        // valid RFC3339 (which is ASCII), so reject instead of panicking.
        if !s.is_char_boundary(10) {
            return None;
        }
        s.split_at(10)
    } else {
        (s, "")
    };
    let mut dp = date.split('-');
    let (y, m, d) = (num(dp.next()?)?, num(dp.next()?)?, num(dp.next()?)?);
    if dp.next().is_some() || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) {
        return None;
    }
    let mut epoch = days_from_civil(y, m, d) * 86400;
    if rest.is_empty() {
        return Some(epoch);
    }
    let rest = rest.strip_prefix('T')?;
    if rest.len() < 9 || !rest.is_char_boundary(8) {
        return None;
    }
    let (time, zone) = rest.split_at(8);
    let mut tp = time.split(':');
    let (hh, mm, ss) = (num(tp.next()?)?, num(tp.next()?)?, num(tp.next()?)?);
    if tp.next().is_some() || hh > 23 || mm > 59 || ss > 59 {
        return None;
    }
    epoch += hh * 3600 + mm * 60 + ss;
    match zone {
        "Z" => Some(epoch),
        _ => {
            let sign = match zone.as_bytes().first()? {
                b'+' => 1,
                b'-' => -1,
                _ => return None,
            };
            let (oh, om) = zone[1..].split_once(':')?;
            let (oh, om) = (num(oh)?, num(om)?);
            if oh > 23 || om > 59 {
                return None;
            }
            Some(epoch - sign * (oh * 3600 + om * 60))
        }
    }
}

fn days_in_month(y: i64, m: i64) -> i64 {
    match m {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        _ => {
            if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
                29
            } else {
                28
            }
        }
    }
}

/// Howard Hinnant's algorithms: proleptic Gregorian calendar ↔ days since the epoch.
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146097 + doe - 719468
}

fn civil_from_days(z: i64) -> (i64, i64, i64) {
    let z = z + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = z - era * 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    (if m <= 2 { y + 1 } else { y }, m, d)
}

// ---- stdlib extension: String ----

fn expect_str_arg<'a>(args: &[Value<'a>], method: &str, sp: Span) -> Result<String, Diagnostic> {
    match args.first() {
        Some(Value::Str(s)) => Ok(s.to_string()),
        Some(other) => Err(rt(
            "E0306",
            format!(
                "{method}() expects a String argument, got {}",
                other.type_name()
            ),
            sp,
        )),
        None => Err(rt("E0306", format!("{method}() expects one argument"), sp)),
    }
}

fn m_str_trim<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    Ok(Value::str(s.trim()))
}

/// `.split(sep)` → List of substrings; the separator must be non-empty.
fn m_str_split<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    let sep = expect_str_arg(args, "split", sp)?;
    if sep.is_empty() {
        return Err(rt("E0306", "split() separator must be non-empty", sp));
    }
    Ok(Value::list(s.split(&sep).map(Value::str).collect()))
}

/// `.replace(from, to)` → String with all occurrences replaced.
fn m_str_replace<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    let (Some(Value::Str(from)), Some(Value::Str(to))) = (args.first(), args.get(1)) else {
        return Err(rt(
            "E0306",
            "replace(from, to) expects two String arguments",
            sp,
        ));
    };
    Ok(Value::str(s.replace(from.as_ref(), to)))
}

fn m_str_starts_with<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    let prefix = expect_str_arg(args, "starts_with", sp)?;
    Ok(Value::Bool(s.starts_with(&prefix)))
}

fn m_str_ends_with<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    let suffix = expect_str_arg(args, "ends_with", sp)?;
    Ok(Value::Bool(s.ends_with(&suffix)))
}

/// `.to_int()` — parse (trimmed) into Int; E0314 on failure.
fn m_str_to_int<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    s.trim()
        .parse::<i64>()
        .map(Value::Int)
        .map_err(|_| rt("E0314", format!("cannot parse '{s}' as Int"), sp))
}

fn m_str_to_float<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    s.trim()
        .parse::<f64>()
        .map(Value::Float)
        .map_err(|_| rt("E0314", format!("cannot parse '{s}' as Float"), sp))
}

// ---- stdlib extension: digests and codecs ----
//
// These are pure functions of their input: no I/O, no clock, no randomness, so
// they keep the capability model (D1) and determinism (D13) intact. That is why
// they belong in the core rather than in loadable native plugins, which could
// not offer the same guarantees.

const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// `"text".sha256()` → the lowercase hex digest (config-checksum annotations).
fn m_str_sha256<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(s.as_bytes());
    let mut hex = String::with_capacity(digest.len() * 2);
    for b in digest {
        hex.push_str(&format!("{b:02x}"));
    }
    Ok(Value::str(hex))
}

/// `"text".base64()` → standard base64 with padding (e.g. k8s Secret data).
fn m_str_base64<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    let bytes = s.as_bytes();
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            *chunk.get(1).unwrap_or(&0),
            *chunk.get(2).unwrap_or(&0),
        ];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        for i in 0..4 {
            if i <= chunk.len() {
                out.push(B64[((n >> (18 - 6 * i)) & 0x3f) as usize] as char);
            } else {
                out.push('=');
            }
        }
    }
    Ok(Value::str(out))
}

/// `"aGk=".base64_decode()` → the decoded String; E0321 if it is not valid
/// base64 or does not decode to UTF-8.
fn m_str_base64_decode<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    let err = || rt("E0321", format!("'{s}' is not valid base64"), sp);
    let src: Vec<u8> = s.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
    if src.len() % 4 != 0 {
        return Err(err());
    }
    let mut out: Vec<u8> = Vec::with_capacity(src.len() / 4 * 3);
    for chunk in src.chunks(4) {
        let pad = chunk.iter().filter(|&&b| b == b'=').count();
        // Padding is only legal at the very end, at most two characters.
        if pad > 2 || (pad > 0 && chunk[4 - pad..].iter().any(|&b| b != b'=')) {
            return Err(err());
        }
        let mut n = 0u32;
        for &b in &chunk[..4 - pad] {
            let v = B64.iter().position(|&c| c == b).ok_or_else(err)? as u32;
            n = (n << 6) | v;
        }
        n <<= 6 * pad as u32;
        for i in 0..(3 - pad) {
            out.push(((n >> (16 - 8 * i)) & 0xff) as u8);
        }
    }
    String::from_utf8(out).map(Value::str).map_err(|_| err())
}

// ---- stdlib extension: List ----

/// Total-ish scalar ordering; None means the two values are incomparable.
fn scalar_cmp(a: &Value<'_>, b: &Value<'_>) -> Option<std::cmp::Ordering> {
    use Value::*;
    match (a, b) {
        (Int(x), Int(y)) => Some(x.cmp(y)),
        (Float(x), Float(y)) => x.partial_cmp(y),
        (Int(x), Float(y)) => (*x as f64).partial_cmp(y),
        (Float(x), Int(y)) => x.partial_cmp(&(*y as f64)),
        (Str(x), Str(y)) => Some(x.as_ref().cmp(y.as_ref())),
        (Bool(x), Bool(y)) => Some(x.cmp(y)),
        _ => None,
    }
}

/// `.sort()` — ascending; all elements must be mutually comparable scalars.
fn m_list_sort<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    // Validate up front so sort_by never sees an incomparable pair.
    if let Some(first) = xs.first() {
        for v in xs.iter() {
            if scalar_cmp(first, v).is_none() {
                let mut d = rt(
                    "E0306",
                    format!(
                        "sort() cannot compare {} and {}",
                        first.type_name(),
                        v.type_name()
                    ),
                    sp,
                );
                d.help = Some(mixed_list_help(
                    "sort",
                    matches!(first, Value::Null) || matches!(v, Value::Null),
                ));
                return Err(d);
            }
        }
    }
    let mut out: Vec<Value<'a>> = xs.to_vec();
    out.sort_by(|a, b| scalar_cmp(a, b).unwrap_or(std::cmp::Ordering::Equal));
    Ok(Value::list(out))
}

fn m_list_reverse<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    Ok(Value::list(xs.iter().rev().cloned().collect()))
}

/// Advice for a list whose elements are not uniformly usable.
///
/// The two causes need different cures, and offering the wrong one wastes the
/// reader's next attempt. A `Null` almost always arrived from parsed YAML or
/// JSON, where an empty value is a real and common shape, and `.compact()`
/// removes exactly those. A genuine mix of scalar types is a different mistake
/// with no one-call fix, so it is not offered one.
fn mixed_list_help(method: &str, saw_null: bool) -> String {
    if saw_null {
        format!(
            "a null in a list usually came from parsed YAML or JSON; drop them first: xs.compact().{method}()"
        )
    } else {
        format!(
            "{method}() needs every element to be the same kind of scalar; map or filter the odd ones out first"
        )
    }
}

/// `.sum()` — Int if all Int, Float if any Float; E0304 on Int overflow.
fn m_list_sum<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let _ = args;
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let any_float = xs.iter().any(|v| matches!(v, Value::Float(_)));
    if any_float {
        let mut acc = 0.0f64;
        for v in xs.iter() {
            match v {
                Value::Int(n) => acc += *n as f64,
                Value::Float(f) => acc += *f,
                other => {
                    let mut d = rt(
                        "E0306",
                        format!("sum() expects numbers, got {}", other.type_name()),
                        sp,
                    );
                    d.help = Some(mixed_list_help("sum", matches!(other, Value::Null)));
                    return Err(d);
                }
            }
        }
        Ok(Value::Float(acc))
    } else {
        let mut acc = 0i64;
        for v in xs.iter() {
            match v {
                Value::Int(n) => {
                    acc = acc
                        .checked_add(*n)
                        .ok_or_else(|| rt("E0304", "sum() overflows i64", sp))?
                }
                other => {
                    let mut d = rt(
                        "E0306",
                        format!("sum() expects numbers, got {}", other.type_name()),
                        sp,
                    );
                    d.help = Some(mixed_list_help("sum", matches!(other, Value::Null)));
                    return Err(d);
                }
            }
        }
        Ok(Value::Int(acc))
    }
}

fn list_extreme<'a>(
    xs: &[Value<'a>],
    want_max: bool,
    method: &str,
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let mut best = xs.first().ok_or_else(|| {
        let mut d = rt("E0317", format!("{method}() on an empty list"), sp);
        d.help = Some(format!(
            "when the list may be empty: xs.len() > 0 ? xs.{method}() : 0"
        ));
        d
    })?;
    for v in &xs[1..] {
        let ord = scalar_cmp(v, best).ok_or_else(|| {
            let mut d = rt(
                "E0306",
                format!(
                    "{method}() cannot compare {} and {}",
                    v.type_name(),
                    best.type_name()
                ),
                sp,
            );
            d.help = Some(mixed_list_help(
                method,
                matches!(v, Value::Null) || matches!(best, Value::Null),
            ));
            d
        })?;
        if (want_max && ord == std::cmp::Ordering::Greater)
            || (!want_max && ord == std::cmp::Ordering::Less)
        {
            best = v;
        }
    }
    Ok(best.clone())
}

fn m_list_min<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    list_extreme(xs, false, "min", sp)
}

fn m_list_max<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    list_extreme(xs, true, "max", sp)
}

/// `.flatten()` — one level: nested lists are spread, scalars kept as-is.
fn m_list_flatten<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let mut out: Vec<Value<'a>> = Vec::new();
    for v in xs.iter() {
        match v {
            Value::List(inner) => out.extend(inner.iter().cloned()),
            other => out.push(other.clone()),
        }
    }
    Ok(Value::list(out))
}

/// `.slice(start, end)` — half-open `[start, end)`, indices clamped to bounds.
fn m_list_slice<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::List(xs) = recv else {
        unreachable!()
    };
    let (Some(Value::Int(start)), Some(Value::Int(end))) = (args.first(), args.get(1)) else {
        return Err(rt(
            "E0306",
            "slice(start, end) expects two Int arguments",
            sp,
        ));
    };
    if *start < 0 || *end < 0 {
        return Err(rt("E0306", "slice() indices must be non-negative", sp));
    }
    let len = xs.len();
    let s = (*start as usize).min(len);
    let e = (*end as usize).clamp(s, len);
    Ok(Value::list(xs[s..e].to_vec()))
}

/// `.slice(start, end)` on a String — half-open, indices clamped, **in chars**.
///
/// Chars rather than bytes because `len()` counts chars: if they disagreed,
/// `s.slice(0, s.len())` would panic or truncate the moment a manifest carried
/// anything outside ASCII, which configuration routinely does.
///
/// Its absence was a real gap. Trimming a trailing `/` from a topic went through
/// `split("/").filter(...).join("/")` — the examples carried a comment
/// apologising for it.
fn m_str_slice<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Str(s) = recv else { unreachable!() };
    let (Some(Value::Int(start)), Some(Value::Int(end))) = (args.first(), args.get(1)) else {
        let mut d = rt("E0306", "slice(start, end) expects two Int arguments", sp);
        d.help = Some("to drop a trailing character: s.slice(0, s.len() - 1)".into());
        return Err(d);
    };
    if *start < 0 || *end < 0 {
        let mut d = rt("E0306", "slice() indices must be non-negative", sp);
        d.help = Some("count from the end with len(): s.slice(0, s.len() - 1)".into());
        return Err(d);
    }
    let len = s.chars().count();
    let from = (*start as usize).min(len);
    let to = (*end as usize).clamp(from, len);
    let out: String = s.chars().skip(from).take(to - from).collect();
    Ok(Value::str(out))
}

/// `.to_float()` on an Int: the only way to widen one.
///
/// Before this, an Int reached Float by being divided by `1.0` — correct under
/// D6, since Float is contagious, but it reads as a trick rather than as intent.
fn m_int_to_float<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    _sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    let Value::Int(n) = recv else { unreachable!() };
    Ok(Value::Float(*n as f64))
}

// ---- stdlib extension: numeric + universal to_str ----

fn m_num_abs<'a>(
    _it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    match recv {
        Value::Int(n) => n
            .checked_abs()
            .map(Value::Int)
            .ok_or_else(|| rt("E0304", "abs() overflows i64", sp)),
        Value::Float(f) => Ok(Value::Float(f.abs())),
        _ => unreachable!(),
    }
}

/// `.to_str()` — scalar → its String rendering (same as string interpolation).
fn m_to_str<'a>(
    it: &mut Interpreter<'a>,
    recv: &Value<'a>,
    _args: &[Value<'a>],
    sp: Span,
) -> Result<Value<'a>, Diagnostic> {
    Ok(Value::str(it.display(recv, sp, TextCtx::Message)?))
}

fn json_to_value<'a>(j: serde_json::Value) -> Value<'a> {
    match j {
        serde_json::Value::Null => Value::Null,
        serde_json::Value::Bool(b) => Value::Bool(b),
        // The number is taken as the text JSON carried and parsed here, not by
        // serde_json. Its float parser is off by one unit in the last place
        // against Rust's on some inputs: `3.3333333333333333e+65` read from
        // JSON and the same digits read from YAML produced two different
        // values, so a manifest's result depended on which format the number
        // arrived in. Found by fuzz_bridge.
        serde_json::Value::Number(n) => {
            let text = n.as_str();
            match text.parse::<i64>() {
                Ok(i) => Value::Int(i),
                Err(_) => Value::Float(text.parse::<f64>().unwrap_or(f64::NAN)),
            }
        }
        serde_json::Value::String(s) => Value::str(s),
        serde_json::Value::Array(xs) => Value::list(xs.into_iter().map(json_to_value).collect()),
        serde_json::Value::Object(m) => Value::Object(Arc::new(
            m.into_iter().map(|(k, v)| (k, json_to_value(v))).collect(),
        )),
    }
}

fn toml_to_value<'a>(t: toml::Value) -> Value<'a> {
    match t {
        toml::Value::String(s) => Value::str(s),
        toml::Value::Integer(n) => Value::Int(n),
        toml::Value::Float(n) => Value::Float(n),
        toml::Value::Boolean(b) => Value::Bool(b),
        toml::Value::Datetime(d) => Value::str(d.to_string()),
        toml::Value::Array(xs) => Value::list(xs.into_iter().map(toml_to_value).collect()),
        toml::Value::Table(t) => Value::Object(Arc::new(
            t.into_iter().map(|(k, v)| (k, toml_to_value(v))).collect(),
        )),
    }
}