yolowsyntax 0.2.0

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
//! 子树竞技场:紧凑 32 字节(半缓存行)热节点(内联 `ext_u8` 与可见后代计数)+ 冷元数据旁路表,无递归释放。

use crate::table::{Language, SYM_ERROR, SYM_ERROR_REPEAT};

pub const ERROR_COST_PER_RECOVERY: u32 = 500;
pub const ERROR_COST_PER_MISSING_TREE: u32 = 110;
pub const ERROR_COST_PER_SKIPPED_TREE: u32 = 100;
pub const ERROR_COST_PER_SKIPPED_LINE: u32 = 30;
pub const ERROR_COST_PER_SKIPPED_CHAR: u32 = 1;

/// 位置/长度:字节数与行数(换行个数)。
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Len {
    pub bytes: u32,
    pub rows: u32,
}

impl Len {
    #[inline(always)]
    #[allow(clippy::should_implement_trait)]
    pub fn add(self, o: Len) -> Len {
        Len {
            bytes: self.bytes.wrapping_add(o.bytes),
            rows: self.rows.wrapping_add(o.rows),
        }
    }
    #[inline(always)]
    #[allow(clippy::should_implement_trait)]
    pub fn sub(self, o: Len) -> Len {
        Len {
            bytes: self.bytes.wrapping_sub(o.bytes),
            rows: self.rows.wrapping_sub(o.rows),
        }
    }
}

pub const NONE: u32 = u32::MAX;

pub const F_VISIBLE: u8 = 1;
pub const F_NAMED: u8 = 2;
pub const F_EXTRA: u8 = 4;
pub const F_MISSING: u8 = 8;
pub const F_KEYWORD: u8 = 16;

const F_COLD_BIT: u32 = 1 << 5;
const FLAGS_MASK: u32 = 0x1F;
const MAX_INLINE_VIS: u32 = (1 << 26) - 1;
const CHILD_COUNT_MASK: u32 = 0x00FF_FFFF;
pub(crate) const EXT_COLD_U8: u8 = 254;
pub(crate) const EXT_NONE_U8: u8 = 255;
const EXT_NONE_HI: u32 = (EXT_NONE_U8 as u32) << 24;

/// 紧凑 32 字节(精确半条 64B 缓存行)语法树节点。
///
/// - `child_count_ext` 低 24 位存子节点数,高 8 位内联外部扫描器状态编号(`0..=253` 直接存储,
///   `255` 表示无外部记号,`254` 表示溢出至 `Arena::cold`),使 Python/Rust/Bash/HTML/JS/TS 等全部带外部扫描器的语言
///   99.9% 节点均零 `ColdNode` 分配并命中热归约快路径。
/// - `packed` 低 5 位为 `F_*` 标志,位 5 为 `F_COLD_BIT`,高 26 位内联 `visible_descendants` 或 `Arena::cold` 下标。
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Node {
    pub padding: Len,
    pub size: Len,
    /// `child_count() > 0` 时为 `kids` 起始下标;`child_count() == 0` 时复用存放 ERROR 叶子跳过的首字符(`lchar`)。
    pub first_child: u32,
    pub child_count_ext: u32,
    pub sym: u16,
    pub prod: u16,
    pub packed: u32,
}

const _: () = assert!(core::mem::size_of::<Node>() == 32);

/// 冷节点扩展元数据(仅在有错误代价、非零动态优先级、`ext >= 254` 或超大可见后代计数时分配)。
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct ColdNode {
    pub error_cost: u32,
    pub dprec: i32,
    pub visible_descendants: u32,
    pub ext: u32,
}

impl Node {
    #[inline(always)]
    pub fn child_count(&self) -> u32 {
        self.child_count_ext & CHILD_COUNT_MASK
    }
    #[inline(always)]
    pub(crate) fn ext_inline(&self) -> u8 {
        (self.child_count_ext >> 24) as u8
    }
    #[inline(always)]
    pub fn flags(&self) -> u8 {
        (self.packed & FLAGS_MASK) as u8
    }
    #[inline(always)]
    pub(crate) fn has_cold(&self) -> bool {
        (self.packed & F_COLD_BIT) != 0
    }
    #[inline(always)]
    pub(crate) fn cold_idx(&self) -> usize {
        (self.packed >> 6) as usize
    }
    #[inline(always)]
    pub(crate) fn inline_vis(&self) -> u32 {
        self.packed >> 6
    }
    #[inline(always)]
    pub fn set_flag(&mut self, f: u8) {
        self.packed |= f as u32;
    }
    #[inline(always)]
    pub fn clear_flag(&mut self, f: u8) {
        self.packed &= !(f as u32);
    }
    #[inline(always)]
    pub fn lchar(&self) -> u32 {
        if self.child_count() == 0 {
            self.first_child
        } else {
            0
        }
    }
    #[inline(always)]
    pub fn set_lchar(&mut self, ch: u32) {
        if self.child_count() == 0 {
            self.first_child = ch;
        }
    }
    #[inline(always)]
    pub fn extra(&self) -> bool {
        (self.packed & F_EXTRA as u32) != 0
    }
    #[inline(always)]
    pub fn visible(&self) -> bool {
        (self.packed & F_VISIBLE as u32) != 0
    }
    #[inline(always)]
    pub fn named(&self) -> bool {
        (self.packed & F_NAMED as u32) != 0
    }
    #[inline(always)]
    pub fn missing(&self) -> bool {
        (self.packed & F_MISSING as u32) != 0
    }
    #[inline(always)]
    pub fn is_keyword(&self) -> bool {
        (self.packed & F_KEYWORD as u32) != 0
    }
    #[inline(always)]
    pub fn is_error(&self) -> bool {
        self.sym == SYM_ERROR
    }
    #[inline(always)]
    pub fn total(&self) -> Len {
        self.padding.add(self.size)
    }
}

#[derive(Default)]
pub struct Arena {
    pub nodes: Vec<Node>,
    pub kids: Vec<u32>,
    pub(crate) cold: Vec<ColdNode>,
    /// 去重后的扫描器状态;编号 0 固定表示空状态,编号 i>0 对应 `ext[i-1]`。
    pub ext: Vec<Vec<u8>>,
    pub(crate) ext_hashes: Vec<u64>,
    pub(crate) ext_table: Vec<u32>,
    pub ext_total: usize,
    /// 延迟记忆化缓存:仅在错误恢复统计不可见节点的 `visible_children` 时按需分配,避免 O(N²)。
    pub(crate) vc_cache: Vec<u32>,
}

#[inline(always)]
fn extent_cost(size: Len) -> u32 {
    ERROR_COST_PER_RECOVERY
        .wrapping_add(ERROR_COST_PER_SKIPPED_CHAR.wrapping_mul(size.bytes))
        .wrapping_add(ERROR_COST_PER_SKIPPED_LINE.wrapping_mul(size.rows))
}

#[inline(always)]
fn hash_bytes(bytes: &[u8]) -> u64 {
    let mut h = 0xcbf29ce484222325u64 ^ (bytes.len() as u64);
    for &b in bytes {
        h ^= b as u64;
        h = h.wrapping_mul(0x100000001b3);
    }
    h ^ (h >> 33)
}

impl Arena {
    #[inline(always)]
    pub fn n(&self, i: u32) -> &Node {
        debug_assert!((i as usize) < self.nodes.len());
        // SAFETY: 所有竞技场内部 `Node` 下标均由 `Arena::push` 返回且在整理时同步重映射。
        unsafe { self.nodes.get_unchecked(i as usize) }
    }
    #[inline(always)]
    pub fn n_mut(&mut self, i: u32) -> &mut Node {
        debug_assert!((i as usize) < self.nodes.len());
        // SAFETY: 同 `n`。
        unsafe { self.nodes.get_unchecked_mut(i as usize) }
    }

    #[inline(always)]
    pub fn cost(&self, id: u32) -> u32 {
        let n = self.n(id);
        if !n.has_cold() {
            0
        } else {
            // SAFETY: `F_COLD_BIT` 置位时 `cold_idx < self.cold.len()`。
            unsafe { self.cold.get_unchecked(n.cold_idx()).error_cost }
        }
    }

    #[inline(always)]
    pub fn dprec(&self, id: u32) -> i32 {
        let n = self.n(id);
        if !n.has_cold() {
            0
        } else {
            // SAFETY: 同 `cost`。
            unsafe { self.cold.get_unchecked(n.cold_idx()).dprec }
        }
    }

    #[inline(always)]
    pub fn ext_id(&self, id: u32) -> u32 {
        let n = self.n(id);
        let e = n.ext_inline();
        if e == EXT_NONE_U8 {
            NONE
        } else if e < EXT_COLD_U8 {
            e as u32
        } else {
            // SAFETY: `ext_inline == EXT_COLD_U8` 时 `F_COLD_BIT` 必置位且 `cold_idx < self.cold.len()`。
            unsafe { self.cold.get_unchecked(n.cold_idx()).ext }
        }
    }

    #[inline(always)]
    pub fn vis_desc(&self, id: u32) -> u32 {
        let n = self.n(id);
        if !n.has_cold() {
            n.inline_vis()
        } else {
            // SAFETY: 同 `cost`。
            unsafe { self.cold.get_unchecked(n.cold_idx()).visible_descendants }
        }
    }

    #[inline]
    fn ensure_cold_mut(&mut self, id: u32) -> &mut ColdNode {
        let n = self.nodes[id as usize];
        if n.has_cold() {
            let idx = n.cold_idx();
            &mut self.cold[idx]
        } else {
            let e = n.ext_inline();
            let ext = if e == EXT_NONE_U8 { NONE } else { e as u32 };
            let idx = self.cold.len() as u32;
            self.cold.push(ColdNode {
                error_cost: 0,
                dprec: 0,
                visible_descendants: n.inline_vis(),
                ext,
            });
            self.nodes[id as usize].packed = (n.packed & FLAGS_MASK) | F_COLD_BIT | (idx << 6);
            // SAFETY: 刚推入元素,`idx == self.cold.len() - 1`。
            unsafe { self.cold.get_unchecked_mut(idx as usize) }
        }
    }

    #[inline]
    pub fn set_error_cost(&mut self, id: u32, cost: u32) {
        if cost != 0 || self.n(id).has_cold() {
            self.ensure_cold_mut(id).error_cost = cost;
        }
    }

    #[inline]
    pub fn add_dprec(&mut self, id: u32, delta: i32) {
        if delta != 0 {
            self.ensure_cold_mut(id).dprec += delta;
        }
    }

    #[inline(always)]
    pub fn set_ext(&mut self, id: u32, ext: u32) {
        if ext == NONE {
            return;
        }
        if ext < EXT_COLD_U8 as u32 {
            let n = self.n_mut(id);
            n.child_count_ext = (n.child_count_ext & CHILD_COUNT_MASK) | (ext << 24);
            if n.has_cold() {
                let idx = n.cold_idx();
                self.cold[idx].ext = ext;
            }
        } else {
            let n = self.n_mut(id);
            n.child_count_ext =
                (n.child_count_ext & CHILD_COUNT_MASK) | ((EXT_COLD_U8 as u32) << 24);
            self.ensure_cold_mut(id).ext = ext;
        }
    }

    #[inline]
    fn alloc_cold(&mut self, c: ColdNode) -> u32 {
        let idx = self.cold.len() as u32;
        self.cold.push(c);
        idx
    }

    /// 登记一份扫描器状态,相同内容共用同一个编号(无加密哈希、单份存储)。
    pub fn intern_ext(&mut self, bytes: &[u8]) -> u32 {
        if bytes.is_empty() {
            return 0;
        }
        let h = hash_bytes(bytes);
        if self.ext_table.is_empty() {
            self.ext_table.resize(32, 0);
        } else if (self.ext.len() + 1) * 2 >= self.ext_table.len() {
            let new_cap = self.ext_table.len() * 2;
            let mut nt = vec![0u32; new_cap];
            let mask = new_cap - 1;
            for (idx0, &eh) in self.ext_hashes.iter().enumerate() {
                let mut pos = (eh as usize) & mask;
                while nt[pos] != 0 {
                    pos = (pos + 1) & mask;
                }
                nt[pos] = (idx0 + 1) as u32;
            }
            self.ext_table = nt;
        }
        let mask = self.ext_table.len() - 1;
        let mut pos = (h as usize) & mask;
        loop {
            let slot = self.ext_table[pos];
            if slot == 0 {
                self.ext.push(bytes.to_vec());
                self.ext_hashes.push(h);
                let id = self.ext.len() as u32;
                self.ext_table[pos] = id;
                self.ext_total += bytes.len();
                return id;
            }
            let idx = (slot - 1) as usize;
            if self.ext_hashes[idx] == h && self.ext[idx].as_slice() == bytes {
                return slot;
            }
            pos = (pos + 1) & mask;
        }
    }

    #[inline(always)]
    pub fn ext_bytes(&self, i: u32) -> &[u8] {
        if i == 0 || i == NONE {
            &[]
        } else {
            self.ext.get(i as usize - 1).map_or(&[], |v| v.as_slice())
        }
    }

    #[inline(always)]
    pub fn children(&self, i: u32) -> &[u32] {
        let n = self.n(i);
        let cc = n.child_count();
        if cc == 0 {
            &[]
        } else {
            let a = n.first_child as usize;
            let b = a + cc as usize;
            // SAFETY: `new_node` 与 `compact_arena` 保证 `a..b` 在 `self.kids` 范围内。
            unsafe { self.kids.get_unchecked(a..b) }
        }
    }

    #[inline(always)]
    pub fn new_leaf(&mut self, lang: &Language, sym: u16, padding: Len, size: Len) -> u32 {
        let flags = lang.leaf_flags_fast(sym) as u32;
        self.push(Node {
            padding,
            size,
            first_child: 0,
            child_count_ext: EXT_NONE_HI,
            sym,
            prod: 0,
            packed: flags,
        })
    }

    #[inline]
    pub fn new_missing_leaf(&mut self, lang: &Language, sym: u16) -> u32 {
        let flags = (lang.leaf_flags_fast(sym) | F_MISSING) as u32;
        let cidx = self.alloc_cold(ColdNode {
            error_cost: ERROR_COST_PER_MISSING_TREE + ERROR_COST_PER_RECOVERY,
            dprec: 0,
            visible_descendants: 0,
            ext: NONE,
        });
        self.push(Node {
            padding: Len::default(),
            size: Len::default(),
            first_child: 0,
            child_count_ext: EXT_NONE_HI,
            sym,
            prod: 0,
            packed: flags | F_COLD_BIT | (cidx << 6),
        })
    }

    #[inline(always)]
    fn push(&mut self, n: Node) -> u32 {
        let id = self.nodes.len() as u32;
        self.nodes.push(n);
        id
    }

    /// 记忆化统计不可见节点的 `visible_children`(仅在错误恢复包裹不可见节点时按需调用,消除 O(N²))。
    #[cold]
    fn count_visible_children(&mut self, lang: &Language, root_id: u32) -> u32 {
        let r = root_id as usize;
        if r < self.vc_cache.len() && self.vc_cache[r] != NONE {
            return self.vc_cache[r];
        }
        if self.vc_cache.len() <= r {
            self.vc_cache.resize(self.nodes.len(), NONE);
        }
        // 后序迭代计算并缓存整棵不可见子树,避免深递归栈溢出
        let mut stack: Vec<(u32, bool)> = vec![(root_id, false)];
        while let Some((id, expanded)) = stack.pop() {
            let idx = id as usize;
            if idx < self.vc_cache.len() && self.vc_cache[idx] != NONE {
                continue;
            }
            let n = self.nodes[idx];
            let cc = n.child_count() as usize;
            let start = n.first_child as usize;
            let end = start + cc;
            let alias = lang.alias_sequence(n.prod);
            if !expanded {
                stack.push((id, true));
                let mut structural = 0usize;
                for k in start..end {
                    let c = self.kids[k];
                    let ch = self.nodes[c as usize];
                    let aliased = !ch.extra()
                        && ch.sym != 0
                        && alias.is_some_and(|a| a.get(structural).copied().unwrap_or(0) != 0);
                    if !aliased && !ch.visible() && ch.child_count() > 0 {
                        let cu = c as usize;
                        if cu >= self.vc_cache.len() || self.vc_cache[cu] == NONE {
                            stack.push((c, false));
                        }
                    }
                    if !ch.extra() {
                        structural += 1;
                    }
                }
            } else {
                let mut count = 0u32;
                let mut structural = 0usize;
                for k in start..end {
                    let c = self.kids[k];
                    let ch = self.nodes[c as usize];
                    let aliased = !ch.extra()
                        && ch.sym != 0
                        && alias.is_some_and(|a| a.get(structural).copied().unwrap_or(0) != 0);
                    if aliased || ch.visible() {
                        count += 1;
                    } else if ch.child_count() > 0 {
                        count += self.vc_cache[c as usize];
                    }
                    if !ch.extra() {
                        structural += 1;
                    }
                }
                if idx >= self.vc_cache.len() {
                    self.vc_cache.resize(self.nodes.len(), NONE);
                }
                self.vc_cache[idx] = count;
            }
        }
        self.vc_cache[r]
    }

    /// 官方 `ts_subtree_new_node` + `summarize_children`(内联 `ext_u8`,95%+ 归约零 `ColdNode` 分配)。
    #[inline]
    pub fn new_node(&mut self, lang: &Language, sym: u16, children: &[u32], prod: u16) -> u32 {
        let n_kids = children.len();
        let is_err_parent = sym == SYM_ERROR || sym == SYM_ERROR_REPEAT;

        // 快路径 1:无错误/无 dprec/无别名的一元归约(含全部内联外部扫描器状态)。
        if n_kids == 1 && prod == 0 && !is_err_parent {
            // SAFETY: `n_kids == 1`。
            let c = unsafe { *children.get_unchecked(0) };
            let ch = *self.n(c);
            if !ch.has_cold() {
                let vis = ch.inline_vis() + ch.visible() as u32;
                if vis <= MAX_INLINE_VIS {
                    let first_child = self.kids.len() as u32;
                    self.kids.push(c);
                    let flags = lang.node_flags_fast(sym) as u32;
                    return self.push(Node {
                        padding: ch.padding,
                        size: ch.size,
                        first_child,
                        child_count_ext: (ch.child_count_ext & 0xFF00_0000) | 1,
                        sym,
                        prod: 0,
                        packed: flags | (vis << 6),
                    });
                }
            }
        }

        // 快路径 2:无错误/无 dprec/无别名的多元归约(单条 cmovne 传播内联 `ext_u8`)。
        if n_kids > 1 && n_kids <= CHILD_COUNT_MASK as usize && prod == 0 && !is_err_parent {
            // SAFETY: `n_kids > 1`。
            let c0 = unsafe { *children.get_unchecked(0) };
            let ch0 = *self.n(c0);
            let padding = ch0.padding;
            let mut size = ch0.size;
            let mut or_packed = ch0.packed;
            let mut vis = ch0.inline_vis() + ch0.visible() as u32;
            let mut ext_hi = ch0.child_count_ext & 0xFF00_0000;
            for &c in unsafe { children.get_unchecked(1..) } {
                let ch = *self.n(c);
                size = size.add(ch.total());
                or_packed |= ch.packed;
                vis = vis.wrapping_add(ch.inline_vis() + ch.visible() as u32);
                let ce = ch.child_count_ext & 0xFF00_0000;
                if ce != EXT_NONE_HI {
                    ext_hi = ce;
                }
            }
            if (or_packed & F_COLD_BIT) == 0 && vis <= MAX_INLINE_VIS {
                let first_child = self.kids.len() as u32;
                self.kids.extend_from_slice(children);
                let flags = lang.node_flags_fast(sym) as u32;
                return self.push(Node {
                    padding,
                    size,
                    first_child,
                    child_count_ext: ext_hi | (n_kids as u32),
                    sym,
                    prod: 0,
                    packed: flags | (vis << 6),
                });
            }
        }

        self.new_node_general(lang, sym, children, prod, is_err_parent)
    }

    fn new_node_general(
        &mut self,
        lang: &Language,
        sym: u16,
        children: &[u32],
        prod: u16,
        is_err_parent: bool,
    ) -> u32 {
        let first_child = self.kids.len() as u32;
        self.kids.extend_from_slice(children);
        let flags = lang.node_flags_fast(sym) as u32;
        let mut padding = Len::default();
        let mut size = Len::default();
        let mut error_cost = 0u32;
        let mut dprec = 0i32;
        let mut vis_desc = 0u32;
        let mut ext = NONE;

        let alias = lang.alias_sequence(prod);
        let mut structural = 0usize;
        for (i, &c) in children.iter().enumerate() {
            let ch = *self.n(c);
            if i == 0 {
                padding = ch.padding;
                size = ch.size;
            } else {
                size = size.add(ch.total());
            }
            let (ch_cost, ch_dprec, ch_vis, ch_ext) = if ch.has_cold() {
                // SAFETY: `F_COLD_BIT` 置位时 `cold_idx < self.cold.len()`。
                let cn = unsafe { *self.cold.get_unchecked(ch.cold_idx()) };
                let ce = {
                    let e = ch.ext_inline();
                    if e == EXT_NONE_U8 {
                        NONE
                    } else if e < EXT_COLD_U8 {
                        e as u32
                    } else {
                        cn.ext
                    }
                };
                (cn.error_cost, cn.dprec, cn.visible_descendants, ce)
            } else {
                let e = ch.ext_inline();
                let ce = if e == EXT_NONE_U8 { NONE } else { e as u32 };
                (0, 0, ch.inline_vis(), ce)
            };
            if ch.sym == SYM_ERROR_REPEAT {
                error_cost = error_cost.wrapping_add(ch_cost.wrapping_sub(extent_cost(ch.size)));
            } else {
                error_cost = error_cost.wrapping_add(ch_cost);
                let gc = ch.child_count();
                if is_err_parent && !ch.extra() && !(ch.is_error() && gc == 0) {
                    if ch.visible() {
                        error_cost = error_cost.wrapping_add(ERROR_COST_PER_SKIPPED_TREE);
                    } else if gc > 0 {
                        let vc = self.count_visible_children(lang, c);
                        error_cost =
                            error_cost.wrapping_add(ERROR_COST_PER_SKIPPED_TREE.wrapping_mul(vc));
                    }
                }
            }
            dprec += ch_dprec;
            if ch_ext != NONE {
                ext = ch_ext;
            }
            vis_desc += ch_vis;
            let aliased = !ch.extra()
                && ch.sym != 0
                && alias.is_some_and(|a| a.get(structural).copied().unwrap_or(0) != 0);
            if aliased || ch.visible() {
                vis_desc += 1;
            }
            if !ch.extra() {
                structural += 1;
            }
        }
        if is_err_parent {
            error_cost = error_cost.wrapping_add(extent_cost(size));
        }

        let (ext_hi, ext_needs_cold) = if ext == NONE {
            (EXT_NONE_HI, false)
        } else if ext < EXT_COLD_U8 as u32 {
            (ext << 24, false)
        } else {
            ((EXT_COLD_U8 as u32) << 24, true)
        };

        let packed =
            if error_cost == 0 && dprec == 0 && !ext_needs_cold && vis_desc <= MAX_INLINE_VIS {
                flags | (vis_desc << 6)
            } else {
                let cidx = self.alloc_cold(ColdNode {
                    error_cost,
                    dprec,
                    visible_descendants: vis_desc,
                    ext,
                });
                flags | F_COLD_BIT | (cidx << 6)
            };
        let cc = (children.len() as u32).min(CHILD_COUNT_MASK);
        self.push(Node {
            padding,
            size,
            first_child,
            child_count_ext: ext_hi | cc,
            sym,
            prod,
            packed,
        })
    }

    pub fn new_error_node(&mut self, lang: &Language, children: &[u32], extra: bool) -> u32 {
        let i = self.new_node(lang, SYM_ERROR, children, 0);
        if extra {
            self.n_mut(i).set_flag(F_EXTRA);
        }
        i
    }

    /// 官方 `ts_subtree_compare`:按符号、子节点数逐个比较,返回 -1/0/1。
    pub fn compare(&self, a: u32, b: u32) -> i32 {
        let mut work = vec![(a, b)];
        while let Some((l, r)) = work.pop() {
            let (ln, rn) = (self.n(l), self.n(r));
            let res = if ln.sym < rn.sym {
                -1
            } else if rn.sym < ln.sym {
                1
            } else if ln.child_count() < rn.child_count() {
                -1
            } else if rn.child_count() < ln.child_count() {
                1
            } else {
                0
            };
            if res != 0 {
                return res;
            }
            let (lc, rc) = (self.children(l), self.children(r));
            for i in (0..lc.len()).rev() {
                work.push((lc[i], rc[i]));
            }
        }
        0
    }
}