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
//! Tests of the restage driver (`techy::transform`).

// The fixtures mint node extensions through `Lang::make_node_ext` and hand the
// result to `NodeTreeBuilder::add`, the way the parser does. `Latexlike`'s
// extension type happens to be `()` today, which makes those bindings unit-valued;
// keeping them spelled out is what keeps the fixtures honest if the type changes.
#![allow(clippy::let_unit_value)]

use core::convert::Infallible;

use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;

use crate::engine::Language;
use crate::error::Recovery;
use crate::latexlike::{
    argument_specs, CallableType, Latexlike, LatexlikeDriver, MacroSpec,
};
use crate::node::{
    validate_tree, NodeId, NodeKind, NodeRef, NodeTree, SlotRole,
};
use crate::scopes::Package;
use crate::source::TextContent;
use crate::state::{Lang, ParsingState};

use super::{
    Restage, RestageContext, RestageError, RestageVisitor, RestagedArgument, RestagedSlot,
    TreeRestager,
};

/// The suite's shorthand: a default-configured [`TreeRestager`] run (most tests
/// exercise the visitor contract, not the run configuration).
fn restage<L, A, B, V>(
    tree: &NodeTree<L, A>,
    visitor: &mut V,
) -> Result<NodeTree<L, B>, RestageError<V::Error>>
where
    L: Lang,
    V: RestageVisitor<L, A, B> + ?Sized,
{
    TreeRestager::new(visitor).restage(tree)
}

/// The documented reentrant-visitor error pattern: one boxed self-referential
/// `From` impl makes every context op `?`-propagatable.
#[derive(Clone, Debug, PartialEq, Eq)]
struct OpError(Box<RestageError<OpError>>);

impl From<RestageError<OpError>> for OpError {
    fn from(error: RestageError<OpError>) -> OpError {
        OpError(Box::new(error))
    }
}

impl core::fmt::Display for OpError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "op failed: {}", self.0)
    }
}

/// Parse `input` with the plain latexlike preset (strict).
fn parse(input: &str) -> NodeTree<Latexlike> {
    let language: Language<Latexlike> = Language::new(
        LatexlikeDriver::new(Recovery::Strict),
        ParsingState::lang_initial().expect("seed state"),
    );
    let result = language.parse(input).expect("test inputs parse cleanly");
    assert!(result.diagnostics.is_empty(), "unexpected diagnostics: {:?}", result.diagnostics);
    result.tree
}

/// Parse `input` with macros `\a{…}{…}` (two mandatory brace arguments, the
/// second named "closing") and `\o[…]{…}` (optional + mandatory).
fn parse_with_macros(input: &str) -> NodeTree<Latexlike> {
    let mut package = Package::new("test-macros");
    let mut a_args = argument_specs(&["{", "{"]).unwrap();
    let second = Arc::get_mut(&mut a_args[1]).expect("fresh spec");
    second.name = Some("closing".into());
    package.insert(CallableType::Macro, "a", MacroSpec::new(a_args));
    package.insert(
        CallableType::Macro,
        "o",
        MacroSpec::new(argument_specs(&["[", "{"]).unwrap()),
    );
    let language: Language<Latexlike> = Language::new(
        LatexlikeDriver::new(Recovery::Strict),
        ParsingState::lang_initial_with_packages([package]).expect("seed state"),
    );
    let result = language.parse(input).expect("test inputs parse cleanly");
    assert!(result.diagnostics.is_empty(), "unexpected diagnostics: {:?}", result.diagnostics);
    result.tree
}

/// The origin-tracking convention's annotation type.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Origin {
    original: NodeId,
}

/// A `Descend`-everything closure visitor annotating each copy with its
/// original node (the module-docs recipe).
fn origins(
    node: NodeRef<'_, Latexlike>,
    _cx: &mut RestageContext<'_, Latexlike, (), Origin>,
) -> Result<Restage<Origin>, Infallible> {
    Ok(Restage::Descend(Origin { original: node.id() }))
}

// --- the identity pass: annotation flow -------------------------------------------------

#[test]
fn identity_restage_preserves_structure_and_mints_annotations() {
    let input = parse("a{b}c");
    let output: NodeTree<Latexlike, Origin> = restage(&input, &mut origins).unwrap();

    validate_tree(&output).unwrap();
    assert_eq!(output.node_count(), input.node_count());
    // Identity restaging preserves the breadth-first layout: nodes correspond
    // 1:1 in storage order, and every annotation names its original.
    for (old, new) in input.iter_storage_order().zip(output.iter_storage_order()) {
        assert_eq!(new.annotation().original, old.id());
        assert_eq!(new.kind().as_str(), old.kind().as_str());
        assert_eq!(new.span(), old.span());
        assert_eq!(new.child_count(), old.child_count());
    }
    // The trees are distinct layouts: ids are tagged apart.
    assert_ne!(output.root().id(), input.root().id());
}

#[test]
fn the_closure_blanket_supports_inline_closures() {
    // The `restage(&tree, &mut |node, cx| …)` spelling from the records — the
    // closure needs its parameter types spelled once (two generic parameters
    // under a higher-ranked bound), everything else infers.
    let input = parse("hello");
    let output = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              _cx: &mut RestageContext<'_, Latexlike, (), u32>| {
            Ok::<_, Infallible>(Restage::Descend(node.span().len() as u32))
        },
    )
    .unwrap();
    assert_eq!(*output.root().annotation(), 5);
}

// --- Emit: drop, replace, no-descent ----------------------------------------------------

#[test]
fn emit_empty_drops_the_subtree() {
    let input = parse("a{b}c");
    let output = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              _cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            Ok::<_, Infallible>(if node.is_group() {
                Restage::Emit(vec![])
            } else {
                Restage::Descend(())
            })
        },
    )
    .unwrap();

    validate_tree(&output).unwrap();
    let root = output.root();
    assert_eq!(root.child_count(), 2);
    assert_eq!(root.child(0).unwrap().chars(), Some("a"));
    assert_eq!(root.child(1).unwrap().chars(), Some("c"));
}

#[test]
fn emit_replaces_without_descending() {
    // Replace the whole group with a synthesized chars node (the explicit
    // make_node_ext staging recipe on the raw builder) and count visits: the
    // group's children must never be visited.
    let input = parse("x{y}z");
    let mut visited: Vec<String> = Vec::new();
    let output = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            visited.push(node.summary());
            if node.is_group() {
                let kind: NodeKind<Latexlike> =
                    NodeKind::chars(TextContent::Owned("Q".into()));
                let span = node.span().clone();
                let state = node.parsing_state().clone();
                let builder = cx.builder();
                let ext = <Latexlike as Lang>::make_node_ext(
                    &kind,
                    &span,
                    &state,
                    builder.staged_children(&[]),
                )
                .expect("mint node ext");
                let id = builder
                    .add(kind, span, state, Vec::new(), ext, ())
                    .map_err(RestageError::<Infallible>::Build)?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok::<_, RestageError<Infallible>>(Restage::Descend(()))
            }
        },
    )
    .unwrap();

    validate_tree(&output).unwrap();
    assert_eq!(output.root().child(1).unwrap().chars(), Some("Q"));
    assert_eq!(output.root().child_count(), 3);
    // Root, "x", the group, "z" — but never "y".
    assert!(visited.iter().all(|s| s != "chars(y)"), "visited: {visited:?}");
    assert_eq!(visited.len(), 4);
}

// --- error paths ------------------------------------------------------------------------

#[test]
fn dropping_the_root_is_root_not_singular() {
    let input = parse("a");
    let result = restage(
        &input,
        &mut |_node: NodeRef<'_, Latexlike>,
              _cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            Ok::<_, Infallible>(Restage::Emit(vec![]))
        },
    );
    assert!(matches!(result, Err(RestageError::RootNotSingular { count: 0 })));
}

#[test]
fn visitor_errors_ride_through_typed() {
    #[derive(Clone, Debug, PartialEq, Eq)]
    struct BadNode(NodeId);

    impl core::fmt::Display for BadNode {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            write!(f, "bad node {:?}", self.0)
        }
    }

    let input = parse("a{b}c");
    let group_id = input.root().child(1).unwrap().id();
    let result: Result<NodeTree<Latexlike, ()>, _> = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              _cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            if node.is_group() {
                Err(BadNode(node.id()))
            } else {
                Ok(Restage::Descend(()))
            }
        },
    );
    let error = result.unwrap_err();
    assert_eq!(error, RestageError::Visitor(BadNode(group_id)));
    // The uniform-Clone principle, conditionally: E: Clone ⇒ the error clones.
    let _ = error.clone();
    // The rendering carries the visitor's own error.
    assert!(error.to_string().contains(&BadNode(group_id).to_string()), "{error}");
}

#[test]
fn dropped_content_parent_is_diagnosed() {
    // \a{1}{2}: each argument's content is designated inside its group node
    // (`InChildrenOf`). Dropping a group while Descend-ing the callable leaves
    // the record unanchorable — the driver refuses with the diagnosis.
    let input = parse_with_macros(r"\a{1}{2}");
    let dropped_group = input.root().child(0).unwrap().child(0).unwrap();
    assert!(dropped_group.is_group());

    let result = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              _cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            Ok::<_, Infallible>(if node.id() == dropped_group.id() {
                Restage::Emit(vec![])
            } else {
                Restage::Descend(())
            })
        },
    );
    let error = result.unwrap_err();
    let RestageError::ContentParentDropped { callable, parent, replaced_by } = &error else {
        panic!("expected ContentParentDropped, got {error:?}");
    };
    assert_eq!(*callable, input.root().child(0).unwrap().id());
    assert_eq!(*parent, dropped_group.id());
    assert_eq!(*replaced_by, Some(0));
}

#[test]
fn emptied_region_restages_as_provided_with_empty_region() {
    // Dropping the *content* of an argument (not its group wrapper) empties the
    // region's content — the argument stays provided (absent ≠ empty).
    let input = parse_with_macros(r"\a{1}{2}");
    let output = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              _cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            Ok::<_, Infallible>(if node.chars() == Some("1") {
                Restage::Emit(vec![])
            } else {
                Restage::Descend(())
            })
        },
    )
    .unwrap();

    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();
    let arguments = callable.arguments().unwrap();
    assert!(arguments.get(0).unwrap().is_provided());
    let content = callable.argument_content_nodes(0).unwrap();
    assert!(content.is_empty());
    assert_eq!(
        callable
            .argument_content_nodes(1)
            .unwrap()
            .first()
            .unwrap()
            .chars(),
        Some("2")
    );
}

// --- structural descent: slot roles -----------------------------------------------------

/// A hand-staged callable with Content, Attached, and Hidden slots
/// (framework-style) — the fixture of the descent and slot-op tests.
fn three_slot_fixture() -> NodeTree<Latexlike> {
    use crate::latexlike::{BodyMarker, InvocationSyntaxData};
    use crate::node::{
        CallableData, ChildRegion, ContentNodes, NodeTreeBuilder, ParsedArguments,
        ParsedSlot, ParsedSlots,
    };
    use crate::source::{Source, SourceSpan};
    use crate::spec::StdCallableSpec;

    let source = Arc::new(Source::new("stub"));
    let span = || SourceSpan::new(&source, 0..4);
    let state = Arc::new(ParsingState::<Latexlike>::lang_initial().expect("seed state"));

    let mut builder: NodeTreeBuilder<Latexlike> = NodeTreeBuilder::new();
    let chars = |builder: &mut NodeTreeBuilder<Latexlike>, text: &str| {
        let kind = NodeKind::chars(TextContent::Owned(text.into()));
        let ext = <Latexlike as Lang>::make_node_ext(
            &kind,
            &span(),
            &state,
            builder.staged_children(&[]),
        )
        .expect("mint node ext");
        builder.add(kind, span(), state.clone(), Vec::new(), ext, ()).unwrap()
    };
    let content_child = chars(&mut builder, "content");
    let attached_child = chars(&mut builder, "attached");
    let hidden_child = chars(&mut builder, "hidden");

    let slot = |offset: u32, role: SlotRole| {
        ParsedSlot::new_unnamed(
            ChildRegion::new(offset..offset + 1, ContentNodes::InRegion(0..1)),
            role,
            BodyMarker::not_body(),
        )
    };
    let kind: NodeKind<Latexlike> = NodeKind::callable(CallableData {
        callable_type: CallableType::Macro,
        name: "stub".into(),
        spec: Arc::new(StdCallableSpec::default()),
        arguments: ParsedArguments::empty(),
        slots: ParsedSlots::new(vec![
            slot(0, SlotRole::Content),
            slot(1, SlotRole::Attached),
            slot(2, SlotRole::Hidden),
        ]),
        invocation_syntax: InvocationSyntaxData::Macro {
            escape_char: '\\',
            post_space: TextContent::Owned("".into()),
        },
    });
    let children = vec![content_child, attached_child, hidden_child];
    let ext = <Latexlike as Lang>::make_node_ext(
        &kind,
        &span(),
        &state,
        builder.staged_children(&children),
    )
    .expect("mint node ext");
    let root = builder.add(kind, span(), state.clone(), children, ext, ()).unwrap();
    builder.finish(root).unwrap()
}

#[test]
fn descend_visits_slot_children_of_every_role() {
    // The driver must visit slot children of all three roles uniformly.
    let input = three_slot_fixture();

    let mut seen: Vec<String> = Vec::new();
    let output = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              _cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            if let Some(text) = node.chars() {
                seen.push(text.to_string());
            }
            Ok::<_, Infallible>(Restage::Descend(()))
        },
    )
    .unwrap();

    assert_eq!(seen, ["content", "attached", "hidden"]);
    // The roles survive the restage verbatim.
    let slots = output.root().slots().unwrap();
    let roles: Vec<SlotRole> = slots.iter().map(|slot| slot.role).collect();
    assert_eq!(roles, [SlotRole::Content, SlotRole::Attached, SlotRole::Hidden]);
}

// --- region ops + bundles (M3) ----------------------------------------------------------

/// The T5 paradigm: swap the two arguments of `\a` — two `restage_argument`
/// calls plus one reordered `restage_invocation` (a reentrant trait visitor:
/// the ops re-enter `self` for the region nodes).
struct SwapArguments;

impl RestageVisitor<Latexlike, (), ()> for SwapArguments {
    type Error = OpError;

    fn restage(
        &mut self,
        node: NodeRef<'_, Latexlike>,
        cx: &mut RestageContext<'_, Latexlike, (), ()>,
    ) -> Result<Restage<()>, OpError> {
        if node.name() == Some("a") {
            let first = cx.restage_argument(node, 0, self)?;
            let second = cx.restage_argument_named(node, "closing", self)?;
            let id = cx.restage_invocation(node, vec![second, first], vec![], ())?;
            Ok(Restage::Emit(vec![id]))
        } else {
            Ok(Restage::Descend(()))
        }
    }
}

#[test]
fn argument_swap_round_trip() {
    let input = parse_with_macros(r"\a{1}{2}");
    let output = restage(&input, &mut SwapArguments).unwrap();

    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();
    assert_eq!(callable.name(), Some("a"));

    // The records swapped wholesale — content, spans, and specs travel together.
    let arguments = callable.arguments().unwrap();
    assert_eq!(arguments.len(), 2);
    assert_eq!(arguments.get(0).unwrap().name(), Some("closing"));
    assert_eq!(arguments.get(1).unwrap().name(), None);
    let first_content = callable.argument_content_nodes(0).unwrap();
    assert_eq!(first_content.first().unwrap().chars(), Some("2"));
    let second_content = callable.argument_content_nodes(1).unwrap();
    assert_eq!(second_content.first().unwrap().chars(), Some("1"));

    // Sibling spans are now out of source order — legal in transform trees.
    let group_spans: Vec<_> = callable
        .children()
        .iter()
        .map(|child| child.span().range())
        .collect();
    assert_eq!(group_spans, [5..8, 2..5]);
    // The callable's own identity is carried verbatim.
    assert_eq!(callable.span().range(), input.root().child(0).unwrap().span().range());
}

#[test]
fn absent_arguments_transfer_presence() {
    // \o's optional argument is not provided: the bundle is absent, and the
    // restaged record stays absent (absent ≠ empty).
    struct Reinvoke;
    impl RestageVisitor<Latexlike, (), ()> for Reinvoke {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.name() == Some("o") {
                let optional = cx.restage_argument(node, 0, self)?;
                assert!(!optional.is_provided());
                assert!(optional.nodes().is_empty());
                let mandatory = cx.restage_argument(node, 1, self)?;
                assert!(mandatory.is_provided());
                let id = cx.restage_invocation(node, vec![optional, mandatory], vec![], ())?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok(Restage::Descend(()))
            }
        }
    }

    let input = parse_with_macros(r"\o{x}");
    let output = restage(&input, &mut Reinvoke).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();
    let arguments = callable.arguments().unwrap();
    assert!(!arguments.get(0).unwrap().is_provided());
    assert!(arguments.get(1).unwrap().is_provided());
    assert_eq!(
        callable.argument_content_nodes(1).unwrap().first().unwrap().chars(),
        Some("x")
    );
}

#[test]
fn unwrapping_groups_via_restage_children() {
    struct UnwrapGroups;
    impl RestageVisitor<Latexlike, (), ()> for UnwrapGroups {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.is_group() {
                Ok(Restage::Emit(cx.restage_children(node, self)?))
            } else {
                Ok(Restage::Descend(()))
            }
        }
    }

    let input = parse("a{b{c}}d");
    let output = restage(&input, &mut UnwrapGroups).unwrap();
    validate_tree(&output).unwrap();
    let texts: Vec<_> = output
        .root()
        .children()
        .iter()
        .map(|child| child.chars().unwrap().to_string())
        .collect();
    assert_eq!(texts, ["a", "b", "c", "d"]);
}

#[test]
fn restage_subtree_duplicates_and_redrives() {
    // Driving the same node twice is legal: replace "x" with a fresh restage
    // of the group's subtree, while the group is also driven as itself.
    struct Duplicate {
        group: NodeId,
    }
    impl RestageVisitor<Latexlike, (), ()> for Duplicate {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.chars() == Some("x") {
                let group = node.tree().node(self.group);
                Ok(Restage::Emit(cx.restage_subtree(group, self)?))
            } else {
                Ok(Restage::Descend(()))
            }
        }
    }

    let input = parse("x{y}");
    let group = input.root().child(1).unwrap().id();
    let output = restage(&input, &mut Duplicate { group }).unwrap();
    validate_tree(&output).unwrap();
    let root = output.root();
    assert_eq!(root.child_count(), 2);
    assert!(root.child(0).unwrap().is_group());
    assert!(root.child(1).unwrap().is_group());
    assert_eq!(root.child(0).unwrap().child(0).unwrap().chars(), Some("y"));
    assert_eq!(root.child(1).unwrap().child(0).unwrap().chars(), Some("y"));
    assert_ne!(root.child(0).unwrap().id(), root.child(1).unwrap().id());
}

#[test]
fn restage_slot_carries_name_role_and_content() {
    // Restage slot 1 (Attached) of the fixture and re-invoke with just it.
    struct KeepAttached;
    impl RestageVisitor<Latexlike, (), ()> for KeepAttached {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.is_callable() {
                let slot = cx.restage_slot(node, 1, self)?;
                assert_eq!(slot.role(), SlotRole::Attached);
                assert_eq!(slot.name(), None);
                let id = cx.restage_invocation(node, vec![], vec![slot], ())?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok(Restage::Descend(()))
            }
        }
    }

    let input = three_slot_fixture();
    let output = restage(&input, &mut KeepAttached).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root();
    assert!(callable.arguments().unwrap().is_empty());
    let slots = callable.slots().unwrap();
    assert_eq!(slots.len(), 1);
    assert_eq!(slots.get(0).unwrap().role, SlotRole::Attached);
    assert_eq!(callable.child_count(), 1);
    assert_eq!(
        callable.slot_content_nodes(0).unwrap().first().unwrap().chars(),
        Some("attached")
    );
}

#[test]
fn bundle_accessors_expose_every_constructor_part() {
    // Read a restaged slot's parts back, rebuild it with one node prepended to its
    // content, and re-invoke with the rebuilt bundle — the hand-rebuild route the
    // accessors exist for.
    use crate::node::ContentNodes;

    struct PrependToAttached;
    impl RestageVisitor<Latexlike, (), ()> for PrependToAttached {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if !node.is_callable() {
                return Ok(Restage::Descend(()));
            }
            let slot = cx.restage_slot(node, 1, self)?;
            assert_eq!(slot.role(), SlotRole::Attached);
            assert_eq!(slot.content(), &ContentNodes::InRegion(0..1));
            assert_eq!(slot.nodes().len(), 1);

            let kind: NodeKind<Latexlike> = NodeKind::chars(TextContent::Owned("NEW".into()));
            let span = node.span().clone();
            let state = node.parsing_state().clone();
            let builder = cx.builder();
            let ext = <Latexlike as Lang>::make_node_ext(
                &kind,
                &span,
                &state,
                builder.staged_children(&[]),
            )
            .expect("mint node ext");
            let fresh = builder
                .add(kind, span, state, Vec::new(), ext, ())
                .map_err(RestageError::<OpError>::Build)?;

            // The region grows by one node at its front, so an in-region content
            // range grows with it.
            let content = match slot.content() {
                ContentNodes::InRegion(range) => ContentNodes::InRegion(0..range.end + 1),
                other => panic!("the fixture designates in-region content, got {other:?}"),
            };
            let mut nodes = vec![fresh];
            nodes.extend_from_slice(slot.nodes());
            // `SlotExt` is Lang-defined: `clone` stays right if it stops being `Copy`.
            #[allow(clippy::clone_on_copy)]
            let rebuilt =
                RestagedSlot::new_unnamed(slot.role(), nodes, content, slot.ext().clone());
            let id = cx.restage_invocation(node, vec![], vec![rebuilt], ())?;
            Ok(Restage::Emit(vec![id]))
        }
    }

    let input = three_slot_fixture();
    let output = restage(&input, &mut PrependToAttached).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root();
    let content = callable.slot_content_nodes(0).unwrap();
    assert_eq!(content.len(), 2);
    assert_eq!(content.get(0).unwrap().chars(), Some("NEW"));
    assert_eq!(content.get(1).unwrap().chars(), Some("attached"));
}

#[test]
fn op_misuse_is_diagnosed_not_panicked() {
    struct Misuse;
    impl RestageVisitor<Latexlike, (), ()> for Misuse {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.name() == Some("a") {
                // Unknown argument name:
                let error = cx.restage_argument_named(node, "nonsense", self).unwrap_err();
                assert!(matches!(
                    &error,
                    RestageError::UnknownArgumentName { name, .. } if name == "nonsense"
                ));
                // Argument index out of range:
                let error = cx.restage_argument(node, 7, self).unwrap_err();
                assert!(matches!(
                    error,
                    RestageError::ArgumentIndexOutOfRange { index: 7, count: 2, .. }
                ));
                // Slot index out of range (macros have no slots):
                let error = cx.restage_slot(node, 0, self).unwrap_err();
                assert!(matches!(
                    error,
                    RestageError::SlotIndexOutOfRange { index: 0, count: 0, .. }
                ));
            } else if node.is_chars() {
                // Region ops demand a callable:
                let error = cx.restage_argument(node, 0, self).unwrap_err();
                assert!(matches!(error, RestageError::NotACallable { .. }));
                let error: RestageError<OpError> =
                    cx.restage_invocation(node, vec![], vec![], ()).unwrap_err();
                assert!(matches!(error, RestageError::NotACallable { .. }));
            }
            Ok(Restage::Descend(()))
        }
    }

    let input = parse_with_macros(r"z\a{1}{2}");
    let output = restage(&input, &mut Misuse).unwrap();
    validate_tree(&output).unwrap();
}

#[test]
fn hand_built_bundles_are_first_class() {
    // The constructors are the general take-both form: build an argument bundle
    // from scratch (fresh content, InRegion designation) and re-invoke with it.
    use crate::node::ContentNodes;

    struct Rewrite;
    impl RestageVisitor<Latexlike, (), ()> for Rewrite {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.name() != Some("a") {
                return Ok(Restage::Descend(()));
            }
            let spec = Arc::clone(&node.arguments().unwrap().get(0).unwrap().spec);
            let second = cx.restage_argument(node, 1, self)?;

            // A fresh single-node region whose one node is itself the content.
            let kind: NodeKind<Latexlike> = NodeKind::chars(TextContent::Owned("NEW".into()));
            let span = node.span().clone();
            let state = node.parsing_state().clone();
            let builder = cx.builder();
            let ext = <Latexlike as Lang>::make_node_ext(
                &kind,
                &span,
                &state,
                builder.staged_children(&[]),
            )
            .expect("mint node ext");
            let fresh = builder
                .add(kind, span, state, Vec::new(), ext, ())
                .map_err(RestageError::<OpError>::Build)?;
            let first = RestagedArgument::provided(
                spec,
                vec![fresh],
                ContentNodes::InRegion(0..1),
                (),
            );
            let id = cx.restage_invocation(node, vec![first, second], vec![], ())?;
            Ok(Restage::Emit(vec![id]))
        }
    }

    let input = parse_with_macros(r"\a{1}{2}");
    let output = restage(&input, &mut Rewrite).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();
    assert_eq!(
        callable.argument_content_nodes(0).unwrap().first().unwrap().chars(),
        Some("NEW")
    );
    assert_eq!(
        callable.argument_content_nodes(1).unwrap().first().unwrap().chars(),
        Some("2")
    );
}

// --- content-swap helpers (M4) ----------------------------------------------------------

/// Stage a fresh owned-content chars node through the raw builder (the
/// explicit `make_node_ext` recipe), annotated.
fn stage_chars<B>(
    cx: &mut RestageContext<'_, Latexlike, (), B>,
    at: NodeRef<'_, Latexlike>,
    text: &str,
    annotation: B,
) -> Result<crate::node::BuildId, RestageError<OpError>>
where
    B: Clone + core::fmt::Debug + Send + Sync,
{
    let kind: NodeKind<Latexlike> = NodeKind::chars(TextContent::Owned(text.into()));
    let span = at.span().clone();
    let state = at.parsing_state().clone();
    let builder = cx.builder();
    let ext =
        <Latexlike as Lang>::make_node_ext(&kind, &span, &state, builder.staged_children(&[]))
            .expect("mint node ext");
    builder.add(kind, span, state, Vec::new(), ext, annotation).map_err(RestageError::Build)
}

#[test]
fn content_swap_keeps_wrapper_and_noise_verbatim() {
    // `\a{1} {2}`: argument 1's region is [whitespace noise, group{2}] (the
    // whitespace scanned while looking for the argument is region noise) — the
    // swap keeps both verbatim and re-anchors the designation inside the
    // group's copy.
    struct Swap;
    impl RestageVisitor<Latexlike, (), ()> for Swap {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.name() == Some("a") {
                let fresh = stage_chars(cx, node, "NEW", ())?;
                let first = cx.restage_argument(node, 0, self)?;
                let second = cx.restage_argument_with_content(node, 1, vec![fresh], ())?;
                let id = cx.restage_invocation(node, vec![first, second], vec![], ())?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok(Restage::Descend(()))
            }
        }
    }

    let input = parse_with_macros("\\a{1} {2}");
    // Sanity: the input's second region really carries leading noise.
    assert_eq!(input.root().child(0).unwrap().argument_nodes(1).unwrap().len(), 2);

    let output = restage(&input, &mut Swap).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();

    // Region shape preserved: noise chars node, then the group wrapper.
    let region = callable.argument_nodes(1).unwrap();
    assert_eq!(region.len(), 2);
    assert_eq!(region.get(0).unwrap().chars(), Some(" "));
    let group = region.get(1).unwrap();
    assert!(group.is_group());
    assert_eq!(group.group_delimiters(), Some(("{", "}")));
    // Content swapped, designation re-anchored onto the group's copy.
    let content = callable.argument_content_nodes(1).unwrap();
    assert_eq!(content.len(), 1);
    assert_eq!(content.first().unwrap().chars(), Some("NEW"));
    assert!(callable.arguments().unwrap().get(1).unwrap().is_provided());
}

#[test]
fn content_swap_reanchors_through_deep_wrappers() {
    // `\o[{deep}]{x}`: the optional argument's lone inner group protects and
    // unwraps — its content parent sits at grandchild depth. The swap copies
    // the outer `[…]` and inner `{…}` wrappers verbatim and swaps inside.
    struct Swap;
    impl RestageVisitor<Latexlike, (), ()> for Swap {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.name() == Some("o") {
                let fresh = stage_chars(cx, node, "SWAPPED", ())?;
                let optional = cx.restage_argument_with_content(node, 0, vec![fresh], ())?;
                let mandatory = cx.restage_argument(node, 1, self)?;
                let id = cx.restage_invocation(node, vec![optional, mandatory], vec![], ())?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok(Restage::Descend(()))
            }
        }
    }

    let input = parse_with_macros(r"\o[{deep}]{x}");
    // Sanity: the input's designated content parent is the inner group.
    let input_callable = input.root().child(0).unwrap();
    let inner = input_callable.argument_content_nodes(0).unwrap().first().unwrap().parent().unwrap();
    assert!(inner.is_group());
    assert_ne!(inner.id(), input_callable.id());

    let output = restage(&input, &mut Swap).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();
    let region = callable.argument_nodes(0).unwrap();
    assert_eq!(region.len(), 1);
    let outer = region.first().unwrap();
    assert!(outer.is_group());
    assert_eq!(outer.group_delimiters(), Some(("[", "]")));
    let inner = outer.child(0).unwrap();
    assert!(inner.is_group());
    assert_eq!(inner.group_delimiters(), Some(("{", "}")));
    let content = callable.argument_content_nodes(0).unwrap();
    assert_eq!(content.len(), 1);
    assert_eq!(content.first().unwrap().chars(), Some("SWAPPED"));
}

#[test]
fn content_swap_fills_an_empty_argument() {
    // `\a{}{2}`: an empty-but-provided content range anchored inside the group
    // — the swap splices at the anchored position.
    struct Fill;
    impl RestageVisitor<Latexlike, (), ()> for Fill {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.name() == Some("a") {
                let fresh = stage_chars(cx, node, "filled", ())?;
                let first = cx.restage_argument_with_content(node, 0, vec![fresh], ())?;
                let second = cx.restage_argument(node, 1, self)?;
                let id = cx.restage_invocation(node, vec![first, second], vec![], ())?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok(Restage::Descend(()))
            }
        }
    }

    let input = parse_with_macros(r"\a{}{2}");
    assert!(input.root().child(0).unwrap().argument_content_nodes(0).unwrap().is_empty());
    let output = restage(&input, &mut Fill).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();
    assert_eq!(
        callable.argument_content_nodes(0).unwrap().first().unwrap().chars(),
        Some("filled")
    );
}

#[test]
fn content_swap_on_a_slot_and_its_misuse_errors() {
    struct SwapSlot;
    impl RestageVisitor<Latexlike, (), ()> for SwapSlot {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.is_callable() {
                let fresh = stage_chars(cx, node, "swapped-slot", ())?;
                let slot = cx.restage_slot_with_content(node, 0, vec![fresh], ())?;
                assert_eq!(slot.role(), SlotRole::Content);
                let others = [
                    cx.restage_slot(node, 1, self)?,
                    cx.restage_slot(node, 2, self)?,
                ];
                let mut slots = vec![slot];
                slots.extend(others);
                let id = cx.restage_invocation(node, vec![], slots, ())?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok(Restage::Descend(()))
            }
        }
    }

    let input = three_slot_fixture();
    let output = restage(&input, &mut SwapSlot).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root();
    assert_eq!(
        callable.slot_content_nodes(0).unwrap().first().unwrap().chars(),
        Some("swapped-slot")
    );
    assert_eq!(
        callable.slot_content_nodes(1).unwrap().first().unwrap().chars(),
        Some("attached")
    );

    // Misuse: swapping content of an absent argument is refused.
    struct AbsentSwap;
    impl RestageVisitor<Latexlike, (), ()> for AbsentSwap {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, OpError> {
            if node.name() == Some("o") {
                let fresh = stage_chars(cx, node, "zzz", ())?;
                let error: RestageError<OpError> = cx
                    .restage_argument_with_content(node, 0, vec![fresh], ())
                    .unwrap_err();
                assert!(matches!(error, RestageError::ArgumentAbsent { index: 0, .. }));
            }
            Ok(Restage::Descend(()))
        }
    }
    // NOTE: the staged-but-unused `fresh` node is dropped by finish() (staged
    // nodes unreachable from the root are dropped — builder contract).
    let input = parse_with_macros(r"\o{x}");
    let output = restage(&input, &mut AbsentSwap).unwrap();
    validate_tree(&output).unwrap();
}

// --- ContentParentDropped driver matrix (review should-fix) -----------------------------

#[test]
fn multiplied_content_parent_is_diagnosed() {
    // An `Emit(vec![a, b])` replacement of a designated content parent: the
    // enclosing callable's record cannot re-anchor onto two nodes — the driver
    // refuses with the multiplied count.
    let input = parse_with_macros(r"\a{1}{2}");
    let group_id = input.root().child(0).unwrap().child(0).unwrap().id();

    let result = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            if node.id() == group_id {
                let a = stage_chars(cx, node, "a", ())?;
                let b = stage_chars(cx, node, "b", ())?;
                Ok(Restage::Emit(vec![a, b]))
            } else {
                Ok::<_, RestageError<OpError>>(Restage::Descend(()))
            }
        },
    );
    let error = result.unwrap_err();
    let RestageError::ContentParentDropped { callable, parent, replaced_by } = &error else {
        panic!("expected ContentParentDropped, got {error:?}");
    };
    assert_eq!(*callable, input.root().child(0).unwrap().id());
    assert_eq!(*parent, group_id);
    assert_eq!(*replaced_by, Some(2));
}

#[test]
fn single_node_takeover_of_a_content_parent_carries_the_designation() {
    // The `Replaced::One` verbatim arm: a single-node `Emit` takeover of a
    // content parent re-anchors the designation onto the replacement with the
    // child-offset range carried verbatim (re-validated at staging).
    use crate::latexlike::GroupType;
    use crate::node::GroupData;

    let input = parse_with_macros(r"\a{1}{2}");
    let group_id = input.root().child(0).unwrap().child(0).unwrap().id();

    let output = restage(
        &input,
        &mut |node: NodeRef<'_, Latexlike>,
              cx: &mut RestageContext<'_, Latexlike, (), ()>| {
            if node.id() == group_id {
                // Takeover: a fresh one-child group stands in for `{1}` — a
                // shape the verbatim range 0..1 stays valid against.
                let child = stage_chars(cx, node, "R", ())?;
                let kind: NodeKind<Latexlike> = NodeKind::group(GroupData {
                    group_type: Some(GroupType::Content),
                    open: TextContent::Owned("{".into()),
                    close: TextContent::Owned("}".into()),
                });
                let span = node.span().clone();
                let state = node.parsing_state().clone();
                let builder = cx.builder();
                let ext = <Latexlike as Lang>::make_node_ext(
                    &kind,
                    &span,
                    &state,
                    builder.staged_children(&[child]),
                )
                .expect("mint node ext");
                let id = builder
                    .add(kind, span, state, vec![child], ext, ())
                    .map_err(RestageError::<OpError>::Build)?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok::<_, RestageError<OpError>>(Restage::Descend(()))
            }
        },
    )
    .unwrap();

    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();
    assert!(callable.arguments().unwrap().get(0).unwrap().is_provided());
    let content = callable.argument_content_nodes(0).unwrap();
    assert_eq!(content.len(), 1);
    assert_eq!(content.first().unwrap().chars(), Some("R"));
    // The takeover group is the re-anchored content parent.
    assert_eq!(
        content.first().unwrap().parent().unwrap().group_delimiters(),
        Some(("{", "}"))
    );
    // The untouched second argument restaged normally.
    assert_eq!(
        callable.argument_content_nodes(1).unwrap().first().unwrap().chars(),
        Some("2")
    );
}

#[test]
fn content_swap_annotations_flow_explicitly() {
    // The helper's `annotation` argument lands (cloned) on every verbatim
    // wrapper/noise copy; the caller-staged content keeps its own annotations.
    struct Swap;
    impl RestageVisitor<Latexlike, (), u8> for Swap {
        type Error = OpError;
        fn restage(
            &mut self,
            node: NodeRef<'_, Latexlike>,
            cx: &mut RestageContext<'_, Latexlike, (), u8>,
        ) -> Result<Restage<u8>, OpError> {
            if node.name() == Some("a") {
                let fresh = stage_chars(cx, node, "NEW", 9)?;
                let first = cx.restage_argument(node, 0, self)?;
                let second = cx.restage_argument_with_content(node, 1, vec![fresh], 7)?;
                let id = cx.restage_invocation(node, vec![first, second], vec![], 5)?;
                Ok(Restage::Emit(vec![id]))
            } else {
                Ok(Restage::Descend(1))
            }
        }
    }

    let input = parse_with_macros("\\a{1} {2}");
    let output = restage(&input, &mut Swap).unwrap();
    validate_tree(&output).unwrap();
    let callable = output.root().child(0).unwrap();
    assert_eq!(*callable.annotation(), 5);
    let region = callable.argument_nodes(1).unwrap();
    assert_eq!(*region.get(0).unwrap().annotation(), 7); // noise copy
    assert_eq!(*region.get(1).unwrap().annotation(), 7); // group wrapper copy
    let content = callable.argument_content_nodes(1).unwrap();
    assert_eq!(*content.first().unwrap().annotation(), 9); // caller-staged
    // The visitor-driven first argument flowed through Descend(1).
    let first = callable.argument_content_nodes(0).unwrap();
    assert_eq!(*first.first().unwrap().annotation(), 1);
}

// --- the descent guard bounds the run ------------------------------------------------

#[test]
fn a_depth_limit_refuses_the_restage_of_a_deeper_tree() {
    use crate::engine::{DescentGuard, DescentLimit, StdDescentGuard, StdDescentGuardInit};

    // `a{b}c` drives three levels deep (root list → group → chars).
    let input = parse("a{b}c");
    let keep = |_node: NodeRef<'_, Latexlike>,
                _cx: &mut RestageContext<'_, Latexlike, (), ()>| {
        Ok::<_, Infallible>(Restage::Descend(()))
    };

    let mut visitor = keep;
    let error = TreeRestager::new(&mut visitor)
        .with_descent_guard_init(StdDescentGuardInit::depth_limit(2))
        .restage::<Latexlike, (), ()>(&input)
        .unwrap_err();
    // The refusal is the depth limit's own: the one a guard with that limit gives.
    let mut guard = StdDescentGuard::init(&StdDescentGuardInit::depth_limit(2));
    let refusal = loop {
        if let Err(refusal) = guard.try_enter() {
            break refusal;
        }
    };
    assert!(matches!(
        &error,
        RestageError::DescentLimitExceeded { detail, limit }
            if *detail == refusal.detail && *limit == DescentLimit::Depth { levels: 2 }
    ));

    // A limit the tree fits under restages it whole.
    let mut visitor = keep;
    let output: NodeTree<Latexlike, ()> = TreeRestager::new(&mut visitor)
        .with_descent_guard_init(StdDescentGuardInit::depth_limit(3))
        .restage(&input)
        .unwrap();
    assert_eq!(output.node_count(), input.node_count());
}

#[test]
fn the_unconfigured_default_warns_the_visitor_once_then_refuses() {
    use crate::node::GroupData;
    use crate::source::{Source, SourceSpan};

    // A hand-built chain of nested groups, deeper than any parse could stage.
    let source = alloc::sync::Arc::new(Source::new("stub"));
    let span = || SourceSpan::new(&source, 0..4);
    let state =
        alloc::sync::Arc::new(ParsingState::<Latexlike>::lang_initial().expect("seed state"));
    let mut builder: crate::node::NodeTreeBuilder<Latexlike> =
        crate::node::NodeTreeBuilder::new();
    let kind = NodeKind::chars(TextContent::Owned("x".into()));
    let ext =
        <Latexlike as Lang>::make_node_ext(&kind, &span(), &state, builder.staged_children(&[]))
            .expect("mint node ext");
    let mut node = builder.add(kind, span(), state.clone(), Vec::new(), ext, ()).unwrap();
    for _ in 0..200_000 {
        let kind: NodeKind<Latexlike> = NodeKind::group(GroupData::untyped("{", "}"));
        let children = vec![node];
        let ext = <Latexlike as Lang>::make_node_ext(
            &kind,
            &span(),
            &state,
            builder.staged_children(&children),
        )
        .expect("mint node ext");
        node = builder.add(kind, span(), state.clone(), children, ext, ()).unwrap();
    }
    let deep = builder.finish(node).unwrap();

    /// Restages everything unchanged; counts the guard warnings it observes.
    #[derive(Default)]
    struct Meter {
        warnings: usize,
    }
    impl RestageVisitor<Latexlike, (), ()> for Meter {
        type Error = Infallible;

        fn restage(
            &mut self,
            _node: NodeRef<'_, Latexlike>,
            _cx: &mut RestageContext<'_, Latexlike, (), ()>,
        ) -> Result<Restage<()>, Infallible> {
            Ok(Restage::Descend(()))
        }

        fn observe_descent_warning(&mut self, warning: crate::engine::DescentWarning) {
            // The warning names the limit that applies: the built-in default budget.
            let default = crate::engine::DescentLimit::DefaultStackBudget {
                bytes: crate::engine::StdDescentGuard::DEFAULT_STACK_BUDGET,
            };
            assert_eq!(warning.limit, default);
            self.warnings += 1;
        }
    }

    let mut meter = Meter::default();
    let error = TreeRestager::new(&mut meter).restage::<Latexlike, (), ()>(&deep).unwrap_err();
    let default = crate::engine::DescentLimit::DefaultStackBudget {
        bytes: crate::engine::StdDescentGuard::DEFAULT_STACK_BUDGET,
    };
    assert!(matches!(
        &error,
        RestageError::DescentLimitExceeded { limit, .. } if *limit == default
    ));
    assert_eq!(meter.warnings, 1, "the half-budget warning latches once");
}