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
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
//! 从语法树直接提取大纲:函数、类、导入,以及按顶层符号切成的分段。
//!
//! 直接在 `ParseTree::arena` 上按需展开可见子节点,不构造中间节点树、不遍历函数体与表达式子树、
//! 错误字节按 `cost == 0` O(1) 剪枝,行首索引采用延迟 SIMD 扫描。
//! 输入不可信:大小、时间、符号数都有上限,任何失败都返回 `None`,由调用方退回成一整块代码。

use crate::Limits;
use crate::api::{ParseTree, parse};
use crate::hw;
use crate::langs::{Cont, Lang, Rule, Sp, is_leading, rule};
use crate::table::Language;
use crate::tree::Arena;

/// 超过这个大小不解析。
const MAX_INPUT: usize = 2 << 20;
/// ERROR 节点覆盖的字节超过文件的这个比例(百分比)就不信任这棵树。
const MAX_ERROR_PERCENT: usize = 20;
const MAX_SYMBOLS: usize = 2000;
const MAX_IMPORTS: usize = 500;
const MAX_TEXT: usize = 200;
const MAX_DEPTH: u32 = 64;
const MAX_MILLIS: u64 = 3000;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SymbolKind {
    Function,
    Method,
    Class,
    Struct,
    Enum,
    Interface,
    Trait,
    Type,
    Module,
}

#[derive(Clone, Debug)]
pub struct Symbol {
    pub kind: SymbolKind,
    /// 没有名字的(匿名命名空间、`export default function`)为空串。
    pub name: String,
    pub start_line: u32,
    pub end_line: u32,
    pub depth: u32,
}

/// 字节范围。所有分段首尾相接,正好覆盖整个文件。
#[derive(Clone, Debug)]
pub struct Section {
    pub start: usize,
    pub end: usize,
    /// 形如 `function foo`;文件开头没有符号的部分为 `None`。
    pub title: Option<String>,
}

#[derive(Clone, Debug, Default)]
pub struct Outline {
    pub symbols: Vec<Symbol>,
    pub imports: Vec<String>,
    pub sections: Vec<Section>,
}

/// 提取大纲。不支持的语言、过大的文件、解析不干净或没有符号的文件返回 `None`。
pub fn outline(tag: &str, source: &str) -> Option<Outline> {
    let lang = Lang::from_tag(tag)?;
    if source.is_empty() || source.len() > MAX_INPUT || !lang.has_outline_rules() {
        return None;
    }
    // 输入不可信:运行时的 panic 不能带崩调用方,退回成一整块代码就好
    std::panic::catch_unwind(|| run(lang, source))
        .ok()
        .flatten()
}

/// 竞技场中某个可见节点的轻量视图(零堆分配、不展开其后代)。
#[derive(Clone, Copy)]
struct VItem {
    id: u32,
    offset: u32,
    kind: &'static str,
    field: Option<&'static str>,
    start: usize,
    end: usize,
}

/// 按 `cost == 0` O(1) 剪枝统计顶层 `ERROR` 节点覆盖的字节数,结果与全量 `visit` 完全一致。
fn sum_error_bytes(tree: &ParseTree, table: &'static Language) -> usize {
    let arena = &tree.arena;
    if !tree.has_error() && !arena.n(tree.root).is_error() {
        return 0;
    }
    let mut error_bytes = 0usize;
    // (node_id, alias, alias_named)
    let mut stack = vec![(tree.root, 0u16, false)];
    while let Some((id, alias, alias_named)) = stack.pop() {
        let node = arena.n(id);
        let visible = node.missing()
            || if alias != 0 {
                alias_named
            } else {
                node.visible() && node.named()
            };
        if visible && node.is_error() {
            error_bytes += node.size.bytes as usize;
            continue;
        }
        if arena.cost(id) == 0 || node.child_count() == 0 {
            continue;
        }
        let kids = arena.children(id);
        let alias_seq = table.alias_sequence(node.prod);
        let mut structural = 0usize;
        // 统计非顺序敏感,直接遍历并仅压入含错或本身为错的子节点
        for &child in kids {
            let cn = arena.n(child);
            let mut calias = 0u16;
            let mut calias_named = false;
            if !cn.extra() {
                if let Some(seq) = alias_seq {
                    calias = seq.get(structural).copied().unwrap_or(0);
                    calias_named = calias != 0 && table.named(calias);
                }
                structural += 1;
            }
            if cn.is_error() || arena.cost(child) > 0 {
                stack.push((child, calias, calias_named));
            }
        }
    }
    error_bytes
}

/// 迭代展开任意节点(可见或不可见)的直接可见子节点,语义与 `ParseTree::visit` 严格一致。
fn collect_visible_children(
    arena: &Arena,
    table: &'static Language,
    parent_id: u32,
    parent_offset: u32,
    parent_visible: bool,
    parent_field: Option<u16>,
    out: &mut Vec<VItem>,
) {
    struct ExpFrame {
        id: u32,
        visible: bool,
        field: Option<u16>,
        child_index: usize,
        structural: usize,
        next_offset: u32,
    }

    let mut stack = vec![ExpFrame {
        id: parent_id,
        visible: parent_visible,
        field: parent_field,
        child_index: 0,
        structural: 0,
        next_offset: parent_offset,
    }];

    while let Some(top) = stack.len().checked_sub(1) {
        let pid = stack[top].id;
        let node = arena.n(pid);
        let ci = stack[top].child_index;
        if ci >= node.child_count() as usize {
            stack.pop();
            continue;
        }
        let child = arena.children(pid)[ci];
        let cn = arena.n(child);
        let cur_offset = stack[top].next_offset;
        let p_vis = stack[top].visible;
        let p_field = stack[top].field;

        let mut alias = 0u16;
        let mut alias_named = false;
        let mut field = None;
        if !cn.extra() {
            let st_idx = stack[top].structural;
            if let Some(seq) = table.alias_sequence(node.prod) {
                alias = seq.get(st_idx).copied().unwrap_or(0);
                alias_named = alias != 0 && table.named(alias);
            }
            field = if p_vis { None } else { p_field };
            if let Some(&(s, l)) = table.field_map_slices.get(node.prod as usize) {
                let start_i = s as usize;
                for &(fid, cidx, inh) in &table.field_map_entries[start_i..start_i + l as usize] {
                    if !inh && cidx as usize == st_idx {
                        field = Some(fid);
                        break;
                    }
                }
            }
            stack[top].structural = st_idx + 1;
        }
        stack[top].next_offset = cur_offset + cn.total().bytes;
        stack[top].child_index = ci + 1;

        let vis = cn.missing()
            || if alias != 0 {
                alias_named
            } else {
                cn.visible() && cn.named()
            };
        if vis {
            let sym = if alias != 0 { alias } else { cn.sym };
            let start = (cur_offset + cn.padding.bytes) as usize;
            let end = start + cn.size.bytes as usize;
            out.push(VItem {
                id: child,
                offset: cur_offset,
                kind: table.symbol_name(sym),
                field: field.map(|f| table.field_name(f)),
                start,
                end,
            });
        } else if cn.child_count() > 0 {
            stack.push(ExpFrame {
                id: child,
                visible: false,
                field,
                child_index: 0,
                structural: 0,
                next_offset: cur_offset,
            });
        }
    }
}

fn run(lang: Lang, source: &str) -> Option<Outline> {
    let table = lang.table()?;
    let limits = Limits {
        max_millis: MAX_MILLIS,
        ..Limits::default()
    };
    let tree = parse(table, source.as_bytes(), limits);
    if tree.truncated {
        return None;
    }
    let error_bytes = sum_error_bytes(&tree, table);
    if error_bytes * 100 > source.len() * MAX_ERROR_PERCENT {
        return None;
    }
    let mut w = Walker {
        lang,
        source,
        arena: &tree.arena,
        table,
        lines: Vec::new(),
        out: Outline::default(),
    };

    // 确定顶层可见元素列表(与旧 Nodes::top() 完全等价)
    let root_node = tree.arena.n(tree.root);
    let root_vis = root_node.missing() || (root_node.visible() && root_node.named());
    let mut top_items = Vec::new();
    if root_vis {
        collect_visible_children(&tree.arena, table, tree.root, 0, true, None, &mut top_items);
    } else {
        collect_visible_children(
            &tree.arena,
            table,
            tree.root,
            0,
            false,
            None,
            &mut top_items,
        );
        if top_items.len() == 1 {
            let only = top_items[0];
            top_items.clear();
            collect_visible_children(
                &tree.arena,
                table,
                only.id,
                only.offset,
                true,
                None,
                &mut top_items,
            );
        }
    }

    let mut elements = Vec::with_capacity(top_items.len());
    for item in top_items {
        w.flatten_item(item, 0, &mut elements);
    }
    let mut anchors = Vec::new();
    let single_scope = w.single_scope(&elements);
    for (i, &e) in elements.iter().enumerate() {
        let before = w.out.symbols.len();
        let mut first = None;
        if single_scope == Some(i) && w.scope_inner(e, &mut anchors) {
            continue;
        }
        w.walk(e, false, 0, 0, &mut first);
        if w.out.symbols.len() > before
            && let Some(title) = first
        {
            anchors.push((w.anchor_start(&elements, i), e.end, title));
        }
    }
    if w.out.symbols.is_empty() {
        return None;
    }
    let mut out = w.out;
    out.sections = sections(source, anchors);
    Some(out)
}

/// 把锚点换算成首尾相接的分段:符号之间的内容归入后一段,文件末尾的内容归入最后一段。
fn sections(source: &str, anchors: Vec<(usize, usize, String)>) -> Vec<Section> {
    let mut out: Vec<Section> = Vec::with_capacity(anchors.len() + 1);
    let mut at = 0usize;
    for (i, (start, end, title)) in anchors.into_iter().enumerate() {
        if i == 0 && !source.get(..start).unwrap_or("").trim().is_empty() {
            out.push(Section {
                start: 0,
                end: start,
                title: None,
            });
            at = start;
        }
        // 同一行上挨着的两个符号切不开,并进上一段
        if end <= at {
            continue;
        }
        let stop = line_end(source, end);
        out.push(Section {
            start: at,
            end: stop,
            title: Some(title),
        });
        at = stop;
    }
    match out.last_mut() {
        Some(last) => last.end = source.len(),
        None => out.push(Section {
            start: 0,
            end: source.len(),
            title: None,
        }),
    }
    out
}

#[inline]
fn line_end(source: &str, at: usize) -> usize {
    match source
        .as_bytes()
        .get(at..)
        .and_then(|b| hw::find_byte(b, b'\n'))
    {
        Some(p) => at + p + 1,
        None => source.len(),
    }
}

struct Walker<'a> {
    lang: Lang,
    source: &'a str,
    arena: &'a Arena,
    table: &'static Language,
    lines: Vec<usize>,
    out: Outline,
}

impl Walker<'_> {
    #[inline]
    fn ensure_lines(&mut self) {
        if self.lines.is_empty() {
            hw::find_line_starts(self.source.as_bytes(), &mut self.lines);
        }
    }

    #[inline]
    fn children_of(&self, item: VItem) -> Vec<VItem> {
        let mut out = Vec::new();
        collect_visible_children(
            self.arena,
            self.table,
            item.id,
            item.offset,
            true,
            None,
            &mut out,
        );
        out
    }

    #[inline]
    fn field_in(children: &[VItem], name: &str) -> Option<VItem> {
        children.iter().copied().find(|c| c.field == Some(name))
    }

    #[inline]
    fn field_of(&self, item: VItem, name: &str) -> Option<VItem> {
        let kids = self.children_of(item);
        Self::field_in(&kids, name)
    }

    #[inline]
    fn text(&self, item: VItem) -> &str {
        self.source.get(item.start..item.end).unwrap_or("")
    }

    /// 压掉空白、截断到上限(在字符边界上)。
    fn clean(&self, s: &str) -> String {
        let mut out = String::with_capacity(s.len().min(MAX_TEXT));
        for word in s.split_whitespace() {
            if !out.is_empty() {
                out.push(' ');
            }
            for c in word.chars() {
                if out.len() + c.len_utf8() > MAX_TEXT {
                    return out;
                }
                out.push(c);
            }
        }
        out
    }

    #[inline]
    fn line(&mut self, at: usize) -> u32 {
        self.ensure_lines();
        self.lines.partition_point(|&s| s <= at) as u32
    }

    /// 透明层(预处理条件、`extern "C"`)展开成它的子节点。
    fn flatten_item(&self, item: VItem, depth: u32, out: &mut Vec<VItem>) {
        if matches!(rule(self.lang, item.kind), Rule::Flat) && depth < MAX_DEPTH {
            for c in self.children_of(item) {
                self.flatten_item(c, depth + 1, out);
            }
        } else {
            out.push(item);
        }
    }

    fn flatten_children(&self, parent: VItem, depth: u32, out: &mut Vec<VItem>) {
        for c in self.children_of(parent) {
            self.flatten_item(c, depth, out);
        }
    }

    /// 符号所在分段的起点:所在行的行首,再往前包含紧贴着的注释和属性(中间没有空行)。
    fn anchor_start(&mut self, elements: &[VItem], i: usize) -> usize {
        let mut line = self.line(elements[i].start);
        for &n in elements[..i].iter().rev() {
            if !is_leading(n.kind) {
                break;
            }
            // 注释结束位置可能带着换行符,取最后一个字节所在的行
            let end_line = self.line(n.end.saturating_sub(1).max(n.start));
            if end_line + 1 != line {
                break;
            }
            line = self.line(n.start);
        }
        self.lines[line.saturating_sub(1) as usize]
    }

    fn name(&self, item: VItem, kids: &[VItem]) -> String {
        // Verilog 的名字嵌在 header 里,没有 name 字段:取最先出现的标识符
        if self.lang == Lang::Verilog {
            let mut todo = vec![(item, 0u32)];
            while let Some((at, depth)) = todo.pop() {
                let cs = if at.id == item.id && at.offset == item.offset {
                    kids.to_vec()
                } else {
                    self.children_of(at)
                };
                for &c in cs.iter().rev() {
                    if depth < 6
                        && !matches!(c.kind, "list_of_port_declarations" | "data_type_or_void")
                    {
                        todo.push((c, depth + 1));
                    }
                }
                if at.kind == "simple_identifier" {
                    return self.clean(self.text(at));
                }
            }
            return String::new();
        }
        // Rust 的 impl 没有 name,用它实现的类型当名字;C 的函数虽然也有 type 字段,那是返回类型
        let field = if item.kind == "impl_item" {
            "type"
        } else {
            "name"
        };
        if let Some(c) = Self::field_in(kids, field) {
            return self.clean(self.text(c));
        }
        // Common Lisp:名字在 defun_header 的 function_name 字段里
        for &c in kids {
            if c.kind == "defun_header"
                && let Some(n) = self.field_of(c, "function_name")
            {
                return self.clean(self.text(n));
            }
        }
        // C 系函数:名字藏在 declarator 链的最里面
        let mut at_kids: Vec<VItem>;
        let mut cur_kids = kids;
        for step in 0..16 {
            let next = Self::field_in(cur_kids, "declarator").or_else(|| {
                cur_kids.iter().copied().find(|c| {
                    let k = c.kind;
                    k.ends_with("declarator")
                        || is_identifier(k)
                        || matches!(
                            k,
                            "signature"
                                | "type_head"
                                | "call_expression"
                                | "where_expression"
                                | "typed_expression"
                                | "type_name"
                                | "function_clause"
                                | "function_command"
                                | "macro_command"
                                | "argument_list"
                                | "argument"
                                | "parametrized_type_expression"
                        )
                })
            });
            match next {
                Some(c) if is_identifier(c.kind) => return self.clean(self.text(c)),
                Some(c) if step + 1 < 16 => {
                    at_kids = self.children_of(c);
                    cur_kids = &at_kids;
                }
                _ => break,
            }
        }
        String::new()
    }

    fn push(
        &mut self,
        kind: SymbolKind,
        label: &str,
        name: String,
        item: VItem,
        depth: u32,
        first: &mut Option<String>,
    ) {
        if self.out.symbols.len() >= MAX_SYMBOLS {
            return;
        }
        if first.is_none() {
            *first = Some(if name.is_empty() {
                label.to_string()
            } else {
                format!("{label} {name}")
            });
        }
        let (s, e) = (item.start, item.end);
        let (start_line, end_line) = (self.line(s), self.line(e.saturating_sub(1).max(s)));
        self.out.symbols.push(Symbol {
            kind,
            name,
            start_line,
            end_line,
            depth,
        });
    }

    fn import(&mut self, item: VItem) {
        if self.out.imports.len() < MAX_IMPORTS {
            let t = self.clean(self.text(item));
            self.out.imports.push(t);
        }
    }

    /// 顶层只有一个作用域容器(命名空间、`mod`),其余元素都不产生符号时,返回它的下标。
    fn single_scope(&self, elements: &[VItem]) -> Option<usize> {
        let mut found = None;
        for (i, &e) in elements.iter().enumerate() {
            match rule(self.lang, e.kind) {
                Rule::Sym(_, _, Cont::Scope) if found.is_none() => found = Some(i),
                Rule::Skip | Rule::Import => {}
                _ => return None,
            }
        }
        found
    }

    /// 往作用域容器里切一层:容器自己记一个符号,分段锚点落在它的直接成员上。
    /// 成员里一个符号都没有时撤销并返回假,由调用方按普通符号处理。
    fn scope_inner(&mut self, item: VItem, anchors: &mut Vec<(usize, usize, String)>) -> bool {
        let Rule::Sym(k, label, _) = rule(self.lang, item.kind) else {
            return false;
        };
        let kids = self.children_of(item);
        let base = self.out.symbols.len();
        let name = self.name(item, &kids);
        self.push(k, label, name, item, 0, &mut None);
        let body = Self::field_in(&kids, "body").unwrap_or(item);
        let mut inner = Vec::new();
        self.flatten_children(body, 1, &mut inner);
        let mut found = Vec::new();
        for (j, &e) in inner.iter().enumerate() {
            let before = self.out.symbols.len();
            let mut first = None;
            self.walk(e, false, 1, 1, &mut first);
            if self.out.symbols.len() > before
                && let Some(title) = first
            {
                found.push((self.anchor_start(&inner, j), e.end, title));
            }
        }
        if found.is_empty() {
            self.out.symbols.truncate(base);
            return false;
        }
        anchors.extend(found);
        true
    }

    /// `budget`:还能穿过几层不认识的节点(容器的 body)。顶层为 0,不往普通语句里找符号。
    fn walk(
        &mut self,
        item: VItem,
        in_type: bool,
        budget: u32,
        depth: u32,
        first: &mut Option<String>,
    ) {
        if depth >= MAX_DEPTH {
            return;
        }
        let kind = item.kind;
        match rule(self.lang, kind) {
            Rule::Sym(k, label, cont) => {
                let kids = self.children_of(item);
                let needs_body = self.lang.is_c_family()
                    && matches!(
                        kind,
                        "struct_specifier" | "class_specifier" | "enum_specifier"
                    );
                if needs_body && Self::field_in(&kids, "body").is_none() {
                    return;
                }
                let (k, label) = if k == SymbolKind::Function && in_type {
                    (SymbolKind::Method, "method")
                } else {
                    (k, label)
                };
                let name = self.name(item, &kids);
                self.push(k, label, name, item, depth, first);
                if !matches!(cont, Cont::No) {
                    for c in kids {
                        self.walk(c, matches!(cont, Cont::Type), 1, depth + 1, first);
                    }
                }
            }
            Rule::Wrap | Rule::Flat => {
                for c in self.children_of(item) {
                    self.walk(c, in_type, budget, depth + 1, first);
                }
            }
            Rule::Import => self.import(item),
            Rule::Special(sp) => self.special(sp, item, depth, first),
            Rule::Skip => {
                if budget > 0 {
                    for c in self.children_of(item) {
                        self.walk(c, in_type, budget - 1, depth + 1, first);
                    }
                }
            }
        }
    }

    fn special(&mut self, sp: Sp, item: VItem, depth: u32, first: &mut Option<String>) {
        match sp {
            Sp::GoImport => self.go_imports(item, 0),
            Sp::ExCall => self.ex_call(item, depth, first),
            Sp::RAssign => {
                // `name <- function(...) ...`
                let kids = self.children_of(item);
                let lhs = Self::field_in(&kids, "lhs");
                let rhs = Self::field_in(&kids, "rhs");
                if let (Some(l), Some(r)) = (lhs, rhs)
                    && r.kind == "function_definition"
                    && l.kind == "identifier"
                {
                    let name = self.clean(self.text(l));
                    self.push(SymbolKind::Function, "function", name, item, depth, first);
                }
            }
            Sp::GoType => {
                for c in self.children_of(item) {
                    if !matches!(c.kind, "type_spec" | "type_alias") {
                        continue;
                    }
                    let ckids = self.children_of(c);
                    let shape = Self::field_in(&ckids, "type").map(|t| t.kind);
                    let (k, label) = match shape {
                        Some("struct_type") => (SymbolKind::Struct, "struct"),
                        Some("interface_type") => (SymbolKind::Interface, "interface"),
                        _ => (SymbolKind::Type, "type"),
                    };
                    let name = self.name(c, &ckids);
                    self.push(k, label, name, c, depth, first);
                }
            }
            Sp::JsVar => {
                for c in self.children_of(item) {
                    if c.kind != "variable_declarator" {
                        continue;
                    }
                    let ckids = self.children_of(c);
                    let (k, label) = match Self::field_in(&ckids, "value").map(|v| v.kind) {
                        Some(
                            "arrow_function"
                            | "function_expression"
                            | "function"
                            | "generator_function",
                        ) => (SymbolKind::Function, "function"),
                        Some("class") => (SymbolKind::Class, "class"),
                        _ => continue,
                    };
                    let name = self.name(c, &ckids);
                    self.push(k, label, name, c, depth, first);
                }
            }
            Sp::CDecl => {
                // `typedef struct {...} X;`、`struct X {...} y;`:只有带定义体的才算符号
                let kids = self.children_of(item);
                let Some(t) = Self::field_in(&kids, "type") else {
                    return;
                };
                let (k, label) = match t.kind {
                    "struct_specifier" => (SymbolKind::Struct, "struct"),
                    "class_specifier" => (SymbolKind::Class, "class"),
                    "enum_specifier" => (SymbolKind::Enum, "enum"),
                    _ => return,
                };
                let tkids = self.children_of(t);
                if Self::field_in(&tkids, "body").is_none() {
                    return;
                }
                let mut name = Self::field_in(&tkids, "name")
                    .map_or(String::new(), |c| self.clean(self.text(c)));
                if name.is_empty() {
                    name = Self::field_in(&kids, "declarator")
                        .map_or(String::new(), |c| self.clean(self.text(c)));
                }
                self.push(k, label, name, item, depth, first);
            }
        }
    }

    /// Elixir 里一切都是 `call`:按目标标识符判断是 `def*`、`defmodule` 还是导入。
    fn ex_call(&mut self, item: VItem, depth: u32, first: &mut Option<String>) {
        let kids = self.children_of(item);
        let Some(t) = Self::field_in(&kids, "target") else {
            return;
        };
        if t.kind != "identifier" {
            return;
        }
        let word = self.text(t).to_string();
        let args = kids.iter().copied().find(|c| c.kind == "arguments");
        let first_arg = args.and_then(|a| {
            self.children_of(a)
                .into_iter()
                .find(|c| c.kind != "comment")
        });
        let (kind, label, container) = match word.as_str() {
            "import" | "alias" | "use" | "require" => return self.import(item),
            "defmodule" => (SymbolKind::Module, "module", true),
            "defprotocol" => (SymbolKind::Interface, "protocol", true),
            "defimpl" => (SymbolKind::Module, "impl", true),
            "def" | "defp" | "defmacro" | "defmacrop" => {
                if depth > 0 {
                    (SymbolKind::Method, "method", false)
                } else {
                    (SymbolKind::Function, "function", false)
                }
            }
            _ => return,
        };
        // 函数头可能是 `name(args)`、`name(args) when guard` 或单独的标识符
        let mut at = first_arg;
        for _ in 0..8 {
            match at {
                Some(a) if a.kind == "binary_operator" => at = self.field_of(a, "left"),
                Some(a) if a.kind == "call" => at = self.field_of(a, "target"),
                _ => break,
            }
        }
        let name = at.map(|a| self.clean(self.text(a))).unwrap_or_default();
        self.push(kind, label, name, item, depth, first);
        if container {
            for c in kids.into_iter().filter(|c| c.kind == "do_block") {
                for d in self.children_of(c) {
                    self.walk(d, true, 1, depth + 1, first);
                }
            }
        }
    }

    fn go_imports(&mut self, item: VItem, depth: u32) {
        for c in self.children_of(item) {
            match c.kind {
                "import_spec" => self.import(c),
                "import_spec_list" if depth < 2 => self.go_imports(c, depth + 1),
                _ => {}
            }
        }
    }
}

fn is_identifier(kind: &str) -> bool {
    matches!(
        kind,
        "identifier"
            | "simple_identifier"
            | "field_identifier"
            | "qualified_identifier"
            | "type_identifier"
            | "value_name"
            | "module_name"
            | "type_constructor"
            | "class_name"
            | "module_type_name"
            | "moduleName"
            | "function_name"
            | "simple_name"
            | "atom"
            | "unquoted_argument"
            | "lower_case_identifier"
            | "method_identifier"
            | "destructor_name"
            | "operator_name"
    )
}