scryer-engine 0.1.0

Tree-sitter and stack-graphs AST indexing engine for Scryer code intelligence
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
use std::path::Path;
use tree_sitter::{Node, Parser};

use super::ParseMode;
use crate::payload::{ParsedFilePayload, RawScope, RawSymbol};

/// Tree-sitter AST parser and entity extractor for Rust source code.
pub struct RustAstParser;

impl RustAstParser {
    /// Parse Rust source code and extract all declarations, signatures, docstrings, and lexical scopes.
    pub fn parse(
        relative_path: &Path,
        content: &[u8],
        content_hash: &str,
        mode: ParseMode,
    ) -> anyhow::Result<ParsedFilePayload> {
        let source_str = std::str::from_utf8(content)
            .map_err(|e| anyhow::anyhow!("Invalid UTF-8 in {}: {e}", relative_path.display()))?;

        let mut parser = Parser::new();
        let language = tree_sitter_rust::LANGUAGE;
        parser
            .set_language(&language.into())
            .map_err(|e| anyhow::anyhow!("Failed to set Rust tree-sitter language: {e}"))?;

        let tree = parser.parse(content, None).ok_or_else(|| {
            anyhow::anyhow!("Tree-sitter failed to parse {}", relative_path.display())
        })?;

        let base_module = match &mode {
            ParseMode::Workspace => module_path_for(relative_path),
            ParseMode::DependencyPublicSurface { crate_name } => {
                dependency_module_path_for(relative_path, crate_name)
            }
        };
        let mut extractor = AstExtractor::new(source_str, base_module, mode);
        extractor.traverse(tree.root_node(), None, &[]);

        let line_count = source_str.lines().count() as u32;

        Ok(ParsedFilePayload {
            relative_path: relative_path.to_path_buf(),
            content_hash: content_hash.to_string(),
            language: "rust".to_string(),
            line_count: if line_count == 0 { 1 } else { line_count },
            byte_size: content.len(),
            scopes: extractor.scopes,
            symbols: extractor.symbols,
            references: Vec::new(),
            edges: Vec::new(),
        })
    }
}

/// Directories that root a Cargo target inside a package.
const TARGET_DIRS: [&str; 4] = ["src", "tests", "benches", "examples"];

/// Compute the crate root path for a Rust source file: the package name (`-` → `_`) for
/// files under `<pkg>/src`, or `crate` for a root-level `src/`. Test, bench and example
/// targets get a `tests`/`benches`/`examples` segment (`test` for a root-level `tests/`).
pub fn crate_root_for(rel_path: &Path) -> String {
    module_parts(rel_path).0
}

/// Compute the Rust module path of a file from its project-relative path.
///
/// E.g. `src/lib.rs` → `crate`, `src/foo/bar.rs` → `crate::foo::bar`,
/// `crates/my-pkg/src/foo.rs` → `my_pkg::foo`.
pub fn module_path_for(rel_path: &Path) -> String {
    let (root, modules) = module_parts(rel_path);
    std::iter::once(root)
        .chain(modules)
        .collect::<Vec<_>>()
        .join("::")
}

/// Compute the module path for a file inside an external dependency crate.
///
/// Strips `src/` prefix and `.rs` extension, dropping `lib`, `mod`, or `main` stems,
/// and prepends the package name with dashes replaced by underscores.
pub fn dependency_module_path_for(rel_path: &Path, crate_name: &str) -> String {
    let root = crate_name.replace('-', "_");
    let parts: Vec<String> = rel_path
        .iter()
        .map(|p| p.to_string_lossy().to_string())
        .collect();

    let after_src: &[String] = if let Some(idx) = parts.iter().position(|p| p == "src") {
        &parts[idx + 1..]
    } else {
        &parts
    };

    let modules: Vec<String> = after_src
        .iter()
        .filter_map(|part| match part.strip_suffix(".rs") {
            Some("mod" | "lib" | "main") => None,
            Some(stem) => Some(stem.to_string()),
            None => Some(part.clone()),
        })
        .collect();

    if modules.is_empty() {
        root
    } else {
        std::iter::once(root)
            .chain(modules)
            .collect::<Vec<_>>()
            .join("::")
    }
}

fn module_parts(rel_path: &Path) -> (String, Vec<String>) {
    let parts: Vec<String> = rel_path
        .iter()
        .map(|p| p.to_string_lossy().to_string())
        .collect();

    let file_modules = |rest: &[String]| -> Vec<String> {
        rest.iter()
            .filter_map(|part| match part.strip_suffix(".rs") {
                Some("mod" | "lib" | "main") => None,
                Some(stem) => Some(stem.to_string()),
                None => Some(part.clone()),
            })
            .collect()
    };

    // Directories above the target dir can't be part of the module path.
    let dirs = &parts[..parts.len().saturating_sub(1)];
    let Some(idx) = dirs.iter().position(|p| TARGET_DIRS.contains(&p.as_str())) else {
        return match parts.split_first() {
            Some((first, rest)) => (first.clone(), file_modules(rest)),
            None => ("crate".to_string(), Vec::new()),
        };
    };

    let target = parts[idx].as_str();
    let root = match idx {
        0 if target == "src" => "crate".to_string(),
        0 if target == "tests" => "test".to_string(),
        0 => target.to_string(),
        _ => {
            let pkg = parts[idx - 1].replace('-', "_");
            if target == "src" {
                pkg
            } else {
                format!("{pkg}::{target}")
            }
        }
    };
    (root, file_modules(&parts[idx + 1..]))
}

struct AstExtractor<'a> {
    source: &'a str,
    base_module: String,
    mode: ParseMode,
    scopes: Vec<RawScope>,
    symbols: Vec<RawSymbol>,
}

impl<'a> AstExtractor<'a> {
    fn new(source: &'a str, base_module: String, mode: ParseMode) -> Self {
        Self {
            source,
            base_module,
            mode,
            scopes: Vec::new(),
            symbols: Vec::new(),
        }
    }

    fn add_scope(&mut self, kind: &str, node: Node, parent_scope: Option<usize>) -> usize {
        let local_id = self.scopes.len();
        self.scopes.push(RawScope {
            local_id,
            parent_local_id: parent_scope,
            scope_kind: kind.to_string(),
            start_byte: node.start_byte(),
            end_byte: node.end_byte(),
            start_line: (node.start_position().row + 1) as u32,
            end_line: (node.end_position().row + 1) as u32,
        });
        local_id
    }

    fn extract_docstring(&self, node: Node) -> Option<String> {
        let mut docs = Vec::new();

        // 1. Check preceding comments immediately before node.start_byte()
        let start_byte = node.start_byte();
        let preceding_text = &self.source[..start_byte];
        let lines: Vec<&str> = preceding_text.lines().collect();

        let mut doc_lines = Vec::new();
        for line in lines.iter().rev() {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                // If we already collected some doc lines, empty line might separate outer attributes
                if !doc_lines.is_empty() {
                    break;
                }
                continue;
            }
            if trimmed.starts_with("///") {
                let content = trimmed
                    .strip_prefix("///")
                    .unwrap_or("")
                    .trim_start_matches(' ');
                doc_lines.push(content.to_string());
            } else if trimmed.starts_with("#[") || trimmed.starts_with("//") {
                // Skip attribute or normal comment between doc comment and item
                continue;
            } else {
                break;
            }
        }

        doc_lines.reverse();
        if !doc_lines.is_empty() {
            docs.push(doc_lines.join("\n"));
        }

        // 2. Also check if node itself contains inner doc comments (//! or #[doc])
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "line_comment" {
                let text = self.get_node_text(child).trim();
                if text.starts_with("//!") {
                    let content = text
                        .strip_prefix("//!")
                        .unwrap_or("")
                        .trim_start_matches(' ');
                    docs.push(content.to_string());
                }
            }
        }

        if docs.is_empty() {
            None
        } else {
            Some(docs.join("\n").trim().to_string())
        }
    }

    fn get_node_text(&self, node: Node) -> &'a str {
        &self.source[node.start_byte()..node.end_byte()]
    }

    fn extract_visibility(&self, node: Node) -> String {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "visibility_modifier" {
                let vis_text = self.get_node_text(child).trim();
                if vis_text == "pub" {
                    return "public".to_string();
                } else if vis_text.contains("crate")
                    || vis_text.contains("super")
                    || vis_text.contains("in ")
                {
                    return "crate".to_string();
                } else {
                    return "public".to_string();
                }
            }
        }
        "private".to_string()
    }

    fn extract_signature(&self, node: Node) -> String {
        let text = self.get_node_text(node);

        // Find signature up to `{` or `;`
        let sig_end = text
            .find('{')
            .or_else(|| text.find(';'))
            .unwrap_or(text.len());

        let sig = &text[..sig_end];

        // Clean up leading attributes like #[derive(...)]
        let mut lines = Vec::new();
        for line in sig.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("#[") || trimmed.starts_with("///") || trimmed.starts_with("//")
            {
                continue;
            }
            lines.push(trimmed);
        }

        let condensed = lines.join(" ");
        condensed
            .split_whitespace()
            .collect::<Vec<&str>>()
            .join(" ")
    }

    fn make_qualified_name(&self, name: &str, qualifiers: &[String]) -> String {
        let mut parts = vec![self.base_module.clone()];
        parts.extend_from_slice(qualifiers);
        parts.push(name.to_string());
        parts.join("::")
    }

    fn traverse(&mut self, node: Node, current_scope: Option<usize>, qualifiers: &[String]) {
        let is_dep_mode = self.mode.is_dependency_public_surface();

        match node.kind() {
            "function_item" => {
                let name = node
                    .child_by_field_name("name")
                    .map(|n| self.get_node_text(n))
                    .unwrap_or("anonymous_fn");

                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let qualified_name = self.make_qualified_name(name, qualifiers);

                self.symbols.push(RawSymbol {
                    scope_local_id: current_scope,
                    name: name.to_string(),
                    qualified_name,
                    kind: "fn".to_string(),
                    visibility,
                    signature,
                    docstring,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                });

                // In dependency public surface mode, bypass function body block traversal
                if is_dep_mode {
                    return;
                }

                // Function creates a new scope for its body
                let fn_scope = self.add_scope("function", node, current_scope);

                // Traverse function children within fn_scope
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() == "parameters" || child.kind() == "visibility_modifier" {
                        continue;
                    }
                    self.traverse(child, Some(fn_scope), qualifiers);
                }
            }

            "struct_item" => {
                let name = node
                    .child_by_field_name("name")
                    .map(|n| self.get_node_text(n))
                    .unwrap_or("AnonymousStruct");

                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let qualified_name = self.make_qualified_name(name, qualifiers);

                self.symbols.push(RawSymbol {
                    scope_local_id: current_scope,
                    name: name.to_string(),
                    qualified_name,
                    kind: "struct".to_string(),
                    visibility,
                    signature,
                    docstring,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                });

                if is_dep_mode {
                    return;
                }

                let struct_scope = self.add_scope("class", node, current_scope);
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.traverse(child, Some(struct_scope), qualifiers);
                }
            }

            "enum_item" => {
                let name = node
                    .child_by_field_name("name")
                    .map(|n| self.get_node_text(n))
                    .unwrap_or("AnonymousEnum");

                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let qualified_name = self.make_qualified_name(name, qualifiers);

                self.symbols.push(RawSymbol {
                    scope_local_id: current_scope,
                    name: name.to_string(),
                    qualified_name,
                    kind: "enum".to_string(),
                    visibility,
                    signature,
                    docstring,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                });

                if is_dep_mode {
                    return;
                }

                let enum_scope = self.add_scope("class", node, current_scope);
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.traverse(child, Some(enum_scope), qualifiers);
                }
            }

            "union_item" => {
                let name = node
                    .child_by_field_name("name")
                    .map(|n| self.get_node_text(n))
                    .unwrap_or("AnonymousUnion");

                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let qualified_name = self.make_qualified_name(name, qualifiers);

                self.symbols.push(RawSymbol {
                    scope_local_id: current_scope,
                    name: name.to_string(),
                    qualified_name,
                    kind: "struct".to_string(),
                    visibility,
                    signature,
                    docstring,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                });

                if is_dep_mode {
                    return;
                }

                let union_scope = self.add_scope("class", node, current_scope);
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.traverse(child, Some(union_scope), qualifiers);
                }
            }

            "trait_item" => {
                let name = node
                    .child_by_field_name("name")
                    .map(|n| self.get_node_text(n))
                    .unwrap_or("AnonymousTrait");

                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let qualified_name = self.make_qualified_name(name, qualifiers);

                self.symbols.push(RawSymbol {
                    scope_local_id: current_scope,
                    name: name.to_string(),
                    qualified_name,
                    kind: "trait".to_string(),
                    visibility,
                    signature,
                    docstring,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                });

                if is_dep_mode {
                    return;
                }

                let trait_scope = self.add_scope("class", node, current_scope);
                let mut new_qualifiers = qualifiers.to_vec();
                new_qualifiers.push(name.to_string());

                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.traverse(child, Some(trait_scope), &new_qualifiers);
                }
            }

            "impl_item" => {
                let target_type = node
                    .child_by_field_name("type")
                    .map(|n| self.get_node_text(n).trim())
                    .unwrap_or("Unknown");

                let target_type_clean = target_type.split('<').next().unwrap_or(target_type).trim();

                let impl_scope = if !is_dep_mode {
                    Some(self.add_scope("class", node, current_scope))
                } else {
                    None
                };

                let mut new_qualifiers = qualifiers.to_vec();
                if !target_type_clean.is_empty() && target_type_clean != "Unknown" {
                    new_qualifiers.push(target_type_clean.to_string());
                }

                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.traverse(child, impl_scope, &new_qualifiers);
                }
            }

            "mod_item" => {
                let name = node
                    .child_by_field_name("name")
                    .map(|n| self.get_node_text(n))
                    .unwrap_or("anonymous_mod");

                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let qualified_name = self.make_qualified_name(name, qualifiers);

                self.symbols.push(RawSymbol {
                    scope_local_id: current_scope,
                    name: name.to_string(),
                    qualified_name,
                    kind: "mod".to_string(),
                    visibility,
                    signature,
                    docstring,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                });

                // If module has a body, create a module scope and qualify children
                if let Some(body) = node.child_by_field_name("body") {
                    let mod_scope = if !is_dep_mode {
                        Some(self.add_scope("module", node, current_scope))
                    } else {
                        None
                    };
                    let mut new_qualifiers = qualifiers.to_vec();
                    new_qualifiers.push(name.to_string());

                    let mut cursor = body.walk();
                    for child in body.children(&mut cursor) {
                        self.traverse(child, mod_scope, &new_qualifiers);
                    }
                }
            }

            "type_item" => {
                let name = node
                    .child_by_field_name("name")
                    .map(|n| self.get_node_text(n))
                    .unwrap_or("AnonymousType");

                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let qualified_name = self.make_qualified_name(name, qualifiers);

                self.symbols.push(RawSymbol {
                    scope_local_id: current_scope,
                    name: name.to_string(),
                    qualified_name,
                    kind: "type".to_string(),
                    visibility,
                    signature,
                    docstring,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                });
            }

            "const_item" | "static_item" => {
                let name = node
                    .child_by_field_name("name")
                    .map(|n| self.get_node_text(n))
                    .unwrap_or("ANONYMOUS_CONST");

                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let qualified_name = self.make_qualified_name(name, qualifiers);

                self.symbols.push(RawSymbol {
                    scope_local_id: current_scope,
                    name: name.to_string(),
                    qualified_name,
                    kind: "const".to_string(),
                    visibility,
                    signature,
                    docstring,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                });
            }

            "use_declaration" => {
                let visibility = self.extract_visibility(node);
                if is_dep_mode && visibility != "public" {
                    return;
                }

                let signature = self.extract_signature(node);
                let docstring = self.extract_docstring(node);
                let items = extract_use_items(self.source, node);

                for item in items {
                    let qualified_name = self.make_qualified_name(&item.local_name, qualifiers);
                    self.symbols.push(RawSymbol {
                        scope_local_id: current_scope,
                        name: item.local_name,
                        qualified_name,
                        kind: "reexport".to_string(),
                        visibility: visibility.clone(),
                        signature: signature.clone(),
                        docstring: docstring.clone(),
                        start_byte: item.start_byte,
                        end_byte: item.end_byte,
                        start_line: item.start_line,
                        end_line: item.end_line,
                    });
                }
            }

            "closure_expression" => {
                if is_dep_mode {
                    return;
                }
                let closure_scope = self.add_scope("closure", node, current_scope);
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.traverse(child, Some(closure_scope), qualifiers);
                }
            }

            "block" => {
                if is_dep_mode {
                    return;
                }
                // Check if this block is already the body of an enclosing function/closure/impl
                // If the parent is a function or closure, its scope already represents it
                let is_direct_body = node.parent().is_some_and(|p| {
                    p.kind() == "function_item" || p.kind() == "closure_expression"
                });

                if is_direct_body {
                    let mut cursor = node.walk();
                    for child in node.children(&mut cursor) {
                        self.traverse(child, current_scope, qualifiers);
                    }
                } else {
                    let block_scope = self.add_scope("block", node, current_scope);
                    let mut cursor = node.walk();
                    for child in node.children(&mut cursor) {
                        self.traverse(child, Some(block_scope), qualifiers);
                    }
                }
            }

            _ => {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.traverse(child, current_scope, qualifiers);
                }
            }
        }
    }
}

/// Extract the members of the Rust type `type_name` declared in `source`: struct fields,
/// enum variants, trait items, and the traits it implements within the same file.
///
/// Each entry is prefixed with its kind (`field:`, `variant:`, `method:`, `type:`,
/// `const:`, `impl:`). Returns an empty list when the type isn't declared in `source`.
pub fn extract_type_members(source: &str, type_name: &str) -> Vec<String> {
    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_rust::LANGUAGE.into())
        .is_err()
    {
        return Vec::new();
    }
    let Some(tree) = parser.parse(source, None) else {
        return Vec::new();
    };

    let text = |node: Node| &source[node.start_byte()..node.end_byte()];
    let mut members = Vec::new();
    let mut found_decl = false;
    let mut impls = Vec::new();

    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        match node.kind() {
            "struct_item" | "union_item" | "enum_item" | "trait_item"
                if !found_decl && node.child_by_field_name("name").map(text) == Some(type_name) =>
            {
                found_decl = true;
                if let Some(body) = node.child_by_field_name("body") {
                    collect_body_members(body, source, &mut members);
                }
            }
            "impl_item" => {
                let impl_type = node.child_by_field_name("type").map(|t| {
                    let t = text(t);
                    t.split('<').next().unwrap_or(t).trim()
                });
                let impl_type = impl_type.map(|t| t.rsplit("::").next().unwrap_or(t));
                if impl_type == Some(type_name)
                    && let Some(tr) = node.child_by_field_name("trait")
                {
                    impls.push(format!("impl: {}", condense(text(tr))));
                }
            }
            _ => {
                let mut cursor = node.walk();
                stack.extend(node.children(&mut cursor));
            }
        }
    }

    if !found_decl {
        return Vec::new();
    }
    members.extend(impls);
    members
}

fn collect_body_members(body: Node, source: &str, members: &mut Vec<String>) {
    let text = |node: Node| &source[node.start_byte()..node.end_byte()];
    let mut tuple_index = 0;
    let mut cursor = body.walk();
    for child in body.named_children(&mut cursor) {
        let entry = match child.kind() {
            "field_declaration" => format!("field: {}", condense(text(child))),
            "enum_variant" => format!("variant: {}", condense(text(child))),
            "function_signature_item" | "function_item" => {
                let sig = text(child);
                let sig = sig.split('{').next().unwrap_or(sig).trim_end_matches(';');
                format!("method: {}", condense(sig))
            }
            "associated_type" => format!("type: {}", condense(text(child))),
            "const_item" => format!("const: {}", condense(text(child))),
            // Tuple struct fields: `(pub u32, String)`
            "visibility_modifier" => continue,
            kind if body.kind() == "ordered_field_declaration_list" && kind != "attribute_item" => {
                let entry = format!("field: {tuple_index}: {}", condense(text(child)));
                tuple_index += 1;
                entry
            }
            _ => continue,
        };
        members.push(entry);
    }
}

/// Collapse a declaration onto one line, dropping comments and attributes.
fn condense(text: &str) -> String {
    text.lines()
        .map(|line| match line.find("//") {
            Some(idx) => &line[..idx],
            None => line,
        })
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with("#["))
        .collect::<Vec<_>>()
        .join(" ")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .replace(", }", " }")
        .replace(", )", ")")
        .trim_end_matches(',')
        .to_string()
}

/// An individual item imported or re-exported via a `use` declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtractedUseItem {
    pub local_name: String,
    pub target_path: String,
    pub start_byte: usize,
    pub end_byte: usize,
    pub start_line: u32,
    pub end_line: u32,
    pub col_number: u32,
}

/// Recursively extract imported or re-exported items from a `use_declaration` AST node.
pub fn extract_use_items(source: &str, use_node: Node) -> Vec<ExtractedUseItem> {
    let mut items = Vec::new();

    fn collect_items(source: &str, node: Node, prefix: &str, items: &mut Vec<ExtractedUseItem>) {
        let text = |n: Node| &source[n.start_byte()..n.end_byte()];
        match node.kind() {
            "use_declaration" => {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() != "visibility_modifier"
                        && child.kind() != "use"
                        && child.kind() != ";"
                    {
                        collect_items(source, child, prefix, items);
                    }
                }
            }
            "scoped_use_list" => {
                let path_node = node.child_by_field_name("path");
                let list_node = node.child_by_field_name("list");
                let base = if let Some(p) = path_node {
                    let p_txt = text(p);
                    if prefix.is_empty() {
                        p_txt.to_string()
                    } else {
                        format!("{prefix}::{p_txt}")
                    }
                } else {
                    prefix.to_string()
                };
                if let Some(list) = list_node {
                    collect_items(source, list, &base, items);
                }
            }
            "use_list" => {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() != "{" && child.kind() != "}" && child.kind() != "," {
                        collect_items(source, child, prefix, items);
                    }
                }
            }
            "use_as_clause" => {
                let path_node = node.child_by_field_name("path");
                let alias_node = node.child_by_field_name("alias");
                if let (Some(path), Some(alias)) = (path_node, alias_node) {
                    let target_sub = text(path);
                    let target_path = if prefix.is_empty() {
                        target_sub.to_string()
                    } else {
                        format!("{prefix}::{target_sub}")
                    };
                    let local_name = text(alias).to_string();
                    items.push(ExtractedUseItem {
                        local_name,
                        target_path,
                        start_byte: node.start_byte(),
                        end_byte: node.end_byte(),
                        start_line: (node.start_position().row + 1) as u32,
                        end_line: (node.end_position().row + 1) as u32,
                        col_number: node.start_position().column as u32,
                    });
                }
            }
            "scoped_identifier" => {
                let target_sub = text(node);
                let target_path = if prefix.is_empty() {
                    target_sub.to_string()
                } else {
                    format!("{prefix}::{target_sub}")
                };
                let local_name = node
                    .child_by_field_name("name")
                    .map(|n| text(n).to_string())
                    .unwrap_or_else(|| {
                        target_sub
                            .rsplit("::")
                            .next()
                            .unwrap_or(target_sub)
                            .to_string()
                    });
                items.push(ExtractedUseItem {
                    local_name,
                    target_path,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                    col_number: node.start_position().column as u32,
                });
            }
            "identifier" => {
                let id_text = text(node).to_string();
                let target_path = if prefix.is_empty() {
                    id_text.clone()
                } else {
                    format!("{prefix}::{id_text}")
                };
                items.push(ExtractedUseItem {
                    local_name: id_text,
                    target_path,
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                    col_number: node.start_position().column as u32,
                });
            }
            "self" => {
                let local_name = prefix.rsplit("::").next().unwrap_or("self").to_string();
                items.push(ExtractedUseItem {
                    local_name,
                    target_path: prefix.to_string(),
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: (node.start_position().row + 1) as u32,
                    end_line: (node.end_position().row + 1) as u32,
                    col_number: node.start_position().column as u32,
                });
            }
            "use_wildcard" => {}
            _ => {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    collect_items(source, child, prefix, items);
                }
            }
        }
    }

    collect_items(source, use_node, "", &mut items);
    items
}