badness 0.14.0

A language server, formatter, and linter for LaTeX
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
//! The expl3 call-site model: **argspec arity** for expl3 function names, and
//! the **statement segmentation** built on it.
//!
//! Two halves, both semantics layered on the syntax tree (like
//! [`define`](super::define)'s definition scan): [`expl3_slots`] derives
//! per-slot arity from the letters after the final `:` in `\cs_new:Npn`,
//! `\tl_if_empty:nTF`, …, and [`segment_expl_statements`] applies it to an
//! in-region element stream to produce the statement model the formatter's
//! expl3 layout consumes. Neither builds `Ir` or touches layout policy — a
//! wrong answer here can only produce ugly formatting downstream, never a
//! wrong tree or a lost byte.
//!
//! Like [`xparse`](super::xparse), the argspec is a spec mini-language that is
//! *parsed*, never executed (AGENTS.md decision #1): each letter names the
//! **shape** an argument takes at the call site, a bounded, purely lexical
//! fact — squarely decision #2's "the semantic layer assigns arity". No
//! signature database is involved: the name string alone carries the spec, so
//! there is nothing to curate and nothing to drift. Only meaningful inside an
//! expl3 region, where `:`/`_` are catcode-11 and the whole name lexes as one
//! `CONTROL_WORD` — callers of the segmentation guarantee the stream is
//! in-region (out-of-region, colon names lex split and everything degrades to
//! the fallback).
//!
//! The letter-by-letter model (interface3's argument specifiers):
//!
//! - `N`, `V` → [`Expl3Slot::SingleToken`]: one token, typically a control
//!   sequence (`V` differs from `N` only in *expansion*, not call-site shape).
//! - `n`, `c`, `v`, `o`, `x`, `e`, `f` → [`Expl3Slot::Group`]: one braced
//!   `{…}` group (again, the letters differ only in how the material is
//!   processed, which we never model).
//! - `T`, `F` → [`Expl3Slot::Branch`]: a braced conditional branch. Sanctioned
//!   only as a *trailing* run — in a standard argspec `T`/`F` are always last,
//!   so a mid-spec `T`/`F` is treated as unknown.
//! - `p` → [`Expl3Slot::ParameterText`]: TeX parameter text (`#1#2…`), which
//!   has no fixed token count but a static *end*: TeX's own rule that the
//!   parameter text runs to the first explicit `{`. The consumer scans by that
//!   shape.
//! - `w` (arbitrary delimiters) and `D` (kernel primitive) have no lexically
//!   derivable call-site shape → the whole name is unrecognized (`None`), as is
//!   any unknown letter (including one added to expl3 after this list was
//!   written — new letters degrade to unrecognized, never to a wrong arity).

use std::collections::VecDeque;

use crate::ast::command_name;
use crate::parser::lexer::expl_toggle;
use crate::syntax::{SyntaxElement, SyntaxKind, SyntaxNode, is_collapsible_trivia, is_param_digit};

/// The call-site shape of one expl3 argument slot, derived from an argspec letter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Expl3Slot {
    /// `N`, `V`: exactly one token, typically a control sequence.
    SingleToken,
    /// `n`, `c`, `v`, `o`, `x`, `e`, `f`: one braced `{…}` group.
    Group,
    /// `T`, `F`: a braced conditional branch (a [`Group`](Expl3Slot::Group) a
    /// consumer may lay out specially).
    Branch,
    /// `p`: TeX parameter text — the tokens up to (not including) the next
    /// explicit `{`.
    ParameterText,
}

/// The argument slots of an expl3 function name, read from its argspec suffix
/// (the substring after the *final* `:`), or `None` when the name has no
/// derivable call-site arity.
///
/// `Some` iff the name contains a `:` and every suffix letter is a fixed-shape
/// letter per the module docs; an empty suffix (`\scan_stop:`, `\group_end:`)
/// is `Some(vec![])` — a recognized zero-argument call. `None` for a colonless
/// name (`\def`, `\@ifpackageloaded`), or a spec containing `w`, `D`, a
/// mid-spec `T`/`F`, or any unknown letter.
pub fn expl3_slots(name: &str) -> Option<Vec<Expl3Slot>> {
    let argspec = name.rsplit_once(':')?.1;
    let chars: Vec<char> = argspec.chars().collect();
    let branches = chars
        .iter()
        .rev()
        .take_while(|c| matches!(c, 'T' | 'F'))
        .count();
    let mut slots = Vec::with_capacity(chars.len());
    for c in &chars[..chars.len() - branches] {
        // `T`/`F` never match here, so a *mid*-spec `T`/`F` (nonstandard) falls
        // through to unknown.
        slots.push(match c {
            'N' | 'V' => Expl3Slot::SingleToken,
            'n' | 'c' | 'v' | 'o' | 'x' | 'e' | 'f' => Expl3Slot::Group,
            'p' => Expl3Slot::ParameterText,
            _ => return None,
        });
    }
    slots.extend(std::iter::repeat_n(Expl3Slot::Branch, branches));
    Some(slots)
}

/// The number of trailing `T`/`F` branch arguments of an expl3 conditional, read
/// from the command *name*'s argspec (the substring after the final `:`).
/// `\tl_if_empty:nTF` → `Some(2)`, `\bool_if:nT`/`:nF` → `Some(1)`; `None` for any
/// name without a `:`-argspec ending in `T`/`F` — a non-conditional expl3 function
/// (`\seq_new:N`), or a LaTeX2e command with no colon (`\@ifpackageloaded`). In an
/// expl3 argspec `T`/`F` denote *only* the true/false branch slots, so a trailing
/// `T`/`F` run is exactly the branch count.
///
/// Deliberately **not** derived from [`expl3_slots`]: this counts the raw
/// trailing run, so a name whose *earlier* letters make the arity unrecognized
/// (a hypothetical `:wTF` shape) still reports its branches — the conditional
/// layout keys on the branches alone and must not regress when the full arity
/// model bows out.
pub fn conditional_branches(name: &str) -> Option<usize> {
    let argspec = name.rsplit_once(':')?.1;
    let n = argspec
        .chars()
        .rev()
        .take_while(|c| *c == 'T' || *c == 'F')
        .count();
    (n > 0).then_some(n)
}

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

    #[test]
    fn slots_read_from_name_suffix() {
        assert_eq!(
            expl3_slots("cs_new:Npn"),
            Some(vec![SingleToken, ParameterText, Group])
        );
        assert_eq!(
            expl3_slots("str_if_eq:nnTF"),
            Some(vec![Group, Group, Branch, Branch])
        );
        assert_eq!(
            expl3_slots("prop_get:NnNTF"),
            Some(vec![SingleToken, Group, SingleToken, Branch, Branch])
        );
        assert_eq!(expl3_slots("tl_set:Nn"), Some(vec![SingleToken, Group]));
        assert_eq!(
            expl3_slots("exp_args:NNo"),
            Some(vec![SingleToken, SingleToken, Group])
        );
        assert_eq!(expl3_slots("tl_set:Nv"), Some(vec![SingleToken, Group]));
        assert_eq!(expl3_slots("use:c"), Some(vec![Group]));
        assert_eq!(expl3_slots("tl_set:Nx"), Some(vec![SingleToken, Group]));
    }

    #[test]
    fn zero_argument_names_are_recognized() {
        assert_eq!(expl3_slots("scan_stop:"), Some(vec![]));
        assert_eq!(expl3_slots("group_begin:"), Some(vec![]));
        assert_eq!(expl3_slots("prg_return_true:"), Some(vec![]));
    }

    #[test]
    fn underivable_specs_are_unrecognized() {
        // `w`: arbitrary delimiters; `D`: kernel primitive of arbitrary arity.
        assert_eq!(expl3_slots("use_none_delimit_by_q_stop:w"), None);
        assert_eq!(expl3_slots("exp_after:wN"), None);
        assert_eq!(expl3_slots("tex_relax:D"), None);
        // Mid-spec `T`/`F` is nonstandard, so unknown.
        assert_eq!(expl3_slots("odd:TnF"), None);
        // Unknown letter anywhere bows out entirely — never a partial arity.
        assert_eq!(expl3_slots("odd:nZn"), None);
    }

    #[test]
    fn colonless_names_are_unrecognized() {
        assert_eq!(expl3_slots("def"), None);
        assert_eq!(expl3_slots("@ifpackageloaded"), None);
        assert_eq!(expl3_slots("IfBooleanTF"), None);
        assert_eq!(expl3_slots("l_tmpa_tl"), None);
    }

    #[test]
    fn exp_internal_drivers() {
        // The `\::n` expansion drivers: name is empty, spec is real. Their
        // runtime protocol is nothing like a call site, but the greedy shape
        // rules in the consumer keep them on the fallback path anyway; the
        // lexical read here is just the suffix.
        assert_eq!(expl3_slots("::n"), Some(vec![Group]));
        assert_eq!(expl3_slots(":::"), Some(vec![]));
    }

    #[test]
    fn conditional_branches_read_from_name_suffix() {
        // Trailing `T`/`F` run in the argspec (after the final `:`) is the branch
        // count; non-conditionals and colonless 2e names are `None`.
        assert_eq!(conditional_branches("tl_if_empty:nTF"), Some(2));
        assert_eq!(conditional_branches("bool_if:nT"), Some(1));
        assert_eq!(conditional_branches("bool_if:nF"), Some(1));
        assert_eq!(conditional_branches("str_if_eq:nnTF"), Some(2));
        assert_eq!(conditional_branches("int_compare:nNnTF"), Some(2));
        assert_eq!(conditional_branches("seq_map_inline:Nn"), None);
        assert_eq!(conditional_branches("prg_return_true:"), None);
        assert_eq!(conditional_branches("tl_new:N"), None);
        // A LaTeX2e conditional has no `:`-argspec, so it is never matched (issue
        // #94's `\@ifpackageloaded` stays on the width path).
        assert_eq!(conditional_branches("@ifpackageloaded"), None);
        assert_eq!(conditional_branches("IfBooleanTF"), None);
    }

    #[test]
    fn branches_survive_underivable_arity() {
        // The documented asymmetry: arity bows out, branch count must not.
        assert_eq!(expl3_slots("odd_if:wTF"), None);
        assert_eq!(conditional_branches("odd_if:wTF"), Some(2));
    }
}

// --- Statement segmentation -------------------------------------------------
//
// Structural statement segmentation for expl3 code — the S4 mechanism.
//
// [`segment_expl_statements`] walks a stream of in-region sibling elements (a
// paragraph run or a brace-group body) and decides, for every gap between
// elements, whether a statement boundary sits there. The layout loop
// (`lower_expl_code`) then commits logical lines where the map says, instead
// of where the *author's* newlines fell — retiring the unsafe
// newline-vs-space trivia read (the root of the K&R↔Allman idempotency
// family; see `formatter.md`, § Trivia-invariant layout).
//
// A statement is a **call unit**: a head `COMMAND` whose name has a derivable
// argspec arity ([`expl3_slots`]) plus the elements its slots consume.
// Consumption is a pure shape scan — no `Ir` is built here — over two sources
// in order: the head's own greedily-attached children (the parser attaches
// every trailing `{…}` regardless of arity, decision #8), then the following
// siblings. Greedy attachment routinely gives an argument to the *wrong
// owner* (`\cs_new:Nn \foo:n {body}` attaches `{body}` to `\foo:n`); when a
// `COMMAND` node satisfies a single-token slot, its own attached children are
// *peeled* back onto the front of the scan queue so they can satisfy the
// outer head's remaining slots. Only the head's argspec ever drives
// consumption — an argument's own argspec is inert data, exactly as TeX
// grabs it.
//
// The trivia the scan may read is confined to *preserved* predicates:
// - a **blank line** (a gap of two or more newlines) ends the unit where it
//   stands — the partial unit commits as-is, pass-stably, because blank-line
//   presence is preserved by the formatter;
// - a **comment** sharing a line with consumed material is transparent to
//   consumption (the layout loop makes it end its physical line; the unit
//   continues), while an **own-line** comment mid-unit ends the unit where it
//   stands exactly like a blank line — its flanking newlines bound the gap
//   (`advance` counts them across the skipped comment), so the partial unit
//   commits pass-stably. When the comment rides *inside* a greedily-attached
//   sibling, the committed unit still carries that sibling whole (boundaries
//   never split a node), so the call's text stays together anyway. A comment
//   trailing a *complete* unit is pulled into the statement so it stays on
//   the call's line. Comment presence and own-line-ness are preserved
//   predicates;
// - a lone-newline-vs-space gap is **never** read on the structural path.
//
// Anything the shape scan cannot resolve — an unrecognized head (no `:`
// suffix, or a `w`/`D`/unknown letter), a slot facing the wrong shape, a
// docstrip `GUARD` mid-unit (guarded alternative bodies make arity lie,
// issue #78), or the stream ending mid-unit — degrades that statement to the
// **fallback**: the authored physical line is the statement, exactly the old
// `SplitAtNewlines` behavior demoted to a per-line escape hatch (Tier 2; see
// `formatter.md`, § Known violations). Recognition is re-attempted at every
// statement start, so recognized and fallback statements interleave
// deterministically; a recognized head *mid*-fallback-line is never split
// out.

/// The statement-boundary map for one element stream: `boundary_after(i)` says
/// a statement ends in the gap after element `i`. Boundaries sit on whole
/// top-level siblings — a boundary never splits a CST node, so anything the
/// greedy parser over-attached to a consumed sibling rides along in its
/// statement.
pub struct StatementMap {
    boundary_after: Vec<bool>,
    glue_before: Vec<bool>,
    glued: Vec<bool>,
    fallback: Vec<bool>,
}

impl StatementMap {
    /// Whether a statement boundary sits in the gap after element `idx`.
    pub fn boundary_after(&self, idx: usize) -> bool {
        self.boundary_after.get(idx).copied().unwrap_or(false)
    }

    /// Whether the gap *before* element `idx` must render unbreakable. Set for
    /// a recognized-head `COMMAND` sitting mid-way through a fallback
    /// statement: a width wrap at that gap would start a printed line with the
    /// recognized head, which the next pass segments as its own statement
    /// mid-way through this one and the passes disagree (`l3fp-trig.dtx`'s
    /// `\@@_sep:`-delimited protocols, `xo-or.dtx`'s `=~ \exp_not:c {…}\space`
    /// trace lines). Every other fallback gap stays breakable: a printed
    /// continuation line starting with anything unrecognized re-segments to
    /// exactly that line and renders to itself, the fallback's fixed point.
    pub fn glue_before(&self, idx: usize) -> bool {
        self.glue_before.get(idx).copied().unwrap_or(false)
    }

    /// Whether element `idx` belongs to a recognized statement that absorbed
    /// trailing same-line material ([`absorb_trailing_junk`]) — a call unit
    /// followed by unrecognized tokens or a comment on its authored line
    /// (xparse's `\bool_if:NTF … { \cs_set:cpn } … ##1 \q_@@ …` definition
    /// trickery). Such a statement renders with every top-level gap
    /// unbreakable: its junk extent is newline-keyed (the fallback's Tier-2
    /// residue), so a width wrap moving material across a line boundary would
    /// change the extent — and with it the trailing-command glue decision —
    /// on the next pass. All-hard gaps preserve the authored line shape
    /// (node-internal layout still breaks freely and re-reads node-internal),
    /// which is a fixed point by construction.
    pub fn is_glued(&self, idx: usize) -> bool {
        self.glued.get(idx).copied().unwrap_or(false)
    }

    /// Whether element `idx` belongs to a fallback statement. A fallback line
    /// commits as a plain *greedy* fill, never the sticky fill structural
    /// statements use: greedy packing is self-fulfilling (each printed line
    /// re-segments to a fallback statement that re-fills to exactly itself),
    /// while a sticky cascade forces atoms that would fit onto their own
    /// broken lines — a shape the next pass's shorter per-line statements
    /// do not reproduce.
    pub fn is_fallback(&self, idx: usize) -> bool {
        self.fallback.get(idx).copied().unwrap_or(false)
    }
}

/// Segment an in-region element stream into statements. See the module docs
/// for the model; the caller guarantees the stream is inside an expl3 region
/// (so `:`/`_` were letters and names carry their argspec suffix).
pub fn segment_expl_statements(elements: &[SyntaxElement]) -> StatementMap {
    let mut boundary_after = vec![false; elements.len()];
    let mut glue_before = vec![false; elements.len()];
    let mut glued = vec![false; elements.len()];
    let mut fallback = vec![false; elements.len()];
    let mut i = 0;
    while i < elements.len() {
        match &elements[i] {
            SyntaxElement::Token(t) if is_collapsible_trivia(t.kind()) => i += 1,
            // A comment, guard, or doc margin between statements ends at its
            // newline exactly as today (each is line-structured in the source);
            // the boundary keeps the next statement off its line. Comment
            // presence/own-line-ness and guard/margin column-0 are preserved
            // predicates, so the read is sanctioned.
            SyntaxElement::Token(t)
                if matches!(
                    t.kind(),
                    SyntaxKind::COMMENT | SyntaxKind::GUARD | SyntaxKind::DOC_MARGIN
                ) =>
            {
                if followed_by_newline(elements, i) {
                    boundary_after[i] = true;
                }
                i += 1;
            }
            SyntaxElement::Node(n) if n.kind() == SyntaxKind::COMMAND => {
                // A region toggle (`\ExplSyntaxOn`, `\ProvidesExplPackage`, …)
                // is colonless but in the shared toggle name set and takes no
                // trailing call-site material beyond its greedily-attached
                // groups: a recognized zero-arity unit. Without this, every
                // region's opening line would stay a newline-keyed fallback
                // statement and strict trivia-invariance could never hold for
                // any expl3 stream.
                let slots = if node_is_expl_toggle(n) {
                    Some(Vec::new())
                } else {
                    command_name(n).and_then(|name| expl3_slots(&name))
                };
                match slots.and_then(|slots| consume_unit(elements, i, &slots)) {
                    Some(end) => {
                        let full = absorb_trailing_junk(elements, end);
                        if full > end {
                            glued[i..=full].fill(true);
                        }
                        boundary_after[full] = true;
                        i = full + 1;
                    }
                    None => {
                        i = fallback_line(
                            elements,
                            i,
                            &mut boundary_after,
                            &mut glue_before,
                            &mut fallback,
                        )
                    }
                }
            }
            _ => {
                i = fallback_line(
                    elements,
                    i,
                    &mut boundary_after,
                    &mut glue_before,
                    &mut fallback,
                )
            }
        }
    }
    StatementMap {
        boundary_after,
        glue_before,
        glued,
        fallback,
    }
}

/// Whether a `COMMAND`'s name token is one of the shared expl3 region-toggle
/// spellings (`parser::lexer::expl_toggle`).
fn node_is_expl_toggle(node: &SyntaxNode) -> bool {
    node.children_with_tokens()
        .filter_map(|el| el.into_token())
        .find(|t| t.kind() == SyntaxKind::CONTROL_WORD)
        .is_some_and(|t| expl_toggle(t.text()).is_some())
}

/// Whether only inline whitespace separates element `idx` from the next
/// newline (or the stream end) — i.e. the element ends its physical line.
fn followed_by_newline(elements: &[SyntaxElement], idx: usize) -> bool {
    for element in &elements[idx + 1..] {
        match element {
            SyntaxElement::Token(t) if t.kind() == SyntaxKind::WHITESPACE => {}
            SyntaxElement::Token(t) if t.kind() == SyntaxKind::NEWLINE => return true,
            _ => return false,
        }
    }
    true
}

/// The fallback: the statement is the authored physical line, verbatim the old
/// `SplitAtNewlines` rule demoted to a per-statement escape hatch. Marks the
/// boundary after the line's last non-trivia element and returns the index to
/// resume the outer walk from.
fn fallback_line(
    elements: &[SyntaxElement],
    start: usize,
    boundary_after: &mut [bool],
    glue_before: &mut [bool],
    fallback: &mut [bool],
) -> usize {
    let mut last = start;
    let mut j = start;
    while j < elements.len() {
        match &elements[j] {
            SyntaxElement::Token(t) if is_collapsible_trivia(t.kind()) => {
                if t.kind() == SyntaxKind::NEWLINE {
                    boundary_after[last] = true;
                    fallback[start..=last].fill(true);
                    return j;
                }
                j += 1;
            }
            element => {
                // A recognized head mid-line must never start a printed
                // continuation line (see [`StatementMap::glue_before`]).
                if j > start
                    && let SyntaxElement::Node(n) = element
                    && n.kind() == SyntaxKind::COMMAND
                    && (node_is_expl_toggle(n)
                        || command_name(n).is_some_and(|name| expl3_slots(&name).is_some()))
                {
                    glue_before[j] = true;
                }
                last = j;
                j += 1;
            }
        }
    }
    boundary_after[last] = true;
    fallback[start..=last].fill(true);
    elements.len()
}

/// Extend a completed unit over trailing same-line *junk*: unrecognized
/// material — punctuation and words (`\int_use:N \c@… , %mc-num`'s comma),
/// unrecognized command tokens, a trailing comment — that the author wrote as
/// part of the call's line. The scan never crosses a newline (junk on a later
/// line stays its own fallback statement, and a recognized head is never
/// pulled apart from fallback material it shares a line with) and stops at
/// the next recognized head or toggle (the next call), a `{…}` group (a
/// statement-leading block keeps its continuation-hang treatment), or a guard
/// or doc margin (line-structured). This same-line read is part of the
/// fallback's Tier-2 residue, not the structural model; a comment stays
/// sanctioned either way (own-line-ness is a preserved predicate).
fn absorb_trailing_junk(elements: &[SyntaxElement], end: usize) -> usize {
    let mut end = end;
    let mut j = end + 1;
    while j < elements.len() {
        match &elements[j] {
            SyntaxElement::Token(t) if is_collapsible_trivia(t.kind()) => {
                if t.kind() == SyntaxKind::NEWLINE {
                    break;
                }
                j += 1;
            }
            SyntaxElement::Token(t) if t.kind() == SyntaxKind::COMMENT => {
                end = j;
                break;
            }
            SyntaxElement::Token(t)
                if matches!(t.kind(), SyntaxKind::GUARD | SyntaxKind::DOC_MARGIN) =>
            {
                break;
            }
            SyntaxElement::Node(n) if n.kind() == SyntaxKind::GROUP => break,
            SyntaxElement::Node(n)
                if n.kind() == SyntaxKind::COMMAND
                    && (node_is_expl_toggle(n)
                        || command_name(n).is_some_and(|name| expl3_slots(&name).is_some())) =>
            {
                break;
            }
            _ => {
                end = j;
                j += 1;
            }
        }
    }
    end
}

/// Why slot consumption stopped early.
enum Stop {
    /// A blank line: the unit ends here and the partial statement commits
    /// as-is (blank-line presence is a preserved predicate, so pass-stable).
    End,
    /// The shape scan cannot resolve the unit — degrade to [`fallback_line`].
    Abort,
}

/// Consume `slots` for the head at `head_idx`, returning the index of the last
/// sibling element the unit spans (the head itself for a zero-arity or
/// entirely head-internal unit), or `None` to degrade to the fallback.
fn consume_unit(elements: &[SyntaxElement], head_idx: usize, slots: &[Expl3Slot]) -> Option<usize> {
    let head = elements[head_idx].as_node()?;
    let mut cur = UnitCursor::new(elements, head_idx, head);
    for slot in slots {
        let took = match slot {
            Expl3Slot::SingleToken => cur.take_single_token(),
            Expl3Slot::Group | Expl3Slot::Branch => cur.take_group(),
            Expl3Slot::ParameterText => cur.take_parameter_text(),
        };
        match took {
            Ok(()) => {}
            Err(Stop::End) => break,
            Err(Stop::Abort) => return None,
        }
    }
    Some(cur.last_sib)
}

/// The consumption cursor: candidates come from the peel **queue** first (an
/// already-consumed `COMMAND`'s attached children), then from the sibling
/// stream. Trivia, comments, and `~` are skipped in place (a `~` is a space
/// token TeX skips before an undelimited argument, so it can never satisfy a
/// slot — it stays in the extent for the layout loop's tilde arm).
struct UnitCursor<'a> {
    elements: &'a [SyntaxElement],
    queue: VecDeque<SyntaxElement>,
    /// Next sibling index to pull from.
    sib: usize,
    /// Last sibling index consumed into the unit — the unit's extent.
    last_sib: usize,
    /// A peeked candidate not yet consumed; the index is its sibling position
    /// when it came from the sibling stream (`None` for queue candidates).
    peeked: Option<(SyntaxElement, Option<usize>)>,
}

impl<'a> UnitCursor<'a> {
    fn new(elements: &'a [SyntaxElement], head_idx: usize, head: &SyntaxNode) -> Self {
        let mut cur = UnitCursor {
            elements,
            queue: VecDeque::new(),
            sib: head_idx + 1,
            last_sib: head_idx,
            peeked: None,
        };
        cur.queue_children_after_name(head, false);
        cur
    }

    /// Push `node`'s children after its name token onto the queue — at the
    /// back when seeding from the head, at the **front** when peeling an
    /// argument (its children must be scanned before later siblings).
    fn queue_children_after_name(&mut self, node: &SyntaxNode, front: bool) {
        let mut seen_name = false;
        let mut after: Vec<SyntaxElement> = Vec::new();
        for child in node.children_with_tokens() {
            if seen_name {
                after.push(child);
            } else if matches!(
                child.kind(),
                SyntaxKind::CONTROL_WORD | SyntaxKind::CONTROL_SYMBOL
            ) {
                seen_name = true;
            }
        }
        if front {
            for el in after.into_iter().rev() {
                self.queue.push_front(el);
            }
        } else {
            self.queue.extend(after);
        }
    }

    /// The next slot candidate, without consuming it.
    fn peek(&mut self) -> Result<&SyntaxElement, Stop> {
        if self.peeked.is_none() {
            self.peeked = Some(self.advance()?);
        }
        Ok(&self.peeked.as_ref().expect("just filled").0)
    }

    /// Consume the next slot candidate, extending the unit over it.
    fn bump(&mut self) -> Result<SyntaxElement, Stop> {
        let (el, sib_idx) = match self.peeked.take() {
            Some(peeked) => peeked,
            None => self.advance()?,
        };
        if let Some(idx) = sib_idx {
            self.last_sib = idx;
        }
        Ok(el)
    }

    /// Scan forward to the next candidate, skipping inline trivia, comments,
    /// and `~`. A blank-line gap is [`Stop::End`]; a guard or doc margin
    /// mid-unit, or the stream running out, is [`Stop::Abort`].
    fn advance(&mut self) -> Result<(SyntaxElement, Option<usize>), Stop> {
        let mut gap_newlines = 0usize;
        loop {
            let (el, sib_idx) = if let Some(el) = self.queue.pop_front() {
                (el, None)
            } else {
                let Some(el) = self.elements.get(self.sib) else {
                    return Err(Stop::Abort);
                };
                // A blank line must end the unit *before* it is crossed, so
                // peek the newline count without consuming past it.
                if let SyntaxElement::Token(t) = el
                    && t.kind() == SyntaxKind::NEWLINE
                    && gap_newlines >= 1
                {
                    return Err(Stop::End);
                }
                let idx = self.sib;
                self.sib += 1;
                (el.clone(), Some(idx))
            };
            match &el {
                SyntaxElement::Token(t) if is_collapsible_trivia(t.kind()) => {
                    if t.kind() == SyntaxKind::NEWLINE {
                        gap_newlines += 1;
                        if gap_newlines >= 2 {
                            return Err(Stop::End);
                        }
                    }
                }
                SyntaxElement::Token(t) if t.kind() == SyntaxKind::COMMENT => {}
                SyntaxElement::Token(t) if t.kind() == SyntaxKind::TILDE => {}
                SyntaxElement::Token(t)
                    if matches!(t.kind(), SyntaxKind::GUARD | SyntaxKind::DOC_MARGIN) =>
                {
                    return Err(Stop::Abort);
                }
                _ => return Ok((el, sib_idx)),
            }
        }
    }

    /// An `N`/`V` slot: one token — a control sequence, a `#`-parameter, a
    /// braced group (TeX-faithful: braces around an `N` argument are grabbed
    /// whole; `N` vs `n` is convention, not matching behavior), or a `COMMAND`
    /// node whose *name* satisfies the slot and whose greedily-attached
    /// children are peeled back for the head's remaining slots.
    fn take_single_token(&mut self) -> Result<(), Stop> {
        let el = self.bump()?;
        match &el {
            SyntaxElement::Token(t)
                if matches!(
                    t.kind(),
                    SyntaxKind::CONTROL_WORD | SyntaxKind::CONTROL_SYMBOL
                ) =>
            {
                Ok(())
            }
            SyntaxElement::Token(t) if t.kind() == SyntaxKind::HASH => {
                // `#1` (or `##1` in a nested definition): hash(es) plus one
                // parameter digit read as one parameter token.
                loop {
                    let next = self.bump()?;
                    match &next {
                        SyntaxElement::Token(t) if t.kind() == SyntaxKind::HASH => {}
                        SyntaxElement::Token(t)
                            if t.kind() == SyntaxKind::WORD && is_param_digit(t) =>
                        {
                            return Ok(());
                        }
                        _ => return Err(Stop::Abort),
                    }
                }
            }
            SyntaxElement::Node(n) if n.kind() == SyntaxKind::COMMAND => {
                self.queue_children_after_name(n, true);
                Ok(())
            }
            SyntaxElement::Node(n) if n.kind() == SyntaxKind::GROUP => Ok(()),
            _ => Err(Stop::Abort),
        }
    }

    /// An `n`-family or `T`/`F` slot: exactly a braced group. A bare token is
    /// legal TeX for an undelimited argument, but accepting it would let
    /// sloppy shapes (and the `\::n` expansion-driver protocol) swallow the
    /// next statement's head — those stay on the fallback path instead.
    fn take_group(&mut self) -> Result<(), Stop> {
        let el = self.bump()?;
        match &el {
            SyntaxElement::Node(n) if n.kind() == SyntaxKind::GROUP => Ok(()),
            _ => Err(Stop::Abort),
        }
    }

    /// A `p` slot: TeX parameter text — everything up to (not including) the
    /// first explicit `{`, which is left for the following slot. Tokens and
    /// `[…]` are parameter text; a control sequence delimiting the text
    /// (`#1 \q_stop {body}`) has its own over-attached children peeled, so the
    /// terminating group is found wherever greedy attachment put it. The
    /// `#{`-terminated form works out to the same rule (the `{` opens the
    /// replacement text).
    fn take_parameter_text(&mut self) -> Result<(), Stop> {
        loop {
            if let SyntaxElement::Node(n) = self.peek()?
                && n.kind() == SyntaxKind::GROUP
            {
                return Ok(());
            }
            let el = self.bump()?;
            match &el {
                SyntaxElement::Token(_) => {}
                SyntaxElement::Node(n) if n.kind() == SyntaxKind::COMMAND => {
                    self.queue_children_after_name(n, true);
                }
                SyntaxElement::Node(n) if n.kind() == SyntaxKind::OPTIONAL => {}
                _ => return Err(Stop::Abort),
            }
        }
    }
}

#[cfg(test)]
mod segmentation_tests {
    use super::*;
    use crate::parser::parse;
    use crate::syntax::SyntaxNode;

    /// Segment the first paragraph of `src` (which must open with
    /// `\ExplSyntaxOn` so the lexer treats `:`/`_` as letters) and render each
    /// statement's source text with whitespace collapsed, for stable
    /// assertions.
    fn statements(src: &str) -> Vec<String> {
        let parsed = parse(src);
        assert!(parsed.errors.is_empty(), "test source should parse cleanly");
        let root = SyntaxNode::new_root(parsed.green);
        let para = root
            .children()
            .find(|n| n.kind() == SyntaxKind::PARAGRAPH)
            .expect("a paragraph");
        let elements: Vec<SyntaxElement> = para.children_with_tokens().collect();
        statement_texts(&elements)
    }

    fn statement_texts(elements: &[SyntaxElement]) -> Vec<String> {
        let map = segment_expl_statements(elements);
        let mut out = Vec::new();
        let mut cur = String::new();
        for (i, el) in elements.iter().enumerate() {
            cur.push_str(&el.to_string());
            if map.boundary_after(i) {
                let text = normalize(&cur);
                if !text.is_empty() {
                    out.push(text);
                }
                cur.clear();
            }
        }
        let tail = normalize(&cur);
        if !tail.is_empty() {
            out.push(tail);
        }
        out
    }

    fn normalize(s: &str) -> String {
        s.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    #[test]
    fn statements_are_structural_units() {
        // Mid-call newlines join; the colonless toggles fall back per-line.
        let got = statements(
            "\\ExplSyntaxOn\n\\tl_set:Nn \\l_a\n  { x }\n\\group_begin:\n\\ExplSyntaxOff\n",
        );
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\tl_set:Nn \\l_a { x }",
                "\\group_begin:",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn same_line_calls_split() {
        let got =
            statements("\\ExplSyntaxOn\n\\group_begin: \\int_zero:N \\l_a\n\\ExplSyntaxOff\n");
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\group_begin:",
                "\\int_zero:N \\l_a",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn npn_definition_is_one_unit() {
        // `N` takes `\foo:n`, `p` scans `#1`, `n` takes the body — across the
        // authored Allman break.
        let got =
            statements("\\ExplSyntaxOn\n\\cs_new:Npn \\foo:n #1\n  { body #1 }\n\\ExplSyntaxOff\n");
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\cs_new:Npn \\foo:n #1 { body #1 }",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn peel_back_reclaims_over_attached_group() {
        // Greedy attachment gives `{ body }` to `\foo:n`; the `N` slot takes
        // the name and the peeled group satisfies the outer `n` slot.
        let got = statements("\\ExplSyntaxOn\n\\cs_new:Nn \\foo:n\n  { body }\n\\ExplSyntaxOff\n");
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\cs_new:Nn \\foo:n { body }",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn exp_args_chain_is_one_unit() {
        let got = statements(
            "\\ExplSyntaxOn\n\\exp_args:NNo \\tl_set:Nn \\l_a { \\l_b }\n\\ExplSyntaxOff\n",
        );
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\exp_args:NNo \\tl_set:Nn \\l_a { \\l_b }",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn hash_parameter_satisfies_single_token_slot() {
        let got = statements("\\ExplSyntaxOn\n\\tl_set:Nn #1 { x }\n\\ExplSyntaxOff\n");
        assert_eq!(
            got,
            vec!["\\ExplSyntaxOn", "\\tl_set:Nn #1 { x }", "\\ExplSyntaxOff"]
        );
    }

    #[test]
    fn delimited_parameter_text_peels_the_body() {
        // `{ body }` greedily attached to `\q_stop`; the p-scan peels it and
        // stops there, leaving it for the trailing `n` slot.
        let got = statements(
            "\\ExplSyntaxOn\n\\cs_new:Npn \\foo:w #1 \\q_stop { body }\n\\ExplSyntaxOff\n",
        );
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\cs_new:Npn \\foo:w #1 \\q_stop { body }",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn unknown_head_falls_back_to_its_line() {
        // `\exp_after:wN` has no derivable arity: its authored line is the
        // statement, and the recognized call sharing that line is not split out.
        let got = statements(
            "\\ExplSyntaxOn\n\\exp_after:wN \\foo \\tl_set:Nn \\l_a { x }\n\\group_begin:\n\\ExplSyntaxOff\n",
        );
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\exp_after:wN \\foo \\tl_set:Nn \\l_a { x }",
                "\\group_begin:",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn shape_mismatch_falls_back() {
        // The `n` slot faces a command, not a group: the whole statement
        // degrades to newline splitting rather than swallowing the next head.
        let got = statements("\\ExplSyntaxOn\n\\tl_set:Nn\n\\l_a\n\\ExplSyntaxOff\n");
        assert_eq!(
            got,
            vec!["\\ExplSyntaxOn", "\\tl_set:Nn", "\\l_a", "\\ExplSyntaxOff"]
        );
    }

    #[test]
    fn trailing_comment_rides_the_statement() {
        let got = statements("\\ExplSyntaxOn\n\\tl_set:Nn \\l_a { x } % note\n\\ExplSyntaxOff\n");
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\tl_set:Nn \\l_a { x } % note",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn leftover_attached_group_rides_the_statement() {
        // `\use:n` has arity 1; the second group is over-attached to the head
        // node, and boundaries never split a node, so it stays in the unit.
        let got = statements("\\ExplSyntaxOn\n\\use:n { a } { b }\n\\ExplSyntaxOff\n");
        assert_eq!(
            got,
            vec!["\\ExplSyntaxOn", "\\use:n { a } { b }", "\\ExplSyntaxOff"]
        );
    }

    #[test]
    fn conditional_call_is_one_unit() {
        let got = statements(
            "\\ExplSyntaxOn\n\\str_if_eq:nnTF { a } { b }\n  { yes }\n  { no }\n\\ExplSyntaxOff\n",
        );
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\str_if_eq:nnTF { a } { b } { yes } { no }",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn blank_line_ends_the_unit() {
        // Inside a group body a blank line can sit mid-call: the unit commits
        // as-is before it, and the stranded group starts a fresh statement.
        let src = "\\ExplSyntaxOn\n\\use:n { \\tl_set:Nn \\l_a\n\n  { x } }\n\\ExplSyntaxOff\n";
        let parsed = parse(src);
        assert!(parsed.errors.is_empty());
        let root = SyntaxNode::new_root(parsed.green);
        let group = root
            .descendants()
            .find(|n| n.kind() == SyntaxKind::GROUP)
            .expect("a group");
        let body: Vec<SyntaxElement> = group
            .children_with_tokens()
            .filter(|el| !matches!(el.kind(), SyntaxKind::L_BRACE | SyntaxKind::R_BRACE))
            .collect();
        assert_eq!(statement_texts(&body), vec!["\\tl_set:Nn \\l_a", "{ x }"]);
    }

    #[test]
    fn guard_mid_unit_aborts_to_fallback() {
        // A docstrip guard inside the unit (issue #78: guarded alternative
        // bodies make arity lie) aborts consumption; the statement degrades to
        // the fallback, and the guard-bearing sibling rides it whole because
        // boundaries never split a node.
        use crate::parser::lexer::LexConfig;
        use crate::parser::{LatexFlavor, parse_with_flavor};
        let src = "% \\begin{macrocode}\n\\ExplSyntaxOn\n\\tl_set:Nn \\l_a\n%<latexrelease>  { x }\n\\ExplSyntaxOff\n% \\end{macrocode}\n";
        let config = LexConfig {
            flavor: LatexFlavor::Package,
            dtx: true,
        };
        let parsed = parse_with_flavor(src, config);
        assert!(parsed.errors.is_empty(), "test source should parse cleanly");
        let root = SyntaxNode::new_root(parsed.green);
        let para = root
            .descendants()
            .find(|n| n.kind() == SyntaxKind::PARAGRAPH)
            .expect("a paragraph");
        let elements: Vec<SyntaxElement> = para.children_with_tokens().collect();
        let map = segment_expl_statements(&elements);
        assert_eq!(
            statement_texts(&elements),
            vec![
                "\\ExplSyntaxOn",
                "\\tl_set:Nn \\l_a %<latexrelease> { x }",
                "\\ExplSyntaxOff",
            ]
        );
        let guarded_end = elements
            .iter()
            .position(|el| el.to_string().contains("latexrelease"))
            .expect("the guarded sibling");
        assert!(
            map.is_fallback(guarded_end),
            "the aborted unit must be a fallback statement"
        );
    }

    #[test]
    fn e_and_f_letters_consume_braced_groups() {
        let got = statements(
            "\\ExplSyntaxOn\n\\tl_set:Ne \\l_a\n  { x }\n\\tl_set:Nf \\l_b\n  { y }\n\\ExplSyntaxOff\n",
        );
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\tl_set:Ne \\l_a { x }",
                "\\tl_set:Nf \\l_b { y }",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn stream_ending_mid_unit_falls_back() {
        // The `n` slot is still open when the group body runs out: the unit
        // aborts to the fallback rather than committing a partial unit.
        let src = "\\ExplSyntaxOn\n\\use:n { \\tl_set:Nn \\l_a }\n\\ExplSyntaxOff\n";
        let parsed = parse(src);
        assert!(parsed.errors.is_empty());
        let root = SyntaxNode::new_root(parsed.green);
        let group = root
            .descendants()
            .find(|n| n.kind() == SyntaxKind::GROUP)
            .expect("a group");
        let body: Vec<SyntaxElement> = group
            .children_with_tokens()
            .filter(|el| !matches!(el.kind(), SyntaxKind::L_BRACE | SyntaxKind::R_BRACE))
            .collect();
        let map = segment_expl_statements(&body);
        assert_eq!(statement_texts(&body), vec!["\\tl_set:Nn \\l_a"]);
        let head = body
            .iter()
            .position(|el| el.as_node().is_some())
            .expect("the head command");
        assert!(
            map.is_fallback(head),
            "a unit cut off by the stream end must be a fallback statement"
        );
    }

    #[test]
    fn own_line_comment_in_attached_span_rides_the_sibling() {
        // The own-line comment's flanking newlines bound the gap like a blank
        // line, ending the unit at the `N` slot — but greedy attachment put
        // the comment *and* the group inside the `\l_a` sibling, and
        // boundaries never split a node, so the committed partial unit still
        // carries the whole sibling. Pass-stable either way (comment
        // own-line-ness is a preserved predicate).
        let got =
            statements("\\ExplSyntaxOn\n\\tl_set:Nn \\l_a\n% note\n  { x }\n\\ExplSyntaxOff\n");
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\tl_set:Nn \\l_a % note { x }",
                "\\ExplSyntaxOff",
            ]
        );
    }

    #[test]
    fn own_line_comment_at_sibling_level_ends_the_unit() {
        // Before a candidate no comment can bind to (`#1` parameter text, not
        // a `COMMAND`), the own-line comment stays a sibling: the unit ends at
        // the gap, the comment keeps its own line, and the leftover material
        // falls back per-line.
        let got = statements(
            "\\ExplSyntaxOn\n\\cs_new:Npn \\foo:n\n% note\n#1 { body }\n\\ExplSyntaxOff\n",
        );
        assert_eq!(
            got,
            vec![
                "\\ExplSyntaxOn",
                "\\cs_new:Npn \\foo:n",
                "% note",
                "#1 { body }",
                "\\ExplSyntaxOff",
            ]
        );
    }
}