decomment 0.1.0

Remove comments from source text in 13 languages without touching strings, templates, or regex literals.
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
use alloc::string::String;

use crate::error::{Unterminated, UnterminatedKind};
use crate::language::Syntax;
use crate::options::{Mode, Options};

/// The result of a [`crate::strip`] call.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Stripped {
    /// The input with the selected comments removed.
    pub output: String,
    /// The one construct still open where the scan ended, if any.
    ///
    /// The scan ends at end of input in every mode but [`Mode::First`], which
    /// ends it at the comment it removes. A construct that opens after that
    /// point is never read and never reported.
    pub unterminated: Option<Unterminated>,
}

/// How many `${` levels a template can nest before the scanner stops entering
/// code state. One bit per level in a `u128`, so nesting costs no allocation.
const STACK_BITS: u32 = 128;

/// The most bytes a C++ raw string delimiter may hold, from the C++ grammar.
const CPP_DELIM_MAX: usize = 16;

/// Keywords after which a `/` starts a regex literal rather than a division.
/// None of them can end an expression.
const REGEX_KEYWORDS: [&[u8]; 14] = [
    b"return",
    b"typeof",
    b"instanceof",
    b"in",
    b"of",
    b"new",
    b"delete",
    b"void",
    b"throw",
    b"case",
    b"do",
    b"else",
    b"yield",
    b"await",
];

/// What ends a string form.
#[derive(Clone, Copy)]
enum Close {
    /// `count` copies of `quote`, then `hashes` `#` bytes.
    Fence {
        quote: u8,
        count: usize,
        hashes: usize,
    },
    /// `)`, then the delimiter recorded at `start..end`, then `"`.
    CppDelim { start: usize, end: usize },
}

/// One string form, reduced to the four decisions the scan loop makes.
#[derive(Clone, Copy)]
struct StrForm {
    close: Close,
    /// A backslash consumes the byte after it.
    escapes: bool,
    /// The form closes at a line terminator and is never reported unterminated.
    line_terminated: bool,
    /// A doubled closing quote is an escaped quote rather than the close.
    doubled: bool,
}

impl StrForm {
    /// A plain quoted string that ends at the first unescaped closing quote.
    fn quoted(quote: u8, escapes: bool, line_terminated: bool) -> StrForm {
        StrForm {
            close: Close::Fence {
                quote,
                count: 1,
                hashes: 0,
            },
            escapes,
            line_terminated,
            doubled: false,
        }
    }
}

pub(crate) struct Scanner<'a> {
    src: &'a str,
    b: &'a [u8],
    syn: Syntax,
    opts: Options,
    out: String,
    /// Start of the run of kept bytes not yet written to `out`.
    kept_from: usize,
    i: usize,
    unterminated: Option<Unterminated>,
    /// The previous significant token can end an expression, so a `/` after it
    /// is a division. Whitespace and comments do not change it.
    prev_value: bool,
    /// A regex candidate already failed on this line, so offer no more until
    /// this offset. This is what keeps the scan linear.
    regex_off_until: usize,
    /// One bit per open brace inside a template. A set bit means the brace was
    /// a `${`, so the matching `}` returns to template text.
    tstack: u128,
    tdepth: u32,
    /// Braces past the bit stack. Popped before the bit stack, so nesting order
    /// stays correct however deep the input goes.
    over: usize,
    in_template: bool,
    /// Offset of the outermost open backtick, for the unterminated report.
    template_start: usize,
    /// `Mode::First` has removed its comment, so the rest is copied verbatim.
    done: bool,
}

impl<'a> Scanner<'a> {
    pub(crate) fn new(src: &'a str, opts: Options) -> Scanner<'a> {
        Scanner {
            src,
            b: src.as_bytes(),
            syn: Syntax::for_language(opts.language),
            opts,
            out: String::with_capacity(src.len()),
            kept_from: 0,
            i: 0,
            unterminated: None,
            prev_value: false,
            regex_off_until: 0,
            tstack: 0,
            tdepth: 0,
            over: 0,
            in_template: false,
            template_start: 0,
            done: false,
        }
    }

    pub(crate) fn run(mut self) -> Stripped {
        while self.i < self.b.len() && !self.done {
            if self.in_template {
                self.template();
            } else {
                self.code();
            }
        }
        // A backtick as the last byte, or a `${` still open, leaves the scan in
        // a template that the template loop never carried to end of input.
        if self.i >= self.b.len() && (self.in_template || self.tdepth > 0) {
            self.report(UnterminatedKind::StringLiteral, self.template_start);
        }
        let tail = self.kept_from;
        push_range(&mut self.out, self.src, tail, self.src.len());
        Stripped {
            output: self.out,
            unterminated: self.unterminated,
        }
    }

    /// One step of the code state. Every branch advances `self.i`.
    fn code(&mut self) {
        let i = self.i;
        let c = self.b[i];

        // Comment openers win over every other reading of the same bytes. A
        // regex cannot start with `/` or `*`, so testing them first is safe.
        if let Some((open, close)) = self.syn.block {
            if self.b[i..].starts_with(open) {
                self.block_comment(i, open, close);
                return;
            }
        }
        if let Some(open) = self.syn.line {
            if self.b[i..].starts_with(open) {
                self.line_comment(i, open);
                return;
            }
        }

        match c {
            b'"' => self.open_double(i),
            b'\'' => self.open_single(i),
            b'`' if self.syn.js => {
                // Only the outermost backtick is worth reporting, and tdepth is
                // zero exactly when no template encloses this one.
                if self.tdepth == 0 {
                    self.template_start = i;
                }
                self.in_template = true;
                self.i = i + 1;
            }
            b'`' if self.syn.go_raw => {
                self.i = self.scan_string(i, i + 1, StrForm::quoted(b'`', false, false));
                self.prev_value = true;
            }
            b'@' if self.syn.csharp_verbatim && self.b.get(i + 1) == Some(&b'"') => {
                let mut form = StrForm::quoted(b'"', false, false);
                form.doubled = true;
                self.i = self.scan_string(i, i + 2, form);
                self.prev_value = true;
            }
            b'#' if self.syn.swift_raw => self.swift_raw(i),
            b'/' if self.syn.js => self.slash(i),
            b'{' if self.syn.js => {
                if self.tdepth > 0 {
                    self.push_bit(false);
                }
                self.prev_value = false;
                self.i = i + 1;
            }
            b'}' if self.syn.js => {
                if self.tdepth > 0 && self.pop_bit() {
                    self.in_template = true;
                }
                self.prev_value = true;
                self.i = i + 1;
            }
            b'+' | b'-' if self.b.get(i + 1) == Some(&c) => {
                // `++` and `--` end an expression, so a `/` after them divides.
                self.prev_value = true;
                self.i = i + 2;
            }
            _ if is_word_start(c) => self.word(i),
            b'0'..=b'9' => {
                // A number ends an expression, so a `/` after it divides.
                let mut j = i;
                while self.b.get(j).is_some_and(is_number_byte) {
                    j += 1;
                }
                self.prev_value = true;
                self.i = j;
            }
            _ => {
                if c == b')' || c == b']' {
                    self.prev_value = true;
                } else if !is_space(c) {
                    self.prev_value = false;
                }
                self.i = i + 1;
            }
        }
    }

    /// One step of the template state, which runs until a backtick or a `${`.
    fn template(&mut self) {
        let n = self.b.len();
        let mut i = self.i;
        while i < n {
            let c = self.b[i];
            if c == b'\\' {
                i = i.saturating_add(2).min(n);
                continue;
            }
            if c == b'`' {
                self.in_template = false;
                self.prev_value = true;
                self.i = i + 1;
                return;
            }
            // Past the depth cap a `${` stays template text. The region is
            // still string data, so nothing inside it can be deleted.
            if c == b'$' && self.b.get(i + 1) == Some(&b'{') && self.tdepth < STACK_BITS {
                self.push_bit(true);
                self.in_template = false;
                self.prev_value = false;
                self.i = i + 2;
                return;
            }
            i += 1;
        }
        self.i = n;
        self.report(UnterminatedKind::StringLiteral, self.template_start);
    }

    fn block_comment(&mut self, start: usize, open: &[u8], close: &[u8]) {
        let end = self.block_end(start, open, close);
        let stop = end.unwrap_or(self.b.len());
        if end.is_none() {
            // The comment ran to end of input, so it is open there whatever the
            // mode does with its text.
            self.report(UnterminatedKind::BlockComment, start);
        }
        if self.removes_block() && !self.is_bang(start + open.len()) {
            self.cut(start, stop);
        }
        self.i = stop;
    }

    /// End of the block comment that opens at `start`, or `None` at end of input.
    fn block_end(&self, start: usize, open: &[u8], close: &[u8]) -> Option<usize> {
        // The search starts after the opener, so `/**/` is an empty comment and
        // `/*/` is unterminated.
        let mut i = start + open.len();
        let mut depth = 1usize;
        while i < self.b.len() {
            if self.b[i..].starts_with(close) {
                depth -= 1;
                if depth == 0 {
                    return Some(i + close.len());
                }
                i += close.len();
            } else if self.syn.nests && self.b[i..].starts_with(open) {
                depth = depth.saturating_add(1);
                i += open.len();
            } else {
                i += 1;
            }
        }
        None
    }

    fn line_comment(&mut self, start: usize, open: &[u8]) {
        let body = start + open.len();
        let end = self.line_end(body);
        if self.removes_line() && !self.is_bang(body) {
            self.cut(start, end);
        }
        self.i = end;
    }

    /// Offset of the line terminator at or after `from`, or end of input.
    fn line_end(&self, from: usize) -> usize {
        let mut i = from;
        while i < self.b.len() {
            let c = self.b[i];
            if c == b'\n' || c == b'\r' || self.is_unicode_sep(i) {
                return i;
            }
            i += 1;
        }
        self.b.len()
    }

    /// U+2028 and U+2029 end a line comment in JavaScript and TypeScript. They
    /// are matched as exact three byte sequences, so no character arithmetic
    /// can split a multi-byte character.
    fn is_unicode_sep(&self, i: usize) -> bool {
        self.syn.js
            && self.b[i] == 0xE2
            && self.b.get(i + 1) == Some(&0x80)
            && matches!(self.b.get(i + 2), Some(0xA8 | 0xA9))
    }

    fn open_double(&mut self, at: usize) {
        if !self.syn.double_quote {
            self.prev_value = false;
            self.i = at + 1;
            return;
        }
        let (body, form) = if self.syn.triple_double && self.quote_run(at, b'"') >= 3 {
            (at + 3, triple(b'"'))
        } else if self.syn.sql {
            let mut form = StrForm::quoted(b'"', false, false);
            form.doubled = true;
            (at + 1, form)
        } else {
            // Rust string literals span lines. The other forms that reach here
            // close at the line terminator, so one stray quote cannot disable
            // comment removal for the rest of the file.
            (at + 1, StrForm::quoted(b'"', true, !self.syn.rust))
        };
        self.i = self.scan_string(at, body, form);
        self.prev_value = true;
    }

    fn open_single(&mut self, at: usize) {
        if !self.syn.single_quote {
            self.prev_value = false;
            self.i = at + 1;
            return;
        }
        if self.syn.triple_single && self.quote_run(at, b'\'') >= 3 {
            self.i = self.scan_string(at, at + 3, triple(b'\''));
            self.prev_value = true;
            return;
        }
        if self.syn.rust {
            self.rust_quote(at);
            return;
        }
        let form = if self.syn.sql {
            let mut form = StrForm::quoted(b'\'', false, false);
            form.doubled = true;
            form
        } else {
            StrForm::quoted(b'\'', true, true)
        };
        self.i = self.scan_string(at, at + 1, form);
        self.prev_value = true;
    }

    /// In Rust a `'` is a lifetime as often as a character literal. It opens a
    /// character literal when the next byte is `\`, or the byte after next is
    /// `'`. That covers `'a'`, `'\n'`, `'\u{1F600}'`, and leaves `&'static`.
    fn rust_quote(&mut self, at: usize) {
        let escaped = self.b.get(at + 1) == Some(&b'\\');
        let short = self.b.get(at + 2) == Some(&b'\'');
        if escaped || short {
            self.i = self.scan_string(at, at + 1, StrForm::quoted(b'\'', true, true));
        } else {
            self.i = at + 1;
        }
        self.prev_value = true;
    }

    /// Swift raw strings open with one or more `#` and a quote. A `#` that is
    /// not followed by a quote is a directive such as `#if`, so it is code.
    fn swift_raw(&mut self, at: usize) {
        let mut hashes = 0usize;
        while self.b.get(at + hashes) == Some(&b'#') {
            hashes += 1;
        }
        let quote_at = at + hashes;
        if self.b.get(quote_at) != Some(&b'"') {
            self.prev_value = false;
            self.i = at + hashes;
            return;
        }
        let count = if self.quote_run(quote_at, b'"') >= 3 {
            3
        } else {
            1
        };
        let form = StrForm {
            close: Close::Fence {
                quote: b'"',
                count,
                hashes,
            },
            escapes: false,
            line_terminated: false,
            doubled: false,
        };
        self.i = self.scan_string(at, quote_at + count, form);
        self.prev_value = true;
    }

    /// A word run, which also carries the quote prefixes of three languages and
    /// the keyword test that decides whether a later `/` starts a regex.
    fn word(&mut self, at: usize) {
        let mut end = at;
        while end < self.b.len() && is_word_byte(self.b[end]) {
            end += 1;
        }
        let run = &self.b[at..end];
        let next = self.b.get(end).copied();

        if self.syn.rust && (run == b"r" || run == b"br") {
            let mut hashes = 0usize;
            while self.b.get(end + hashes) == Some(&b'#') {
                hashes += 1;
            }
            if self.b.get(end + hashes) == Some(&b'"') {
                let form = StrForm {
                    close: Close::Fence {
                        quote: b'"',
                        count: 1,
                        hashes,
                    },
                    escapes: false,
                    line_terminated: false,
                    doubled: false,
                };
                self.i = self.scan_string(at, end + hashes + 1, form);
                self.prev_value = true;
                return;
            }
        }
        if self.syn.rust && run == b"b" && next == Some(b'\'') {
            self.rust_quote(end);
            return;
        }
        if self.syn.cpp_raw && run == b"R" && next == Some(b'"') {
            if let Some((body, form)) = self.cpp_delim(end + 1) {
                self.i = self.scan_string(at, body, form);
                self.prev_value = true;
                return;
            }
        }
        let python_quote = next.is_some_and(|c| c == b'"' || c == b'\'')
            && run.len() <= 2
            && run.iter().all(|c| b"rRbBfFuU".contains(c));
        if self.syn.python_prefix && python_quote {
            // An `r` prefix keeps the backslash in the value, and a backslash
            // still stops the next quote from closing the literal. Every prefix
            // scans the same way, so the prefix letters change nothing here.
            if next == Some(b'"') {
                self.open_double(end);
            } else {
                self.open_single(end);
            }
            return;
        }

        // A keyword that cannot end an expression leaves `prev_value` false, so
        // the next `/` is read as a regex literal.
        self.prev_value = !(self.syn.js && REGEX_KEYWORDS.contains(&run));
        self.i = end;
    }

    /// Read a C++ raw string delimiter starting at the byte after `R"`. Returns
    /// the first body offset and the form, or `None` when the bytes are not a
    /// raw string after all, in which case the caller reads an ordinary string.
    fn cpp_delim(&self, from: usize) -> Option<(usize, StrForm)> {
        let mut end = from;
        while end < self.b.len() && end - from <= CPP_DELIM_MAX {
            match self.b[end] {
                b'(' => {
                    let form = StrForm {
                        close: Close::CppDelim { start: from, end },
                        escapes: false,
                        line_terminated: false,
                        doubled: false,
                    };
                    return Some((end + 1, form));
                }
                b')' | b'\\' | b' ' | b'\n' | b'\r' => return None,
                _ => end += 1,
            }
        }
        None
    }

    /// Consume a string form. Returns the offset just past it, or end of input.
    fn scan_string(&mut self, open_at: usize, body: usize, form: StrForm) -> usize {
        let n = self.b.len();
        let mut i = body;
        while i < n {
            let c = self.b[i];
            if form.escapes && c == b'\\' {
                i = i.saturating_add(2).min(n);
                continue;
            }
            // A Swift raw string escapes with a backslash and its own hash
            // count, so `\#"` is a quote inside the literal and not the close.
            if c == b'\\' && self.syn.swift_raw {
                if let Close::Fence { hashes, .. } = form.close {
                    if hashes > 0 && self.hashes_at(i + 1, hashes) {
                        i = i.saturating_add(hashes + 2).min(n);
                        continue;
                    }
                }
            }
            if form.line_terminated && (c == b'\n' || c == b'\r') {
                // The terminator belongs to the code, not to the string.
                return i;
            }
            match form.close {
                Close::Fence {
                    quote,
                    count,
                    hashes,
                } => {
                    if c == quote && self.fence_at(i, quote, count, hashes) {
                        let end = i + count + hashes;
                        if form.doubled && self.b.get(end) == Some(&quote) {
                            i = end + 1;
                            continue;
                        }
                        return end;
                    }
                }
                Close::CppDelim { start, end } => {
                    if c == b')' && self.delim_at(i + 1, start, end) {
                        return i + 1 + (end - start) + 1;
                    }
                }
            }
            i += 1;
        }
        if !form.line_terminated {
            self.report(UnterminatedKind::StringLiteral, open_at);
        }
        n
    }

    fn fence_at(&self, i: usize, quote: u8, count: usize, hashes: usize) -> bool {
        match self.b.get(i..i + count + hashes) {
            Some(run) => {
                run[..count].iter().all(|byte| *byte == quote)
                    && run[count..].iter().all(|byte| *byte == b'#')
            }
            None => false,
        }
    }

    fn hashes_at(&self, i: usize, hashes: usize) -> bool {
        self.b
            .get(i..i + hashes)
            .is_some_and(|run| run.iter().all(|byte| *byte == b'#'))
    }

    fn delim_at(&self, i: usize, start: usize, end: usize) -> bool {
        let len = end - start;
        self.b.get(i..i + len) == self.b.get(start..end) && self.b.get(i + len) == Some(&b'"')
    }

    /// How many copies of `quote` sit at `at`, capped at three.
    fn quote_run(&self, at: usize, quote: u8) -> usize {
        let mut n = 0usize;
        while n < 3 && self.b.get(at + n) == Some(&quote) {
            n += 1;
        }
        n
    }

    /// A `/` in JavaScript or TypeScript, already known not to open a comment.
    fn slash(&mut self, at: usize) {
        if self.prev_value || at < self.regex_off_until {
            self.prev_value = false;
            self.i = at + 1;
            return;
        }
        match self.regex_end(at) {
            Some(end) => {
                self.prev_value = true;
                self.i = end;
            }
            None => {
                // The candidate was a misread. Read it as division and offer no
                // more candidates on this line, which bounds the rescan.
                self.regex_off_until = self.line_end(at + 1);
                self.prev_value = false;
                self.i = at + 1;
            }
        }
    }

    /// End of the regex literal that opens at `at`, flags included, or `None`
    /// if it reaches a line terminator or end of input without closing.
    fn regex_end(&self, at: usize) -> Option<usize> {
        let n = self.b.len();
        let mut i = at + 1;
        let mut in_class = false;
        while i < n {
            let c = self.b[i];
            if c == b'\\' {
                i = i.saturating_add(2);
                continue;
            }
            if c == b'\n' || c == b'\r' || self.is_unicode_sep(i) {
                return None;
            }
            if in_class {
                if c == b']' {
                    in_class = false;
                }
            } else if c == b'[' {
                in_class = true;
            } else if c == b'/' {
                let mut end = i + 1;
                while end < n && is_word_byte(self.b[end]) {
                    end += 1;
                }
                return Some(end);
            }
            i += 1;
        }
        None
    }

    /// Delete `from..to`, writing back the line terminators it held when
    /// `preserve_newlines` is set.
    fn cut(&mut self, from: usize, to: usize) {
        push_range(&mut self.out, self.src, self.kept_from, from);
        if self.opts.preserve_newlines {
            for byte in &self.b[from..to] {
                if *byte == b'\n' || *byte == b'\r' {
                    self.out.push(*byte as char);
                }
            }
        }
        self.kept_from = to;
        if self.opts.mode == Mode::First {
            self.done = true;
        }
    }

    fn removes_line(&self) -> bool {
        matches!(self.opts.mode, Mode::All | Mode::Line | Mode::First)
    }

    fn removes_block(&self) -> bool {
        matches!(self.opts.mode, Mode::All | Mode::Block | Mode::First)
    }

    /// A comment body that starts with `!` is a banner. The body begins at the
    /// byte after the opening marker, so `///` is not one.
    fn is_bang(&self, body: usize) -> bool {
        self.opts.keep_bang_comments && self.b.get(body) == Some(&b'!')
    }

    fn report(&mut self, kind: UnterminatedKind, offset: usize) {
        // Only the construct open where the scan ends can be reported, and the
        // scan stops there, so the first report is the only one.
        if self.unterminated.is_none() {
            self.unterminated = Some(Unterminated { kind, offset });
        }
    }

    fn push_bit(&mut self, is_template: bool) {
        if self.tdepth < STACK_BITS {
            if is_template {
                self.tstack |= 1u128 << self.tdepth;
            } else {
                self.tstack &= !(1u128 << self.tdepth);
            }
            self.tdepth += 1;
        } else {
            self.over = self.over.saturating_add(1);
        }
    }

    fn pop_bit(&mut self) -> bool {
        if self.over > 0 {
            self.over -= 1;
            return false;
        }
        self.tdepth -= 1;
        self.tstack >> self.tdepth & 1 == 1
    }
}

/// A triple quoted multi-line string form.
fn triple(quote: u8) -> StrForm {
    StrForm {
        close: Close::Fence {
            quote,
            count: 3,
            hashes: 0,
        },
        escapes: true,
        line_terminated: false,
        doubled: false,
    }
}

/// Append `src[from..to]`. Every cut point sits on an ASCII marker byte, so the
/// range is always a character boundary. `get` keeps a mistake from panicking
/// inside a caller.
fn push_range(out: &mut String, src: &str, from: usize, to: usize) {
    if let Some(text) = src.get(from..to) {
        out.push_str(text);
    }
}

fn is_word_start(c: u8) -> bool {
    c.is_ascii_alphabetic() || c == b'_' || c == b'$' || c >= 0x80
}

/// Digits, hex letters, exponent letters, and the decimal point.
fn is_number_byte(c: &u8) -> bool {
    c.is_ascii_alphanumeric() || *c == b'.'
}

fn is_word_byte(c: u8) -> bool {
    is_word_start(c) || c.is_ascii_digit()
}

fn is_space(c: u8) -> bool {
    matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C)
}