serde_ucl 0.3.0

UCL (Universal Configuration Language) with serde: reads and writes UCL as libucl does
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
//! UCL value model.
//!
//! The model follows libucl's object tree. A key in an object holds an [`Entry`] of one or more
//! values: more than one is libucl's *implicit array* (`UCL_OBJECT_MULTIVALUE`), created when a
//! key repeats. An explicit array written with `[...]` is a single [`UclValue::Array`] value, so
//! the two stay distinct:
//!
//! ```text
//! k = [1, 2]; k = 3    →  entry "k" with two values: Array[1, 2], Integer 3
//! ```
//!
//! Each value in an entry carries the priority of the chunk it came from (0–15, as in libucl) and
//! whether it was copied by `.inherit`. Both only matter while duplicate keys are resolved; see
//! [`UclObject::insert_with_strategy`].

use indexmap::IndexMap;
use smallvec::SmallVec;
use std::fmt;

/// Explicit array (`[...]`).
pub type UclArray = Vec<UclValue>;

/// A UCL value.
///
/// Cloning and comparing do not recurse: they take the same stack at any depth of nesting.
/// Dropping a value, and formatting it with `Debug`, recurse once per level.
#[derive(Debug)]
pub enum UclValue {
    Object(UclObject),
    Array(UclArray),
    Integer(i64),
    Float(f64),
    /// Time in seconds (`10s`, `5min`, `10ms`): libucl's `UCL_TIME`.
    Time(f64),
    String(String),
    Boolean(bool),
    Null,
}

/// Written out rather than derived, which would recurse once per level of nesting: `.inherit`
/// copies values nested as deep as the parser allows (spec §9.7, §11.2), and a derived clone of
/// such a value overflows a 2 MiB stack in a debug build. The copy keeps each value's priority
/// and marks.
impl Clone for UclValue {
    fn clone(&self) -> Self {
        match self {
            UclValue::Object(_) | UclValue::Array(_) => clone_tree(self),
            UclValue::Integer(i) => UclValue::Integer(*i),
            UclValue::Float(f) => UclValue::Float(*f),
            UclValue::Time(t) => UclValue::Time(*t),
            UclValue::String(s) => UclValue::String(s.clone()),
            UclValue::Boolean(b) => UclValue::Boolean(*b),
            UclValue::Null => UclValue::Null,
        }
    }
}

/// Written out rather than derived, which would recurse once per level of nesting: `==` compares
/// as the derived comparisons of [`UclValue`], [`UclObject`], [`Entry`] and [`Slot`] would, with a
/// heap stack. Values of different kinds differ; floats and times compare as `f64` (a NaN equals
/// nothing); objects compare as maps, their keys in any order; the values of an entry compare in
/// order, each with its priority and marks.
impl PartialEq for UclValue {
    fn eq(&self, other: &Self) -> bool {
        let mut pending = Vec::new();
        push_values(self, other, &mut pending) && equal_pending(pending)
    }
}

/// See [`UclValue`]'s `PartialEq`.
impl PartialEq for UclObject {
    fn eq(&self, other: &Self) -> bool {
        let mut pending = Vec::new();
        push_objects(self, other, &mut pending) && equal_pending(pending)
    }
}

/// See [`UclValue`]'s `PartialEq`.
impl PartialEq for Entry {
    fn eq(&self, other: &Self) -> bool {
        let mut pending = Vec::new();
        push_entries(self, other, &mut pending) && equal_pending(pending)
    }
}

/// See [`UclValue`]'s `PartialEq`.
impl PartialEq for Slot {
    fn eq(&self, other: &Self) -> bool {
        let mut pending = Vec::new();
        push_slots(self, other, &mut pending) && equal_pending(pending)
    }
}

/// Pairs of values still to compare.
type Pending<'a> = Vec<(&'a UclValue, &'a UclValue)>;

/// Whether every pair in `pending`, and every pair of values inside them, is equal.
fn equal_pending(mut pending: Pending<'_>) -> bool {
    while let Some((a, b)) = pending.pop() {
        if !push_values(a, b, &mut pending) {
            return false;
        }
    }
    true
}

/// Compares `a` and `b` without the values inside them, which it pushes to `pending` in pairs.
fn push_values<'a>(a: &'a UclValue, b: &'a UclValue, pending: &mut Pending<'a>) -> bool {
    match (a, b) {
        (UclValue::Object(x), UclValue::Object(y)) => push_objects(x, y, pending),
        (UclValue::Array(x), UclValue::Array(y)) => {
            pending.extend(x.iter().zip(y));
            x.len() == y.len()
        }
        (UclValue::Integer(x), UclValue::Integer(y)) => x == y,
        (UclValue::Float(x), UclValue::Float(y)) | (UclValue::Time(x), UclValue::Time(y)) => x == y,
        (UclValue::String(x), UclValue::String(y)) => x == y,
        (UclValue::Boolean(x), UclValue::Boolean(y)) => x == y,
        (UclValue::Null, UclValue::Null) => true,
        _ => false,
    }
}

fn push_objects<'a>(x: &'a UclObject, y: &'a UclObject, pending: &mut Pending<'a>) -> bool {
    x.entries.len() == y.entries.len()
        && x.entries.iter().all(|(key, entry)| {
            y.entries
                .get(key)
                .is_some_and(|other| push_entries(entry, other, pending))
        })
}

fn push_entries<'a>(x: &'a Entry, y: &'a Entry, pending: &mut Pending<'a>) -> bool {
    x.slots.len() == y.slots.len()
        && x.slots
            .iter()
            .zip(&y.slots)
            .all(|(s, t)| push_slots(s, t, pending))
}

fn push_slots<'a>(s: &'a Slot, t: &'a Slot, pending: &mut Pending<'a>) -> bool {
    pending.push((&s.value, &t.value));
    (s.priority, s.inherited, s.collected) == (t.priority, t.inherited, t.collected)
}

/// A copy of the container `root`, built with a heap stack: every value is copied after the
/// values inside it, which wait on `done` in order until their container is built.
fn clone_tree(root: &UclValue) -> UclValue {
    enum Step<'a> {
        /// Copy this value: a scalar at once, a container after its values.
        Copy(&'a UclValue),
        /// Build the copy of this container from the copies of its values on `done`.
        Build(&'a UclValue),
    }
    let mut todo = vec![Step::Copy(root)];
    let mut done: Vec<UclValue> = Vec::new();
    while let Some(step) = todo.pop() {
        match step {
            Step::Copy(value @ UclValue::Object(object)) => {
                todo.push(Step::Build(value));
                todo.extend(
                    object
                        .entries()
                        .flat_map(Entry::values)
                        .rev()
                        .map(Step::Copy),
                );
            }
            Step::Copy(value @ UclValue::Array(items)) => {
                todo.push(Step::Build(value));
                todo.extend(items.iter().rev().map(Step::Copy));
            }
            Step::Copy(scalar) => done.push(scalar.clone()),
            Step::Build(UclValue::Object(object)) => {
                let count = object.entries().map(Entry::len).sum::<usize>();
                let mut values = done.split_off(done.len() - count).into_iter();
                let entries = object
                    .entries
                    .iter()
                    .map(|(key, entry)| {
                        let slots = entry
                            .slots
                            .iter()
                            .map(|slot| slot.with_value(values.next().expect("copied")))
                            .collect();
                        (key.clone(), Entry { slots })
                    })
                    .collect();
                done.push(UclValue::Object(UclObject { entries }));
            }
            Step::Build(UclValue::Array(items)) => {
                let elements = done.split_off(done.len() - items.len());
                done.push(UclValue::Array(elements));
            }
            Step::Build(_) => unreachable!("only containers are built"),
        }
    }
    done.pop().expect("the root was copied")
}

/// Drops `value` with a heap stack. Dropping a value recurses once per level of nesting, which
/// matters where the call stack is already deep, or the value deeper than the parser allows.
pub(crate) fn discard(value: UclValue) {
    let mut stack = vec![value];
    while let Some(value) = stack.pop() {
        match value {
            UclValue::Object(object) => stack.extend(
                object
                    .into_iter()
                    .flat_map(|(_, entry)| entry.into_values()),
            ),
            UclValue::Array(items) => stack.extend(items),
            _ => {}
        }
    }
}

/// Keeps only the first value of each entry whose first value is an object or an array, in
/// every object inside `value`, `value` itself included: the rule of `.inherit` copies at every
/// level of the copy (spec §9.7). Entries whose first value is anything else keep all their
/// values. Walks with a heap stack, and discards the values it removes the same way.
pub(crate) fn keep_first_container_values(value: &mut UclValue) {
    let mut stack = vec![value];
    let mut removed = Vec::new();
    while let Some(value) = stack.pop() {
        match value {
            UclValue::Object(object) => {
                for entry in object.entries.values_mut() {
                    if entry.slots.len() > 1 && is_container(&entry.slots[0].value) {
                        removed.extend(entry.slots.drain(1..).map(Slot::into_value));
                    }
                    stack.extend(entry.slots.iter_mut().map(Slot::value_mut));
                }
            }
            UclValue::Array(items) => stack.extend(items.iter_mut()),
            _ => {}
        }
    }
    for value in removed {
        discard(value);
    }
}

/// The most containers (objects and arrays) nested inside one another in `value`, itself
/// included: 0 for a scalar, 1 for a container that holds only scalars. Counted with a heap
/// stack.
pub(crate) fn nesting(value: &UclValue) -> usize {
    let mut deepest = 0;
    let mut stack = vec![(value, 1)];
    while let Some((value, depth)) = stack.pop() {
        match value {
            UclValue::Object(object) => {
                deepest = deepest.max(depth);
                stack.extend(
                    object
                        .entries()
                        .flat_map(Entry::values)
                        .map(|v| (v, depth + 1)),
                );
            }
            UclValue::Array(items) => {
                deepest = deepest.max(depth);
                stack.extend(items.iter().map(|v| (v, depth + 1)));
            }
            _ => {}
        }
    }
    deepest
}

impl UclValue {
    /// Returns true if the value is an object
    pub fn is_object(&self) -> bool {
        matches!(self, UclValue::Object(_))
    }

    /// Returns true if the value is an explicit array
    pub fn is_array(&self) -> bool {
        matches!(self, UclValue::Array(_))
    }

    /// Returns true if the value is a string
    pub fn is_string(&self) -> bool {
        matches!(self, UclValue::String(_))
    }

    /// Returns true if the value is a time
    pub fn is_time(&self) -> bool {
        matches!(self, UclValue::Time(_))
    }

    /// Returns true if this is a Null variant
    pub fn is_null(&self) -> bool {
        matches!(self, UclValue::Null)
    }

    /// Returns the object if this is an Object variant
    pub fn as_object(&self) -> Option<&UclObject> {
        match self {
            UclValue::Object(obj) => Some(obj),
            _ => None,
        }
    }

    /// Returns the object mutably if this is an Object variant
    pub fn as_object_mut(&mut self) -> Option<&mut UclObject> {
        match self {
            UclValue::Object(obj) => Some(obj),
            _ => None,
        }
    }

    /// Returns the array if this is an Array variant
    pub fn as_array(&self) -> Option<&UclArray> {
        match self {
            UclValue::Array(arr) => Some(arr),
            _ => None,
        }
    }

    /// Returns the array mutably if this is an Array variant
    pub fn as_array_mut(&mut self) -> Option<&mut UclArray> {
        match self {
            UclValue::Array(arr) => Some(arr),
            _ => None,
        }
    }

    /// Returns the string if this is a String variant
    pub fn as_str(&self) -> Option<&str> {
        match self {
            UclValue::String(s) => Some(s),
            _ => None,
        }
    }

    /// Returns the integer if this is an Integer variant
    pub fn as_integer(&self) -> Option<i64> {
        match self {
            UclValue::Integer(i) => Some(*i),
            _ => None,
        }
    }

    /// Returns the float if this is a Float variant
    pub fn as_float(&self) -> Option<f64> {
        match self {
            UclValue::Float(f) => Some(*f),
            _ => None,
        }
    }

    /// Returns the number of seconds if this is a Time variant
    pub fn as_time(&self) -> Option<f64> {
        match self {
            UclValue::Time(t) => Some(*t),
            _ => None,
        }
    }

    /// Returns the boolean if this is a Boolean variant
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            UclValue::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    /// Name of the value's type, as libucl spells it (`ucl_object_type_to_string`).
    pub fn type_name(&self) -> &'static str {
        match self {
            UclValue::Object(_) => "object",
            UclValue::Array(_) => "array",
            UclValue::Integer(_) => "int",
            UclValue::Float(_) => "float",
            UclValue::Time(_) => "time",
            UclValue::String(_) => "string",
            UclValue::Boolean(_) => "boolean",
            UclValue::Null => "null",
        }
    }
}

/// How a key that is already present is resolved: libucl's `ucl_duplicate_strategy`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub enum DuplicateStrategy {
    /// Priority-aware (libucl's default): equal priority adds the value to the entry (implicit
    /// array), higher priority replaces the entry, lower priority is dropped.
    #[default]
    Append,
    /// Merge containers: a new object's keys go into the existing object, a new array's
    /// elements into the existing array. Scalars follow [`DuplicateStrategy::Append`].
    Merge,
    /// Replace the existing entry regardless of priority.
    Rewrite,
    /// Fail on the duplicate.
    Error,
}

/// Parser flags: libucl's `ucl_parser_flags`, bit for bit.
///
/// Only [`ParserFlags::KEY_LOWERCASE`] and [`ParserFlags::NO_IMPLICIT_ARRAYS`] affect
/// [`UclObject::insert_with_strategy`]; the others are read by the parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct ParserFlags(u32);

impl ParserFlags {
    /// No flags (`UCL_PARSER_DEFAULT`).
    pub const DEFAULT: Self = Self(0);
    /// Convert all keys to lower case.
    pub const KEY_LOWERCASE: Self = Self(1 << 0);
    /// Parse input in zero-copy mode if possible.
    pub const ZEROCOPY: Self = Self(1 << 1);
    /// Do not parse time suffixes; treat such values as strings.
    pub const NO_TIME: Self = Self(1 << 2);
    /// Collect repeated keys into an explicit array instead of an implicit one.
    pub const NO_IMPLICIT_ARRAYS: Self = Self(1 << 3);
    /// Save comments in the parser context.
    pub const SAVE_COMMENTS: Self = Self(1 << 4);
    /// Reject macros as syntax errors and switch off variable expansion (spec §12.6).
    pub const DISABLE_MACRO: Self = Self(1 << 5);
    /// Do not set the `FILENAME` and `CURDIR` variables.
    pub const NO_FILEVARS: Self = Self(1 << 6);

    const ALL: u32 = (1 << 7) - 1;

    /// No flags.
    pub const fn empty() -> Self {
        Self(0)
    }

    /// The raw bits, equal to libucl's values.
    pub const fn bits(self) -> u32 {
        self.0
    }

    /// Builds flags from raw bits, dropping unknown bits.
    pub const fn from_bits_truncate(bits: u32) -> Self {
        Self(bits & Self::ALL)
    }

    /// Returns true if every flag in `other` is set.
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// Returns true if no flag is set.
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Sets the flags in `other`.
    pub fn insert(&mut self, other: Self) {
        self.0 |= other.0;
    }

    /// Clears the flags in `other`.
    pub fn remove(&mut self, other: Self) {
        self.0 &= !other.0;
    }
}

impl std::ops::BitOr for ParserFlags {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl std::ops::BitOrAssign for ParserFlags {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

impl std::ops::BitAnd for ParserFlags {
    type Output = Self;

    fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
    }
}

/// Returned by [`UclObject::insert_with_strategy`] when a repeated key cannot take another value:
/// under [`DuplicateStrategy::Error`], for a container type mismatch under
/// [`DuplicateStrategy::Merge`], and for the `NO_IMPLICIT_ARRAYS` repeat of spec §8.5.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DuplicateKeyError {
    pub key: String,
}

impl fmt::Display for DuplicateKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "key '{}' cannot take another value", self.key)
    }
}

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

/// The highest priority, 15. Priorities are kept modulo 16, as libucl keeps them (spec §8.3):
/// only their 4 least significant bits are used.
pub const MAX_PRIORITY: u8 = 0x0f;

/// Where [`UclObject::insert_slot_placed`] put a value. A parser that fills containers in place
/// uses it to find the container it has just inserted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Placement {
    /// The value is value `n` of the key's entry.
    Slot(usize),
    /// The value is element `n` of the explicit array that is the entry's first value: a repeat
    /// collected under [`ParserFlags::NO_IMPLICIT_ARRAYS`] (spec §8.5).
    Collected(usize),
    /// The value, a container, was merged into the entry's first value, a container of the same
    /// type (spec §8.4).
    Merged,
    /// The value was discarded: the existing value has a higher priority (spec §8.3).
    Dropped,
}

/// One value of an [`Entry`], with its priority and `.inherit` flag.
#[derive(Debug, Clone)]
pub struct Slot {
    value: UclValue,
    priority: u8,
    inherited: bool,
    /// Set on an explicit array built from repeated keys under `NO_IMPLICIT_ARRAYS`.
    collected: bool,
}

impl Slot {
    /// A value with the given priority (masked to 0–15).
    pub fn new(value: UclValue, priority: u8) -> Self {
        Self {
            value,
            priority: priority & MAX_PRIORITY,
            inherited: false,
            collected: false,
        }
    }

    /// A value copied from another object by `.inherit`.
    #[cfg(test)]
    pub(crate) fn inherited(value: UclValue, priority: u8) -> Self {
        Self::new(value, priority).into_inherited()
    }

    /// An explicit array that collects a key's repeats under `NO_IMPLICIT_ARRAYS` (spec §8.5),
    /// at priority 0.
    pub(crate) fn collection(value: UclValue) -> Self {
        Self {
            collected: true,
            ..Self::new(value, 0)
        }
    }

    /// A slot with this slot's priority and marks that holds `value`.
    pub(crate) fn with_value(&self, value: UclValue) -> Self {
        Self { value, ..*self }
    }

    /// The slot marked as copied by `.inherit` (spec §9.7). Its value, priority and
    /// `NO_IMPLICIT_ARRAYS` collection mark are kept.
    pub(crate) fn into_inherited(self) -> Self {
        Self {
            inherited: true,
            ..self
        }
    }

    pub fn value(&self) -> &UclValue {
        &self.value
    }

    pub fn value_mut(&mut self) -> &mut UclValue {
        &mut self.value
    }

    pub fn into_value(self) -> UclValue {
        self.value
    }

    /// Priority 0–15.
    pub fn priority(&self) -> u8 {
        self.priority
    }

    /// True if the value was copied by `.inherit`.
    pub fn is_inherited(&self) -> bool {
        self.inherited
    }

    /// True for the explicit array that collects a key's repeats under `NO_IMPLICIT_ARRAYS`.
    pub(crate) fn is_collected(&self) -> bool {
        self.collected
    }
}

/// The values of one key: always at least one. More than one is an implicit array.
#[derive(Debug, Clone)]
pub struct Entry {
    slots: SmallVec<[Slot; 1]>,
}

impl Entry {
    /// An entry with one value at priority 0.
    pub fn new(value: UclValue) -> Self {
        Self::from_slot(Slot::new(value, 0))
    }

    /// An entry with one slot.
    pub fn from_slot(slot: Slot) -> Self {
        let mut slots = SmallVec::new();
        slots.push(slot);
        Self { slots }
    }

    /// Number of values (1 unless this is an implicit array).
    pub fn len(&self) -> usize {
        self.slots.len()
    }

    /// Always false: an entry holds at least one value.
    pub fn is_empty(&self) -> bool {
        false
    }

    /// True if the key was repeated (libucl's implicit array).
    pub fn is_multi(&self) -> bool {
        self.slots.len() > 1
    }

    /// The first value, which is what libucl's `ucl_object_lookup` returns.
    pub fn first(&self) -> &UclValue {
        &self.slots[0].value
    }

    /// The first value, mutably.
    pub fn first_mut(&mut self) -> &mut UclValue {
        &mut self.slots[0].value
    }

    /// The last value.
    pub fn last(&self) -> &UclValue {
        &self.slots[self.slots.len() - 1].value
    }

    /// All values in insertion order.
    pub fn values(&self) -> Values<'_> {
        Values(self.slots.iter())
    }

    /// All values with their priority and flags.
    pub fn slots(&self) -> &[Slot] {
        &self.slots
    }

    /// Value `index` of the entry, mutably.
    pub fn value_at_mut(&mut self, index: usize) -> Option<&mut UclValue> {
        self.slots.get_mut(index).map(|s| &mut s.value)
    }

    /// Adds a value to the entry at priority 0, making it an implicit array.
    pub fn push(&mut self, value: UclValue) {
        self.slots.push(Slot::new(value, 0));
    }

    /// Adds a slot to the entry.
    pub fn push_slot(&mut self, slot: Slot) {
        self.slots.push(slot);
    }

    /// The single value, or an explicit array of all values for an implicit array.
    ///
    /// This is the view serde and JSON-like consumers get: a repeated key reads as a sequence.
    pub fn into_value(self) -> UclValue {
        if self.slots.len() == 1 {
            self.slots.into_iter().next().unwrap().value
        } else {
            UclValue::Array(self.slots.into_iter().map(|s| s.value).collect())
        }
    }

    /// All values in insertion order.
    pub fn into_values(self) -> impl Iterator<Item = UclValue> {
        self.slots.into_iter().map(|s| s.value)
    }

    fn head(&self) -> &Slot {
        &self.slots[0]
    }

    /// Resolves a repeated key by priority (spec §8.3), comparing with the first value: a higher
    /// priority replaces the entry, a lower one is dropped, and an equal one is added (§8.2), or
    /// collected into an explicit array under `NO_IMPLICIT_ARRAYS` (§8.5). With
    /// `replace_inherited`, an inherited first value is replaced whatever the priorities.
    fn add_by_priority(
        &mut self,
        key: &str,
        slot: Slot,
        replace_inherited: bool,
        flags: ParserFlags,
    ) -> Result<Placement, DuplicateKeyError> {
        let head = self.head();
        if (replace_inherited && head.inherited) || slot.priority > head.priority {
            *self = Entry::from_slot(slot);
            Ok(Placement::Slot(0))
        } else if slot.priority == head.priority {
            if flags.contains(ParserFlags::NO_IMPLICIT_ARRAYS) {
                return self.collect(key, slot);
            }
            self.slots.push(slot);
            Ok(Placement::Slot(self.slots.len() - 1))
        } else {
            Ok(Placement::Dropped)
        }
    }

    /// Adds a repeated value under `NO_IMPLICIT_ARRAYS` (spec §8.5). The first repeat replaces the
    /// entry with an explicit array of the old and new values; later repeats are appended to it.
    /// Only the entry's first value goes into the array: other values, which only `.inherit`
    /// with `replace=true` can add under this flag, are dropped (QUESTIONS.md #25).
    ///
    /// Two details follow the oracle rather than the spec text (QUESTIONS.md #3, #4):
    /// - The collection array has priority 0, whatever its elements' priorities, so a later value
    ///   with a priority above 0 replaces it.
    /// - If `merge` has replaced the collection array with a scalar, a later repeat is an error.
    fn collect(&mut self, key: &str, slot: Slot) -> Result<Placement, DuplicateKeyError> {
        if self.head().collected {
            return match &mut self.slots[0].value {
                UclValue::Array(items) => {
                    items.push(slot.value);
                    Ok(Placement::Collected(items.len() - 1))
                }
                _ => Err(DuplicateKeyError {
                    key: key.to_owned(),
                }),
            };
        }
        let head = std::mem::take(&mut self.slots)
            .into_iter()
            .next()
            .expect("an entry holds at least one value");
        let items: UclArray = vec![head.value, slot.value];
        *self = Entry::from_slot(Slot::collection(UclValue::Array(items)));
        Ok(Placement::Collected(1))
    }

    /// Resolves a repeated key under [`DuplicateStrategy::Merge`] (spec §8.4), by the type of the
    /// first value. Only the first value takes part; any other values of the entry are kept
    /// (QUESTIONS.md #1).
    ///
    /// - Object and object: the new object's values are inserted into the first value one by one,
    ///   with `Merge`. The first value keeps its priority.
    /// - Array and array: the new elements are appended. The array keeps its priority.
    /// - Object and array, or array and object: error.
    /// - Object or array, and a scalar (**quirk**): the scalar takes the container's place and
    ///   keeps the container's priority and inherited mark.
    /// - Scalar first: resolved by priority as under `Append`. An inherited first value is not
    ///   replaced unconditionally here (QUESTIONS.md #2).
    fn merge(
        &mut self,
        key: &str,
        slot: Slot,
        flags: ParserFlags,
    ) -> Result<Placement, DuplicateKeyError> {
        let head = &mut self.slots[0];
        if !is_container(&head.value) {
            return self.add_by_priority(key, slot, false, flags);
        }
        if !is_container(&slot.value) {
            head.value = slot.value;
            return Ok(Placement::Slot(0));
        }
        match (&mut head.value, slot.value) {
            (UclValue::Object(target), UclValue::Object(source)) => {
                for (name, entry) in source {
                    for inner in entry.slots {
                        target.insert_slot_with_strategy(
                            name.as_str(),
                            inner,
                            DuplicateStrategy::Merge,
                            flags,
                        )?;
                    }
                }
                Ok(Placement::Merged)
            }
            (UclValue::Array(target), UclValue::Array(source)) => {
                target.extend(source);
                Ok(Placement::Merged)
            }
            _ => Err(DuplicateKeyError {
                key: key.to_owned(),
            }),
        }
    }
}

fn is_container(value: &UclValue) -> bool {
    matches!(value, UclValue::Object(_) | UclValue::Array(_))
}

/// Iterator over the values of an [`Entry`].
#[derive(Debug, Clone)]
pub struct Values<'a>(std::slice::Iter<'a, Slot>);

impl<'a> Iterator for Values<'a> {
    type Item = &'a UclValue;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|s| &s.value)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl DoubleEndedIterator for Values<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(|s| &s.value)
    }
}

impl ExactSizeIterator for Values<'_> {}

/// A UCL object: keys in insertion order, each with one or more values.
///
/// Equality ignores key order, like `IndexMap`; the order of values inside an entry matters.
/// Comparing does not recurse ([`UclValue`]).
#[derive(Debug, Clone, Default)]
pub struct UclObject {
    entries: IndexMap<String, Entry>,
}

impl UclObject {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            entries: IndexMap::with_capacity(capacity),
        }
    }

    /// Number of keys.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub fn contains_key(&self, key: &str) -> bool {
        self.entries.contains_key(key)
    }

    /// The first value of `key`, as libucl's `ucl_object_lookup` returns it.
    pub fn get(&self, key: &str) -> Option<&UclValue> {
        self.entries.get(key).map(Entry::first)
    }

    /// The first value of `key`, mutably.
    pub fn get_mut(&mut self, key: &str) -> Option<&mut UclValue> {
        self.entries.get_mut(key).map(Entry::first_mut)
    }

    /// Every value of `key` in insertion order; empty if the key is absent.
    pub fn get_all(&self, key: &str) -> Values<'_> {
        match self.entries.get(key) {
            Some(entry) => entry.values(),
            None => Values([].iter()),
        }
    }

    pub fn entry(&self, key: &str) -> Option<&Entry> {
        self.entries.get(key)
    }

    pub fn entry_mut(&mut self, key: &str) -> Option<&mut Entry> {
        self.entries.get_mut(key)
    }

    /// The key and entry at position `index` in insertion order.
    pub fn get_index(&self, index: usize) -> Option<(&String, &Entry)> {
        self.entries.get_index(index)
    }

    /// The key and entry at position `index` in insertion order, the entry mutable.
    pub fn get_index_mut(&mut self, index: usize) -> Option<(&String, &mut Entry)> {
        self.entries.get_index_mut(index)
    }

    /// The position of `key` in insertion order.
    pub fn index_of(&self, key: &str) -> Option<usize> {
        self.entries.get_index_of(key)
    }

    /// Changes the spelling of key `old` to `new`, keeping its position and entry. Returns false
    /// if `old` is absent or `new` is another key already present.
    pub fn rename_key(&mut self, old: &str, new: impl Into<String>) -> bool {
        match self.entries.get_index_of(old) {
            Some(index) => self.entries.replace_index(index, new.into()).is_ok(),
            None => false,
        }
    }

    /// Sets `key` to a single value, replacing every existing value. An existing key keeps its
    /// position.
    pub fn insert(&mut self, key: impl Into<String>, value: UclValue) -> Option<Entry> {
        self.entries.insert(key.into(), Entry::new(value))
    }

    /// Sets `key` to `entry`, replacing an existing entry in place.
    pub fn insert_entry(&mut self, key: impl Into<String>, entry: Entry) -> Option<Entry> {
        self.entries.insert(key.into(), entry)
    }

    /// Adds a value to `key`: a new key, or one more value of an existing key (implicit array).
    pub fn append(&mut self, key: impl Into<String>, value: UclValue) {
        let key = key.into();
        match self.entries.get_mut(&key) {
            Some(entry) => entry.push(value),
            None => {
                self.entries.insert(key, Entry::new(value));
            }
        }
    }

    /// Removes `key`, keeping the order of the others.
    pub fn remove(&mut self, key: &str) -> Option<Entry> {
        self.entries.shift_remove(key)
    }

    /// Removes and returns the entry at `index`, keeping the order of the others.
    pub fn remove_index(&mut self, index: usize) -> Option<(String, Entry)> {
        self.entries.shift_remove_index(index)
    }

    /// Keys and entries in insertion order.
    pub fn iter(&self) -> indexmap::map::Iter<'_, String, Entry> {
        self.entries.iter()
    }

    /// Keys and entries in insertion order, entries mutable.
    pub fn iter_mut(&mut self) -> indexmap::map::IterMut<'_, String, Entry> {
        self.entries.iter_mut()
    }

    pub fn keys(&self) -> indexmap::map::Keys<'_, String, Entry> {
        self.entries.keys()
    }

    /// Entries in insertion order.
    pub fn entries(&self) -> indexmap::map::Values<'_, String, Entry> {
        self.entries.values()
    }

    /// Inserts `value` under `key`, resolving an existing key by `strategy` and `priority`,
    /// and applying `flags`. Behaviour is specified in `docs/spec/08-duplicates.md`; see
    /// [`UclObject::insert_slot_with_strategy`].
    pub fn insert_with_strategy(
        &mut self,
        key: impl Into<String>,
        value: UclValue,
        priority: u8,
        strategy: DuplicateStrategy,
        flags: ParserFlags,
    ) -> Result<(), DuplicateKeyError> {
        self.insert_slot_with_strategy(key, Slot::new(value, priority), strategy, flags)
    }

    /// [`UclObject::insert_with_strategy`] for a prepared slot.
    ///
    /// Under [`ParserFlags::KEY_LOWERCASE`] the key is lowercased first, ASCII letters only
    /// (spec §8.6, §12.1). A new key is added at the end. A key already present keeps its
    /// position, and `strategy` decides the outcome (spec §8.2–§8.5):
    ///
    /// - [`DuplicateStrategy::Append`]: an inherited first value is replaced. Otherwise the new
    ///   priority is compared with the first value's: higher replaces the entry, lower is
    ///   dropped, equal adds the value (or collects it under [`ParserFlags::NO_IMPLICIT_ARRAYS`]).
    /// - [`DuplicateStrategy::Rewrite`]: the entry is replaced by the new value.
    /// - [`DuplicateStrategy::Error`]: [`DuplicateKeyError`], with the object unchanged.
    /// - [`DuplicateStrategy::Merge`]: containers are merged, and a scalar first value is
    ///   resolved as under `Append` (see the rules on `Entry::merge` in the source).
    ///
    /// Under `Merge`, an object is merged into entry by entry, so when a nested insert fails the
    /// entries before it have already been merged.
    pub fn insert_slot_with_strategy(
        &mut self,
        key: impl Into<String>,
        slot: Slot,
        strategy: DuplicateStrategy,
        flags: ParserFlags,
    ) -> Result<(), DuplicateKeyError> {
        self.insert_slot_placed(key, slot, strategy, flags)
            .map(|_| ())
    }

    /// [`UclObject::insert_slot_with_strategy`], reporting where the value went.
    ///
    /// The key the value is stored under is `key`, lowercased under
    /// [`ParserFlags::KEY_LOWERCASE`].
    pub fn insert_slot_placed(
        &mut self,
        key: impl Into<String>,
        slot: Slot,
        strategy: DuplicateStrategy,
        flags: ParserFlags,
    ) -> Result<Placement, DuplicateKeyError> {
        let mut key = key.into();
        if flags.contains(ParserFlags::KEY_LOWERCASE) {
            key.make_ascii_lowercase();
        }
        let Some(entry) = self.entries.get_mut(&key) else {
            self.entries.insert(key, Entry::from_slot(slot));
            return Ok(Placement::Slot(0));
        };
        match strategy {
            DuplicateStrategy::Append => entry.add_by_priority(&key, slot, true, flags),
            DuplicateStrategy::Merge => entry.merge(&key, slot, flags),
            DuplicateStrategy::Rewrite => {
                *entry = Entry::from_slot(slot);
                Ok(Placement::Slot(0))
            }
            DuplicateStrategy::Error => Err(DuplicateKeyError { key }),
        }
    }
}

impl std::ops::Index<&str> for UclObject {
    type Output = UclValue;

    /// The first value of `key`. Panics if the key is absent.
    fn index(&self, key: &str) -> &UclValue {
        self.get(key)
            .unwrap_or_else(|| panic!("key '{key}' not found in UCL object"))
    }
}

impl IntoIterator for UclObject {
    type Item = (String, Entry);
    type IntoIter = indexmap::map::IntoIter<String, Entry>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.into_iter()
    }
}

impl<'a> IntoIterator for &'a UclObject {
    type Item = (&'a String, &'a Entry);
    type IntoIter = indexmap::map::Iter<'a, String, Entry>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.iter()
    }
}

impl<K: Into<String>> FromIterator<(K, UclValue)> for UclObject {
    /// Collects pairs with [`UclObject::append`]: a repeated key becomes an implicit array.
    fn from_iter<I: IntoIterator<Item = (K, UclValue)>>(iter: I) -> Self {
        let mut object = UclObject::new();
        for (k, v) in iter {
            object.append(k, v);
        }
        object
    }
}

impl<K: Into<String>> Extend<(K, UclValue)> for UclObject {
    fn extend<I: IntoIterator<Item = (K, UclValue)>>(&mut self, iter: I) {
        for (k, v) in iter {
            self.append(k, v);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn int(i: i64) -> UclValue {
        UclValue::Integer(i)
    }

    fn values(obj: &UclObject, key: &str) -> Vec<UclValue> {
        obj.get_all(key).cloned().collect()
    }

    #[test]
    fn clone_keeps_order_priorities_and_marks() {
        let mut inner = UclObject::new();
        inner.insert_entry("z", Entry::from_slot(Slot::inherited(int(1), 3)));
        inner.append("y", UclValue::Time(1.5));
        inner.append("y", UclValue::Array(vec![int(2), UclValue::Null]));
        let mut obj = UclObject::new();
        obj.insert("b", UclValue::Object(inner));
        obj.insert_entry(
            "a",
            Entry::from_slot(Slot::collection(UclValue::Array(vec![
                UclValue::String("s".into()),
                UclValue::Array(vec![]),
                UclValue::Object(UclObject::new()),
            ]))),
        );
        obj.append("a", UclValue::Float(-0.0));
        let value = UclValue::Object(obj);
        let copy = value.clone();
        // Derived `PartialEq` compares every slot's priority and marks too.
        assert_eq!(copy, value);
        let (copy, value) = (copy.as_object().unwrap(), value.as_object().unwrap());
        assert_eq!(copy.keys().collect::<Vec<_>>(), ["b", "a"]);
        let inner = copy["b"].as_object().unwrap();
        assert_eq!(inner.keys().collect::<Vec<_>>(), ["z", "y"]);
        let z = &inner.entry("z").unwrap().slots()[0];
        assert_eq!((z.priority(), z.is_inherited()), (3, true));
        assert!(copy.entry("a").unwrap().slots()[0].is_collected());
        assert!(value.entry("a").unwrap().slots()[0].is_collected());
    }

    #[test]
    fn clone_does_not_recurse() {
        // Objects and arrays alternating, nested 20,000 deep: a derived clone overflows a
        // 2 MiB stack at about 550 levels in a debug build.
        std::thread::Builder::new()
            .stack_size(2 << 20)
            .spawn(|| {
                let mut value = int(1);
                for depth in 0..20_000 {
                    value = if depth % 2 == 0 {
                        UclValue::Array(vec![value])
                    } else {
                        UclValue::Object([("k", value)].into_iter().collect())
                    };
                }
                let copy = value.clone();
                assert_eq!(nesting(&copy), 20_000);
                // Comparing does not recurse either.
                assert!(copy == value);
                // Dropping recurses; it is not under test.
                std::mem::forget((value, copy));
            })
            .unwrap()
            .join()
            .unwrap();
    }

    #[test]
    fn equality_is_that_of_the_derived_comparisons() {
        let obj = |entries: Vec<(&str, Vec<Slot>)>| {
            let mut o = UclObject::new();
            for (key, slots) in entries {
                let mut slots = slots.into_iter();
                let mut entry = Entry::from_slot(slots.next().unwrap());
                slots.for_each(|slot| entry.push_slot(slot));
                o.insert_entry(key.to_string(), entry);
            }
            UclValue::Object(o)
        };
        let s = |v: UclValue| Slot::new(v, 0);
        let a = obj(vec![
            ("x", vec![s(int(1))]),
            ("y", vec![s(int(2)), s(int(3))]),
        ]);
        // Keys in any order; values of an entry in order.
        let b = obj(vec![
            ("y", vec![s(int(2)), s(int(3))]),
            ("x", vec![s(int(1))]),
        ]);
        assert!(a == b);
        let c = obj(vec![
            ("x", vec![s(int(1))]),
            ("y", vec![s(int(3)), s(int(2))]),
        ]);
        assert!(a != c);
        // Priority and marks count.
        let d = obj(vec![
            ("x", vec![Slot::new(int(1), 2)]),
            ("y", vec![s(int(2)), s(int(3))]),
        ]);
        assert!(a != d);
        let e = obj(vec![
            ("x", vec![Slot::inherited(int(1), 0)]),
            ("y", vec![s(int(2)), s(int(3))]),
        ]);
        assert!(a != e);
        let f = obj(vec![
            ("x", vec![Slot::collection(int(1))]),
            ("y", vec![s(int(2)), s(int(3))]),
        ]);
        assert!(a != f);
        // A missing key, an extra one, a different kind.
        assert!(a != obj(vec![("x", vec![s(int(1))])]));
        assert!(obj(vec![("x", vec![s(int(1))])]) != a);
        assert!(int(1) != UclValue::Float(1.0));
        assert!(UclValue::Float(1.0) != UclValue::Time(1.0));
        assert!(UclValue::Time(1.5) == UclValue::Time(1.5));
        // A NaN equals nothing, itself included.
        assert!(UclValue::Float(f64::NAN) != UclValue::Float(f64::NAN));
        assert!(
            UclValue::Array(vec![UclValue::Float(f64::NAN)])
                != UclValue::Array(vec![UclValue::Float(f64::NAN)])
        );
        // Arrays by length and element.
        let arr = |items: Vec<UclValue>| UclValue::Array(items);
        assert!(arr(vec![int(1), arr(vec![])]) == arr(vec![int(1), arr(vec![])]));
        assert!(arr(vec![int(1)]) != arr(vec![int(1), int(1)]));
        assert!(arr(vec![arr(vec![int(1)])]) != arr(vec![arr(vec![int(2)])]));
        // The object, entry and slot comparisons agree with the value's.
        let (UclValue::Object(x), UclValue::Object(y)) = (&a, &b) else {
            unreachable!()
        };
        assert!(x == y);
        assert!(x.entry("y") == y.entry("y"));
        assert!(x.entry("x") != y.entry("y"));
        assert!(x.entry("y").unwrap().slots()[0] == y.entry("y").unwrap().slots()[0]);
        assert!(x.entry("y").unwrap().slots()[0] != y.entry("y").unwrap().slots()[1]);
    }

    fn insert(obj: &mut UclObject, key: &str, v: UclValue, pri: u8, s: DuplicateStrategy) {
        obj.insert_with_strategy(key, v, pri, s, ParserFlags::DEFAULT)
            .unwrap();
    }

    #[test]
    fn test_append_equal_priority_makes_implicit_array() {
        let mut obj = UclObject::new();
        insert(&mut obj, "k", int(1), 0, DuplicateStrategy::Append);
        insert(&mut obj, "k", int(2), 0, DuplicateStrategy::Append);
        assert_eq!(values(&obj, "k"), vec![int(1), int(2)]);
        assert!(obj.entry("k").unwrap().is_multi());
        assert_eq!(obj.get("k"), Some(&int(1)));
    }

    #[test]
    fn test_explicit_array_is_not_flattened() {
        // libucl: `k = [1,2]; k = 3` is two values, the first an explicit array.
        let mut obj = UclObject::new();
        insert(
            &mut obj,
            "k",
            UclValue::Array(vec![int(1), int(2)]),
            0,
            DuplicateStrategy::Append,
        );
        insert(&mut obj, "k", int(3), 0, DuplicateStrategy::Append);
        assert_eq!(
            values(&obj, "k"),
            vec![UclValue::Array(vec![int(1), int(2)]), int(3)]
        );
    }

    #[test]
    fn test_append_keeps_key_position() {
        let mut obj = UclObject::new();
        insert(&mut obj, "a", int(1), 0, DuplicateStrategy::Append);
        insert(&mut obj, "b", int(2), 0, DuplicateStrategy::Append);
        insert(&mut obj, "a", int(3), 0, DuplicateStrategy::Append);
        assert_eq!(obj.keys().collect::<Vec<_>>(), vec!["a", "b"]);
    }

    #[test]
    fn test_append_priorities() {
        let mut obj = UclObject::new();
        insert(&mut obj, "k", int(1), 2, DuplicateStrategy::Append);
        // lower priority: dropped
        insert(&mut obj, "k", int(2), 1, DuplicateStrategy::Append);
        assert_eq!(values(&obj, "k"), vec![int(1)]);
        // higher priority: replaces the whole entry
        insert(&mut obj, "k", int(3), 0, DuplicateStrategy::Append);
        insert(&mut obj, "k", int(4), 5, DuplicateStrategy::Append);
        assert_eq!(values(&obj, "k"), vec![int(4)]);
        assert_eq!(obj.entry("k").unwrap().slots()[0].priority(), 5);
    }

    #[test]
    fn test_priority_is_masked_to_four_bits() {
        assert_eq!(Slot::new(UclValue::Null, 0x1f).priority(), 0x0f);
    }

    #[test]
    fn test_inherited_value_is_always_replaced() {
        let mut obj = UclObject::new();
        obj.insert_slot_with_strategy(
            "k",
            Slot::inherited(int(1), 3),
            DuplicateStrategy::Append,
            ParserFlags::DEFAULT,
        )
        .unwrap();
        insert(&mut obj, "k", int(2), 0, DuplicateStrategy::Append);
        assert_eq!(values(&obj, "k"), vec![int(2)]);
    }

    #[test]
    fn test_rewrite_and_error() {
        let mut obj = UclObject::new();
        insert(&mut obj, "k", int(1), 5, DuplicateStrategy::Rewrite);
        insert(&mut obj, "k", int(2), 0, DuplicateStrategy::Rewrite);
        assert_eq!(values(&obj, "k"), vec![int(2)]);

        let err = obj
            .insert_with_strategy(
                "k",
                int(3),
                0,
                DuplicateStrategy::Error,
                ParserFlags::DEFAULT,
            )
            .unwrap_err();
        assert_eq!(
            err,
            DuplicateKeyError {
                key: "k".to_string()
            }
        );
        assert_eq!(values(&obj, "k"), vec![int(2)]);
    }

    #[test]
    fn test_merge_objects_and_arrays() {
        let mut first = UclObject::new();
        first.insert("a", int(1));
        let mut second = UclObject::new();
        second.insert("b", int(2));
        second.insert("a", int(3));

        let mut obj = UclObject::new();
        insert(
            &mut obj,
            "o",
            UclValue::Object(first),
            0,
            DuplicateStrategy::Merge,
        );
        insert(
            &mut obj,
            "o",
            UclValue::Object(second),
            0,
            DuplicateStrategy::Merge,
        );
        let merged = obj.get("o").unwrap().as_object().unwrap();
        assert_eq!(values(merged, "a"), vec![int(1), int(3)]);
        assert_eq!(values(merged, "b"), vec![int(2)]);
        assert_eq!(obj.entry("o").unwrap().len(), 1);

        insert(
            &mut obj,
            "arr",
            UclValue::Array(vec![int(1)]),
            0,
            DuplicateStrategy::Merge,
        );
        insert(
            &mut obj,
            "arr",
            UclValue::Array(vec![int(2)]),
            0,
            DuplicateStrategy::Merge,
        );
        assert_eq!(obj.get("arr"), Some(&UclValue::Array(vec![int(1), int(2)])));
    }

    #[test]
    fn test_no_implicit_arrays_collects_into_one_explicit_array() {
        let flags = ParserFlags::NO_IMPLICIT_ARRAYS;
        let mut obj = UclObject::new();
        for i in 1..=3 {
            obj.insert_with_strategy("k", int(i), 0, DuplicateStrategy::Append, flags)
                .unwrap();
        }
        assert_eq!(
            values(&obj, "k"),
            vec![UclValue::Array(vec![int(1), int(2), int(3)])]
        );

        // A user-written array is not the collection array: it becomes its first element.
        let mut obj = UclObject::new();
        let written = UclValue::Array(vec![int(1), int(2)]);
        obj.insert_with_strategy("k", written.clone(), 0, DuplicateStrategy::Append, flags)
            .unwrap();
        obj.insert_with_strategy("k", int(3), 0, DuplicateStrategy::Append, flags)
            .unwrap();
        assert_eq!(
            values(&obj, "k"),
            vec![UclValue::Array(vec![written, int(3)])]
        );
    }

    #[test]
    fn test_key_lowercase_flag() {
        let mut obj = UclObject::new();
        obj.insert_with_strategy(
            "ALIAS",
            int(1),
            0,
            DuplicateStrategy::Append,
            ParserFlags::KEY_LOWERCASE,
        )
        .unwrap();
        assert!(obj.contains_key("alias"));
        assert!(!obj.contains_key("ALIAS"));
    }

    fn object(pairs: &[(&str, UclValue)]) -> UclValue {
        UclValue::Object(pairs.iter().cloned().collect())
    }

    fn priorities(obj: &UclObject, key: &str) -> Vec<u8> {
        obj.entry(key)
            .unwrap()
            .slots()
            .iter()
            .map(Slot::priority)
            .collect()
    }

    fn insert_slot(obj: &mut UclObject, key: &str, slot: Slot, s: DuplicateStrategy) {
        obj.insert_slot_with_strategy(key, slot, s, ParserFlags::DEFAULT)
            .unwrap();
    }

    #[test]
    fn test_rewrite_takes_the_new_priority() {
        let mut obj = UclObject::new();
        insert(&mut obj, "k", int(1), 3, DuplicateStrategy::Rewrite);
        insert(&mut obj, "k", int(2), 1, DuplicateStrategy::Rewrite);
        assert_eq!(values(&obj, "k"), vec![int(2)]);
        assert_eq!(priorities(&obj, "k"), vec![1]);
    }

    #[test]
    fn test_error_strategy_rejects_repeat_of_inherited_value() {
        let mut obj = UclObject::new();
        insert_slot(
            &mut obj,
            "k",
            Slot::inherited(int(1), 0),
            DuplicateStrategy::Error,
        );
        let err = obj
            .insert_with_strategy(
                "k",
                int(2),
                0,
                DuplicateStrategy::Error,
                ParserFlags::DEFAULT,
            )
            .unwrap_err();
        assert_eq!(err.key, "k");
        assert_eq!(values(&obj, "k"), vec![int(1)]);
    }

    #[test]
    fn test_merge_container_then_scalar_keeps_container_priority() {
        // spec §8.4, strategy_merge_scalar_keeps_container_priority
        let mut obj = UclObject::new();
        insert(
            &mut obj,
            "a",
            object(&[("x", int(1))]),
            3,
            DuplicateStrategy::Merge,
        );
        insert(&mut obj, "a", int(2), 1, DuplicateStrategy::Merge);
        assert_eq!(values(&obj, "a"), vec![int(2)]);
        assert_eq!(priorities(&obj, "a"), vec![3]);

        insert(
            &mut obj,
            "b",
            UclValue::Array(vec![int(1)]),
            1,
            DuplicateStrategy::Merge,
        );
        insert(&mut obj, "b", int(2), 3, DuplicateStrategy::Merge);
        assert_eq!(values(&obj, "b"), vec![int(2)]);
        assert_eq!(priorities(&obj, "b"), vec![1]);
    }

    #[test]
    fn test_merge_container_type_mismatch_is_an_error() {
        let arr = UclValue::Array(vec![int(1)]);
        let obj_value = object(&[("x", int(1))]);
        for (first, second) in [(arr.clone(), obj_value.clone()), (obj_value, arr)] {
            let mut obj = UclObject::new();
            insert(&mut obj, "a", first, 0, DuplicateStrategy::Merge);
            let err = obj
                .insert_with_strategy(
                    "a",
                    second,
                    0,
                    DuplicateStrategy::Merge,
                    ParserFlags::DEFAULT,
                )
                .unwrap_err();
            assert_eq!(err.key, "a");
        }
    }

    #[test]
    fn test_merge_arrays_keep_the_existing_priority() {
        // spec §8.4, strategy_merge_arrays_ignore_priority
        let mut obj = UclObject::new();
        insert(
            &mut obj,
            "a",
            UclValue::Array(vec![int(1)]),
            3,
            DuplicateStrategy::Merge,
        );
        insert(
            &mut obj,
            "a",
            UclValue::Array(vec![int(2)]),
            1,
            DuplicateStrategy::Merge,
        );
        assert_eq!(
            values(&obj, "a"),
            vec![UclValue::Array(vec![int(1), int(2)])]
        );
        assert_eq!(priorities(&obj, "a"), vec![3]);
    }

    #[test]
    fn test_merge_nested_values_resolve_by_their_own_priority() {
        // spec §8.4, include_merge_lower_priority_still_merges; a nested scalar with a higher
        // priority replaces (oracle probe, QUESTIONS.md #1).
        let mut inner = UclObject::new();
        insert(&mut inner, "a", int(1), 3, DuplicateStrategy::Append);
        let mut obj = UclObject::new();
        insert(
            &mut obj,
            "x",
            UclValue::Object(inner),
            3,
            DuplicateStrategy::Append,
        );

        let mut lower = UclObject::new();
        insert(&mut lower, "b", int(2), 1, DuplicateStrategy::Append);
        insert(
            &mut obj,
            "x",
            UclValue::Object(lower),
            1,
            DuplicateStrategy::Merge,
        );
        let mut higher = UclObject::new();
        insert(&mut higher, "a", int(9), 5, DuplicateStrategy::Append);
        insert(
            &mut obj,
            "x",
            UclValue::Object(higher),
            5,
            DuplicateStrategy::Merge,
        );

        assert_eq!(priorities(&obj, "x"), vec![3]);
        let merged = obj.get("x").unwrap().as_object().unwrap();
        assert_eq!(merged.keys().collect::<Vec<_>>(), vec!["a", "b"]);
        assert_eq!(values(merged, "a"), vec![int(9)]);
        assert_eq!(priorities(merged, "a"), vec![5]);
        assert_eq!(priorities(merged, "b"), vec![1]);
    }

    #[test]
    fn test_merge_uses_only_the_first_value() {
        // Oracle probe, QUESTIONS.md #1: other values of the entry are kept.
        let mut obj = UclObject::new();
        insert(
            &mut obj,
            "a",
            object(&[("x", int(1))]),
            0,
            DuplicateStrategy::Append,
        );
        insert(
            &mut obj,
            "a",
            object(&[("y", int(2))]),
            0,
            DuplicateStrategy::Append,
        );
        insert(
            &mut obj,
            "a",
            object(&[("z", int(3))]),
            0,
            DuplicateStrategy::Merge,
        );
        assert_eq!(
            values(&obj, "a"),
            vec![
                object(&[("x", int(1)), ("z", int(3))]),
                object(&[("y", int(2))])
            ]
        );
        insert(&mut obj, "a", int(5), 0, DuplicateStrategy::Merge);
        assert_eq!(values(&obj, "a"), vec![int(5), object(&[("y", int(2))])]);
    }

    #[test]
    fn test_merge_scalar_first_follows_append_priorities() {
        // spec §8.4, strategy_merge_scalars_append, strategy_merge_scalar_then_object
        let mut obj = UclObject::new();
        insert(&mut obj, "a", int(1), 2, DuplicateStrategy::Merge);
        insert(
            &mut obj,
            "a",
            object(&[("y", int(2))]),
            2,
            DuplicateStrategy::Merge,
        );
        insert(&mut obj, "a", int(3), 1, DuplicateStrategy::Merge);
        assert_eq!(values(&obj, "a"), vec![int(1), object(&[("y", int(2))])]);
        insert(&mut obj, "a", int(4), 5, DuplicateStrategy::Merge);
        assert_eq!(values(&obj, "a"), vec![int(4)]);
    }

    #[test]
    fn test_merge_does_not_replace_inherited_values() {
        // Oracle probes, QUESTIONS.md #2: an inherited scalar gets another value, an inherited
        // object is merged into and stays inherited.
        let mut obj = UclObject::new();
        insert_slot(
            &mut obj,
            "s",
            Slot::inherited(int(1), 0),
            DuplicateStrategy::Append,
        );
        insert(&mut obj, "s", int(2), 0, DuplicateStrategy::Merge);
        assert_eq!(values(&obj, "s"), vec![int(1), int(2)]);

        let inherited = Slot::inherited(object(&[("x", int(1))]), 0);
        insert_slot(&mut obj, "o", inherited, DuplicateStrategy::Append);
        insert(
            &mut obj,
            "o",
            object(&[("y", int(2))]),
            0,
            DuplicateStrategy::Merge,
        );
        assert_eq!(
            values(&obj, "o"),
            vec![object(&[("x", int(1)), ("y", int(2))])]
        );
        insert(
            &mut obj,
            "o",
            object(&[("z", int(3))]),
            0,
            DuplicateStrategy::Append,
        );
        assert_eq!(values(&obj, "o"), vec![object(&[("z", int(3))])]);
    }

    #[test]
    fn test_no_implicit_arrays_priorities() {
        // Oracle probes, QUESTIONS.md #3: priorities are compared first; the collection array
        // has priority 0, so a later value with a higher priority replaces it.
        let flags = ParserFlags::NO_IMPLICIT_ARRAYS;
        let mut obj = UclObject::new();
        for (v, pri) in [(1, 0), (2, 3), (3, 1), (4, 3)] {
            obj.insert_with_strategy("a", int(v), pri, DuplicateStrategy::Append, flags)
                .unwrap();
        }
        assert_eq!(
            values(&obj, "a"),
            vec![UclValue::Array(vec![int(2), int(4)])]
        );
        assert_eq!(priorities(&obj, "a"), vec![0]);
        obj.insert_with_strategy("a", int(5), 3, DuplicateStrategy::Append, flags)
            .unwrap();
        assert_eq!(values(&obj, "a"), vec![int(5)]);
        assert_eq!(priorities(&obj, "a"), vec![3]);

        // An inherited value is replaced, not collected.
        let mut obj = UclObject::new();
        obj.insert_slot_with_strategy(
            "a",
            Slot::inherited(int(1), 0),
            DuplicateStrategy::Append,
            flags,
        )
        .unwrap();
        obj.insert_with_strategy("a", int(2), 0, DuplicateStrategy::Append, flags)
            .unwrap();
        assert_eq!(values(&obj, "a"), vec![int(2)]);
    }

    #[test]
    fn test_no_implicit_arrays_under_merge() {
        // Oracle probes, QUESTIONS.md #4: the collection array is an ordinary array for `merge`.
        let flags = ParserFlags::NO_IMPLICIT_ARRAYS;
        let merge = DuplicateStrategy::Merge;
        let mut obj = UclObject::new();
        for v in [int(1), int(2), UclValue::Array(vec![int(3)])] {
            obj.insert_with_strategy("b", v, 0, merge, flags).unwrap();
        }
        assert_eq!(
            values(&obj, "b"),
            vec![UclValue::Array(vec![int(1), int(2), int(3)])]
        );
        obj.insert_with_strategy("b", int(5), 0, merge, flags)
            .unwrap();
        assert_eq!(values(&obj, "b"), vec![int(5)]);
        // The scalar took the collection array's place; a later repeat is an error.
        assert!(
            obj.insert_with_strategy("b", int(6), 0, DuplicateStrategy::Append, flags)
                .is_err()
        );
    }

    #[test]
    fn test_key_lowercase_merges_keys_that_differ_in_case() {
        // spec §8.6, §12.1: ASCII letters only.
        let flags = ParserFlags::KEY_LOWERCASE;
        let mut obj = UclObject::new();
        for key in ["A", "a", "É"] {
            obj.insert_with_strategy(key, int(1), 0, DuplicateStrategy::Append, flags)
                .unwrap();
        }
        assert_eq!(obj.keys().collect::<Vec<_>>(), vec!["a", "É"]);
        assert_eq!(values(&obj, "a"), vec![int(1), int(1)]);
    }

    #[test]
    fn test_entry_into_value_views_implicit_array_as_sequence() {
        let mut entry = Entry::new(int(1));
        assert_eq!(entry.clone().into_value(), int(1));
        entry.push(int(2));
        assert_eq!(entry.into_value(), UclValue::Array(vec![int(1), int(2)]));
    }

    #[test]
    fn test_insert_slot_placed_reports_where_the_value_went() {
        let append = DuplicateStrategy::Append;
        let flags = ParserFlags::DEFAULT;
        let mut obj = UclObject::new();
        let place = |obj: &mut UclObject, v, pri, s, f| {
            obj.insert_slot_placed("k", Slot::new(v, pri), s, f)
                .unwrap()
        };
        assert_eq!(
            place(&mut obj, int(1), 1, append, flags),
            Placement::Slot(0)
        );
        assert_eq!(
            place(&mut obj, int(2), 1, append, flags),
            Placement::Slot(1)
        );
        assert_eq!(
            place(&mut obj, int(3), 0, append, flags),
            Placement::Dropped
        );
        assert_eq!(
            place(&mut obj, int(4), 2, append, flags),
            Placement::Slot(0)
        );

        let merge = DuplicateStrategy::Merge;
        let empty = || UclValue::Object(UclObject::new());
        let mut obj = UclObject::new();
        assert_eq!(
            place(&mut obj, empty(), 0, merge, flags),
            Placement::Slot(0)
        );
        assert_eq!(place(&mut obj, empty(), 0, merge, flags), Placement::Merged);

        let nia = ParserFlags::NO_IMPLICIT_ARRAYS;
        let mut obj = UclObject::new();
        assert_eq!(place(&mut obj, int(1), 0, append, nia), Placement::Slot(0));
        assert_eq!(
            place(&mut obj, empty(), 0, append, nia),
            Placement::Collected(1)
        );
        assert_eq!(
            place(&mut obj, empty(), 0, append, nia),
            Placement::Collected(2)
        );
        assert!(
            obj.entry_mut("k")
                .unwrap()
                .value_at_mut(0)
                .unwrap()
                .is_array()
        );
    }

    #[test]
    fn test_parser_flags_match_libucl_bits() {
        assert_eq!(ParserFlags::KEY_LOWERCASE.bits(), 1);
        assert_eq!(ParserFlags::NO_FILEVARS.bits(), 64);
        let flags = ParserFlags::NO_TIME | ParserFlags::DISABLE_MACRO;
        assert!(flags.contains(ParserFlags::NO_TIME));
        assert!(!flags.contains(ParserFlags::ZEROCOPY));
        assert_eq!(ParserFlags::from_bits_truncate(0xffff).bits(), 127);
    }
}