techy 0.2.0

A fast, extensible LaTeX parser for Rust
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
//! Tree validation: [`validate_tree`], the public checker of the invariants every
//! finished tree satisfies, and the test oracle layered on top of it.
//!
//! [`validate_tree`] checks the **all-trees law** — what every finished tree must
//! satisfy whatever its origin — and reports the first violation as a `Result`. In test
//! builds only, the crate-internal `check_tree_invariants` additionally asserts the
//! stricter **span-tiling law**, the byte accounting that holds for the parse trees of
//! a language declaring
//! [`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING).
//!
//! The split is deliberate: legitimate transform output (spliced, reordered, or
//! synthesized nodes) breaks the byte accounting *by design*, so the byte checks are
//! **a test utility, not builder law** — a future construct that legitimately breaks
//! byte accounting (say a tolerant root recovery that *skips* a stray close delimiter,
//! leaving an unrepresented byte) amends a test, not the architecture.
//!
//! The all-trees law is a subset of the span-tiling law, and the trees of a language
//! that does not declare span tiling owe the all-trees law alone.

use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use core::ops::Range;

use crate::source::{Span, TextContent};
use crate::state::Lang;

use super::kind::NodeKind;
use super::tree::{NodeData, NodeId, NodeTree};

/// Checks a tree against the **all-trees law**: the invariants every finished
/// [`NodeTree`] satisfies however it was built — parsed, restaged, spliced together
/// from several trees, or synthesized.
///
/// Reach for it wherever trees of unknown provenance arrive: a framework accepting
/// rebuilt or spliced trees, a binding for another language, a fuzzer. It never panics,
/// and it is O(n) in the number of nodes.
///
/// A tree that passes guarantees:
///
/// 1. **Structural sanity.** Children ranges are in bounds and lie after their own node
///    (the breadth-first layout); every non-root node is inside exactly one parent's
///    children range, so each node has a single parent and is reachable from the root;
///    the root is nobody's child; `Chars` and `Comment` nodes are childless.
/// 2. **Region tiling.** A `Callable`'s argument and slot regions are resolved and tile
///    its children block exactly, in order (arguments before slots, whatever each
///    slot's [`SlotRole`](super::SlotRole)); every content range lies within its
///    content parent's children; and a content parent other than the callable itself
///    lies inside its own region's subtree.
/// 3. **Text payload residency.** Every span-backed payload
///    ([`TextContent::Spanned`](crate::source::TextContent)) is a valid
///    `char`-boundary range of the node's own source. Residency only: nothing is
///    checked about *where* within the node such a payload sits.
///
/// Deliberately **not** checked: the span-tiling law's byte accounting, which
/// legitimate transform output breaks by design — no byte partition of content
/// interiors, no requirement that children share their parent's source or follow one
/// another in source order, no positional pinning of payloads (chars content equal to
/// the node's span, delimiters as prefix and suffix, and so on). A tree drawing on
/// several sources (attached `\input` content, a cross-tree splice) passes.
///
/// # Errors
///
/// Returns the first violation found, as a [`TreeViolation`] naming the offending node
/// and what is wrong with it.
pub fn validate_tree<L: Lang, A>(tree: &NodeTree<L, A>) -> Result<(), TreeViolation> {
    let n = tree.node_count();
    if n == 0 {
        // Unreachable for trees built by `NodeTreeBuilder::finish` (which always
        // stages a root); kept so the checker is total.
        return Err(TreeViolation { node: None, kind: TreeViolationKind::Empty });
    }

    // --- 1. structural sanity ---------------------------------------------------------
    // The parent map is *recomputed* from the children ranges: the tree's stored parent
    // table is derived data, and re-deriving the relation here is the check itself.
    let mut parent: Vec<Option<u32>> = vec![None; n];
    for (i, data) in tree.nodes().iter().enumerate() {
        let children = data.children.clone();
        if children.start > children.end || children.end as usize > n {
            return Err(TreeViolation {
                node: Some(tree.make_id(i as u32)),
                kind: TreeViolationKind::ChildrenOutOfBounds { children, node_count: n },
            });
        }
        if !children.is_empty() && children.start as usize <= i {
            return Err(TreeViolation {
                node: Some(tree.make_id(i as u32)),
                kind: TreeViolationKind::ChildrenNotAfterParent { children },
            });
        }
        for c in children {
            if let Some(first) = parent[c as usize] {
                return Err(TreeViolation {
                    node: Some(tree.make_id(c)),
                    kind: TreeViolationKind::MultipleParents {
                        first_parent: tree.make_id(first),
                        second_parent: tree.make_id(i as u32),
                    },
                });
            }
            parent[c as usize] = Some(i as u32);
        }
    }
    if let Some(p) = parent[0] {
        return Err(TreeViolation {
            node: Some(tree.make_id(0)),
            kind: TreeViolationKind::RootHasParent { parent: tree.make_id(p) },
        });
    }
    for (i, p) in parent.iter().enumerate().skip(1) {
        if p.is_none() {
            return Err(TreeViolation {
                node: Some(tree.make_id(i as u32)),
                kind: TreeViolationKind::Unreachable,
            });
        }
    }

    // --- 2. + 3. per-node record and payload checks ------------------------------------
    for (i, data) in tree.nodes().iter().enumerate() {
        validate_node(tree, &parent, i, data)?;
    }
    Ok(())
}

fn validate_node<L: Lang, A>(
    tree: &NodeTree<L, A>,
    parent: &[Option<u32>],
    i: usize,
    data: &NodeData<L>,
) -> Result<(), TreeViolation> {
    let source_content = data.span.source().content();

    // `Spanned` residency: a valid char-boundary range of the node's own source.
    let residency = |text: &TextContent, what: &'static str| -> Result<(), TreeViolation> {
        if let TextContent::Spanned(s) = text {
            if source_content.get(s.range()).is_none() {
                return Err(TreeViolation {
                    node: Some(tree.make_id(i as u32)),
                    kind: TreeViolationKind::SpannedContentInvalid {
                        what,
                        span: *s,
                        content_len: source_content.len(),
                    },
                });
            }
        }
        Ok(())
    };
    let leaf_without_children = |kind: &'static str| -> Result<(), TreeViolation> {
        if !data.children.is_empty() {
            return Err(TreeViolation {
                node: Some(tree.make_id(i as u32)),
                kind: TreeViolationKind::LeafWithChildren { kind },
            });
        }
        Ok(())
    };

    match &data.kind {
        NodeKind::Chars { content } => {
            leaf_without_children("Chars")?;
            residency(content, "chars content")
        }
        NodeKind::Comment(data) => {
            leaf_without_children("Comment")?;
            residency(&data.content, "comment content")?;
            residency(&data.start, "comment start delimiter")?;
            residency(&data.post_space, "comment post-space")
        }
        NodeKind::List => Ok(()),
        NodeKind::Group(group) => {
            residency(&group.open, "group open delimiter")?;
            residency(&group.close, "group close delimiter")
        }
        NodeKind::Callable(callable) => {
            // The invocation-syntax payload is Lang-opaque to the all-trees law
            // (its span-backed fields are the Lang's recording discipline; the
            // in-crate span-tiling oracle checks the shipped payloads).
            validate_regions(tree, parent, i, data, callable)
        }
    }
}

/// Region tiling (all-trees law, point 2): the callable's resolved regions tile its
/// children block; content ranges sit inside their content parent, which sits inside
/// its own region's subtree.
fn validate_regions<L: Lang, A>(
    tree: &NodeTree<L, A>,
    parent: &[Option<u32>],
    i: usize,
    data: &NodeData<L>,
    callable: &super::kind::CallableData<L>,
) -> Result<(), TreeViolation> {
    let node = tree.make_id(i as u32);
    let block = &data.children;
    let regions = callable
        .arguments
        .iter()
        .filter_map(|argument| argument.region.as_ref())
        .chain(callable.slots.iter().map(|slot| &slot.region));
    let mut next = block.start;
    for (r, region) in regions.enumerate() {
        if !region.is_resolved() {
            return Err(TreeViolation {
                node: Some(node),
                kind: TreeViolationKind::UnresolvedRegion { region: r },
            });
        }
        let children = region.children();
        if children.start != next || children.end > block.end || children.start > children.end
        {
            return Err(TreeViolation {
                node: Some(node),
                kind: TreeViolationKind::RegionNotTiling {
                    region: r,
                    children,
                    block: block.clone(),
                    expected_start: next,
                },
            });
        }
        next = children.end;

        let content = region.content_range();
        let content_parent = region.content_parent();
        if content_parent.index() == i {
            if content.start < children.start || content.end > children.end {
                return Err(TreeViolation {
                    node: Some(node),
                    kind: TreeViolationKind::ContentOutsideRegion {
                        region: r,
                        content,
                        region_children: children,
                    },
                });
            }
        } else {
            let Some(parent_data) = tree.nodes().get(content_parent.index()) else {
                // Not a node of this tree at all — certainly not inside the subtree.
                return Err(TreeViolation {
                    node: Some(node),
                    kind: TreeViolationKind::ContentParentOutsideSubtree {
                        region: r,
                        content_parent,
                    },
                });
            };
            let parent_children = parent_data.children.clone();
            if content.start < parent_children.start || content.end > parent_children.end {
                return Err(TreeViolation {
                    node: Some(node),
                    kind: TreeViolationKind::ContentOutsideContentParent {
                        region: r,
                        content,
                        parent_children,
                    },
                });
            }
            // Walk up from the content parent to its child-of-the-callable ancestor;
            // that ancestor must be one of this region's nodes. Terminates: the
            // structural pass verified children lie strictly after their parent, so
            // each step strictly decreases the index.
            let mut a = content_parent.index() as u32;
            loop {
                let Some(p) = parent[a as usize] else {
                    return Err(TreeViolation {
                        node: Some(node),
                        kind: TreeViolationKind::ContentParentOutsideSubtree {
                            region: r,
                            content_parent,
                        },
                    });
                };
                if p == i as u32 {
                    break;
                }
                a = p;
            }
            if !children.contains(&a) {
                return Err(TreeViolation {
                    node: Some(node),
                    kind: TreeViolationKind::ContentParentOutsideRegion {
                        region: r,
                        content_parent,
                        region_children: children,
                    },
                });
            }
        }
    }
    if next != block.end {
        return Err(TreeViolation {
            node: Some(node),
            kind: TreeViolationKind::ChildrenNotInRegions { unassigned: next..block.end },
        });
    }
    Ok(())
}

/// The error that [`validate_tree`] returns when a tree violates one of the invariants
/// that every finished tree must satisfy.
///
/// The field `node` identifies the node concerned, and the field `kind` describes the
/// violation. The [`Display`](core::fmt::Display) text is a complete message that
/// contains the values concerned, so you can write it directly to a log or use it as a
/// panic message.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct TreeViolation {
    /// The node concerned by the violation, or `None` if the violation does not concern
    /// a single node, as for [`Empty`](TreeViolationKind::Empty). For a violation that
    /// concerns an argument or slot region, this is the callable node. For
    /// [`MultipleParents`](TreeViolationKind::MultipleParents), this is the node that
    /// has two parents.
    pub node: Option<NodeId>,
    /// The kind of violation.
    pub kind: TreeViolationKind,
}

impl TreeViolation {
    /// A violation value from its parts, for consumers of [`validate_tree`] that need
    /// to manufacture violations to test their own handling code.
    ///
    /// The struct is `#[non_exhaustive]`: its fields are readable everywhere, but
    /// outside this crate a value cannot be built with a struct literal.
    pub fn new(node: Option<NodeId>, kind: TreeViolationKind) -> TreeViolation {
        TreeViolation { node, kind }
    }
}

/// The kind of violation that a [`TreeViolation`] reports, with the values concerned.
///
/// Node indices and children ranges refer to the order in which the tree stores its
/// nodes (see [`NodeId::index`]). The argument and slot regions of a callable are
/// numbered from 0, arguments first; an argument that was not given in the source has
/// no region and no number.
///
/// The [`Display`](core::fmt::Display) text is a lowercase phrase, which the `Display`
/// text of [`TreeViolation`] inserts after the node concerned.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TreeViolationKind {
    /// The tree contains no nodes. A tree built by
    /// [`NodeTreeBuilder::finish`](super::NodeTreeBuilder::finish) always contains at
    /// least its root node.
    Empty,
    /// The children range of the node is inverted or extends past the last node of the
    /// tree.
    ChildrenOutOfBounds {
        /// The children range of the node.
        children: Range<u32>,
        /// The number of nodes in the tree.
        node_count: usize,
    },
    /// The children range of the node is not empty and does not start after the node
    /// itself. A tree stores its nodes in breadth-first order, so the children of a node
    /// always follow the node.
    ChildrenNotAfterParent {
        /// The children range of the node.
        children: Range<u32>,
    },
    /// The node is in the children ranges of two nodes.
    MultipleParents {
        /// The first of the two parents, in storage order.
        first_parent: NodeId,
        /// The second of the two parents.
        second_parent: NodeId,
    },
    /// The root node (index 0) is in the children range of another node.
    RootHasParent {
        /// The node whose children range contains the root.
        parent: NodeId,
    },
    /// The node is not in the children range of any node, so it is not reachable from
    /// the root.
    Unreachable,
    /// A `Chars` node or a `Comment` node has children.
    LeafWithChildren {
        /// The kind of the node: `"Chars"` or `"Comment"`.
        kind: &'static str,
    },
    /// An argument or slot region of the callable is unresolved: its ranges are child
    /// offsets, and not node indices of the tree.
    /// [`NodeTreeBuilder::finish`](super::NodeTreeBuilder::finish) resolves every region
    /// of the tree that it builds (see
    /// [`ChildRegion::is_resolved`](super::ChildRegion::is_resolved)).
    UnresolvedRegion {
        /// The number of the region.
        region: usize,
    },
    /// An argument or slot region does not start where the previous region ends, or it
    /// extends past the children of the callable. The regions must cover the children
    /// of the callable in order and without gaps: first the arguments, then the slots.
    RegionNotTiling {
        /// The number of the region.
        region: usize,
        /// The node indices of the region.
        children: Range<u32>,
        /// The children range of the callable.
        block: Range<u32>,
        /// The node index at which the region must start.
        expected_start: u32,
    },
    /// Children of the callable that follow its last argument or slot region are not in
    /// any region. The regions must cover all children of the callable.
    ChildrenNotInRegions {
        /// The node indices of the children that are not in any region.
        unassigned: Range<u32>,
    },
    /// The content range of a region whose content parent is the callable itself
    /// extends past the nodes of the region.
    ContentOutsideRegion {
        /// The number of the region.
        region: usize,
        /// The content range.
        content: Range<u32>,
        /// The node indices of the region.
        region_children: Range<u32>,
    },
    /// The content range of a region extends past the children of its content parent.
    ContentOutsideContentParent {
        /// The number of the region.
        region: usize,
        /// The content range.
        content: Range<u32>,
        /// The children range of the content parent.
        parent_children: Range<u32>,
    },
    /// The content parent of a region is not inside the subtree of the callable. This
    /// variant also reports a content parent that is not a node of the tree.
    ContentParentOutsideSubtree {
        /// The number of the region.
        region: usize,
        /// The content parent.
        content_parent: NodeId,
    },
    /// The content parent of a region is inside the subtree of the callable, but not
    /// inside the subtree of the region.
    ContentParentOutsideRegion {
        /// The number of the region.
        region: usize,
        /// The content parent.
        content_parent: NodeId,
        /// The node indices of the region.
        region_children: Range<u32>,
    },
    /// A `Spanned` text of the node is not a range of the source of the node on
    /// character boundaries.
    SpannedContentInvalid {
        /// The text concerned, for instance `"chars content"` or
        /// `"group open delimiter"`.
        what: &'static str,
        /// The span of the text.
        span: Span,
        /// The length of the source content of the node, in bytes.
        content_len: usize,
    },
}

impl TreeViolationKind {
    /// The variant's name without its data (`"Empty"`, `"ChildrenOutOfBounds"`, …),
    /// for log labels and name-keyed tables.
    ///
    /// Follows [`NodeKind::as_str`](super::NodeKind::as_str). The full detail is the
    /// [`Display`](core::fmt::Display) rendering of the violation; the offending values
    /// are on the variants themselves.
    pub const fn as_str(&self) -> &'static str {
        match self {
            TreeViolationKind::Empty => "Empty",
            TreeViolationKind::ChildrenOutOfBounds { .. } => "ChildrenOutOfBounds",
            TreeViolationKind::ChildrenNotAfterParent { .. } => "ChildrenNotAfterParent",
            TreeViolationKind::MultipleParents { .. } => "MultipleParents",
            TreeViolationKind::RootHasParent { .. } => "RootHasParent",
            TreeViolationKind::Unreachable => "Unreachable",
            TreeViolationKind::LeafWithChildren { .. } => "LeafWithChildren",
            TreeViolationKind::UnresolvedRegion { .. } => "UnresolvedRegion",
            TreeViolationKind::RegionNotTiling { .. } => "RegionNotTiling",
            TreeViolationKind::ChildrenNotInRegions { .. } => "ChildrenNotInRegions",
            TreeViolationKind::ContentOutsideRegion { .. } => "ContentOutsideRegion",
            TreeViolationKind::ContentOutsideContentParent { .. } => {
                "ContentOutsideContentParent"
            }
            TreeViolationKind::ContentParentOutsideSubtree { .. } => {
                "ContentParentOutsideSubtree"
            }
            TreeViolationKind::ContentParentOutsideRegion { .. } => {
                "ContentParentOutsideRegion"
            }
            TreeViolationKind::SpannedContentInvalid { .. } => "SpannedContentInvalid",
        }
    }
}

impl fmt::Display for TreeViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.node {
            Some(id) => write!(f, "Invalid tree at node {}: {}", id.index(), self.kind),
            None => write!(f, "Invalid tree: {}", self.kind),
        }
    }
}

impl fmt::Display for TreeViolationKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TreeViolationKind::Empty => {
                write!(f, "missing root node")
            }
            TreeViolationKind::ChildrenOutOfBounds { children, node_count } => {
                write!(
                    f,
                    "children range {:?} out of bounds (the tree has {} nodes)",
                    children, node_count
                )
            }
            TreeViolationKind::ChildrenNotAfterParent { children } => {
                write!(f, "children range {:?} must start after the node", children)
            }
            TreeViolationKind::MultipleParents { first_parent, second_parent } => write!(
                f,
                "the node is a child of both node {} and node {}",
                first_parent.index(),
                second_parent.index()
            ),
            TreeViolationKind::RootHasParent { parent } => {
                write!(f, "the root is a child of node {}", parent.index())
            }
            TreeViolationKind::Unreachable => {
                write!(f, "the node is not reachable from the root")
            }
            TreeViolationKind::LeafWithChildren { kind } => {
                write!(f, "‘{}’ nodes may not have children", kind)
            }
            TreeViolationKind::UnresolvedRegion { region } => {
                write!(f, "argument or slot region {} is unresolved", region)
            }
            TreeViolationKind::RegionNotTiling { region, children, block, expected_start } => {
                write!(
                    f,
                    "argument or slot region {} (nodes {:?}) must start at node {} and \
                     lie within the children {:?} of the callable",
                    region, children, expected_start, block
                )
            }
            TreeViolationKind::ChildrenNotInRegions { unassigned } => write!(
                f,
                "children {:?} are not in any argument or slot region (the regions must \
                 cover all children of the callable)",
                unassigned
            ),
            TreeViolationKind::ContentOutsideRegion { region, content, region_children } => {
                write!(
                    f,
                    "content range {:?} of region {} must lie within the nodes {:?} of \
                     the region",
                    content, region, region_children
                )
            }
            TreeViolationKind::ContentOutsideContentParent {
                region,
                content,
                parent_children,
            } => write!(
                f,
                "content range {:?} of region {} must lie within the children {:?} of its \
                 content parent",
                content, region, parent_children
            ),
            TreeViolationKind::ContentParentOutsideSubtree { region, content_parent } => {
                write!(
                    f,
                    "content parent {} of region {} is not inside the subtree of the \
                     callable",
                    content_parent.index(),
                    region
                )
            }
            TreeViolationKind::ContentParentOutsideRegion {
                region,
                content_parent,
                region_children,
            } => write!(
                f,
                "content parent {} of region {} is not inside the subtree of the region \
                 (nodes {:?})",
                content_parent.index(),
                region,
                region_children
            ),
            TreeViolationKind::SpannedContentInvalid { what, span, content_len } => write!(
                f,
                "span {:?} of the {} must lie within the source of the node ({} bytes) on \
                 character boundaries",
                span, what, content_len
            ),
        }
    }
}

impl core::error::Error for TreeViolation {}

/// Check a finished tree against the **span-tiling law** — the all-trees law
/// ([`validate_tree`]) plus the byte accounting that holds for the parse trees of a
/// language that obeys span tiling
/// ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING)) — panicking
/// with a description of the first violation. The in-crate test oracle (assert every
/// tree a parser produces); run it liberally, it is O(n).
///
/// For a language with `OBEYS_SPAN_TILING = false` the byte accounting does not
/// apply — its parsers make no assumption about where tokens come from, so nothing
/// pins a node's payload to a position or a sibling to its neighbor — and only the
/// all-trees law is checked.
///
/// On top of the all-trees law, this checks:
///
/// 1. **Partition of content interiors.** The sibling spans of a `List`'s or
///    `Group`'s children partition the parent's content interior exactly — no gaps,
///    no double counting. A `List`'s interior is its whole span; a `Group`'s interior
///    is its span minus the delimiters.
/// 2. **Callable children-block contiguity.** A `Callable`'s children block is
///    span-contiguous and lies inside the node's span.
/// 3. **Positional payload pins.** Where a `Spanned` payload has a pinned position
///    (chars content = the node's span; comment start/content/post-space partition
///    the node's span; group delimiters are prefix/suffix), the exact position is
///    checked. The **invocation-syntax payload is deliberately not read here**:
///    it is Lang-owned opaque data to core — the latexlike preset layers its
///    payload pins in its own checker (`check_latexlike_tree_invariants`).
/// 4. **Children share the parent's source** (byte comparisons presuppose it).
#[cfg(test)]
pub(crate) fn check_tree_invariants<L: Lang, A>(tree: &NodeTree<L, A>) {
    if let Err(violation) = validate_tree(tree) {
        panic!("tree invariant violated: {}", violation);
    }
    if !L::OBEYS_SPAN_TILING {
        // The byte accounting below *is* span tiling; a language that does not declare
        // it owes only the all-trees law.
        return;
    }
    for (i, data) in tree.nodes().iter().enumerate() {
        check_span_tiling_node(tree, i, data);
    }
}

/// The span-tiling byte accounting for one node (see [`check_tree_invariants`];
/// the all-trees law has already passed, and the language obeys span tiling).
///
/// Byte accounting is scoped **per source** via the slot roles
/// ([`SlotRole`](super::SlotRole)): children in an `Attached` slot's region live
/// in the attached source (`\input`) and are excluded from the including
/// callable's children-in-source/contiguity checks — with their own per-source
/// accounting (one source per attached region, span-contiguous within it) —
/// while children in a `Hidden` slot's region carry **no** byte accounting at
/// all (the ruled `Hidden` semantics). Declaration replaces source-change
/// inference: the excluded regions are invisible to the parent's accounting,
/// so the remaining children must be contiguous across them.
#[cfg(test)]
fn check_span_tiling_node<L: Lang, A>(tree: &NodeTree<L, A>, i: usize, data: &NodeData<L>) {
    let span = data.span.range();
    let source = data.span.source();

    // Resolved length of a payload (what interior arithmetic is based on).
    let text_len = |text: &TextContent| text.resolve(source).len();

    // The children of a node must live in its source for byte comparisons to mean
    // anything; check it wherever children exist.
    let assert_children_in_source = || {
        for child in tree.nodes_in(data.children.clone()) {
            assert!(
                child.span().same_source(&data.span),
                "node {}: child {} lives in a different source",
                i,
                child.id().index()
            );
        }
    };

    match &data.kind {
        NodeKind::Chars { content } => {
            if let TextContent::Spanned(s) = content {
                assert!(
                    s.range() == span,
                    "node {}: spanned chars content {:?} is not the node's span {:?}",
                    i,
                    s,
                    span
                );
            }
        }

        NodeKind::Comment(data) => {
            let (start, content, post_space) = (&data.start, &data.content, &data.post_space);
            if let TextContent::Spanned(s) = start {
                assert!(
                    s.start() == span.start,
                    "node {}: spanned comment start {:?} does not begin the node's span {:?}",
                    i,
                    s,
                    span
                );
            }
            if let TextContent::Spanned(s) = post_space {
                assert!(
                    s.end() == span.end,
                    "node {}: spanned comment post-space {:?} does not end the node's span {:?}",
                    i,
                    s,
                    span
                );
            }
            if let (TextContent::Spanned(s), TextContent::Spanned(c), TextContent::Spanned(p)) =
                (start, content, post_space)
            {
                assert!(
                    s.end() == c.start() && c.end() == p.start(),
                    "node {}: comment parts {:?}/{:?}/{:?} do not partition the node's span {:?}",
                    i,
                    s,
                    c,
                    p,
                    span
                );
            }
        }

        NodeKind::List => {
            assert_children_in_source();
            check_interior_partition(tree, i, data, span.clone());
        }

        NodeKind::Group(group) => {
            let open_len = text_len(&group.open);
            let close_len = text_len(&group.close);
            assert!(
                open_len + close_len <= span.len(),
                "node {}: group delimiters (lengths {} + {}) exceed the node's span {:?}",
                i,
                open_len,
                close_len,
                span
            );
            if let TextContent::Spanned(s) = &group.open {
                assert!(
                    s.range() == (span.start..span.start + open_len),
                    "node {}: spanned open delimiter {:?} is not the prefix of span {:?}",
                    i,
                    s,
                    span
                );
            }
            if let TextContent::Spanned(s) = &group.close {
                assert!(
                    s.range() == (span.end - close_len..span.end),
                    "node {}: spanned close delimiter {:?} is not the suffix of span {:?}",
                    i,
                    s,
                    span
                );
            }
            assert_children_in_source();
            check_interior_partition(tree, i, data, span.start + open_len..span.end - close_len);
        }

        NodeKind::Callable(callable) => {
            // The trigger-spelling facts live in the Lang-owned invocation-syntax
            // payload (invariant 3 as amended) — opaque to core, so no payload
            // byte accounting happens here: the latexlike preset pins its
            // recorded spellings (macro spelling + post-space, specials
            // name-as-written, environment begin/end scaffolding) in its own
            // checker, `check_latexlike_tree_invariants` (D-plan-12 Option B).

            // Partition the children block by slot role (see the fn docs):
            // `Attached` regions get their own per-source accounting below,
            // `Hidden` regions get none, the rest is the parent's accounting.
            use super::SlotRole;
            let attached_regions: Vec<Range<u32>> = callable
                .slots
                .iter()
                .filter(|slot| slot.role == SlotRole::Attached)
                .map(|slot| slot.region.children())
                .collect();
            let hidden_regions: Vec<Range<u32>> = callable
                .slots
                .iter()
                .filter(|slot| slot.role == SlotRole::Hidden)
                .map(|slot| slot.region.children())
                .collect();
            let excluded = |index: u32| {
                attached_regions
                    .iter()
                    .chain(hidden_regions.iter())
                    .any(|region| region.contains(&index))
            };

            // The parent-source sequence (arguments + `Content` slots):
            // children share the parent's source, lie inside the node's span,
            // and are span-contiguous *across* the excluded regions.
            let mut prev_end: Option<usize> = None;
            for child in tree.nodes_in(data.children.clone()) {
                if excluded(child.id().index() as u32) {
                    continue;
                }
                assert!(
                    child.span().same_source(&data.span),
                    "node {}: child {} lives in a different source",
                    i,
                    child.id().index()
                );
                let child_span = child.span().range();
                assert!(
                    span.start <= child_span.start && child_span.end <= span.end,
                    "node {}: child {} span {:?} escapes the callable's span {:?}",
                    i,
                    child.id().index(),
                    child_span,
                    span
                );
                if let Some(end) = prev_end {
                    assert!(
                        child_span.start == end,
                        "node {}: children block not span-contiguous at child {} \
                         (previous ends at {}, next starts at {})",
                        i,
                        child.id().index(),
                        end,
                        child_span.start
                    );
                }
                prev_end = Some(child_span.end);
            }

            // Each `Attached` region's own per-source accounting: one source
            // per region (the attached source), span-contiguous within it.
            for region in &attached_regions {
                let mut prev: Option<super::NodeRef<'_, L, A>> = None;
                for child in tree.nodes_in(region.clone()) {
                    if let Some(prev) = &prev {
                        assert!(
                            child.span().same_source(prev.span()),
                            "node {}: attached region {:?} spans several sources \
                             (children {} and {})",
                            i,
                            region,
                            prev.id().index(),
                            child.id().index()
                        );
                        assert!(
                            child.span().range().start == prev.span().range().end,
                            "node {}: attached region {:?} not span-contiguous at \
                             child {} (previous ends at {}, next starts at {})",
                            i,
                            region,
                            child.id().index(),
                            prev.span().range().end,
                            child.span().range().start
                        );
                    }
                    prev = Some(child);
                }
            }
        }
    }
}

/// Check helper: the children of node `i` partition `interior` exactly.
#[cfg(test)]
fn check_interior_partition<L: Lang, A>(
    tree: &NodeTree<L, A>,
    i: usize,
    data: &NodeData<L>,
    interior: Range<usize>,
) {
    let mut pos = interior.start;
    for child in tree.nodes_in(data.children.clone()) {
        let child_span = child.span().range();
        assert!(
            child_span.start == pos,
            "node {}: gap {}..{} before child {} (span tiling)",
            i,
            pos,
            child_span.start,
            child.id().index()
        );
        pos = child_span.end;
    }
    assert!(
        pos == interior.end,
        "node {}: children end at {} but the content interior ends at {} \
         (span tiling)",
        i,
        pos,
        interior.end
    );
}

#[cfg(test)]
mod tests {
    use super::super::arguments::{
        ChildRegion, ContentNodes, ParsedArguments, ParsedSlot, ParsedSlots, SlotRole,
    };
    use super::super::builder::NodeTreeBuilder;
    use super::super::kind::{CallableData, GroupData, NodeKind};
    use super::super::tree::{next_tree_tag, NodeTree, TreeCore, NO_PARENT};
    use super::*;
    use crate::scopes::ScopeStack;
    use crate::source::{Source, SourceSpan, Span};
    use crate::spec::{CallableSpec, StdCallableSpec};
    use crate::state::{ParsingState, StateData, TrivialLang};
    use crate::token::{
        CommandRules, CommentRules, ForbiddenCharsRules, GroupRules, ParagraphRules,
        SpecialsRules, TokenRules, WhitespaceRules,
    };
    use alloc::sync::Arc;

    #[derive(Debug, Clone, Copy)]
    struct PlainLang;
    impl TrivialLang for PlainLang {}

    fn state() -> Arc<ParsingState<PlainLang>> {
        Arc::new(ParsingState::new(StateData {
            rules: TokenRules {
                whitespace: WhitespaceRules { enabled: true, chars: " \t\n".into() },
                paragraphs: ParagraphRules { enabled: true },
                groups: GroupRules {
                    enabled: true,
                    rules: alloc::vec::Vec::new(),
                    temporary: alloc::vec::Vec::new(),
                    expecting_close: None,
                },
                commands: CommandRules {
                    enabled: true,
                    rules: alloc::vec::Vec::new(),
                },
                comments: CommentRules {
                    enabled: true,
                    rules: alloc::vec::Vec::new(),
                },
                specials: SpecialsRules { enabled: true },
                forbidden_chars: ForbiddenCharsRules { chars: "".into() },
            },
            scopes: ScopeStack::new(),
            mode: (),
            ext: (),
        }))
    }

    /// `"a{bc}d"` hand-built correctly: root List [chars, group [chars], chars].
    fn build_valid() -> NodeTree<PlainLang> {
        let source: Arc<Source> = Arc::new(Source::new("a{bc}d"));
        let st = state();
        let mut builder: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let a = builder.add(
            NodeKind::chars(Span::new(0, 1)),
            SourceSpan::new(&source, 0..1),
            Arc::clone(&st),
            alloc::vec![], (), (),
        ).unwrap();
        let bc = builder.add(
            NodeKind::chars(Span::new(2, 4)),
            SourceSpan::new(&source, 2..4),
            Arc::clone(&st),
            alloc::vec![], (), (),
        ).unwrap();
        let group = builder.add(
            NodeKind::group(GroupData::new(0u32, Span::new(1, 2), Span::new(4, 5))),
            SourceSpan::new(&source, 1..5),
            Arc::clone(&st),
            alloc::vec![bc], (), (),
        ).unwrap();
        let d = builder.add(
            NodeKind::chars(Span::new(5, 6)),
            SourceSpan::new(&source, 5..6),
            Arc::clone(&st),
            alloc::vec![], (), (),
        ).unwrap();
        let root = builder.add(
            NodeKind::list(),
            SourceSpan::entire(&source),
            Arc::clone(&st),
            alloc::vec![a, group, d], (), (),
        ).unwrap();
        builder.finish(root).unwrap()
    }

    #[test]
    fn tree_violation_new_constructs_matchable_values() {
        // Consumers of `validate_tree` manufacture violations to test their own
        // handling code; the constructed value matches like a checker-produced one.
        let tree = build_valid();
        let id = tree.root().id();
        let violation = TreeViolation::new(Some(id), TreeViolationKind::Unreachable);
        assert_eq!(violation.node, Some(id));
        assert!(matches!(violation.kind, TreeViolationKind::Unreachable));

        let anonymous = TreeViolation::new(None, TreeViolationKind::Empty);
        assert!(anonymous.node.is_none());
        assert!(matches!(anonymous.kind, TreeViolationKind::Empty));
    }

    #[test]
    fn as_str_answers_the_bare_variant_name() {
        // The duplicate name table below is deliberate and exhaustive (no `_` arm):
        // adding or renaming a variant fails compilation here, keeping `as_str` in
        // step.
        fn expected(kind: &TreeViolationKind) -> &'static str {
            match kind {
                TreeViolationKind::Empty => "Empty",
                TreeViolationKind::ChildrenOutOfBounds { .. } => "ChildrenOutOfBounds",
                TreeViolationKind::ChildrenNotAfterParent { .. } => "ChildrenNotAfterParent",
                TreeViolationKind::MultipleParents { .. } => "MultipleParents",
                TreeViolationKind::RootHasParent { .. } => "RootHasParent",
                TreeViolationKind::Unreachable => "Unreachable",
                TreeViolationKind::LeafWithChildren { .. } => "LeafWithChildren",
                TreeViolationKind::UnresolvedRegion { .. } => "UnresolvedRegion",
                TreeViolationKind::RegionNotTiling { .. } => "RegionNotTiling",
                TreeViolationKind::ChildrenNotInRegions { .. } => "ChildrenNotInRegions",
                TreeViolationKind::ContentOutsideRegion { .. } => "ContentOutsideRegion",
                TreeViolationKind::ContentOutsideContentParent { .. } => {
                    "ContentOutsideContentParent"
                }
                TreeViolationKind::ContentParentOutsideSubtree { .. } => {
                    "ContentParentOutsideSubtree"
                }
                TreeViolationKind::ContentParentOutsideRegion { .. } => {
                    "ContentParentOutsideRegion"
                }
                TreeViolationKind::SpannedContentInvalid { .. } => "SpannedContentInvalid",
            }
        }

        let tree = build_valid();
        let id = tree.root().id();
        let kinds = alloc::vec![
            TreeViolationKind::Empty,
            TreeViolationKind::ChildrenOutOfBounds { children: 0..9, node_count: 5 },
            TreeViolationKind::ChildrenNotAfterParent { children: 0..1 },
            TreeViolationKind::MultipleParents { first_parent: id, second_parent: id },
            TreeViolationKind::RootHasParent { parent: id },
            TreeViolationKind::Unreachable,
            TreeViolationKind::LeafWithChildren { kind: "Chars" },
            TreeViolationKind::UnresolvedRegion { region: 0 },
            TreeViolationKind::RegionNotTiling {
                region: 0,
                children: 1..2,
                block: 1..2,
                expected_start: 1,
            },
            TreeViolationKind::ChildrenNotInRegions { unassigned: 1..2 },
            TreeViolationKind::ContentOutsideRegion {
                region: 0,
                content: 1..2,
                region_children: 1..2,
            },
            TreeViolationKind::ContentOutsideContentParent {
                region: 0,
                content: 1..2,
                parent_children: 1..2,
            },
            TreeViolationKind::ContentParentOutsideSubtree { region: 0, content_parent: id },
            TreeViolationKind::ContentParentOutsideRegion {
                region: 0,
                content_parent: id,
                region_children: 1..2,
            },
            TreeViolationKind::SpannedContentInvalid {
                what: "chars content",
                span: Span::new(0, 1),
                content_len: 1,
            },
        ];
        for kind in &kinds {
            assert_eq!(kind.as_str(), expected(kind));
        }
    }

    /// Assemble a tree directly from node data, bypassing the builder's validation —
    /// the only way to construct all-trees-law violations, since `finish()` rejects
    /// them (in-crate hand shape; the placeholder parent table is never read:
    /// `validate_tree` recomputes the relation).
    fn hand_tree(nodes: alloc::vec::Vec<NodeData<PlainLang>>) -> NodeTree<PlainLang> {
        let n = nodes.len();
        NodeTree {
            core: Arc::new(TreeCore {
                nodes,
                parent: alloc::vec![NO_PARENT; n],
                tree_tag: next_tree_tag(),
                single_source: false,
            }),
            annotations: alloc::vec![(); n],
        }
    }

    fn node_data(
        kind: NodeKind<PlainLang>,
        source: &Arc<Source>,
        span: core::ops::Range<usize>,
        children: core::ops::Range<u32>,
    ) -> NodeData<PlainLang> {
        NodeData {
            kind,
            ext: (),
            span: SourceSpan::new(source, span),
            parsing_state: state(),
            children,
        }
    }

    // --- validate_tree: the all-trees law ---------------------------------------------

    #[test]
    fn validate_accepts_a_valid_tree() {
        validate_tree(&build_valid()).unwrap();
        validate_tree(&build_valid().materialize()).unwrap();
    }

    #[test]
    fn validate_reports_multiple_parents() {
        // Root List claims 1..3; node 1 (List) also claims node 2.
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let tree = hand_tree(alloc::vec![
            node_data(NodeKind::list(), &source, 0..2, 1..3),
            node_data(NodeKind::list(), &source, 0..2, 2..3),
            node_data(NodeKind::chars(Span::new(0, 2)), &source, 0..2, 0..0),
        ]);
        let violation = validate_tree(&tree).unwrap_err();
        assert_eq!(violation.node, Some(tree.make_id(2)));
        assert_eq!(
            violation.kind,
            TreeViolationKind::MultipleParents {
                first_parent: tree.make_id(0),
                second_parent: tree.make_id(1),
            }
        );
    }

    #[test]
    fn validate_reports_unreachable_nodes() {
        // Root claims nothing; node 1 is inside no children range.
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let tree = hand_tree(alloc::vec![
            node_data(NodeKind::list(), &source, 0..2, 0..0),
            node_data(NodeKind::chars(Span::new(0, 2)), &source, 0..2, 0..0),
        ]);
        let violation = validate_tree(&tree).unwrap_err();
        assert_eq!(violation.node, Some(tree.make_id(1)));
        assert_eq!(violation.kind, TreeViolationKind::Unreachable);
    }

    #[test]
    fn validate_reports_broken_region_tiling() {
        // A callable whose one slot region starts past the children block's start.
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let mut region = ChildRegion::new(0..1, ContentNodes::InRegion(0..1));
        let callable = CallableData {
            callable_type: 0u32,
            name: "m".into(),
            spec: Arc::new(StdCallableSpec::default()) as Arc<dyn CallableSpec<PlainLang>>,
            arguments: ParsedArguments::empty(),
            slots: ParsedSlots::new(alloc::vec![]),
            invocation_syntax: (),
        };
        let tree = {
            let mut nodes = alloc::vec![
                node_data(NodeKind::list(), &source, 0..2, 1..2),
                node_data(NodeKind::callable(callable), &source, 0..2, 2..3),
                node_data(NodeKind::chars(Span::new(0, 2)), &source, 0..2, 0..0),
            ];
            let tag = next_tree_tag();
            // The region claims 3..3 — the block 2..3 expects it to start at 2.
            region.resolve(3..3, 3..3, 1, tag);
            match &mut nodes[1].kind {
                NodeKind::Callable(data) => {
                    data.slots =
                        ParsedSlots::new(alloc::vec![ParsedSlot::new(
                            region,
                            "s",
                            SlotRole::Content,
                            ()
                        )]);
                }
                _ => unreachable!("node 1 is the callable"),
            }
            let n = nodes.len();
            NodeTree {
                core: Arc::new(TreeCore {
                    nodes,
                    parent: alloc::vec![NO_PARENT; n],
                    tree_tag: tag,
                    single_source: false,
                }),
                annotations: alloc::vec![(); n],
            }
        };
        let violation = validate_tree(&tree).unwrap_err();
        assert_eq!(violation.node, Some(tree.make_id(1)));
        assert_eq!(
            violation.kind,
            TreeViolationKind::RegionNotTiling {
                region: 0,
                children: 3..3,
                block: 2..3,
                expected_start: 2,
            }
        );
    }

    #[test]
    fn validate_reports_non_resident_payloads() {
        // Spanned content 0..99 of a 2-byte source: residency, not positional pinning.
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let tree = hand_tree(alloc::vec![node_data(
            NodeKind::chars(Span::new(0, 99)),
            &source,
            0..2,
            0..0
        )]);
        let violation = validate_tree(&tree).unwrap_err();
        assert_eq!(violation.node, Some(tree.make_id(0)));
        assert_eq!(
            violation.kind,
            TreeViolationKind::SpannedContentInvalid {
                what: "chars content",
                span: Span::new(0, 99),
                content_len: 2,
            }
        );
    }

    #[test]
    fn validate_does_no_byte_accounting() {
        // A sibling gap (bytes 0..1 unrepresented) and off-span content: span-tiling
        // violations, but the all-trees law passes.
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let st = state();
        let mut builder: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let b = builder.add(
            NodeKind::chars(Span::new(1, 2)),
            SourceSpan::new(&source, 1..2),
            Arc::clone(&st),
            alloc::vec![], (), (),
        ).unwrap();
        let root = builder.add(
            NodeKind::list(),
            SourceSpan::entire(&source),
            Arc::clone(&st),
            alloc::vec![b], (), (),
        ).unwrap();
        validate_tree(&builder.finish(root).unwrap()).unwrap();
    }

    // --- check_tree_invariants: the span-tiling oracle -------------------------------

    #[test]
    fn accepts_a_valid_tree() {
        check_tree_invariants(&build_valid());
    }

    #[test]
    fn accepts_a_materialized_tree() {
        // All-owned payloads: positional checks are skipped, structure still verified.
        check_tree_invariants(&build_valid().materialize());
    }

    #[test]
    #[should_panic(expected = "span tiling")]
    fn rejects_a_gap_between_siblings() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let st = state();
        let mut builder: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        // Only "b" staged; the root's interior 0..2 has a gap at 0..1.
        let b = builder.add(
            NodeKind::chars(Span::new(1, 2)),
            SourceSpan::new(&source, 1..2),
            Arc::clone(&st),
            alloc::vec![], (), (),
        ).unwrap();
        let root = builder.add(
            NodeKind::list(),
            SourceSpan::entire(&source),
            Arc::clone(&st),
            alloc::vec![b], (), (),
        ).unwrap();
        check_tree_invariants(&builder.finish(root).unwrap());
    }

    /// The byte accounting is the span-tiling law, so a language that declares
    /// `OBEYS_SPAN_TILING = false` is held to the all-trees law alone: the very tree
    /// `rejects_a_gap_between_siblings` panics on passes there.
    #[test]
    fn a_language_that_does_not_obey_span_tiling_is_held_to_the_all_trees_law_only() {
        use crate::constructs::tests::RelaxedStdLang;

        let source: Arc<Source<Option<alloc::string::String>>> = Arc::new(Source::new("ab"));
        let st = crate::constructs::tests::state::<RelaxedStdLang>();
        let mut builder: NodeTreeBuilder<RelaxedStdLang> = NodeTreeBuilder::new();
        let b = builder.add(
            NodeKind::chars(Span::new(1, 2)),
            SourceSpan::new(&source, 1..2),
            Arc::clone(&st),
            alloc::vec![], (), (),
        ).unwrap();
        let root = builder.add(
            NodeKind::list(),
            SourceSpan::entire(&source),
            Arc::clone(&st),
            alloc::vec![b], (), (),
        ).unwrap();
        let tree = builder.finish(root).unwrap();
        validate_tree(&tree).expect("the all-trees law holds");
        check_tree_invariants(&tree);
    }

    #[test]
    #[should_panic(expected = "spanned chars content")]
    fn rejects_spanned_content_that_is_not_the_nodes_span() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let st = state();
        let mut builder: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        // Content span 0..1 under a node span 0..2.
        let root = builder.add(
            NodeKind::chars(Span::new(0, 1)),
            SourceSpan::new(&source, 0..2),
            Arc::clone(&st),
            alloc::vec![], (), (),
        ).unwrap();
        check_tree_invariants(&builder.finish(root).unwrap());
    }

    #[test]
    #[should_panic(expected = "prefix of span")]
    fn rejects_a_group_whose_open_delimiter_is_misplaced() {
        let source: Arc<Source> = Arc::new(Source::new("x{}"));
        let st = state();
        let mut builder: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        // Open delimiter recorded at 0..1 but the group's span starts at 1.
        let root = builder.add(
            NodeKind::group(GroupData::new(0u32, Span::new(0, 1), Span::new(2, 3))),
            SourceSpan::new(&source, 1..3),
            Arc::clone(&st),
            alloc::vec![], (), (),
        ).unwrap();
        check_tree_invariants(&builder.finish(root).unwrap());
    }

    // --- per-source byte accounting via the slot roles ([§dd-dr:slot-roles]) ----------

    /// Build `\input`-shaped trees: a callable in `main` whose one slot (role
    /// `role`) holds children with the given spans in the given sources. The
    /// callable spans the whole 9-byte main source; the root list wraps it.
    fn build_with_slot(
        role: SlotRole,
        children_spans: alloc::vec::Vec<(Arc<Source>, core::ops::Range<usize>)>,
    ) -> NodeTree<PlainLang> {
        let main: Arc<Source> = Arc::new(Source::new(r"\input{f}"));
        let st = state();
        let mut builder: NodeTreeBuilder<PlainLang> = NodeTreeBuilder::new();
        let mut children = alloc::vec::Vec::new();
        for (source, range) in &children_spans {
            children.push(
                builder.add(
                    NodeKind::chars(Span::new(range.start, range.end)),
                    SourceSpan::new(source, range.clone()),
                    Arc::clone(&st),
                    alloc::vec![], (), (),
                ).unwrap(),
            );
        }
        let n = children.len() as u32;
        let callable = CallableData {
            callable_type: 0u32,
            name: "input".into(),
            spec: Arc::new(StdCallableSpec::default()) as Arc<dyn CallableSpec<PlainLang>>,
            arguments: ParsedArguments::empty(),
            slots: ParsedSlots::new(alloc::vec![ParsedSlot::new(
                ChildRegion::new(0..n, ContentNodes::InRegion(0..n)),
                "attached",
                role,
                (),
            )]),
            invocation_syntax: (),
        };
        let callable_id = builder.add(
            NodeKind::callable(callable),
            SourceSpan::entire(&main),
            Arc::clone(&st),
            children, (), (),
        ).unwrap();
        let root = builder.add(
            NodeKind::list(),
            SourceSpan::entire(&main),
            Arc::clone(&st),
            alloc::vec![callable_id], (), (),
        ).unwrap();
        builder.finish(root).unwrap()
    }

    #[test]
    fn attached_slot_children_are_excluded_from_the_parents_accounting() {
        // The `\input` shape: the slot's children live in the attached source —
        // excluded from the includer's children-in-source/contiguity checks,
        // with their own per-source accounting (contiguous in their source).
        let attached: Arc<Source> = Arc::new(Source::new("ab"));
        let tree = build_with_slot(
            SlotRole::Attached,
            alloc::vec![(Arc::clone(&attached), 0..1), (attached, 1..2)],
        );
        check_tree_invariants(&tree);
    }

    #[test]
    #[should_panic(expected = "attached region 2..4 not span-contiguous")]
    fn attached_region_children_must_be_contiguous_in_their_own_source() {
        let attached: Arc<Source> = Arc::new(Source::new("abc"));
        let tree = build_with_slot(
            SlotRole::Attached,
            alloc::vec![(Arc::clone(&attached), 0..1), (attached, 2..3)],
        );
        check_tree_invariants(&tree);
    }

    #[test]
    #[should_panic(expected = "attached region 2..4 spans several sources")]
    fn attached_region_children_must_share_one_source() {
        let first: Arc<Source> = Arc::new(Source::new("ab"));
        let second: Arc<Source> = Arc::new(Source::new("ab"));
        let tree = build_with_slot(
            SlotRole::Attached,
            alloc::vec![(first, 0..1), (second, 1..2)],
        );
        check_tree_invariants(&tree);
    }

    #[test]
    #[should_panic(expected = "lives in a different source")]
    fn content_slot_children_stay_under_the_parents_accounting() {
        // The same foreign-source children under a `Content` slot: the exclusion
        // is *declared* by the role, never inferred from a source change.
        let attached: Arc<Source> = Arc::new(Source::new("ab"));
        let tree = build_with_slot(
            SlotRole::Content,
            alloc::vec![(Arc::clone(&attached), 0..1), (attached, 1..2)],
        );
        check_tree_invariants(&tree);
    }

    #[test]
    fn hidden_slot_children_carry_no_byte_accounting_at_all() {
        // `Hidden` = no byte accounting ([§dd-dr:slot-roles]): a different
        // source AND a gap inside the region — no assertion fires.
        let foreign: Arc<Source> = Arc::new(Source::new("abc"));
        let tree = build_with_slot(
            SlotRole::Hidden,
            alloc::vec![(Arc::clone(&foreign), 0..1), (foreign, 2..3)],
        );
        check_tree_invariants(&tree);
    }

    #[test]
    fn wrapper_panic_carries_the_violation_detail() {
        // The panic message carries the violation's Display rendering — node + detail,
        // exactly as the non-panicking checker reports it.
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let tree = hand_tree(alloc::vec![node_data(
            NodeKind::chars(Span::new(0, 99)),
            &source,
            0..2,
            0..0
        )]);
        let violation = validate_tree(&tree).unwrap_err();
        assert_eq!(violation.node, Some(tree.make_id(0)));
        assert_eq!(
            violation.kind,
            TreeViolationKind::SpannedContentInvalid {
                what: "chars content",
                span: Span::new(0, 99),
                content_len: 2,
            }
        );
        let payload = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
            check_tree_invariants(&tree)
        }))
        .expect_err("the wrapper panics on a violated tree");
        let message = payload
            .downcast_ref::<alloc::string::String>()
            .expect("a formatted panic message");
        assert!(message.contains(&alloc::format!("{violation}")), "{message}");
    }
}