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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
//! 语法表与词法表运行时加速结构(自动机理论 + SIMD 数据布局)。
//!
//! - **Moore 状态输出分解与行去重**(Hopcroft 1971; Tarjan & Yao, CACM 1979):将逐字节 `accept` 提至状态级,
//!   对 128 字节 ASCII 转移行去重;大规模词法表辅以 Myhill–Nerode 字母表等价类压缩(Dragon Book §3.9.8)。
//! - **自动自环提取与 2-nibble SIMD 批量消耗**(Mytkowicz et al., ASPLOS 2014; Langdale & Lemire, VLDB 2019):
//!   为每个含自环的词法状态生成精确 16 字节 `vpshufb`/`vqtbl1q_u8` 查表掩码。
//! - **关键字 DFA→哈希表直译**:对无环 ASCII `keyword_lex` 提取精确开放寻址哈希表与首字节 128-bit 位图。
//! - **SoA 哨兵填充稀疏解析表 + 64-bit 内联单动作表**:适配 16-wide AVX2 / 8-wide NEON 并行符号查找,
//!   并将 >96% 确定性单动作内联为单次 `u64` 读取。

use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};

use crate::hw;
use crate::table::{Action, EOF_CP, Language, LexTable, NO_SYM, SYM_ERROR, SYM_ERROR_REPEAT};

/// 状态内不同 ASCII 字节具有不同 `accept` 的哨兵标记(极少数状态,退回 `Seg` 二分)。
pub(crate) const MIXED_ACCEPT: u16 = 0xFFFE;
/// 该词法状态无自环加速。
pub(crate) const NO_LOOP: u16 = 0xFFFF;
/// 该词法状态行未进入扁平直查表(退回 `Seg` 二分)。
pub(crate) const NO_ROW: u32 = u32::MAX;

/// 极轻量 FxHash,仅用于加载期表构造去重,无加密哈希开销。
#[derive(Default)]
struct FxHasher(u64);

impl Hasher for FxHasher {
    #[inline]
    fn finish(&self) -> u64 {
        self.0
    }
    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        let mut h = self.0;
        let (chunks, rem) = bytes.as_chunks::<8>();
        for c in chunks {
            let v = u64::from_ne_bytes(*c);
            h = (h.rotate_left(5) ^ v).wrapping_mul(0x517cc1b727220a95);
        }
        for &b in rem {
            h = (h.rotate_left(5) ^ b as u64).wrapping_mul(0x517cc1b727220a95);
        }
        self.0 = h;
    }
    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517cc1b727220a95);
    }
}

type FxMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;

/// 词法状态元数据:紧凑 8 字节,单次对齐加载获取行偏移、统一 `accept` 与自环编号。
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub(crate) struct LexStateMeta {
    pub(crate) row_off: u32,
    pub(crate) accept: u16,
    pub(crate) loop_id: u16,
}

/// 词法状态自环集合描述符(128-bit 精确 ASCII 掩码 + 16 字节 2-nibble SIMD 查表)。
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SelfLoop {
    pub(crate) lut16: [u8; 16],
    pub(crate) mask_lo: u64,
    pub(crate) mask_hi: u64,
    /// `1` = advance,`2` = skip。
    pub(crate) kind: u8,
    pub(crate) has_nl: bool,
}

impl SelfLoop {
    /// 判断 ASCII 字节 `b < 128` 是否在自环集合内。
    #[inline(always)]
    pub(crate) fn contains(&self, b: u8) -> bool {
        debug_assert!(b < 128);
        if b < 64 {
            (self.mask_lo >> b) & 1 != 0
        } else {
            (self.mask_hi >> (b - 64)) & 1 != 0
        }
    }
}

/// 词法表运行时加速结构(不参与 `Language` 逻辑等价性比较)。
#[derive(Clone, Debug)]
pub(crate) struct LexAccel {
    pub(crate) states: Vec<LexStateMeta>,
    pub(crate) loops: Vec<SelfLoop>,
    /// `true` 时直接用 `row_off + b` 查 `trans`;`false` 时经 `ascii_class[b]` 映射。
    pub(crate) direct: bool,
    pub(crate) ascii_class: [u8; 128],
    pub(crate) trans: Vec<u16>,
}

impl Default for LexAccel {
    fn default() -> Self {
        Self {
            states: Vec::new(),
            loops: Vec::new(),
            direct: true,
            ascii_class: [0; 128],
            trans: Vec::new(),
        }
    }
}

impl PartialEq for LexAccel {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}
impl Eq for LexAccel {}

#[inline]
fn hash_row_u16_128(row: &[u16; 128]) -> u64 {
    let mut h = 0xcbf29ce484222325u64;
    let ptr = row.as_ptr() as *const u64;
    for k in 0..32 {
        // SAFETY: `[u16; 128]` 占 256 字节,按未对齐 `u64` 读取 32 次完全在数组范围内。
        let v = unsafe { core::ptr::read_unaligned(ptr.add(k)) };
        h = (h.rotate_left(5) ^ v).wrapping_mul(0x517cc1b727220a95);
    }
    h
}

#[inline(always)]
fn range_mask_u128(pos: usize, end: usize) -> u128 {
    debug_assert!(pos < end && end <= 128);
    let hi = if end == 128 {
        u128::MAX
    } else {
        (1u128 << end) - 1
    };
    let lo = (1u128 << pos) - 1;
    hi ^ lo
}

/// 零拷贝开放寻址行去重表(仅存储 `unique_rows` 下标 + 哈希,避免克隆 256 字节键)。
struct RowDeduper {
    rows: Vec<[u16; 128]>,
    hashes: Vec<u64>,
    buckets: Vec<u32>,
    const_map: FxMap<u16, u32>,
}

impl RowDeduper {
    fn new(est: usize) -> Self {
        let cap = (est * 2).next_power_of_two().max(64);
        Self {
            rows: Vec::with_capacity(est.min(512)),
            hashes: Vec::with_capacity(est.min(512)),
            buckets: vec![0u32; cap],
            const_map: FxMap::default(),
        }
    }

    #[inline]
    fn intern_const(&mut self, val: u16) -> u32 {
        if let Some(&id) = self.const_map.get(&val) {
            return id;
        }
        let row = [val; 128];
        let id = self.intern(&row);
        self.const_map.insert(val, id);
        id
    }

    fn grow(&mut self) {
        let new_cap = self.buckets.len() * 2;
        let mut nb = vec![0u32; new_cap];
        let mask = new_cap - 1;
        for (i, &h) in self.hashes.iter().enumerate() {
            let mut pos = (h as usize) & mask;
            while nb[pos] != 0 {
                pos = (pos + 1) & mask;
            }
            nb[pos] = (i + 1) as u32;
        }
        self.buckets = nb;
    }

    #[inline]
    fn intern(&mut self, row: &[u16; 128]) -> u32 {
        let h = hash_row_u16_128(row);
        if (self.rows.len() + 1) * 2 >= self.buckets.len() {
            self.grow();
        }
        let mask = self.buckets.len() - 1;
        let mut pos = (h as usize) & mask;
        loop {
            let slot = self.buckets[pos];
            if slot == 0 {
                let id = self.rows.len() as u32;
                self.rows.push(*row);
                self.hashes.push(h);
                self.buckets[pos] = id + 1;
                return id;
            }
            let idx = (slot - 1) as usize;
            if self.hashes[idx] == h && &self.rows[idx] == row {
                return idx as u32;
            }
            pos = (pos + 1) & mask;
        }
    }
}

/// 构建 `LexTable` 的 Moore 因子化 + Mealy 汇状态融合(`kind=3`)+ 行去重 + 等价类 + 自环 SIMD 加速表。
pub(crate) fn build_lex_accel(t: &LexTable) -> LexAccel {
    let sc = t.state_count();
    if sc == 0 {
        return LexAccel::default();
    }

    // 预扫描纯接受汇状态:该状态对全部 0..=EOF_CP 均停止(kind==0)且接受同一符号 `sym < 0x3FFF`。
    // 指向此类汇状态的 `kind=1` 转移直接融合为操作码 `kind=3`(ADVANCE_AND_ACCEPT_SINK),省去整轮 DFA 迭代与两次访存。
    let mut sink_accept = vec![NO_SYM; sc];
    for (q, slot) in sink_accept.iter_mut().enumerate() {
        let a = t.starts[q] as usize;
        let b = t.starts[q + 1] as usize;
        if a < b {
            let first = t.segs[a];
            let sym = first.accept;
            if sym != NO_SYM
                && sym < 0x3FFF
                && t.segs[a..b]
                    .iter()
                    .all(|seg| seg.kind() == 0 && seg.accept == sym)
            {
                *slot = sym;
            }
        }
    }

    let mut states = Vec::with_capacity(sc);
    let mut loops: Vec<SelfLoop> = Vec::new();
    let mut loop_map: FxMap<(u64, u64, u8), u16> = FxMap::default();
    let mut deduper = RowDeduper::new(sc.min(1024));
    let mut state_row_idx: Vec<u32> = Vec::with_capacity(sc);

    for s in 0..sc {
        let a = t.starts[s] as usize;
        let b = t.starts[s + 1] as usize;

        // 快路径:单段常值状态(占词法状态 ~50%,如纯接受汇态与全跳过态),O(1) 跳过 128 字节填充与哈希。
        if b == a + 1 || a >= b {
            let seg = if a < b {
                t.segs[a]
            } else {
                crate::table::Seg::new(0, NO_SYM, 0, 0)
            };
            let kind = seg.kind();
            let tgt = seg.target();
            if kind != 0 && tgt as usize >= sc {
                state_row_idx.push(NO_ROW);
                states.push(LexStateMeta {
                    row_off: NO_ROW,
                    accept: MIXED_ACCEPT,
                    loop_id: NO_LOOP,
                });
                continue;
            }
            let packed = if kind == 1 && sink_accept[tgt as usize] != NO_SYM {
                (3u16 << 14) | sink_accept[tgt as usize]
            } else {
                seg.packed
            };
            let mut loop_id = NO_LOOP;
            if kind != 0 && tgt as usize == s {
                let key = (u64::MAX, u64::MAX, kind);
                if let Some(&id) = loop_map.get(&key) {
                    loop_id = id;
                } else if loops.len() < NO_LOOP as usize {
                    let id = loops.len() as u16;
                    loops.push(SelfLoop {
                        lut16: hw::build_ascii_lut16(u64::MAX, u64::MAX),
                        mask_lo: u64::MAX,
                        mask_hi: u64::MAX,
                        kind,
                        has_nl: true,
                    });
                    loop_map.insert(key, id);
                    loop_id = id;
                }
            }
            let ridx = deduper.intern_const(packed);
            state_row_idx.push(ridx);
            states.push(LexStateMeta {
                row_off: 0,
                accept: seg.accept,
                loop_id,
            });
            continue;
        }

        let mut row = [0u16; 128];
        let mut uniform_accept = NO_SYM;
        let mut first_seg = true;
        let mut valid_row = true;
        let mut pos = 0usize;
        let (mut m1, mut m2) = (0u128, 0u128);
        for k in 0..(b - a) {
            let seg = t.segs[a + k];
            let next_lo = if k + 1 < b - a {
                t.segs[a + k + 1].lo
            } else {
                128
            };
            let end = (next_lo as usize).min(128);
            if end > pos {
                if first_seg {
                    uniform_accept = seg.accept;
                    first_seg = false;
                } else if seg.accept != uniform_accept {
                    uniform_accept = MIXED_ACCEPT;
                }
                let kind = seg.kind();
                let tgt = seg.target();
                let packed = if kind != 0 {
                    if tgt as usize >= sc {
                        valid_row = false;
                        seg.packed
                    } else if kind == 1 && sink_accept[tgt as usize] != NO_SYM {
                        (3u16 << 14) | sink_accept[tgt as usize]
                    } else {
                        if tgt as usize == s {
                            let rm = range_mask_u128(pos, end);
                            if kind == 1 {
                                m1 |= rm;
                            } else {
                                m2 |= rm;
                            }
                        }
                        seg.packed
                    }
                } else {
                    seg.packed
                };
                row[pos..end].fill(packed);
                pos = end;
            }
            if pos >= 128 {
                break;
            }
        }

        let mut loop_id = NO_LOOP;
        if valid_row && uniform_accept != MIXED_ACCEPT && (m1 | m2) != 0 {
            let c1 = m1.count_ones();
            let c2 = m2.count_ones();
            let (mask, cnt, kind) = if c1 >= c2 {
                (m1, c1, 1u8)
            } else {
                (m2, c2, 2u8)
            };
            let mlo = mask as u64;
            let mhi = (mask >> 64) as u64;
            if cnt >= 2 || (mlo & (1u64 << b' ')) != 0 {
                let key = (mlo, mhi, kind);
                if let Some(&id) = loop_map.get(&key) {
                    loop_id = id;
                } else if loops.len() < NO_LOOP as usize {
                    let id = loops.len() as u16;
                    loops.push(SelfLoop {
                        lut16: hw::build_ascii_lut16(mlo, mhi),
                        mask_lo: mlo,
                        mask_hi: mhi,
                        kind,
                        has_nl: (mlo & (1u64 << b'\n')) != 0,
                    });
                    loop_map.insert(key, id);
                    loop_id = id;
                }
            }
        }

        if valid_row && uniform_accept != MIXED_ACCEPT {
            let ridx = deduper.intern(&row);
            state_row_idx.push(ridx);
            states.push(LexStateMeta {
                row_off: 0,
                accept: uniform_accept,
                loop_id,
            });
        } else {
            state_row_idx.push(NO_ROW);
            states.push(LexStateMeta {
                row_off: NO_ROW,
                accept: MIXED_ACCEPT,
                loop_id: NO_LOOP,
            });
        }
    }

    let unique_rows = deduper.rows;
    let u = unique_rows.len();
    // 唯一行数 <= 512 时直接展平(<= 128 KiB),零等价类二次访存。
    if u * 128 <= 65_536 {
        let mut trans = Vec::with_capacity(u * 128);
        for row in &unique_rows {
            trans.extend_from_slice(row);
        }
        for s in 0..sc {
            let ridx = state_row_idx[s];
            if ridx != NO_ROW {
                states[s].row_off = ridx * 128;
            }
        }
        return LexAccel {
            states,
            loops,
            direct: true,
            ascii_class: [0; 128],
            trans,
        };
    }

    // Myhill–Nerode 字母表等价类压缩(行优先顺序访存计算 128 列哈希,消除 256B 跨步缓存失效)。
    let mut col_hashes = [0xcbf29ce484222325u64; 128];
    for row in &unique_rows {
        for (h, &v) in col_hashes.iter_mut().zip(row.iter()) {
            *h = (h.rotate_left(5) ^ v as u64).wrapping_mul(0x517cc1b727220a95);
        }
    }
    let mut ascii_class = [0u8; 128];
    let mut rep_bytes: Vec<u8> = Vec::with_capacity(128);
    let mut col_hash_buckets: FxMap<u64, Vec<u8>> = FxMap::default();
    for b in 0..128usize {
        let h = col_hashes[b];
        let mut found = None;
        if let Some(cands) = col_hash_buckets.get(&h) {
            for &cls in cands {
                let rb = rep_bytes[cls as usize] as usize;
                if unique_rows.iter().all(|r| r[b] == r[rb]) {
                    found = Some(cls);
                    break;
                }
            }
        }
        let cls = match found {
            Some(c) => c,
            None => {
                let c = rep_bytes.len() as u8;
                rep_bytes.push(b as u8);
                col_hash_buckets.entry(h).or_default().push(c);
                c
            }
        };
        ascii_class[b] = cls;
    }

    let k = rep_bytes.len().max(1);
    let max_rows = (262_144 / k).max(1).min(u);
    let mut trans = Vec::with_capacity(max_rows * k);
    for row in &unique_rows[..max_rows] {
        for &rb in &rep_bytes {
            trans.push(row[rb as usize]);
        }
    }
    for s in 0..sc {
        let ridx = state_row_idx[s];
        if ridx != NO_ROW && (ridx as usize) < max_rows {
            states[s].row_off = ridx * k as u32;
        } else {
            states[s].row_off = NO_ROW;
            states[s].accept = MIXED_ACCEPT;
            states[s].loop_id = NO_LOOP;
        }
    }
    LexAccel {
        states,
        loops,
        direct: false,
        ascii_class,
        trans,
    }
}

/// 关键字 DFA→哈希直查结果。
pub(crate) enum KwLookup {
    /// 数学保证当前单词绝对不是关键字。
    None,
    /// 数学保证当前单词精确匹配关键字 `sym`。
    Match(u16),
    /// 未启用或终态在 `next_byte` 上有续接边,退回 `Lexer::run(&lang.keyword_lex, 0)`。
    Fallback,
}

#[derive(Clone, Copy, Debug, Default)]
struct KwSlot {
    hash: u32,
    /// 高 8 位长度(0 表示空槽),低 24 位为 `pool` 起始偏移。
    off_len: u32,
    sym: u16,
    /// `u16::MAX` 表示终态无任何出边,否则为 `out_masks` 下标。
    out_idx: u16,
}

/// L1d 驻留关键字开放寻址哈希表(直接由 `keyword_lex` 无环有限自动机编译生成)。
#[derive(Clone, Debug, Default)]
pub(crate) struct KeywordTable {
    enabled: bool,
    min_len: u8,
    max_len: u8,
    first_lo: u64,
    first_hi: u64,
    /// 状态 0 上具有 `kind == 2`(SKIP)的 ASCII 首字节掩码;若首字节命中则退回通用 DFA。
    skip0_lo: u64,
    skip0_hi: u64,
    skip0_non_ascii: bool,
    mask: usize,
    slots: Vec<KwSlot>,
    pool: Vec<u8>,
    out_masks: Vec<[u64; 2]>,
}

impl PartialEq for KeywordTable {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}
impl Eq for KeywordTable {}

#[inline(always)]
fn kw_hash(w: &[u8]) -> u32 {
    let mut h = 0x811c9dc5u32 ^ (w.len() as u32);
    for &b in w {
        h ^= b as u32;
        h = h.wrapping_mul(0x0100_0193);
    }
    h ^ (h >> 16)
}

impl KeywordTable {
    #[inline(always)]
    pub(crate) fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// 形式化遍历 `keyword_lex`;支持状态 0 的空白/续行 `SKIP`(记入 `skip0` 哨兵),
    /// 对全部其余可达状态验证为无环、无跳过、纯 ASCII 有限前缀树后启用。
    pub(crate) fn build(t: &LexTable) -> Self {
        let sc = t.state_count();
        if sc == 0 {
            return Self::default();
        }
        struct Entry {
            word: Vec<u8>,
            sym: u16,
            out_lo: u64,
            out_hi: u64,
        }
        let mut entries: Vec<Entry> = Vec::new();
        let mut visiting = vec![false; sc];
        let mut path: Vec<u8> = Vec::with_capacity(32);
        let mut visits = 0usize;
        let mut skip0_mask = 0u128;
        let mut skip0_non_ascii = false;

        #[allow(clippy::too_many_arguments)]
        fn dfs(
            t: &LexTable,
            sc: usize,
            s: usize,
            visiting: &mut [bool],
            path: &mut Vec<u8>,
            entries: &mut Vec<Entry>,
            visits: &mut usize,
            skip0_mask: &mut u128,
            skip0_non_ascii: &mut bool,
        ) -> bool {
            *visits += 1;
            if *visits > 16_384 || visiting[s] || path.len() > 32 {
                return false;
            }
            let a = t.starts[s] as usize;
            let b = t.starts[s + 1] as usize;
            if a >= b {
                return true;
            }
            visiting[s] = true;
            let segs = &t.segs[a..b];
            let first_acc = segs[0].accept;
            let mut out_lo = 0u64;
            let mut out_hi = 0u64;
            let mut edges: Vec<(u8, usize)> = Vec::new();

            for k in 0..segs.len() {
                let seg = segs[k];
                if seg.accept != first_acc {
                    visiting[s] = false;
                    return false;
                }
                let kind = seg.kind();
                let next_lo = if k + 1 < segs.len() {
                    segs[k + 1].lo
                } else {
                    EOF_CP + 1
                };
                if kind == 2 {
                    if s == 0 && path.is_empty() {
                        // 状态 0 空白/续行 SKIP:记录其覆盖字节集,查表时遇此类首字节退回 DFA 保持 100% 等价
                        let start_c = if k == 0 { 0 } else { seg.lo };
                        let ascii_end = next_lo.min(128);
                        if ascii_end > start_c {
                            *skip0_mask |= range_mask_u128(start_c as usize, ascii_end as usize);
                        }
                        if next_lo > 128 {
                            *skip0_non_ascii = true;
                        }
                        continue;
                    }
                    visiting[s] = false;
                    return false;
                }
                if kind == 1 {
                    if next_lo > 128 {
                        visiting[s] = false;
                        return false;
                    }
                    let tgt = seg.target() as usize;
                    if tgt >= sc {
                        visiting[s] = false;
                        return false;
                    }
                    let start_c = if k == 0 { 0 } else { seg.lo };
                    for ch in start_c..next_lo {
                        let c = ch as u8;
                        if c < 64 {
                            out_lo |= 1u64 << c;
                        } else {
                            out_hi |= 1u64 << (c - 64);
                        }
                        edges.push((c, tgt));
                    }
                }
            }

            if first_acc != NO_SYM {
                if path.is_empty() || entries.len() >= 1024 {
                    visiting[s] = false;
                    return false;
                }
                entries.push(Entry {
                    word: path.clone(),
                    sym: first_acc,
                    out_lo,
                    out_hi,
                });
            }

            for (ch, tgt) in edges {
                path.push(ch);
                if !dfs(
                    t,
                    sc,
                    tgt,
                    visiting,
                    path,
                    entries,
                    visits,
                    skip0_mask,
                    skip0_non_ascii,
                ) {
                    visiting[s] = false;
                    return false;
                }
                path.pop();
            }
            visiting[s] = false;
            true
        }

        if !dfs(
            t,
            sc,
            0,
            &mut visiting,
            &mut path,
            &mut entries,
            &mut visits,
            &mut skip0_mask,
            &mut skip0_non_ascii,
        ) || entries.is_empty()
        {
            return Self::default();
        }

        let cap = (entries.len() * 2).next_power_of_two().max(16);
        let mask = cap - 1;
        let mut slots = vec![KwSlot::default(); cap];
        let mut pool = Vec::new();
        let mut out_masks: Vec<[u64; 2]> = Vec::new();
        let mut min_len = u8::MAX;
        let mut max_len = 0u8;
        let (mut first_lo, mut first_hi) = (0u64, 0u64);

        for e in entries {
            let l = e.word.len() as u8;
            min_len = min_len.min(l);
            max_len = max_len.max(l);
            let b0 = e.word[0];
            if b0 < 64 {
                first_lo |= 1u64 << b0;
            } else {
                first_hi |= 1u64 << (b0 - 64);
            }
            let off = pool.len();
            if off >= (1 << 24) {
                return Self::default();
            }
            pool.extend_from_slice(&e.word);
            let out_idx = if e.out_lo == 0 && e.out_hi == 0 {
                u16::MAX
            } else {
                let id = out_masks.len() as u16;
                out_masks.push([e.out_lo, e.out_hi]);
                id
            };
            let h = kw_hash(&e.word);
            let mut idx = (h as usize) & mask;
            while slots[idx].off_len != 0 {
                idx = (idx + 1) & mask;
            }
            slots[idx] = KwSlot {
                hash: h,
                off_len: ((l as u32) << 24) | (off as u32),
                sym: e.sym,
                out_idx,
            };
        }

        KeywordTable {
            enabled: true,
            min_len,
            max_len,
            first_lo,
            first_hi,
            skip0_lo: skip0_mask as u64,
            skip0_hi: (skip0_mask >> 64) as u64,
            skip0_non_ascii,
            mask,
            slots,
            pool,
            out_masks,
        }
    }

    /// 精确查询标识符是否为关键字;对非关键字路径仅需 2–5 周期。
    #[inline(always)]
    pub(crate) fn lookup(&self, word: &[u8], next_byte: Option<u8>) -> KwLookup {
        if !self.enabled {
            return KwLookup::Fallback;
        }
        let len = word.len();
        if len == 0 {
            return KwLookup::None;
        }
        // SAFETY: `len >= 1`。
        let b0 = unsafe { *word.get_unchecked(0) };
        if b0 >= 128 {
            return if self.skip0_non_ascii {
                KwLookup::Fallback
            } else {
                KwLookup::None
            };
        }
        let fhit = if b0 < 64 {
            if ((self.skip0_lo >> b0) & 1) != 0 {
                return KwLookup::Fallback;
            }
            (self.first_lo >> b0) & 1
        } else {
            if ((self.skip0_hi >> (b0 - 64)) & 1) != 0 {
                return KwLookup::Fallback;
            }
            (self.first_hi >> (b0 - 64)) & 1
        };
        if fhit == 0 || len < self.min_len as usize || len > self.max_len as usize {
            return KwLookup::None;
        }
        let h = kw_hash(word);
        let mut idx = (h as usize) & self.mask;
        loop {
            // SAFETY: `idx <= self.mask == self.slots.len() - 1`。
            let slot = unsafe { *self.slots.get_unchecked(idx) };
            let ol = slot.off_len;
            if ol == 0 {
                return KwLookup::None;
            }
            if slot.hash == h && (ol >> 24) as usize == len {
                let off = (ol & 0x00FF_FFFF) as usize;
                // SAFETY: 构造时保证 `off + len <= self.pool.len()`。
                let cand = unsafe { self.pool.get_unchecked(off..off + len) };
                if cand == word {
                    if slot.out_idx == u16::MAX {
                        return KwLookup::Match(slot.sym);
                    }
                    match next_byte {
                        None => return KwLookup::Match(slot.sym),
                        Some(nb) if nb < 128 => {
                            // SAFETY: `slot.out_idx < self.out_masks.len()`。
                            let m = unsafe { *self.out_masks.get_unchecked(slot.out_idx as usize) };
                            let cont = if nb < 64 {
                                (m[0] >> nb) & 1
                            } else {
                                (m[1] >> (nb - 64)) & 1
                            };
                            return if cont == 0 {
                                KwLookup::Match(slot.sym)
                            } else {
                                KwLookup::Fallback
                            };
                        }
                        Some(_) => return KwLookup::Match(slot.sym),
                    }
                }
            }
            idx = (idx + 1) & self.mask;
        }
    }
}

/// 稠密解析表(覆盖热点大状态 `0..states`)。
#[derive(Clone, Debug, Default)]
pub(crate) struct DenseTable {
    pub(crate) states: usize,
    pub(crate) stride: usize,
    pub(crate) stripped: bool,
    pub(crate) data: Vec<u16>,
}

impl PartialEq for DenseTable {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}
impl Eq for DenseTable {}

/// SoA 稀疏解析表(覆盖 `dense.states..state_count`,尾部附加 16 个 `0xFFFF` 哨兵)。
#[derive(Clone, Debug, Default)]
pub(crate) struct SparseEntries {
    pub(crate) syms: Vec<u16>,
    pub(crate) vals: Vec<u16>,
    pub(crate) starts: Vec<u32>,
}

impl PartialEq for SparseEntries {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}
impl Eq for SparseEntries {}

/// 64-bit 内联动作编码:低 3 位为类别,>96% 的单动作无需再解引用 `actions` 切片。
pub(crate) const FA_EMPTY: u64 = 0;
pub(crate) const FA_SHIFT: u64 = 1;
pub(crate) const FA_REDUCE: u64 = 2;
pub(crate) const FA_ACCEPT: u64 = 3;
pub(crate) const FA_RECOVER: u64 = 4;
pub(crate) const FA_MULTI: u64 = 5;

#[inline(always)]
pub(crate) fn fa_tag(v: u64) -> u64 {
    v & 7
}

#[inline(always)]
pub(crate) fn fa_shift_state(v: u64) -> u16 {
    (v >> 16) as u16
}
#[inline(always)]
pub(crate) fn fa_shift_extra(v: u64) -> bool {
    (v & 8) != 0
}
#[inline(always)]
pub(crate) fn fa_shift_rep(v: u64) -> bool {
    (v & 16) != 0
}

#[inline(always)]
pub(crate) fn fa_reduce_count(v: u64) -> u16 {
    ((v >> 3) & 0x0FFF) as u16
}
#[inline(always)]
pub(crate) fn fa_reduce_symbol(v: u64) -> u16 {
    (v >> 16) as u16
}
#[inline(always)]
pub(crate) fn fa_reduce_dprec(v: u64) -> i16 {
    (v >> 32) as i16
}
#[inline(always)]
pub(crate) fn fa_reduce_prod(v: u64) -> u16 {
    (v >> 48) as u16
}

#[inline(always)]
pub(crate) fn fa_multi_start(v: u64) -> usize {
    (v >> 32) as usize
}
#[inline(always)]
pub(crate) fn fa_multi_len(v: u64) -> usize {
    ((v >> 16) & 0xFFFF) as usize
}

/// 打包动作表 + 符号标志位(不参与 `Language` 逻辑等价性比较)。
#[derive(Clone, Debug, Default)]
pub(crate) struct FastParseMeta {
    pub(crate) fast_actions: Vec<u64>,
    /// `node_flags[sym] = symbol_metadata[sym] & 3`。
    pub(crate) node_flags: Vec<u8>,
    /// `leaf_flags[sym] = node_flags[sym] | (sym == 0 ? F_EXTRA : 0)`。
    pub(crate) leaf_flags: Vec<u8>,
}

impl PartialEq for FastParseMeta {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}
impl Eq for FastParseMeta {}

pub(crate) fn build_fast_parse_meta(lang: &Language) -> FastParseMeta {
    let mut fast_actions = vec![FA_EMPTY; lang.actions.len().max(1)];
    let mut i = 0usize;
    while i < lang.actions.len() {
        if let Action::Header(n) = lang.actions[i] {
            let n_us = n as usize;
            let end = i + 1 + n_us;
            if end <= lang.actions.len() {
                if n_us == 1 {
                    fast_actions[i] = match lang.actions[i + 1] {
                        Action::Shift {
                            state,
                            extra,
                            repetition,
                        } => {
                            FA_SHIFT
                                | ((extra as u64) << 3)
                                | ((repetition as u64) << 4)
                                | ((state as u64) << 16)
                        }
                        Action::Reduce {
                            symbol,
                            count,
                            dprec,
                            prod,
                        } if count < 4096 => {
                            FA_REDUCE
                                | ((count as u64) << 3)
                                | ((symbol as u64) << 16)
                                | ((dprec as u16 as u64) << 32)
                                | ((prod as u64) << 48)
                        }
                        Action::Reduce { .. } => FA_MULTI | (1u64 << 16) | (((i + 1) as u64) << 32),
                        Action::Accept => FA_ACCEPT,
                        Action::Recover => FA_RECOVER,
                        Action::Header(_) => FA_EMPTY,
                    };
                } else if n_us > 1 {
                    fast_actions[i] = FA_MULTI | ((n as u64) << 16) | (((i + 1) as u64) << 32);
                }
                i = end;
                continue;
            }
        }
        i += 1;
    }

    let mut node_flags: Vec<u8> = lang.symbol_metadata.iter().map(|&m| m & 3).collect();
    let mut leaf_flags = node_flags.clone();
    if !leaf_flags.is_empty() {
        leaf_flags[0] |= crate::tree::F_EXTRA;
    }
    // 保证 SYM_ERROR / SYM_ERROR_REPEAT 之外的安全上界
    let _ = (SYM_ERROR, SYM_ERROR_REPEAT, &mut node_flags);

    FastParseMeta {
        fast_actions,
        node_flags,
        leaf_flags,
    }
}

/// 从 `entries` / `state_start` 构建 `dense.states..state_count` 的 SoA 哨兵填充稀疏表。
pub(crate) fn build_sparse_entries(
    state_count: usize,
    dense_states: usize,
    state_start: &[u32],
    entries: &[u32],
) -> SparseEntries {
    if dense_states >= state_count || state_start.len() <= state_count {
        return SparseEntries::default();
    }
    let rem_states = state_count - dense_states;
    let first_off = state_start[dense_states] as usize;
    let last_off = state_start[state_count] as usize;
    let total = last_off.saturating_sub(first_off);
    let mut syms = Vec::with_capacity(total + 16);
    let mut vals = Vec::with_capacity(total);
    let mut starts = Vec::with_capacity(rem_states + 1);
    for &off in &state_start[dense_states..=state_count] {
        starts.push(off.saturating_sub(first_off as u32));
    }
    for &x in &entries[first_off..last_off.min(entries.len())] {
        syms.push((x >> 16) as u16);
        vals.push((x & 0xFFFF) as u16);
    }
    syms.extend_from_slice(&[0xFFFF; 16]);
    SparseEntries { syms, vals, starts }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::langs::Lang;
    use crate::lexer::Lexer;

    const ALL_TAGS: [&str; 41] = [
        "c",
        "cpp",
        "csharp",
        "go",
        "java",
        "javascript",
        "typescript",
        "tsx",
        "php",
        "python",
        "rust",
        "lua",
        "bash",
        "ruby",
        "kotlin",
        "css",
        "html",
        "objc",
        "dart",
        "julia",
        "nix",
        "dockerfile",
        "ocaml",
        "elixir",
        "r",
        "svelte",
        "solidity",
        "groovy",
        "make",
        "scheme",
        "commonlisp",
        "pascal",
        "gleam",
        "powershell",
        "cmake",
        "erlang",
        "hcl",
        "vue",
        "d",
        "elm",
        "verilog",
    ];

    #[test]
    fn all_41_lex_accel_matches_raw_lex_find() {
        for tag in ALL_TAGS {
            let lang = Lang::from_tag(tag).unwrap().table().unwrap();
            let t = &lang.lex;
            let accel = &t.accel;
            assert_eq!(accel.states.len(), t.state_count(), "{tag} state len");
            for s in 0..t.state_count() {
                let meta = accel.states[s];
                if meta.row_off == NO_ROW {
                    continue;
                }
                for b in 0u8..128 {
                    let raw = t.find(s as u16, b as u32);
                    assert_eq!(meta.accept, raw.accept, "{tag} s={s} b={b} accept");
                    let col = if accel.direct {
                        b as usize
                    } else {
                        accel.ascii_class[b as usize] as usize
                    };
                    let packed = accel.trans[meta.row_off as usize + col];
                    let kind = packed >> 14;
                    let target = packed & 0x3FFF;
                    if kind == 3 {
                        // Mealy 融合汇状态:原转移应为 kind==1 -> 某纯接受汇状态,且其 accept 等于 target
                        assert_eq!(
                            raw.kind(),
                            1,
                            "{tag} s={s} b={b} fused must come from kind 1"
                        );
                        let sink_s = raw.target();
                        let sink_a = t.starts[sink_s as usize] as usize;
                        let sink_b = t.starts[sink_s as usize + 1] as usize;
                        assert_eq!(sink_b - sink_a, 1, "{tag} fused sink must be 1 seg");
                        assert_eq!(t.segs[sink_a].kind(), 0);
                        assert_eq!(t.segs[sink_a].accept, target);
                    } else {
                        assert_eq!(kind as u8, raw.kind(), "{tag} s={s} b={b} kind");
                        if kind != 0 {
                            assert_eq!(target, raw.target(), "{tag} s={s} b={b} target");
                        }
                    }
                    if meta.loop_id != NO_LOOP {
                        let sl = &accel.loops[meta.loop_id as usize];
                        let is_self = raw.kind() == sl.kind && raw.target() == s as u16;
                        assert_eq!(sl.contains(b), is_self, "{tag} s={s} b={b} self_loop");
                    }
                }
            }
        }
    }

    #[test]
    fn all_41_keyword_tables_match_keyword_lex() {
        let mut enabled_langs = 0usize;
        for tag in ALL_TAGS {
            let lang = Lang::from_tag(tag).unwrap().table().unwrap();
            if lang.keyword_capture_token == 0 || lang.keyword_lex.state_count() == 0 {
                continue;
            }
            if !lang.kw_table.is_enabled() {
                continue;
            }
            enabled_langs += 1;
            // 从 KeywordTable 的 slots 中取出所有关键字做正向/边界/变异校验
            let mut words: Vec<Vec<u8>> = Vec::new();
            for slot in &lang.kw_table.slots {
                if slot.off_len == 0 {
                    continue;
                }
                let len = (slot.off_len >> 24) as usize;
                let off = (slot.off_len & 0x00FF_FFFF) as usize;
                words.push(lang.kw_table.pool[off..off + len].to_vec());
            }
            assert!(!words.is_empty(), "{tag} enabled kw_table has 0 words");

            let mut probes: Vec<Vec<u8>> = words.clone();
            for w in words.iter().take(32) {
                if w.len() > 1 {
                    probes.push(w[..w.len() - 1].to_vec());
                }
                let mut ext = w.clone();
                ext.push(b'x');
                probes.push(ext);
                let mut sp = vec![b' '];
                sp.extend_from_slice(w);
                probes.push(sp);
                let mut bs = vec![b'\\'];
                bs.extend_from_slice(w);
                probes.push(bs);
            }
            probes.push(b"".to_vec());
            probes.push(b"__not_a_keyword_123".to_vec());
            probes.push("中文标识符".as_bytes().to_vec());

            for word in &probes {
                for next_b in [
                    None,
                    Some(b' '),
                    Some(b'_'),
                    Some(b'a'),
                    Some(b'0'),
                    Some(0x80),
                ] {
                    let mut input = word.clone();
                    if let Some(nb) = next_b {
                        input.push(nb);
                    }
                    let mut lx = Lexer::new(&input);
                    lx.start();
                    let ok = lx.run(&lang.keyword_lex, 0);
                    lx.finish();
                    let kend = lx.token_end.unwrap_or(lx.pos).bytes as usize;
                    let expected = if ok && kend == word.len() {
                        Some(lx.result)
                    } else {
                        None
                    };
                    match lang.kw_table.lookup(word, next_b) {
                        KwLookup::None => {
                            assert_eq!(
                                expected,
                                None,
                                "{tag} word={:?} next={next_b:?} missed keyword",
                                String::from_utf8_lossy(word)
                            );
                        }
                        KwLookup::Match(sym) => {
                            assert_eq!(
                                expected,
                                Some(sym),
                                "{tag} word={:?} next={next_b:?} wrong match",
                                String::from_utf8_lossy(word)
                            );
                        }
                        KwLookup::Fallback => {}
                    }
                }
            }
        }
        assert!(
            enabled_langs >= 25,
            "expected >= 25 languages with KeywordTable enabled, got {enabled_langs}"
        );
    }
}