yolowsyntax 0.2.1

Pure-Rust, hardware-accelerated tree-sitter grammar runtime and code outline extractor for 41 languages.
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
//! GLR 图结构栈(对应官方 `stack.c`)+ Elkhound 混合确定性 LR(1) 线性栈快路径(McPeak & Necula, CC 2004)。
//!
//! 当活跃版本数为 1 且处于线性无分叉段(`linear_base` 以上)时,归约直接原地弹出顶部 `SNode`,
//! 零 `Head` 增删、零子树逆序、零死栈节点垃圾;遇 GLR 歧义或错误恢复时 O(1) 无缝无缝切换回完整 GSS。

use crate::table::SYM_ERROR_REPEAT;
use crate::tree::{Arena, Len, NONE};

const MAX_LINK_COUNT: usize = 8;
const MAX_ITERATOR_COUNT: usize = 64;
pub const ERROR_STATE: u16 = 0;

/// 紧凑 8 字节栈边:`node_pending` 低 31 位存前驱栈节点下标,最高位(bit 31)存 `pending`。
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Link {
    node_pending: u32,
    pub tree: u32,
}

const _: () = assert!(core::mem::size_of::<Link>() == 8);

impl Link {
    #[inline(always)]
    pub const fn new(node: u32, tree: u32, pending: bool) -> Self {
        Self {
            node_pending: (node & 0x7FFF_FFFF) | ((pending as u32) << 31),
            tree,
        }
    }
    #[inline(always)]
    pub const fn node(self) -> u32 {
        self.node_pending & 0x7FFF_FFFF
    }
    #[inline(always)]
    pub const fn pending(self) -> bool {
        (self.node_pending >> 31) != 0
    }
    #[inline(always)]
    pub fn set_node(&mut self, node: u32) {
        self.node_pending = (self.node_pending & 0x8000_0000) | (node & 0x7FFF_FFFF);
    }
}

#[derive(Clone, Copy)]
pub struct SNode {
    pub state: u16,
    pub link_len: u8,
    pub pos: Len,
    pub first: Link,
    /// `link_len >= 2` 时指向 `Stack::extra_links` 下标,否则为 NONE。
    pub extra_links: u32,
    pub error_cost: u32,
    pub node_count: u32,
    pub dprec: i32,
    pub depth: u32,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
    Active,
    Paused,
    Halted,
}

#[derive(Clone, Copy)]
pub struct SumEntry {
    pub pos: Len,
    pub depth: u32,
    pub state: u16,
}

#[derive(Clone)]
pub struct Head {
    pub node: u32,
    pub status: Status,
    pub node_count_at_last_error: u32,
    pub summary: Option<Vec<SumEntry>>,
    pub paused_lookahead: u32,
    /// 最后一个外部记号之后的扫描器状态编号(0 为初始空状态)。
    pub ext: u32,
}

pub struct Slice {
    pub version: usize,
    pub trees: Vec<u32>,
}

struct Iter {
    node: u32,
    trees: Vec<u32>,
    count: u32,
    pending: bool,
}

pub struct Stack {
    pub nodes: Vec<SNode>,
    pub extra_links: Vec<[Link; MAX_LINK_COUNT - 1]>,
    pub heads: Vec<Head>,
    base: u32,
    /// Elkhound 线性栈底界:满足 `heads.len() == 1 && heads[0].status == Active && heads[0].node + 1 == nodes.len()`
    /// 时,所有下标 `k > linear_base` 的栈节点严格单链 `first.node == k - 1` 且无外部引用,可原地截断回收。
    pub(crate) linear_base: usize,
    pub(crate) scratch_nodes: Vec<SNode>,
    pub(crate) scratch_extra: Vec<[Link; MAX_LINK_COUNT - 1]>,
    pub(crate) scratch_smap: Vec<u32>,
}

#[inline(always)]
fn subtree_node_count(a: &Arena, t: u32) -> u32 {
    let n = a.n(t);
    let mut c = a.vis_desc(t);
    c += n.visible() as u32;
    c += (n.sym == SYM_ERROR_REPEAT) as u32;
    c
}

/// # Safety
/// 调用方必须保证 `t` 在 `a` 内为有效节点下标且冷节点下标有效。
#[inline(always)]
unsafe fn subtree_node_count_unchecked(a: &Arena, t: u32) -> u32 {
    // SAFETY: 透传调用方契约。
    let n = unsafe { a.n_unchecked(t) };
    let mut c = unsafe { a.vis_desc_unchecked(t) };
    c += n.visible() as u32;
    c += (n.sym == SYM_ERROR_REPEAT) as u32;
    c
}

#[inline]
fn equivalent(a: &Arena, l: u32, r: u32) -> bool {
    if l == r {
        return true;
    }
    if l == NONE || r == NONE {
        return false;
    }
    let (ln, rn) = (a.n(l), a.n(r));
    if ln.sym != rn.sym {
        return false;
    }
    if a.cost(l) > 0 && a.cost(r) > 0 {
        return true;
    }
    ln.padding.bytes == rn.padding.bytes
        && ln.size.bytes == rn.size.bytes
        && ln.child_count() == rn.child_count()
        && ln.extra() == rn.extra()
}

const EMPTY_LINK: Link = Link::new(0, NONE, false);

impl Stack {
    pub fn new() -> Stack {
        let mut s = Stack {
            nodes: Vec::with_capacity(64),
            extra_links: Vec::new(),
            heads: Vec::with_capacity(8),
            base: 0,
            linear_base: 0,
            scratch_nodes: Vec::new(),
            scratch_extra: Vec::new(),
            scratch_smap: Vec::new(),
        };
        s.nodes.push(SNode {
            state: 1,
            link_len: 0,
            pos: Len::default(),
            first: EMPTY_LINK,
            extra_links: NONE,
            error_cost: 0,
            node_count: 0,
            dprec: 0,
            depth: 0,
        });
        s.clear();
        s
    }

    #[inline(always)]
    pub fn link_count(&self, node: u32) -> usize {
        self.nodes[node as usize].link_len as usize
    }

    #[inline(always)]
    pub fn link_at(&self, node: u32, idx: usize) -> Link {
        let n = &self.nodes[node as usize];
        if idx == 0 {
            n.first
        } else {
            self.extra_links[n.extra_links as usize][idx - 1]
        }
    }

    #[inline(always)]
    fn set_link(&mut self, node: u32, idx: usize, link: Link) {
        let n = &mut self.nodes[node as usize];
        if idx == 0 {
            n.first = link;
        } else {
            self.extra_links[n.extra_links as usize][idx - 1] = link;
        }
    }

    #[inline]
    fn push_node_link(&mut self, node: u32, link: Link) {
        self.linear_base = usize::MAX;
        let len = self.nodes[node as usize].link_len as usize;
        if len == 0 {
            let n = &mut self.nodes[node as usize];
            n.first = link;
            n.link_len = 1;
        } else if len < MAX_LINK_COUNT {
            if len == 1 {
                let slot = self.extra_links.len() as u32;
                self.extra_links.push([EMPTY_LINK; MAX_LINK_COUNT - 1]);
                self.extra_links[slot as usize][0] = link;
                let n = &mut self.nodes[node as usize];
                n.extra_links = slot;
                n.link_len = 2;
            } else {
                let slot = self.nodes[node as usize].extra_links as usize;
                self.extra_links[slot][len - 1] = link;
                self.nodes[node as usize].link_len = (len + 1) as u8;
            }
        }
    }

    #[inline]
    fn copy_links(&self, node: u32) -> ([Link; MAX_LINK_COUNT], usize) {
        let n = &self.nodes[node as usize];
        let len = n.link_len as usize;
        let mut out = [EMPTY_LINK; MAX_LINK_COUNT];
        if len > 0 {
            out[0] = n.first;
            if len > 1 {
                let ex = &self.extra_links[n.extra_links as usize];
                out[1..len].copy_from_slice(&ex[..len - 1]);
            }
        }
        (out, len)
    }

    pub fn clear(&mut self) {
        self.heads.clear();
        self.heads.push(Head {
            node: self.base,
            status: Status::Active,
            node_count_at_last_error: 0,
            summary: None,
            paused_lookahead: NONE,
            ext: 0,
        });
        self.linear_base = if self.nodes.len() == 1 && self.base == 0 {
            0
        } else {
            usize::MAX
        };
    }

    #[inline(always)]
    pub fn version_count(&self) -> usize {
        self.heads.len()
    }
    #[inline(always)]
    pub fn state(&self, v: usize) -> u16 {
        self.nodes[self.heads[v].node as usize].state
    }
    #[inline(always)]
    pub fn position(&self, v: usize) -> Len {
        self.nodes[self.heads[v].node as usize].pos
    }
    #[inline(always)]
    pub fn depth(&self, v: usize) -> u32 {
        self.nodes[self.heads[v].node as usize].depth
    }

    /// # Safety
    /// 调用方必须保证 `v < self.heads.len()` 且 `self.heads[v].node < self.nodes.len()`。
    #[inline(always)]
    pub(crate) unsafe fn state_unchecked(&self, v: usize) -> u16 {
        // SAFETY: 由调用方契约保证。
        unsafe {
            let nid = self.heads.get_unchecked(v).node as usize;
            self.nodes.get_unchecked(nid).state
        }
    }

    /// # Safety
    /// 同 [`Self::state_unchecked`]。
    #[inline(always)]
    pub(crate) unsafe fn position_unchecked(&self, v: usize) -> Len {
        // SAFETY: 由调用方契约保证。
        unsafe {
            let nid = self.heads.get_unchecked(v).node as usize;
            self.nodes.get_unchecked(nid).pos
        }
    }

    /// # Safety
    /// 同 [`Self::state_unchecked`]。
    #[inline(always)]
    pub(crate) unsafe fn depth_unchecked(&self, v: usize) -> u32 {
        // SAFETY: 由调用方契约保证。
        unsafe {
            let nid = self.heads.get_unchecked(v).node as usize;
            self.nodes.get_unchecked(nid).depth
        }
    }
    #[inline(always)]
    pub fn is_active(&self, v: usize) -> bool {
        self.heads[v].status == Status::Active
    }
    #[inline(always)]
    pub fn is_halted(&self, v: usize) -> bool {
        self.heads[v].status == Status::Halted
    }
    #[inline(always)]
    pub fn is_paused(&self, v: usize) -> bool {
        self.heads[v].status == Status::Paused
    }
    #[inline(always)]
    pub fn halt(&mut self, v: usize) {
        self.linear_base = usize::MAX;
        self.heads[v].status = Status::Halted;
    }
    #[inline(always)]
    pub fn dynamic_precedence(&self, v: usize) -> i32 {
        self.nodes[self.heads[v].node as usize].dprec
    }
    #[inline]
    pub fn halted_count(&self) -> usize {
        self.heads
            .iter()
            .filter(|h| h.status == Status::Halted)
            .count()
    }

    pub fn error_cost(&self, v: usize) -> u32 {
        let h = &self.heads[v];
        let n = &self.nodes[h.node as usize];
        let mut r = n.error_cost;
        if h.status == Status::Paused
            || (n.state == ERROR_STATE && n.link_len > 0 && n.first.tree == NONE)
        {
            r += crate::tree::ERROR_COST_PER_RECOVERY;
        }
        r
    }

    pub fn node_count_since_error(&mut self, v: usize) -> u32 {
        let nc = self.nodes[self.heads[v].node as usize].node_count;
        let h = &mut self.heads[v];
        if nc < h.node_count_at_last_error {
            h.node_count_at_last_error = nc;
        }
        nc - h.node_count_at_last_error
    }

    #[inline]
    pub fn push(&mut self, a: &Arena, v: usize, tree: u32, pending: bool, state: u16) {
        let prev = self.heads[v].node;
        let prev_us = prev as usize;
        let new_id = self.nodes.len();
        if self.heads.len() == 1 && v == 0 && self.heads[0].status == Status::Active {
            if prev_us + 1 != new_id || self.linear_base > prev_us {
                self.linear_base = new_id;
            }
        } else {
            self.linear_base = usize::MAX;
        }
        let p = self.nodes[prev_us];
        let mut n = SNode {
            state,
            link_len: 1,
            pos: p.pos,
            first: Link::new(prev, tree, pending),
            extra_links: NONE,
            error_cost: p.error_cost,
            node_count: p.node_count,
            dprec: p.dprec,
            depth: p.depth + 1,
        };
        if tree != NONE {
            let t = *a.n(tree);
            n.pos = n.pos.add(t.total());
            let ext_u8 = t.ext_inline();
            if !t.has_cold() {
                n.node_count += t.inline_vis() + t.visible() as u32;
                if ext_u8 < crate::tree::EXT_COLD_U8 {
                    self.heads[v].ext = ext_u8 as u32;
                }
            } else {
                n.error_cost = n.error_cost.wrapping_add(a.cost(tree));
                n.node_count += subtree_node_count(a, tree);
                n.dprec += a.dprec(tree);
                let te = a.ext_id(tree);
                if te != NONE {
                    self.heads[v].ext = te;
                }
            }
        }
        self.nodes.push(n);
        let id = new_id as u32;
        let h = &mut self.heads[v];
        h.node = id;
        if tree == NONE {
            h.node_count_at_last_error = n.node_count;
        }
    }

    /// Elkhound 确定性单版本原地弹出快路径:
    ///
    /// 若当前处于单版本线性区且弹出 `count` 个非 extra 符号不越过 `linear_base`,
    /// 则直接将弹出子树按**正序(左到右)**写入 `trees` 并截断 `self.nodes` 原地回收,
    /// 无需创建临时 `Head`、无需逆序、无需重排版本号。若越过 `linear_base` 则无副作用返回 `false`。
    #[inline]
    pub fn reduce_linear_pop(&mut self, a: &Arena, count: u32, trees: &mut Vec<u32>) -> bool {
        let len = self.nodes.len();
        if self.heads.len() != 1
            || self.heads[0].status != Status::Active
            || self.linear_base >= len
            || self.heads[0].node as usize + 1 != len
        {
            return false;
        }
        let mut idx = len - 1;
        let mut c = 0u32;
        while c < count {
            if idx <= self.linear_base {
                return false;
            }
            let l = self.nodes[idx].first;
            if l.tree != NONE {
                if !a.n(l.tree).extra() {
                    c += 1;
                }
            } else {
                c += 1;
            }
            idx -= 1;
        }
        trees.clear();
        for n in &self.nodes[(idx + 1)..len] {
            let t = n.first.tree;
            if t != NONE {
                trees.push(t);
            }
        }
        self.nodes.truncate(idx + 1);
        self.heads[0].node = idx as u32;
        true
    }

    /// 受信任热路径内部版本:由 [`Parser::run`](crate::parser::Parser::run) 的结构归纳前置条件保证全部下标合法。
    ///
    /// # Safety
    /// 调用方必须保证 `v < self.heads.len()`、`self.heads[v].node < self.nodes.len()`,且 `tree != NONE` 时
    /// `tree` 在 `a` 中有效。
    #[inline(always)]
    pub(crate) unsafe fn push_unchecked(
        &mut self,
        a: &Arena,
        v: usize,
        tree: u32,
        pending: bool,
        state: u16,
    ) {
        // SAFETY: 由调用方契约保证 `v < heads.len()` 且 `prev_us < nodes.len()`。
        let prev = unsafe { self.heads.get_unchecked(v).node };
        let prev_us = prev as usize;
        let new_id = self.nodes.len();
        if self.heads.len() == 1
            && v == 0
            && unsafe { self.heads.get_unchecked(0).status } == Status::Active
        {
            if prev_us + 1 != new_id || self.linear_base > prev_us {
                self.linear_base = new_id;
            }
        } else {
            self.linear_base = usize::MAX;
        }
        // SAFETY: `prev_us < self.nodes.len()`。
        let p = unsafe { *self.nodes.get_unchecked(prev_us) };
        let mut n = SNode {
            state,
            link_len: 1,
            pos: p.pos,
            first: Link::new(prev, tree, pending),
            extra_links: NONE,
            error_cost: p.error_cost,
            node_count: p.node_count,
            dprec: p.dprec,
            depth: p.depth + 1,
        };
        if tree != NONE {
            // SAFETY: 由调用方保证 `tree` 在 `a` 中有效。
            let t = *unsafe { a.n_unchecked(tree) };
            n.pos = n.pos.add(t.total());
            let ext_u8 = t.ext_inline();
            if !t.has_cold() {
                n.node_count += t.inline_vis() + t.visible() as u32;
                if ext_u8 < crate::tree::EXT_COLD_U8 {
                    // SAFETY: `v < self.heads.len()`。
                    unsafe { self.heads.get_unchecked_mut(v).ext = ext_u8 as u32 };
                }
            } else {
                // SAFETY: 由调用方保证 `tree` 及其冷节点在 `a` 中有效。
                unsafe {
                    n.error_cost = n.error_cost.wrapping_add(a.cost_unchecked(tree));
                    n.node_count += subtree_node_count_unchecked(a, tree);
                    n.dprec += a.dprec_unchecked(tree);
                    let te = a.ext_id_unchecked(tree);
                    if te != NONE {
                        self.heads.get_unchecked_mut(v).ext = te;
                    }
                }
            }
        }
        self.nodes.push(n);
        let id = new_id as u32;
        // SAFETY: `v < self.heads.len()`。
        let h = unsafe { self.heads.get_unchecked_mut(v) };
        h.node = id;
        if tree == NONE {
            h.node_count_at_last_error = n.node_count;
        }
    }

    /// 受信任热路径内部版本:原地弹出线性栈段。
    ///
    /// # Safety
    /// 调用方必须保证 `self.nodes` 内所有非 `NONE` `first.tree` 均为 `a` 内有效下标且 `linear_base` 不变量成立。
    #[inline]
    pub(crate) unsafe fn reduce_linear_pop_unchecked(
        &mut self,
        a: &Arena,
        count: u32,
        trees: &mut Vec<u32>,
    ) -> bool {
        let len = self.nodes.len();
        if self.heads.len() != 1
            || unsafe { self.heads.get_unchecked(0).status } != Status::Active
            || self.linear_base >= len
            || unsafe { self.heads.get_unchecked(0).node } as usize + 1 != len
        {
            return false;
        }
        let mut idx = len - 1;
        let mut c = 0u32;
        while c < count {
            if idx <= self.linear_base {
                return false;
            }
            // SAFETY: `self.linear_base < idx < len`,线性不变量保证 `link_len == 1` 且 `first.node() == idx - 1`。
            let l = unsafe { self.nodes.get_unchecked(idx).first };
            if l.tree != NONE {
                // SAFETY: 由调用方保证 `l.tree` 在 `a` 内有效。
                if !unsafe { a.n_unchecked(l.tree) }.extra() {
                    c += 1;
                }
            } else {
                c += 1;
            }
            idx -= 1;
        }
        trees.clear();
        for k in (idx + 1)..len {
            // SAFETY: `k < len`。
            let t = unsafe { self.nodes.get_unchecked(k).first.tree };
            if t != NONE {
                trees.push(t);
            }
        }
        self.nodes.truncate(idx + 1);
        // SAFETY: `self.heads.len() == 1`。
        unsafe { self.heads.get_unchecked_mut(0).node = idx as u32 };
        true
    }

    /// 官方 `stack_node_add_link`(改成工作表迭代,避免深递归)。
    fn add_link(&mut self, a: &Arena, target: u32, link: Link) {
        self.linear_base = usize::MAX;
        let mut work = vec![(target, link)];
        while let Some((me, link)) = work.pop() {
            let link_node = link.node();
            if link_node == me {
                continue;
            }
            let mut handled = false;
            let lcnt = self.link_count(me);
            for i in 0..lcnt {
                let ex = self.link_at(me, i);
                if equivalent(a, ex.tree, link.tree) {
                    let ex_node = ex.node();
                    if ex_node == link_node {
                        if link.tree != NONE
                            && ex.tree != NONE
                            && a.dprec(link.tree) > a.dprec(ex.tree)
                        {
                            self.set_link(me, i, link);
                            let d = self.nodes[link_node as usize].dprec + a.dprec(link.tree);
                            self.nodes[me as usize].dprec = d;
                        }
                        handled = true;
                        break;
                    }
                    let (en, ln) = (
                        &self.nodes[ex_node as usize],
                        &self.nodes[link_node as usize],
                    );
                    if en.state == ln.state
                        && en.pos.bytes == ln.pos.bytes
                        && en.error_cost == ln.error_cost
                    {
                        let mut dp = ln.dprec;
                        let (sub, slen) = self.copy_links(link_node);
                        if link.tree != NONE {
                            dp += a.dprec(link.tree);
                        }
                        for l in &sub[..slen] {
                            work.push((ex_node, *l));
                        }
                        if dp > self.nodes[me as usize].dprec {
                            self.nodes[me as usize].dprec = dp;
                        }
                        handled = true;
                        break;
                    }
                }
            }
            if handled || self.link_count(me) == MAX_LINK_COUNT {
                continue;
            }
            let mut nc = self.nodes[link_node as usize].node_count;
            let mut dp = self.nodes[link_node as usize].dprec;
            if link.tree != NONE {
                nc += subtree_node_count(a, link.tree);
                dp += a.dprec(link.tree);
            }
            self.push_node_link(me, link);
            let m = &mut self.nodes[me as usize];
            if nc > m.node_count {
                m.node_count = nc;
            }
            if dp > m.dprec {
                m.dprec = dp;
            }
        }
    }

    pub fn can_merge(&self, v1: usize, v2: usize) -> bool {
        let (h1, h2) = (&self.heads[v1], &self.heads[v2]);
        let (n1, n2) = (&self.nodes[h1.node as usize], &self.nodes[h2.node as usize]);
        h1.status == Status::Active
            && h2.status == Status::Active
            && n1.state == n2.state
            && n1.pos.bytes == n2.pos.bytes
            && n1.error_cost == n2.error_cost
            && h1.ext == h2.ext
    }

    pub fn merge(&mut self, a: &Arena, v1: usize, v2: usize) -> bool {
        if !self.can_merge(v1, v2) {
            return false;
        }
        self.linear_base = usize::MAX;
        let (n1, n2) = (self.heads[v1].node, self.heads[v2].node);
        let (links, len) = self.copy_links(n2);
        for &l in &links[..len] {
            self.add_link(a, n1, l);
        }
        if self.nodes[n1 as usize].state == ERROR_STATE {
            self.heads[v1].node_count_at_last_error = self.nodes[n1 as usize].node_count;
        }
        self.remove_version(v2);
        true
    }

    pub fn remove_version(&mut self, v: usize) {
        self.linear_base = usize::MAX;
        self.heads.remove(v);
    }

    pub fn renumber_version(&mut self, v1: usize, v2: usize) {
        if v1 == v2 {
            return;
        }
        self.linear_base = usize::MAX;
        let mut src = self.heads.remove(v1);
        if self.heads[v2].summary.is_some() && src.summary.is_none() {
            src.summary = self.heads[v2].summary.take();
        }
        self.heads[v2] = src;
    }

    pub fn swap_versions(&mut self, v1: usize, v2: usize) {
        self.linear_base = usize::MAX;
        self.heads.swap(v1, v2);
    }

    pub fn copy_version(&mut self, v: usize) -> usize {
        self.linear_base = usize::MAX;
        let mut h = self.heads[v].clone();
        h.summary = None;
        self.heads.push(h);
        self.heads.len() - 1
    }

    pub fn pause(&mut self, v: usize, lookahead: u32) {
        self.linear_base = usize::MAX;
        let nc = self.nodes[self.heads[v].node as usize].node_count;
        let h = &mut self.heads[v];
        h.status = Status::Paused;
        h.paused_lookahead = lookahead;
        h.node_count_at_last_error = nc;
    }

    pub fn resume(&mut self, v: usize) -> u32 {
        self.linear_base = usize::MAX;
        let h = &mut self.heads[v];
        h.status = Status::Active;
        std::mem::replace(&mut h.paused_lookahead, NONE)
    }

    pub fn has_advanced_since_error(&self, a: &Arena, v: usize) -> bool {
        let h = &self.heads[v];
        let mut node = h.node;
        if self.nodes[node as usize].error_cost == 0 {
            return true;
        }
        loop {
            let n = &self.nodes[node as usize];
            if n.link_len > 0 && n.first.tree != NONE {
                let l = n.first;
                let t = a.n(l.tree);
                if t.total().bytes > 0 {
                    return true;
                } else if n.node_count > h.node_count_at_last_error && a.cost(l.tree) == 0 {
                    node = l.node();
                    continue;
                }
            }
            return false;
        }
    }

    /// 通用遍历,回调返回 (弹出, 停止)。`goal >= 0` 时收集子树。
    fn iter(
        &mut self,
        a: &Arena,
        version: usize,
        goal: i32,
        mut cb: impl FnMut(&Iter, &SNode) -> (bool, bool),
    ) -> Vec<Slice> {
        let mut slices: Vec<Slice> = Vec::new();
        let include = goal >= 0;
        let mut its = vec![Iter {
            node: self.heads[version].node,
            trees: Vec::new(),
            count: 0,
            pending: true,
        }];
        while !its.is_empty() {
            let mut i = 0usize;
            let mut size = its.len();
            while i < size {
                let node_id = its[i].node;
                let (pop, stop0) = cb(&its[i], &self.nodes[node_id as usize]);
                let link_count = self.link_count(node_id);
                let stop = stop0 || link_count == 0;
                if pop {
                    let mut trees = if stop {
                        std::mem::take(&mut its[i].trees)
                    } else {
                        its[i].trees.clone()
                    };
                    trees.reverse();
                    self.add_slice(version, node_id, trees, &mut slices);
                }
                if stop {
                    its.remove(i);
                    size -= 1;
                    continue;
                }
                for j in 1..=link_count {
                    let (link, idx);
                    if j == link_count {
                        link = self.link_at(node_id, 0);
                        idx = i;
                    } else {
                        if its.len() >= MAX_ITERATOR_COUNT {
                            continue;
                        }
                        link = self.link_at(node_id, j);
                        let c = Iter {
                            node: its[i].node,
                            trees: its[i].trees.clone(),
                            count: its[i].count,
                            pending: its[i].pending,
                        };
                        its.push(c);
                        idx = its.len() - 1;
                    }
                    let it = &mut its[idx];
                    it.node = link.node();
                    if link.tree != NONE {
                        if include {
                            it.trees.push(link.tree);
                        }
                        if !a.n(link.tree).extra() {
                            it.count += 1;
                            if !link.pending() {
                                it.pending = false;
                            }
                        }
                    } else {
                        it.count += 1;
                        it.pending = false;
                    }
                }
                i += 1;
            }
        }
        slices
    }

    fn add_slice(&mut self, original: usize, node: u32, trees: Vec<u32>, slices: &mut Vec<Slice>) {
        self.linear_base = usize::MAX;
        for i in (0..slices.len()).rev() {
            let v = slices[i].version;
            if self.heads[v].node == node {
                slices.insert(i + 1, Slice { version: v, trees });
                return;
            }
        }
        let o = &self.heads[original];
        let head = Head {
            node,
            status: Status::Active,
            node_count_at_last_error: o.node_count_at_last_error,
            summary: None,
            paused_lookahead: NONE,
            ext: o.ext,
        };
        self.heads.push(head);
        slices.push(Slice {
            version: self.heads.len() - 1,
            trees,
        });
    }

    /// 无分叉单链快路径:沿唯一前驱走 `count` 步并将子树逆序写入可复用 `trees`,遇到分叉返回 `None`。
    pub fn pop_count_fast(
        &mut self,
        a: &Arena,
        v: usize,
        count: u32,
        trees: &mut Vec<u32>,
    ) -> Option<usize> {
        trees.clear();
        let mut node_id = self.heads[v].node;
        let mut c = 0u32;
        while c < count {
            let n = &self.nodes[node_id as usize];
            if n.link_len != 1 {
                return None;
            }
            let l = n.first;
            node_id = l.node();
            if l.tree != NONE {
                trees.push(l.tree);
                if !a.n(l.tree).extra() {
                    c += 1;
                }
            } else {
                c += 1;
            }
        }
        trees.reverse();
        self.linear_base = usize::MAX;
        let o = &self.heads[v];
        self.heads.push(Head {
            node: node_id,
            status: Status::Active,
            node_count_at_last_error: o.node_count_at_last_error,
            summary: None,
            paused_lookahead: NONE,
            ext: o.ext,
        });
        Some(self.heads.len() - 1)
    }

    pub fn pop_count(&mut self, a: &Arena, v: usize, count: u32) -> Vec<Slice> {
        self.iter(a, v, count as i32, |it, _| {
            if it.count == count {
                (true, true)
            } else {
                (false, false)
            }
        })
    }

    pub fn pop_all(&mut self, a: &Arena, v: usize) -> Vec<Slice> {
        self.iter(a, v, 0, |_, n| (n.link_len == 0, false))
    }

    pub fn pop_error(&mut self, a: &Arena, v: usize) -> Vec<u32> {
        let node = self.heads[v].node;
        let lcnt = self.link_count(node);
        let mut has = false;
        for i in 0..lcnt {
            let l = self.link_at(node, i);
            if l.tree != NONE && a.n(l.tree).is_error() {
                has = true;
                break;
            }
        }
        if !has {
            return Vec::new();
        }
        let mut found = false;
        let mut pop = self.iter(a, v, 1, |it, _| {
            if !it.trees.is_empty() {
                if !found && a.n(it.trees[0]).is_error() {
                    found = true;
                    (true, true)
                } else {
                    (false, true)
                }
            } else {
                (false, false)
            }
        });
        if pop.is_empty() {
            return Vec::new();
        }
        let s = pop.remove(0);
        self.renumber_version(s.version, v);
        s.trees
    }

    pub fn record_summary(&mut self, a: &Arena, v: usize, max_depth: u32) {
        let mut summary: Vec<SumEntry> = Vec::new();
        let mut cb_summary = std::mem::take(&mut summary);
        self.iter(a, v, -1, |it, n| {
            let depth = it.count;
            if depth > max_depth {
                return (false, true);
            }
            for e in cb_summary.iter().rev() {
                if e.depth < depth {
                    break;
                }
                if e.depth == depth && e.state == n.state {
                    return (false, false);
                }
            }
            cb_summary.push(SumEntry {
                pos: n.pos,
                depth,
                state: n.state,
            });
            (false, false)
        });
        self.heads[v].summary = Some(cb_summary);
    }
}

impl Default for Stack {
    fn default() -> Self {
        Self::new()
    }
}