1use std::cell::RefCell;
2use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
3use std::path::{Path, PathBuf};
4use std::sync::{Arc, LazyLock, Mutex, RwLock};
5use std::time::SystemTime;
6
7#[cfg(any(test, feature = "test-support"))]
8use crate::callgraph_store::join::Parser;
9use streaming_iterator::StreamingIterator;
10#[cfg(not(any(test, feature = "test-support")))]
11use tree_sitter::Parser;
12use tree_sitter::{Node, Query, QueryCursor, Tree};
13
14use crate::cache_freshness::{self};
15use crate::callgraph::resolve_module_path;
16use crate::callgraph_store::join::syntax_index::{Direct, Nav};
17use crate::error::AftError;
18use crate::symbols::{Range, Symbol, SymbolKind, SymbolMatch};
19
20mod file_language;
21pub use file_language::dynamic_language_for_extension;
22mod grammar_selection;
23pub use grammar_selection::grammar_for;
24pub mod dead_code_facts;
25pub mod outline_facts;
26pub mod todo_markers;
27
28const MAX_REEXPORT_DEPTH: usize = 10;
29
30pub const MAX_SIGNATURE_BYTES: usize = 1024;
37
38const TS_QUERY: &str = r#"
41;; function declarations
42(function_declaration
43 name: (identifier) @fn.name) @fn.def
44
45;; function-like values assigned to const/let/var
46(lexical_declaration
47 (variable_declarator
48 name: (identifier) @arrow.name
49 value: (arrow_function) @arrow.body) @arrow.decl) @arrow.def
50(lexical_declaration
51 (variable_declarator
52 name: (identifier) @arrow.name
53 value: (function_expression) @arrow.body) @arrow.decl) @arrow.def
54(lexical_declaration
55 (variable_declarator
56 name: (identifier) @arrow.name
57 value: (generator_function) @arrow.body) @arrow.decl) @arrow.def
58
59;; anonymous default exports
60(export_statement
61 value: (function_expression) @default.body) @default.def
62(export_statement
63 value: (generator_function) @default.body) @default.def
64(export_statement
65 value: (class) @default.body) @default.def
66
67;; class declarations
68(class_declaration
69 name: (type_identifier) @class.name) @class.def
70
71;; method definitions inside classes
72(class_declaration
73 name: (type_identifier) @method.class_name
74 body: (class_body
75 (method_definition
76 name: (property_identifier) @method.name) @method.def))
77
78;; callable fields inside classes
79(class_declaration
80 name: (type_identifier) @class_property.class_name
81 body: (class_body
82 (public_field_definition
83 name: (_) @class_property.name
84 value: (arrow_function) @class_property.value) @class_property.def))
85(class_declaration
86 name: (type_identifier) @class_property.class_name
87 body: (class_body
88 (public_field_definition
89 name: (_) @class_property.name
90 value: (function_expression) @class_property.value) @class_property.def))
91
92;; interface declarations and callable members
93(interface_declaration
94 name: (type_identifier) @interface.name) @interface.def
95(interface_declaration
96 name: (type_identifier) @interface_member.interface_name
97 body: (interface_body
98 (method_signature
99 name: (_) @interface_member.name) @interface_member.def))
100(interface_declaration
101 name: (type_identifier) @interface_property.interface_name
102 body: (interface_body
103 (property_signature
104 name: (_) @interface_property.name) @interface_property.def))
105
106;; callable object-literal properties
107(lexical_declaration
108 (variable_declarator
109 name: (identifier) @object_property.object_name
110 value: (object
111 (pair
112 key: (_) @object_property.name
113 value: (arrow_function) @object_property.value) @object_property.def)))
114(lexical_declaration
115 (variable_declarator
116 name: (identifier) @object_property.object_name
117 value: (object
118 (pair
119 key: (_) @object_property.name
120 value: (function_expression) @object_property.value) @object_property.def)))
121(lexical_declaration
122 (variable_declarator
123 name: (identifier) @object_property.object_name
124 value: (object
125 (pair
126 key: (_) @object_property.name
127 value: (generator_function) @object_property.value) @object_property.def)))
128(lexical_declaration
129 (variable_declarator
130 name: (identifier) @object_property.object_name
131 value: (object
132 (method_definition
133 name: (_) @object_property.name) @object_property.def)))
134
135;; enum declarations
136(enum_declaration
137 name: (identifier) @enum.name) @enum.def
138
139;; type alias declarations
140(type_alias_declaration
141 name: (type_identifier) @type_alias.name) @type_alias.def
142
143;; top-level const/let variable declarations
144(lexical_declaration
145 (variable_declarator
146 name: (identifier) @var.name) @var.decl) @var.def
147
148;; export statement wrappers (top-level only)
149(export_statement) @export.stmt
150"#;
151
152const JS_QUERY: &str = r#"
153;; function declarations
154(function_declaration
155 name: (identifier) @fn.name) @fn.def
156
157;; function-like values assigned to const/let/var
158(lexical_declaration
159 (variable_declarator
160 name: (identifier) @arrow.name
161 value: (arrow_function) @arrow.body) @arrow.decl) @arrow.def
162(lexical_declaration
163 (variable_declarator
164 name: (identifier) @arrow.name
165 value: (function_expression) @arrow.body) @arrow.decl) @arrow.def
166(lexical_declaration
167 (variable_declarator
168 name: (identifier) @arrow.name
169 value: (generator_function) @arrow.body) @arrow.decl) @arrow.def
170
171;; anonymous default exports
172(export_statement
173 value: (function_expression) @default.body) @default.def
174(export_statement
175 value: (generator_function) @default.body) @default.def
176(export_statement
177 value: (class) @default.body) @default.def
178
179;; class declarations
180(class_declaration
181 name: (identifier) @class.name) @class.def
182
183;; method definitions inside classes
184(class_declaration
185 name: (identifier) @method.class_name
186 body: (class_body
187 (method_definition
188 name: (property_identifier) @method.name) @method.def))
189
190;; top-level const/let variable declarations
191(lexical_declaration
192 (variable_declarator
193 name: (identifier) @var.name) @var.decl) @var.def
194
195;; export statement wrappers (top-level only)
196(export_statement) @export.stmt
197"#;
198
199const PY_QUERY: &str = r#"
200;; function definitions (top-level and nested)
201(function_definition
202 name: (identifier) @fn.name) @fn.def
203
204;; class definitions
205(class_definition
206 name: (identifier) @class.name) @class.def
207
208;; decorated definitions (wraps function_definition or class_definition)
209(decorated_definition
210 (decorator) @dec.decorator) @dec.def
211"#;
212
213#[cfg(any(test, feature = "test-support"))]
214pub const RS_QUERY: &str = r#"
215;; free functions (with optional visibility)
216(function_item
217 name: (identifier) @fn.name) @fn.def
218
219;; struct items
220(struct_item
221 name: (type_identifier) @struct.name) @struct.def
222
223;; enum items
224(enum_item
225 name: (type_identifier) @enum.name) @enum.def
226
227;; trait items
228(trait_item
229 name: (type_identifier) @trait.name) @trait.def
230
231;; impl blocks — capture the whole block to find methods
232(impl_item) @impl.def
233
234;; visibility modifiers on any item
235(visibility_modifier) @vis.mod
236"#;
237
238const GO_QUERY: &str = r#"
239;; function declarations
240(function_declaration
241 name: (identifier) @fn.name) @fn.def
242
243;; method declarations (with receiver)
244(method_declaration
245 name: (field_identifier) @method.name) @method.def
246
247;; type declarations (struct and interface)
248[(type_spec
249 name: (type_identifier) @type.name
250 type: (_) @type.body)
251 (type_alias
252 name: (type_identifier) @type.name
253 type: (_) @type.body)] @type.def
254"#;
255
256const C_QUERY: &str = r#"
257;; function definitions
258(function_definition
259 declarator: (function_declarator
260 declarator: (identifier) @fn.name)) @fn.def
261
262;; function declarations / prototypes
263(declaration
264 declarator: (function_declarator
265 declarator: (identifier) @fn.name)) @fn.def
266
267;; struct declarations
268(struct_specifier
269 name: (type_identifier) @struct.name
270 body: (field_declaration_list)) @struct.def
271
272;; enum declarations
273(enum_specifier
274 name: (type_identifier) @enum.name
275 body: (enumerator_list)) @enum.def
276
277;; typedef aliases
278(type_definition
279 declarator: (type_identifier) @type.name) @type.def
280
281;; macros
282(preproc_def
283 name: (identifier) @macro.name) @macro.def
284
285(preproc_function_def
286 name: (identifier) @macro.name) @macro.def
287"#;
288
289const CPP_QUERY: &str = r#"
290;; free function definitions
291(function_definition
292 declarator: (function_declarator
293 declarator: (identifier) @fn.name)) @fn.def
294
295;; free function declarations
296(declaration
297 declarator: (function_declarator
298 declarator: (identifier) @fn.name)) @fn.def
299
300;; inline method definitions / declarations inside class bodies
301(function_definition
302 declarator: (function_declarator
303 declarator: (field_identifier) @method.name)) @method.def
304
305(field_declaration
306 declarator: (function_declarator
307 declarator: (field_identifier) @method.name)) @method.def
308
309;; qualified functions / methods
310(function_definition
311 declarator: (function_declarator
312 declarator: (qualified_identifier
313 scope: (_) @qual.scope
314 name: (identifier) @qual.name))) @qual.def
315
316(declaration
317 declarator: (function_declarator
318 declarator: (qualified_identifier
319 scope: (_) @qual.scope
320 name: (identifier) @qual.name))) @qual.def
321
322;; class / struct / enum / namespace declarations
323(class_specifier
324 name: (_) @class.name) @class.def
325
326(struct_specifier
327 name: (_) @struct.name) @struct.def
328
329(enum_specifier
330 name: (_) @enum.name) @enum.def
331
332(namespace_definition
333 name: (_) @namespace.name) @namespace.def
334
335;; template declarations
336(template_declaration
337 (class_specifier
338 name: (_) @template.class.name) @template.class.item) @template.class.def
339
340(template_declaration
341 (struct_specifier
342 name: (_) @template.struct.name) @template.struct.item) @template.struct.def
343
344(template_declaration
345 (function_definition
346 declarator: (function_declarator
347 declarator: (identifier) @template.fn.name)) @template.fn.item) @template.fn.def
348
349(template_declaration
350 (function_definition
351 declarator: (function_declarator
352 declarator: (qualified_identifier
353 scope: (_) @template.qual.scope
354 name: (identifier) @template.qual.name))) @template.qual.item) @template.qual.def
355"#;
356
357const ZIG_QUERY: &str = r#"
358;; functions
359(function_declaration
360 name: (identifier) @fn.name) @fn.def
361
362;; container declarations bound to const names
363(variable_declaration
364 (identifier) @struct.name
365 "="
366 (struct_declaration) @struct.body) @struct.def
367
368(variable_declaration
369 (identifier) @enum.name
370 "="
371 (enum_declaration) @enum.body) @enum.def
372
373(variable_declaration
374 (identifier) @union.name
375 "="
376 (union_declaration) @union.body) @union.def
377
378;; const declarations
379(variable_declaration
380 (identifier) @const.name) @const.def
381
382;; tests
383(test_declaration
384 (string) @test.name) @test.def
385
386(test_declaration
387 (identifier) @test.name) @test.def
388"#;
389
390const CSHARP_QUERY: &str = r#"
391;; types
392(class_declaration
393 name: (identifier) @class.name) @class.def
394
395(interface_declaration
396 name: (identifier) @interface.name) @interface.def
397
398(struct_declaration
399 name: (identifier) @struct.name) @struct.def
400
401(enum_declaration
402 name: (identifier) @enum.name) @enum.def
403
404;; members
405(method_declaration
406 name: (identifier) @method.name) @method.def
407
408(property_declaration
409 name: (identifier) @property.name) @property.def
410
411;; namespaces
412(namespace_declaration
413 name: (_) @namespace.name) @namespace.def
414
415(file_scoped_namespace_declaration
416 name: (_) @namespace.name) @namespace.def
417"#;
418
419const BASH_QUERY: &str = r#"
422;; function definitions (both `function foo()` and `foo()` styles)
423(function_definition
424 name: (word) @fn.name) @fn.def
425"#;
426
427const SOL_QUERY: &str = r#"
430;; contracts / libraries / interfaces
431(contract_declaration
432 name: (identifier) @contract.name) @contract.def
433
434(library_declaration
435 name: (identifier) @library.name) @library.def
436
437(interface_declaration
438 name: (identifier) @interface.name) @interface.def
439
440;; functions, modifiers, constructors
441(function_definition
442 name: (identifier) @fn.name) @fn.def
443
444(modifier_definition
445 name: (identifier) @modifier.name) @modifier.def
446
447(constructor_definition) @constructor.def
448
449(fallback_receive_definition) @fallback_receive.def
450
451;; events / errors
452(event_definition
453 name: (identifier) @event.name) @event.def
454
455(error_declaration
456 name: (identifier) @error.name) @error.def
457
458;; data types
459(struct_declaration
460 name: (identifier) @struct.name) @struct.def
461
462(enum_declaration
463 name: (identifier) @enum.name) @enum.def
464
465;; state variables (top-level inside a contract)
466(state_variable_declaration
467 name: (identifier) @var.name) @var.def
468"#;
469
470const PASCAL_QUERY: &str = r#"
471;; program / unit
472(program (moduleName (identifier) @program.name)) @program.def
473(unit (moduleName (identifier) @unit.name)) @unit.def
474
475;; type declarations
476(declType (identifier) @type.name) @type.def
477
478;; const / var declarations
479(declConst (identifier) @const.name) @const.def
480(declVar (identifier) @var.name) @var.def
481
482;; procedure / function definitions (implementation)
483(defProc
484 (declProc
485 [
486 (identifier) @proc.name
487 (genericDot) @proc.name
488 ])) @proc.def
489
490;; procedure / function declarations (interface / class)
491(declProc
492 [
493 (identifier) @proc.name
494 (genericDot) @proc.name
495 ]) @proc.def
496"#;
497
498const R_QUERY: &str = r#"
499;; R represents assignments as binary operators. The extractor filters these
500;; broad captures down to top-level assignment operators and classifies
501;; function-valued assignments as functions. Rightward function
502;; assignment parses as a function_definition whose body is a binary_operator.
503(binary_operator) @assign.def
504(function_definition) @function.def
505"#;
506
507const GROOVY_QUERY: &str = r#"
508;; types
509(class_declaration
510 name: (identifier) @class.name) @class.def
511(interface_declaration
512 name: (identifier) @interface.name) @interface.def
513(trait_declaration
514 name: (identifier) @trait.name) @trait.def
515(enum_declaration
516 name: (identifier) @enum.name) @enum.def
517
518;; methods and top-level script functions
519(method_declaration
520 name: [(identifier) (quoted_identifier)] @fn.name) @fn.def
521
522;; fields and properties
523(field_declaration
524 (variable_declarator
525 name: (identifier) @var.name)) @var.def
526
527;; Jenkins declarative pipeline root
528(pipeline_statement) @pipeline.def
529"#;
530
531const OBJC_QUERY: &str = r#"
532;; Objective-C class and protocol containers. The extractor derives names from
533;; the first identifier child because the grammar does not field-name them.
534(class_interface) @class.def
535(class_implementation) @class.def
536(protocol_declaration) @interface.def
537
538;; Method bodies, property declarations, C functions, and typedefs in .m/.mm files.
539(method_definition) @method.def
540(property_declaration) @property.def
541(function_definition) @fn.def
542(type_definition) @type.def
543"#;
544
545const SCSS_QUERY: &str = r#"
546;; SCSS definitions
547(mixin_statement
548 name: (identifier) @mixin.name) @mixin.def
549
550(function_statement
551 name: (identifier) @fn.name) @fn.def
552
553(declaration
554 (property_name) @var.name) @var.def
555
556(rule_set
557 (selectors) @selector.name) @selector.def
558"#;
559
560const SCALA_QUERY: &str = r#"
561;; classes / objects / traits
562(class_definition
563 name: (identifier) @class.name) @class.def
564(object_definition
565 name: (identifier) @object.name) @object.def
566(enum_definition
567 name: (_) @enum.name) @enum.def
568(trait_definition
569 name: (identifier) @trait.name) @trait.def
570;; methods (def)
571(function_definition
572 name: (identifier) @fn.name) @fn.def
573(function_declaration
574 name: (identifier) @fn.name) @fn.def
575;; vals / vars / type aliases
576(val_definition
577 pattern: (identifier) @val.name) @val.def
578(var_definition
579 pattern: (identifier) @var.name) @var.def
580(given_definition
581 name: (_) @given.name) @given.def
582(type_definition
583 name: (type_identifier) @type.name) @type.def
584"#;
585
586const JAVA_QUERY: &str = r#"
587;; types
588(class_declaration
589 name: (identifier) @class.name) @class.def
590(interface_declaration
591 name: (identifier) @interface.name) @interface.def
592(annotation_type_declaration
593 name: (identifier) @interface.name) @interface.def
594(enum_declaration
595 name: (identifier) @enum.name) @enum.def
596(record_declaration
597 name: (identifier) @struct.name) @struct.def
598
599;; members
600(method_declaration
601 name: (identifier) @fn.name) @fn.def
602(constructor_declaration
603 name: (identifier) @fn.name) @fn.def
604(field_declaration
605 declarator: (variable_declarator
606 name: (identifier) @var.name)) @var.def
607"#;
608
609const RUBY_QUERY: &str = r#"
610;; modules / classes
611(module
612 name: (constant) @module.name) @module.def
613(class
614 name: (constant) @class.name) @class.def
615
616;; methods
617(method
618 name: (_) @fn.name) @fn.def
619(singleton_method
620 name: (_) @fn.name) @fn.def
621
622;; constants
623(assignment
624 left: (constant) @var.name) @var.def
625"#;
626
627const KOTLIN_QUERY: &str = r#"
628;; declarations
629(class_declaration
630 (type_identifier) @class.name) @class.def
631(object_declaration
632 (type_identifier) @object.name) @object.def
633(function_declaration
634 (simple_identifier) @fn.name) @fn.def
635(property_declaration
636 (variable_declaration
637 (simple_identifier) @var.name)) @var.def
638(type_alias
639 (type_identifier) @type.name) @type.def
640"#;
641
642const SWIFT_QUERY: &str = r#"
643;; types
644(class_declaration
645 name: (type_identifier) @class.name) @class.def
646(protocol_declaration
647 name: (type_identifier) @interface.name) @interface.def
648
649;; functions and members
650(function_declaration
651 name: (simple_identifier) @fn.name) @fn.def
652(protocol_function_declaration
653 name: (simple_identifier) @fn.name) @fn.def
654(property_declaration
655 name: (pattern
656 bound_identifier: (simple_identifier) @var.name)) @var.def
657(typealias_declaration
658 name: (type_identifier) @type.name) @type.def
659"#;
660
661const PHP_QUERY: &str = r#"
662;; namespaces and types
663(namespace_definition
664 name: (namespace_name) @namespace.name) @namespace.def
665(class_declaration
666 name: (name) @class.name) @class.def
667(interface_declaration
668 name: (name) @interface.name) @interface.def
669(trait_declaration
670 name: (name) @trait.name) @trait.def
671(enum_declaration
672 name: (name) @enum.name) @enum.def
673
674;; functions and members
675(function_definition
676 name: (name) @fn.name) @fn.def
677(method_declaration
678 name: (name) @fn.name) @fn.def
679(property_declaration
680 (property_element
681 name: (variable_name (name) @var.name))) @var.def
682"#;
683
684const LUA_QUERY: &str = r#"
685;; functions
686(function_declaration
687 name: (identifier) @fn.name) @fn.def
688(function_declaration
689 name: (dot_index_expression
690 field: (identifier) @fn.name)) @fn.def
691(function_declaration
692 name: (method_index_expression
693 method: (identifier) @fn.name)) @fn.def
694
695;; locals / module tables
696(variable_declaration
697 (assignment_statement
698 (variable_list
699 name: (identifier) @var.name))) @var.def
700(variable_declaration
701 (assignment_statement
702 (variable_list
703 name: (variable) @var.name))) @var.def
704(variable_declaration
705 (variable_list
706 name: (identifier) @var.name)) @var.def
707(variable_declaration
708 (variable_list
709 name: (variable) @var.name)) @var.def
710"#;
711
712const PERL_QUERY: &str = r#"
713;; packages and subroutines
714(package_statement
715 name: (package) @package.name) @package.def
716(subroutine_declaration_statement
717 name: (bareword) @fn.name) @fn.def
718(method_declaration_statement
719 name: (bareword) @fn.name) @fn.def
720
721;; constants: `use constant NAME => ...;` — the `constant` pragma is filtered in
722;; Rust (the tree-sitter binding does not evaluate `#eq?` predicates).
723(use_statement
724 module: (package) @const.pragma
725 (list_expression (autoquoted_bareword) @const.name)) @const.def
726
727;; lexical / package variables: capture the sigil-bearing variable node so the
728;; symbol name matches `$counter`, not the bare `counter`.
729(variable_declaration
730 variable: (_) @var.name) @var.def
731"#;
732
733pub use crate::lang_id::LangId;
734
735pub fn detect_language(path: &Path) -> Option<LangId> {
737 if is_h_header(path) {
738 return read_source(path)
739 .ok()
740 .and_then(|source| detect_language_from_source(path, &source))
741 .or(Some(LangId::C));
742 }
743 language_for_extension(path)
744}
745
746pub fn detect_language_any(path: &Path, dynamic_languages: bool) -> Option<LangId> {
749 detect_language(path).or_else(|| dynamic_language_for_extension(path, dynamic_languages))
750}
751
752pub fn detect_language_from_source(path: &Path, source: &str) -> Option<LangId> {
754 let lang = language_for_extension(path)?;
755 if is_h_header(path) {
756 return parse_resolved_source(path, source, lang)
757 .ok()
758 .map(|(_, lang)| lang);
759 }
760 Some(lang)
761}
762
763fn is_h_header(path: &Path) -> bool {
764 path.extension().and_then(|ext| ext.to_str()) == Some("h")
765}
766
767pub use crate::lang_id::language_by_extension as language_for_extension;
768
769pub const MARKDOWN_MAX_OPEN_BLOCKS: usize = 128;
777
778pub const MARKDOWN_TOO_DEEP: &str =
781 "markdown is nested too deeply to parse safely (more than 128 open blocks); not parsed";
782
783pub fn markdown_too_deep_to_parse(lang: LangId, source: &str) -> bool {
796 lang == LangId::Markdown
797 && source
798 .split('\n')
799 .any(|line| markdown_line_block_bound(line.as_bytes()) > MARKDOWN_MAX_OPEN_BLOCKS)
800}
801
802fn markdown_line_block_bound(line: &[u8]) -> usize {
806 let space_at = |index: usize| matches!(line.get(index), Some(b' ' | b'\t'));
807 let ends_marker = |index: usize| index >= line.len() || space_at(index);
808 let (mut markers, mut columns, mut index) = (0, 0, 0);
809 while let Some(&byte) = line.get(index) {
810 index = match byte {
811 b' ' => {
812 columns += 1;
813 index + 1
814 }
815 b'\t' => {
816 columns += 4;
817 index + 1
818 }
819 b'>' => {
821 markers += 1;
822 index + 1 + usize::from(space_at(index + 1))
823 }
824 b'-' | b'+' | b'*' if ends_marker(index + 1) => {
825 markers += 1;
826 index + 1 + usize::from(space_at(index + 1))
827 }
828 b'0'..=b'9' => {
829 let digits = line[index..]
830 .iter()
831 .take_while(|byte| byte.is_ascii_digit())
832 .count();
833 let delimiter = index + digits;
834 if !matches!(line.get(delimiter), Some(b'.' | b')')) || !ends_marker(delimiter + 1)
835 {
836 break;
837 }
838 markers += 1;
839 delimiter + 1 + usize::from(space_at(delimiter + 1))
840 }
841 _ => break,
842 };
843 }
844 markers + columns / 2 + 1
845}
846
847fn query_for(lang: LangId) -> Option<&'static str> {
849 match lang {
850 LangId::TypeScript | LangId::Tsx => Some(TS_QUERY),
851 LangId::JavaScript => Some(JS_QUERY),
852 LangId::Python => Some(PY_QUERY),
853 LangId::Rust => None,
854 LangId::Go => Some(GO_QUERY),
855 LangId::C => Some(C_QUERY),
856 LangId::Cpp | LangId::Cuda | LangId::Metal => Some(CPP_QUERY),
857 LangId::Zig => Some(ZIG_QUERY),
858 LangId::CSharp => Some(CSHARP_QUERY),
859 LangId::Bash => Some(BASH_QUERY),
860 LangId::Html => None, LangId::Markdown => None,
862 LangId::Solidity => Some(SOL_QUERY),
863 LangId::Scss => Some(SCSS_QUERY),
864 LangId::Vue => None,
865 LangId::Json => None,
866 LangId::Scala => Some(SCALA_QUERY),
867 LangId::Java => Some(JAVA_QUERY),
868 LangId::Ruby => Some(RUBY_QUERY),
869 LangId::Kotlin => Some(KOTLIN_QUERY),
870 LangId::Swift => Some(SWIFT_QUERY),
871 LangId::Php => Some(PHP_QUERY),
872 LangId::Lua => Some(LUA_QUERY),
873 LangId::Perl => Some(PERL_QUERY),
874 LangId::Yaml => None, LangId::Pascal => Some(PASCAL_QUERY),
876 LangId::R => Some(R_QUERY),
877 LangId::Groovy => Some(GROOVY_QUERY),
878 LangId::ObjC => Some(OBJC_QUERY),
879 LangId::Toml => None,
880 LangId::Luau => None,
881 }
882}
883
884static TS_QUERY_CACHE: LazyLock<Result<Query, String>> =
885 LazyLock::new(|| compile_query(LangId::TypeScript));
886static TSX_QUERY_CACHE: LazyLock<Result<Query, String>> =
887 LazyLock::new(|| compile_query(LangId::Tsx));
888static JS_QUERY_CACHE: LazyLock<Result<Query, String>> =
889 LazyLock::new(|| compile_query(LangId::JavaScript));
890static PY_QUERY_CACHE: LazyLock<Result<Query, String>> =
891 LazyLock::new(|| compile_query(LangId::Python));
892static GO_QUERY_CACHE: LazyLock<Result<Query, String>> =
893 LazyLock::new(|| compile_query(LangId::Go));
894static C_QUERY_CACHE: LazyLock<Result<Query, String>> = LazyLock::new(|| compile_query(LangId::C));
895static CPP_QUERY_CACHE: LazyLock<Result<Query, String>> =
896 LazyLock::new(|| compile_query(LangId::Cpp));
897static CUDA_QUERY_CACHE: LazyLock<Result<Query, String>> =
898 LazyLock::new(|| compile_query(LangId::Cuda));
899static ZIG_QUERY_CACHE: LazyLock<Result<Query, String>> =
900 LazyLock::new(|| compile_query(LangId::Zig));
901static CSHARP_QUERY_CACHE: LazyLock<Result<Query, String>> =
902 LazyLock::new(|| compile_query(LangId::CSharp));
903static BASH_QUERY_CACHE: LazyLock<Result<Query, String>> =
904 LazyLock::new(|| compile_query(LangId::Bash));
905static SOL_QUERY_CACHE: LazyLock<Result<Query, String>> =
906 LazyLock::new(|| compile_query(LangId::Solidity));
907static SCSS_QUERY_CACHE: LazyLock<Result<Query, String>> =
908 LazyLock::new(|| compile_query(LangId::Scss));
909static SCALA_QUERY_CACHE: LazyLock<Result<Query, String>> =
910 LazyLock::new(|| compile_query(LangId::Scala));
911static JAVA_QUERY_CACHE: LazyLock<Result<Query, String>> =
912 LazyLock::new(|| compile_query(LangId::Java));
913static RUBY_QUERY_CACHE: LazyLock<Result<Query, String>> =
914 LazyLock::new(|| compile_query(LangId::Ruby));
915static KOTLIN_QUERY_CACHE: LazyLock<Result<Query, String>> =
916 LazyLock::new(|| compile_query(LangId::Kotlin));
917static SWIFT_QUERY_CACHE: LazyLock<Result<Query, String>> =
918 LazyLock::new(|| compile_query(LangId::Swift));
919static PHP_QUERY_CACHE: LazyLock<Result<Query, String>> =
920 LazyLock::new(|| compile_query(LangId::Php));
921static LUA_QUERY_CACHE: LazyLock<Result<Query, String>> =
922 LazyLock::new(|| compile_query(LangId::Lua));
923static PERL_QUERY_CACHE: LazyLock<Result<Query, String>> =
924 LazyLock::new(|| compile_query(LangId::Perl));
925static PASCAL_QUERY_CACHE: LazyLock<Result<Query, String>> =
926 LazyLock::new(|| compile_query(LangId::Pascal));
927static R_QUERY_CACHE: LazyLock<Result<Query, String>> = LazyLock::new(|| compile_query(LangId::R));
928static GROOVY_QUERY_CACHE: LazyLock<Result<Query, String>> =
929 LazyLock::new(|| compile_query(LangId::Groovy));
930static OBJC_QUERY_CACHE: LazyLock<Result<Query, String>> =
931 LazyLock::new(|| compile_query(LangId::ObjC));
932
933fn compile_query(lang: LangId) -> Result<Query, String> {
934 let query_src = query_for(lang).ok_or_else(|| format!("missing query for {lang:?}"))?;
935 let grammar = grammar_for(lang).map_err(|error| error.to_string())?;
936 Query::new(&grammar, query_src)
937 .map_err(|error| format!("query compile error for {lang:?}: {error}"))
938}
939
940test_support_visibility! {
941fn cached_query_for(lang: LangId) -> Result<Option<&'static Query>, AftError> {
942 if lang == LangId::Luau {
943 grammar_for(lang)?;
944 return Ok(None);
945 }
946 let query = match lang {
947 LangId::TypeScript => Some(&*TS_QUERY_CACHE),
948 LangId::Tsx => Some(&*TSX_QUERY_CACHE),
949 LangId::JavaScript => Some(&*JS_QUERY_CACHE),
950 LangId::Python => Some(&*PY_QUERY_CACHE),
951 LangId::Go => Some(&*GO_QUERY_CACHE),
952 LangId::C => Some(&*C_QUERY_CACHE),
953 LangId::Cpp => Some(&*CPP_QUERY_CACHE),
954 LangId::Cuda => Some(&*CUDA_QUERY_CACHE),
955 LangId::Metal => Some(&*CPP_QUERY_CACHE),
956 LangId::Zig => Some(&*ZIG_QUERY_CACHE),
957 LangId::CSharp => Some(&*CSHARP_QUERY_CACHE),
958 LangId::Bash => Some(&*BASH_QUERY_CACHE),
959 LangId::Solidity => Some(&*SOL_QUERY_CACHE),
960 LangId::Scss => Some(&*SCSS_QUERY_CACHE),
961 LangId::Scala => Some(&*SCALA_QUERY_CACHE),
962 LangId::Java => Some(&*JAVA_QUERY_CACHE),
963 LangId::Ruby => Some(&*RUBY_QUERY_CACHE),
964 LangId::Kotlin => Some(&*KOTLIN_QUERY_CACHE),
965 LangId::Swift => Some(&*SWIFT_QUERY_CACHE),
966 LangId::Php => Some(&*PHP_QUERY_CACHE),
967 LangId::Lua => Some(&*LUA_QUERY_CACHE),
968 LangId::Perl => Some(&*PERL_QUERY_CACHE),
969 LangId::Pascal => Some(&*PASCAL_QUERY_CACHE),
970 LangId::R => Some(&*R_QUERY_CACHE),
971 LangId::Groovy => Some(&*GROOVY_QUERY_CACHE),
972 LangId::ObjC => Some(&*OBJC_QUERY_CACHE),
973 LangId::Rust
974 | LangId::Html
975 | LangId::Markdown
976 | LangId::Vue
977 | LangId::Json
978 | LangId::Yaml
979 | LangId::Toml
980 | LangId::Luau => None,
981 };
982
983 query
984 .map(|result| {
985 result.as_ref().map_err(|message| AftError::ParseError {
986 message: message.clone(),
987 })
988 })
989 .transpose()
990}
991}
992
993thread_local! {
994 #[cfg(any(test, feature = "test-support"))]
997 pub static REUSABLE_PARSERS: RefCell<HashMap<LangId, Parser>> = RefCell::new(HashMap::new());
998 #[cfg(not(any(test, feature = "test-support")))]
999 static REUSABLE_PARSERS: RefCell<HashMap<LangId, Parser>> = RefCell::new(HashMap::new());
1000}
1001
1002pub fn read_source(path: &Path) -> std::io::Result<String> {
1003 #[cfg(any(test, feature = "test-support"))]
1004 work_counters::SOURCE_READS.with(|count| count.set(count.get() + 1));
1005 if !crate::bounded_io::skip_disclosure_active() {
1006 return crate::bounded_io::read_to_string(path);
1007 }
1008 let mut reader = crate::bounded_io::reader(path, None)?;
1009 crate::large_read_counts::allow_whole(
1010 crate::large_read_counts::Site::ParseSource,
1011 path,
1012 reader.size_at_open(),
1013 )?;
1014 let bytes = reader.append(Vec::new(), reader.size_at_open() as usize)?;
1015 let source = String::from_utf8(bytes)
1016 .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
1017 crate::large_read_counts::record_whole(
1018 crate::large_read_counts::Site::ParseSource,
1019 source.len(),
1020 );
1021 Ok(source)
1022}
1023
1024test_support_visibility! {
1025fn captured_source(source: String) -> Arc<String> {
1027 Arc::new(source)
1028}
1029}
1030
1031pub fn parse_source_with_cached_parser(
1033 path: &Path,
1034 source: &str,
1035 lang: LangId,
1036) -> Result<Tree, AftError> {
1037 parse_resolved_source(path, source, lang).map(|(tree, _)| tree)
1038}
1039
1040#[derive(Default)]
1041struct HeaderParseCache {
1042 entries: HashMap<blake3::Hash, (Tree, LangId)>,
1043 order: VecDeque<blake3::Hash>,
1044}
1045
1046static HEADER_PARSE_CACHE: LazyLock<Mutex<HeaderParseCache>> =
1050 LazyLock::new(|| Mutex::new(HeaderParseCache::default()));
1051
1052#[cfg(any(test, feature = "test-support"))]
1053thread_local! {
1054 pub static HEADER_PARSE_ON_MISS: RefCell<Option<Box<dyn FnOnce()>>> = RefCell::new(None);
1055}
1056
1057pub fn cached_header_tree(source: &str, lang: LangId) -> Option<Tree> {
1060 if !matches!(lang, LangId::C | LangId::Cpp | LangId::ObjC) {
1061 return None;
1062 }
1063 HEADER_PARSE_CACHE
1064 .lock()
1065 .unwrap_or_else(|e| e.into_inner())
1066 .entries
1067 .get(&cache_freshness::hash_bytes(source.as_bytes()))
1068 .filter(|(_, resolved)| *resolved == lang)
1069 .map(|(tree, _)| tree.clone())
1070}
1071
1072pub fn parse_resolved_source(
1073 path: &Path,
1074 source: &str,
1075 lang: LangId,
1076) -> Result<(Tree, LangId), AftError> {
1077 if !is_h_header(path) {
1078 return parse_source_with_parser(path, source, lang).map(|tree| (tree, lang));
1079 }
1080 let hash = cache_freshness::hash_bytes(source.as_bytes());
1081 if let Some(parsed) = HEADER_PARSE_CACHE
1082 .lock()
1083 .unwrap_or_else(|e| e.into_inner())
1084 .entries
1085 .get(&hash)
1086 {
1087 return Ok(parsed.clone());
1088 }
1089
1090 #[cfg(any(test, feature = "test-support"))]
1091 HEADER_PARSE_ON_MISS.with(|hook| {
1092 if let Some(hook) = hook.borrow_mut().take() {
1093 hook();
1094 }
1095 });
1096
1097 let c_tree = parse_source_with_parser(path, source, LangId::C)?;
1098 let mut resolved = (c_tree.clone(), LangId::C);
1099 if c_tree.root_node().has_error() {
1100 for candidate in [LangId::Cpp, LangId::ObjC] {
1101 let Some(tree) = parse_source_with_parser_deadline(
1102 path,
1103 source,
1104 candidate,
1105 Some(HEADER_FALLBACK_PARSE_DEADLINE),
1106 )?
1107 else {
1108 continue;
1109 };
1110 if !tree.root_node().has_error() {
1112 resolved = (tree, candidate);
1113 break;
1114 }
1115 }
1116 }
1117 let mut cache = HEADER_PARSE_CACHE.lock().unwrap_or_else(|e| e.into_inner());
1126 if let Some(parsed) = cache.entries.get(&hash) {
1127 return Ok(parsed.clone());
1128 }
1129 if cache.entries.len() == 128 {
1131 if let Some(oldest) = cache.order.pop_front() {
1132 cache.entries.remove(&oldest);
1133 }
1134 }
1135 cache.order.push_back(hash);
1136 cache.entries.insert(hash, resolved.clone());
1137 Ok(resolved)
1138}
1139
1140test_support_visibility! {
1141fn parse_source_with_parser(path: &Path, source: &str, lang: LangId) -> Result<Tree, AftError> {
1142 parse_source_with_parser_deadline(path, source, lang, None)?.ok_or_else(|| {
1143 AftError::ParseError {
1144 message: format!("tree-sitter parse returned None for {}", path.display()),
1145 }
1146 })
1147}
1148}
1149
1150test_support_visibility! {
1151const HEADER_FALLBACK_PARSE_DEADLINE: std::time::Duration = std::time::Duration::from_millis(1900);
1158}
1159
1160test_support_visibility! {
1161fn parse_source_with_parser_deadline(
1162 path: &Path,
1163 source: &str,
1164 lang: LangId,
1165 deadline: Option<std::time::Duration>,
1166) -> Result<Option<Tree>, AftError> {
1167 if markdown_too_deep_to_parse(lang, source) {
1168 return Err(AftError::ParseError {
1169 message: format!("{}: {MARKDOWN_TOO_DEEP}", path.display()),
1170 });
1171 }
1172 #[cfg(feature = "test-hooks")]
1173 SEARCH_PARSE_COUNT.with(|count| count.set(count.get() + 1));
1174 #[cfg(any(test, feature = "test-support"))]
1175 work_counters::CACHED_PARSER_PARSES.with(|count| count.set(count.get() + 1));
1176 REUSABLE_PARSERS.with(|parsers| {
1177 let mut parsers = parsers.borrow_mut();
1178 let mut parser = match parsers.remove(&lang) {
1179 Some(parser) => parser,
1180 None => {
1181 #[cfg(any(test, feature = "test-support"))]
1182 work_counters::GRAMMAR_LOADS.with(|count| count.set(count.get() + 1));
1183 let mut parser = Parser::new();
1184 initialize_parser(&mut parser, lang)?;
1185 parser
1186 }
1187 };
1188 #[cfg(any(test, feature = "test-support"))]
1189 parser.note_parse();
1190 let result = if let Some(deadline) = deadline {
1191 let start = std::time::Instant::now();
1192 let mut expired = false;
1193 let mut progress = |_: &tree_sitter::ParseState| {
1194 if start.elapsed() >= deadline {
1195 expired = true;
1196 std::ops::ControlFlow::Break(())
1197 } else {
1198 std::ops::ControlFlow::Continue(())
1199 }
1200 };
1201 let bytes = source.as_bytes();
1202 let tree = parser.parse_with_options(
1203 &mut |offset, _| bytes.get(offset..).unwrap_or_default(),
1204 None,
1205 Some(tree_sitter::ParseOptions::new().progress_callback(&mut progress)),
1206 );
1207 if expired {
1210 Ok(None)
1211 } else {
1212 tree.map(Some).ok_or_else(|| AftError::ParseError {
1213 message: format!("tree-sitter parse returned None for {}", path.display()),
1214 })
1215 }
1216 } else {
1217 parse_with_parser(&mut parser, path, source, lang, None).map(Some)
1218 };
1219 if matches!(result, Ok(Some(_))) {
1220 parsers.insert(lang, parser);
1221 }
1222 result
1223 })
1224}
1225}
1226
1227const LUAU_PARSE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);
1232
1233#[doc(hidden)]
1234pub fn parse_luau_source(path: &Path, source: &str) -> Result<Tree, AftError> {
1235 parse_source_with_cached_parser(path, source, LangId::Luau)
1236}
1237
1238#[cfg(feature = "test-hooks")]
1239thread_local! {
1240 static LUAU_TEST_DEADLINE: std::cell::Cell<Option<std::time::Duration>> = const { std::cell::Cell::new(None) };
1241}
1242
1243#[cfg(feature = "test-hooks")]
1244#[doc(hidden)]
1245pub fn with_luau_parse_deadline_for_test<T>(
1246 deadline: std::time::Duration,
1247 run: impl FnOnce() -> T,
1248) -> T {
1249 struct Restore(Option<std::time::Duration>);
1250 impl Drop for Restore {
1251 fn drop(&mut self) {
1252 LUAU_TEST_DEADLINE.with(|slot| slot.set(self.0));
1253 }
1254 }
1255 let _restore = Restore(LUAU_TEST_DEADLINE.with(|slot| slot.replace(Some(deadline))));
1256 run()
1257}
1258
1259#[cfg(all(
1260 any(test, feature = "test-support"),
1261 feature = "test-hooks",
1262 feature = "wasm-grammars"
1263))]
1264pub fn install_luau_parser_for_test(parser: Parser) {
1265 REUSABLE_PARSERS.with(|parsers| {
1266 parsers.borrow_mut().insert(LangId::Luau, parser);
1267 });
1268}
1269
1270#[cfg(all(
1271 any(test, feature = "test-support"),
1272 feature = "test-hooks",
1273 feature = "wasm-grammars"
1274))]
1275pub fn retains_luau_parser_for_test() -> bool {
1276 REUSABLE_PARSERS.with(|parsers| parsers.borrow().contains_key(&LangId::Luau))
1277}
1278
1279pub fn luau_parse_deadline() -> std::time::Duration {
1281 #[cfg(feature = "test-hooks")]
1282 let deadline = {
1283 static FROM_ENV: std::sync::LazyLock<Option<std::time::Duration>> =
1284 std::sync::LazyLock::new(|| {
1285 std::env::var("AFT_TEST_GRAMMAR_PARSE_DEADLINE_MS")
1286 .ok()
1287 .map(|value| {
1288 std::time::Duration::from_millis(
1289 value.parse().expect("test parse deadline milliseconds"),
1290 )
1291 })
1292 });
1293 LUAU_TEST_DEADLINE
1294 .with(|slot| slot.get())
1295 .or(*FROM_ENV)
1296 .unwrap_or(LUAU_PARSE_DEADLINE)
1297 };
1298 #[cfg(not(feature = "test-hooks"))]
1299 let deadline = LUAU_PARSE_DEADLINE;
1300 deadline
1301}
1302
1303pub fn parse_with_parser(
1305 parser: &mut tree_sitter::Parser,
1306 path: &Path,
1307 source: &str,
1308 lang: LangId,
1309 old_tree: Option<&Tree>,
1310) -> Result<Tree, AftError> {
1311 let no_tree = || AftError::ParseError {
1312 message: format!("tree-sitter parse returned None for {}", path.display()),
1313 };
1314 let Some(language) = crate::grammar::extractor_name(lang) else {
1315 return parser.parse(source, old_tree).ok_or_else(no_tree);
1316 };
1317 let deadline =
1318 crate::grammar::parse_deadline(language).expect("extractor has a parse deadline");
1319 let start = std::time::Instant::now();
1320 let mut expired = false;
1321 let mut progress = |_: &tree_sitter::ParseState| {
1325 if start.elapsed() >= deadline {
1326 expired = true;
1327 std::ops::ControlFlow::Break(())
1328 } else {
1329 std::ops::ControlFlow::Continue(())
1330 }
1331 };
1332 let bytes = source.as_bytes();
1333 let tree = parser.parse_with_options(
1334 &mut |offset, _| bytes.get(offset..).unwrap_or_default(),
1335 old_tree,
1336 Some(tree_sitter::ParseOptions::new().progress_callback(&mut progress)),
1337 );
1338 if expired || start.elapsed() >= deadline {
1339 return Err(AftError::GrammarParseTimeout {
1340 path: path.display().to_string(),
1341 language: language.into(),
1342 timeout_ms: deadline.as_millis().min(u64::MAX as u128) as u64,
1343 });
1344 }
1345 tree.ok_or_else(no_tree)
1346}
1347
1348pub fn initialize_parser(parser: &mut tree_sitter::Parser, lang: LangId) -> Result<(), AftError> {
1350 let grammar = grammar_for(lang)?;
1351 if let Some(language) = crate::grammar::extractor_name(lang) {
1352 crate::grammar::prepare_parser(parser, language)?;
1353 }
1354 parser
1355 .set_language(&grammar)
1356 .map_err(|error| AftError::ParseError {
1357 message: format!("grammar init failed for {lang:?}: {error}"),
1358 })
1359}
1360
1361#[cfg(feature = "test-hooks")]
1362thread_local! {
1363 static SEARCH_PARSE_COUNT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
1364}
1365
1366#[cfg(feature = "test-hooks")]
1368pub fn search_parse_count_for_test() -> u64 {
1369 SEARCH_PARSE_COUNT.with(std::cell::Cell::get)
1370}
1371
1372test_support_visibility! {
1373struct CachedTree {
1375 mtime: SystemTime,
1376 size: u64,
1377 content_hash: blake3::Hash,
1378 tree: Tree,
1379 lang: LangId,
1380 #[cfg(any(test, feature = "test-support"))]
1381 pub source: Option<Arc<String>>,
1382 #[cfg(not(any(test, feature = "test-support")))]
1383 source: Option<Arc<String>>,
1384}
1385}
1386
1387#[derive(Clone, PartialEq, Eq)]
1389pub struct RustModule {
1390 pub name: String,
1391 pub range: Range,
1392 pub exported: bool,
1393 pub children: Vec<RustModule>,
1394}
1395
1396pub fn rust_modules(root: Node<'_>, source: &str) -> Vec<RustModule> {
1397 #[cfg(any(test, feature = "test-support"))]
1398 work_counters::RUST_MODULE_SCANS.with(|count| count.set(count.get() + 1));
1399 fn immediate_modules<'a>(node: Node<'a>, modules: &mut Vec<Node<'a>>) {
1400 let mut cursor = node.walk();
1401 for child in node.named_children(&mut cursor) {
1402 if child.kind() == "mod_item" {
1403 modules.push(child);
1404 } else {
1405 immediate_modules(child, modules);
1406 }
1407 }
1408 }
1409 let mut modules = Vec::new();
1410 immediate_modules(root, &mut modules);
1411 modules
1412 .into_iter()
1413 .map(|module| {
1414 let mut cursor = module.walk();
1415 let exported = module
1416 .named_children(&mut cursor)
1417 .any(|child| child.kind() == "visibility_modifier");
1418 RustModule {
1419 name: module
1420 .child_by_field_name("name")
1421 .map(|name| node_text(source, &name))
1422 .unwrap_or("module")
1423 .to_string(),
1424 range: node_range_with_decorators(&module, source, LangId::Rust),
1425 exported,
1426 children: module
1427 .child_by_field_name("body")
1428 .map(|body| rust_modules(body, source))
1429 .unwrap_or_default(),
1430 }
1431 })
1432 .collect()
1433}
1434
1435pub struct ParsedFile {
1437 pub source: Arc<String>,
1438 pub tree: Tree,
1439 pub lang: LangId,
1440 pub modules: Option<Arc<Vec<RustModule>>>,
1441 mtime: SystemTime,
1442 size: u64,
1443 content_hash: blake3::Hash,
1444}
1445
1446test_support_visibility! {
1447#[derive(Clone)]
1449struct CachedSymbols {
1450 #[cfg(any(test, feature = "test-support"))]
1451 pub mtime: SystemTime,
1452 #[cfg(not(any(test, feature = "test-support")))]
1453 mtime: SystemTime,
1454 size: u64,
1455 content_hash: blake3::Hash,
1456 symbols: Arc<Vec<Symbol>>,
1460 #[cfg(any(test, feature = "test-support"))]
1461 pub modules: Option<Arc<Vec<RustModule>>>,
1462 #[cfg(not(any(test, feature = "test-support")))]
1463 modules: Option<Arc<Vec<RustModule>>>,
1464 has_error: Option<bool>,
1468 outline_facts: Option<Arc<outline_facts::OutlineParseFacts>>,
1472 shared_table: bool,
1477}
1478}
1479
1480pub struct CachedOutline {
1483 pub symbols: Arc<Vec<Symbol>>,
1484 pub modules: Option<Arc<Vec<RustModule>>>,
1485 pub has_error: bool,
1486 pub facts: Arc<outline_facts::OutlineParseFacts>,
1487}
1488
1489pub fn content_hash_for_source(source: &str) -> blake3::Hash {
1492 if source.len() as u64 > cache_freshness::CONTENT_HASH_SIZE_CAP {
1493 cache_freshness::zero_hash()
1494 } else {
1495 cache_freshness::hash_bytes(source.as_bytes())
1496 }
1497}
1498
1499#[cfg(any(test, feature = "test-support"))]
1500thread_local! {
1501 pub static FRESHNESS_TEST_BARRIERS: std::cell::RefCell<Option<(std::sync::Arc<std::sync::Barrier>, std::sync::Arc<std::sync::Barrier>)>> = const { std::cell::RefCell::new(None) };
1502 pub static CACHE_REFRESH_TEST_MUTATOR: std::cell::RefCell<Option<Box<dyn FnMut()>>> = const { std::cell::RefCell::new(None) };
1503 pub static CACHE_REFRESH_TEST_BARRIERS: std::cell::RefCell<Option<(std::sync::Arc<std::sync::Barrier>, std::sync::Arc<std::sync::Barrier>)>> = const { std::cell::RefCell::new(None) };
1504}
1505
1506test_support_visibility! {
1507fn cached_file_is_fresh(
1508 path: &Path,
1509 cached_mtime: SystemTime,
1510 cached_size: u64,
1511 cached_content_hash: blake3::Hash,
1512 fallback_mtime: SystemTime,
1513) -> bool {
1514 #[cfg(any(test, feature = "test-support"))]
1515 FRESHNESS_TEST_BARRIERS.with(|slot| {
1516 if let Some((arrived, released)) = slot.borrow_mut().take() {
1517 arrived.wait();
1518 released.wait();
1519 }
1520 });
1521 let Ok(metadata) = crate::bounded_io::metadata(path) else {
1522 return false;
1523 };
1524 let current_size = metadata.len();
1525 if current_size != cached_size {
1526 return false;
1527 }
1528
1529 let current_mtime = metadata.modified().unwrap_or(fallback_mtime);
1530 if current_mtime == cached_mtime {
1533 return true;
1534 }
1535 if current_size > cache_freshness::CONTENT_HASH_SIZE_CAP {
1536 return false;
1537 }
1538
1539 matches!(
1540 cache_freshness::hash_file_if_small(path, current_size),
1541 Ok(Some(hash)) if hash == cached_content_hash
1542 )
1543}
1544}
1545
1546#[derive(Clone, Default)]
1549pub struct SymbolCache {
1550 #[cfg(any(test, feature = "test-support"))]
1551 pub entries: HashMap<PathBuf, CachedSymbols>,
1552 #[cfg(not(any(test, feature = "test-support")))]
1553 entries: HashMap<PathBuf, CachedSymbols>,
1554 entry_bytes: u64,
1556 symbol_count: usize,
1557 generation: u64,
1558 mutation_revision: u64,
1560 persisted_revision: u64,
1561 project_root: Option<PathBuf>,
1562}
1563
1564pub type SharedSymbolCache = Arc<RwLock<SymbolCache>>;
1565
1566pub fn symbols_estimated_bytes(symbols: &[Symbol]) -> u64 {
1567 symbols.iter().fold(0u64, |bytes, symbol| {
1568 let scope_bytes = symbol.scope_chain.iter().fold(0u64, |scope_bytes, scope| {
1569 scope_bytes
1570 .saturating_add(std::mem::size_of::<String>() as u64)
1571 .saturating_add(crate::memory::usize_to_u64(scope.len()))
1572 });
1573 bytes
1574 .saturating_add(std::mem::size_of::<Symbol>() as u64)
1575 .saturating_add(crate::memory::usize_to_u64(symbol.name.len()))
1576 .saturating_add(
1577 symbol
1578 .signature
1579 .as_ref()
1580 .map(|signature| crate::memory::usize_to_u64(signature.len()))
1581 .unwrap_or(0),
1582 )
1583 .saturating_add(scope_bytes)
1584 .saturating_add(
1585 symbol
1586 .parent
1587 .as_ref()
1588 .map(|parent| crate::memory::usize_to_u64(parent.len()))
1589 .unwrap_or(0),
1590 )
1591 })
1592}
1593
1594fn module_bytes(modules: &[RustModule]) -> u64 {
1595 modules
1596 .iter()
1597 .map(|module| {
1598 std::mem::size_of::<RustModule>() as u64
1599 + module.name.len() as u64
1600 + module_bytes(&module.children)
1601 })
1602 .sum()
1603}
1604
1605fn cached_symbols_estimated_bytes(path: &Path, cached: &CachedSymbols) -> u64 {
1608 (std::mem::size_of::<PathBuf>() as u64)
1609 .saturating_add(crate::memory::path_bytes(path))
1610 .saturating_add(std::mem::size_of::<CachedSymbols>() as u64)
1611 .saturating_add(if cached.shared_table {
1612 0
1613 } else {
1614 symbols_estimated_bytes(&cached.symbols)
1615 })
1616 .saturating_add(
1617 cached
1618 .modules
1619 .as_deref()
1620 .map_or(0, |modules| module_bytes(modules)),
1621 )
1622 .saturating_add(
1623 cached
1624 .outline_facts
1625 .as_deref()
1626 .map_or(0, |facts| facts.estimated_bytes()),
1627 )
1628}
1629
1630#[cfg(any(test, feature = "test-support"))]
1631thread_local! {
1632 static SYMBOL_CACHE_DECODE_TEST_BARRIERS: std::cell::RefCell<Option<(std::sync::Arc<std::sync::Barrier>, std::sync::Arc<std::sync::Barrier>)>> = const { std::cell::RefCell::new(None) };
1635}
1636
1637impl SymbolCache {
1638 pub fn new() -> Self {
1639 Self {
1640 entries: HashMap::new(),
1641 entry_bytes: 0,
1642 symbol_count: 0,
1643 generation: 0,
1644 mutation_revision: 0,
1645 persisted_revision: 0,
1646 project_root: None,
1647 }
1648 }
1649
1650 pub fn set_project_root(&mut self, project_root: PathBuf) {
1652 debug_assert!(project_root.is_absolute());
1653 self.project_root = Some(project_root);
1654 }
1655
1656 pub fn set_project_root_for_generation(
1659 &mut self,
1660 generation: u64,
1661 project_root: PathBuf,
1662 ) -> bool {
1663 if self.generation != generation {
1664 return false;
1665 }
1666 self.set_project_root(project_root);
1667 true
1668 }
1669
1670 pub fn insert(
1672 &mut self,
1673 path: PathBuf,
1674 mtime: SystemTime,
1675 size: u64,
1676 content_hash: blake3::Hash,
1677 symbols: Vec<Symbol>,
1678 ) -> bool {
1679 self.insert_shared(
1680 path,
1681 mtime,
1682 size,
1683 content_hash,
1684 Arc::new(symbols),
1685 None,
1686 None,
1687 )
1688 }
1689
1690 pub fn insert_shared_table(
1695 &mut self,
1696 path: PathBuf,
1697 mtime: SystemTime,
1698 size: u64,
1699 content_hash: blake3::Hash,
1700 symbols: Arc<Vec<Symbol>>,
1701 ) -> bool {
1702 self.insert_entry(path, mtime, size, content_hash, symbols, None, None, true)
1703 }
1704
1705 #[allow(clippy::too_many_arguments)]
1706 fn insert_shared(
1707 &mut self,
1708 path: PathBuf,
1709 mtime: SystemTime,
1710 size: u64,
1711 content_hash: blake3::Hash,
1712 symbols: Arc<Vec<Symbol>>,
1713 modules: Option<Arc<Vec<RustModule>>>,
1714 has_error: Option<bool>,
1715 ) -> bool {
1716 self.insert_entry(
1717 path,
1718 mtime,
1719 size,
1720 content_hash,
1721 symbols,
1722 modules,
1723 has_error,
1724 false,
1725 )
1726 }
1727
1728 #[allow(clippy::too_many_arguments)]
1729 fn insert_entry(
1730 &mut self,
1731 path: PathBuf,
1732 mtime: SystemTime,
1733 size: u64,
1734 content_hash: blake3::Hash,
1735 symbols: Arc<Vec<Symbol>>,
1736 modules: Option<Arc<Vec<RustModule>>>,
1737 has_error: Option<bool>,
1738 shared_table: bool,
1739 ) -> bool {
1740 if let Some(cached) = self.entries.get_mut(&path) {
1741 if cached.mtime == mtime
1742 && cached.size == size
1743 && cached.content_hash == content_hash
1744 && cached.symbols == symbols
1745 {
1746 if modules.is_some() {
1750 self.entry_bytes = self
1751 .entry_bytes
1752 .saturating_sub(
1753 cached
1754 .modules
1755 .as_deref()
1756 .map_or(0, |modules| module_bytes(modules)),
1757 )
1758 .saturating_add(
1759 modules
1760 .as_deref()
1761 .map_or(0, |modules| module_bytes(modules)),
1762 );
1763 cached.modules = modules;
1764 }
1765 if has_error.is_some() {
1766 cached.has_error = has_error;
1767 }
1768 return false;
1769 }
1770 }
1771 let entry = CachedSymbols {
1772 mtime,
1773 size,
1774 content_hash,
1775 symbols,
1776 modules,
1777 has_error,
1778 outline_facts: None,
1779 shared_table,
1780 };
1781 let next_bytes = if let Some((stored_path, previous)) = self.entries.get_key_value(&path) {
1782 self.entry_bytes = self
1783 .entry_bytes
1784 .saturating_sub(cached_symbols_estimated_bytes(stored_path, previous));
1785 self.symbol_count = self.symbol_count.saturating_sub(previous.symbols.len());
1786 cached_symbols_estimated_bytes(stored_path, &entry)
1787 } else {
1788 cached_symbols_estimated_bytes(&path, &entry)
1789 };
1790 self.entry_bytes = self.entry_bytes.saturating_add(next_bytes);
1791 self.symbol_count = self.symbol_count.saturating_add(entry.symbols.len());
1792 self.entries.insert(path, entry);
1793 self.mutation_revision = self.mutation_revision.wrapping_add(1);
1794 true
1795 }
1796
1797 pub fn insert_for_generation(
1799 &mut self,
1800 generation: u64,
1801 path: PathBuf,
1802 mtime: SystemTime,
1803 size: u64,
1804 content_hash: blake3::Hash,
1805 symbols: Vec<Symbol>,
1806 ) -> bool {
1807 if self.generation != generation {
1808 return false;
1809 }
1810 self.insert(path, mtime, size, content_hash, symbols)
1811 }
1812
1813 pub fn get(&self, path: &Path, mtime: SystemTime) -> Option<Vec<Symbol>> {
1815 self.entries.get(path).and_then(|cached| {
1816 cached_file_is_fresh(path, cached.mtime, cached.size, cached.content_hash, mtime).then(
1817 || {
1818 #[cfg(any(test, feature = "test-support"))]
1819 work_counters::OWNED_SYMBOL_COPIES.with(|count| count.set(count.get() + 1));
1820 cached.symbols.as_ref().clone()
1821 },
1822 )
1823 })
1824 }
1825
1826 pub fn symbol_count_if_metadata_matches(
1832 &self,
1833 path: &Path,
1834 mtime: SystemTime,
1835 size: u64,
1836 ) -> Option<usize> {
1837 self.entries.get(path).and_then(|cached| {
1838 (cached.mtime == mtime && cached.size == size).then_some(cached.symbols.len())
1839 })
1840 }
1841
1842 pub fn contains_path_with_mtime(&self, path: &Path, mtime: SystemTime) -> bool {
1844 self.entries
1845 .get(path)
1846 .is_some_and(|cached| cached.mtime == mtime)
1847 }
1848
1849 pub fn invalidate(&mut self, path: &Path) {
1851 if let Some((stored_path, previous)) = self.entries.remove_entry(path) {
1852 self.entry_bytes = self
1853 .entry_bytes
1854 .saturating_sub(cached_symbols_estimated_bytes(&stored_path, &previous));
1855 self.symbol_count = self.symbol_count.saturating_sub(previous.symbols.len());
1856 self.mutation_revision = self.mutation_revision.wrapping_add(1);
1857 }
1858 }
1859
1860 pub fn reset(&mut self) -> u64 {
1862 self.entries.clear();
1863 self.entry_bytes = 0;
1864 self.symbol_count = 0;
1865 self.project_root = None;
1866 self.generation = self.generation.wrapping_add(1);
1867 self.mutation_revision = 0;
1868 self.persisted_revision = 0;
1869 self.generation
1870 }
1871
1872 pub fn generation(&self) -> u64 {
1874 self.generation
1875 }
1876
1877 pub fn contains_key(&self, path: &Path) -> bool {
1879 self.entries.contains_key(path)
1880 }
1881
1882 pub fn len(&self) -> usize {
1884 self.entries.len()
1885 }
1886
1887 pub fn memory_shape(&self) -> [u64; 5] {
1890 [
1891 self.generation,
1892 self.mutation_revision,
1893 self.entries.len() as u64,
1894 self.entry_bytes,
1895 self.project_root
1896 .as_deref()
1897 .map_or(0, crate::memory::path_bytes),
1898 ]
1899 }
1900
1901 pub fn estimated_memory(&self) -> crate::memory::MemoryEstimate {
1905 let bytes = if self.entries.is_empty() {
1906 0
1907 } else {
1908 self.entry_bytes.saturating_add(
1909 self.project_root
1910 .as_deref()
1911 .map_or(0, crate::memory::path_bytes),
1912 )
1913 };
1914 crate::memory::MemoryEstimate::estimated(bytes)
1915 .count("entries", self.entries.len())
1916 .count("symbols", self.symbol_count)
1917 }
1918
1919 #[cfg(any(test, feature = "test-support"))]
1922 pub fn recounted_memory_for_test(&self) -> crate::memory::MemoryEstimate {
1923 if self.entries.is_empty() {
1924 return crate::memory::MemoryEstimate::estimated(0)
1925 .count("entries", 0)
1926 .count("symbols", 0);
1927 }
1928 let entry_bytes = self.entries.iter().fold(0u64, |bytes, (path, cached)| {
1929 fn module_bytes(modules: &[RustModule]) -> u64 {
1930 modules
1931 .iter()
1932 .map(|module| {
1933 std::mem::size_of::<RustModule>() as u64
1934 + module.name.len() as u64
1935 + module_bytes(&module.children)
1936 })
1937 .sum()
1938 }
1939 bytes
1940 .saturating_add(std::mem::size_of::<PathBuf>() as u64)
1941 .saturating_add(crate::memory::path_bytes(path))
1942 .saturating_add(std::mem::size_of::<CachedSymbols>() as u64)
1943 .saturating_add(if cached.shared_table {
1944 0
1945 } else {
1946 symbols_estimated_bytes(&cached.symbols)
1947 })
1948 .saturating_add(
1949 cached
1950 .modules
1951 .as_deref()
1952 .map_or(0, |modules| module_bytes(modules)),
1953 )
1954 .saturating_add(
1955 cached
1956 .outline_facts
1957 .as_deref()
1958 .map_or(0, |facts| facts.estimated_bytes()),
1959 )
1960 });
1961 let project_root_bytes = self
1962 .project_root
1963 .as_deref()
1964 .map(crate::memory::path_bytes)
1965 .unwrap_or(0);
1966 let symbol_count = self
1967 .entries
1968 .values()
1969 .map(|cached| cached.symbols.len())
1970 .fold(0usize, usize::saturating_add);
1971 crate::memory::MemoryEstimate::estimated(entry_bytes.saturating_add(project_root_bytes))
1972 .count("entries", self.entries.len())
1973 .count("symbols", symbol_count)
1974 }
1975}
1976
1977pub fn cached_symbol_count_shared(
1978 cache: &SharedSymbolCache,
1979 path: &Path,
1980 mtime: SystemTime,
1981 size: u64,
1982) -> Option<usize> {
1983 let cached = cache.read().ok()?.entries.get(path)?.clone();
1984 if cached.mtime == mtime && cached.size == size {
1985 return Some(cached.symbols.len());
1986 }
1987 if !cached_file_is_fresh(path, cached.mtime, cached.size, cached.content_hash, mtime) {
1988 return None;
1989 }
1990 let current = cache.read().ok()?;
1993 current
1994 .entries
1995 .get(path)
1996 .filter(|entry| Arc::ptr_eq(&entry.symbols, &cached.symbols))
1997 .map(|_| cached.symbols.len())
1998}
1999
2000pub struct FileParser {
2003 #[cfg(any(test, feature = "test-support"))]
2004 pub cache: HashMap<PathBuf, CachedTree>,
2005 #[cfg(not(any(test, feature = "test-support")))]
2006 cache: HashMap<PathBuf, CachedTree>,
2007 #[cfg(any(test, feature = "test-support"))]
2008 pub symbol_cache: SharedSymbolCache,
2009 #[cfg(not(any(test, feature = "test-support")))]
2010 symbol_cache: SharedSymbolCache,
2011 symbol_cache_generation: Option<u64>,
2012 capture_source: bool,
2013 dynamic_languages: bool,
2014}
2015
2016impl FileParser {
2017 pub fn new() -> Self {
2019 Self::with_symbol_cache(Arc::new(RwLock::new(SymbolCache::new())))
2020 }
2021
2022 pub fn with_symbol_cache(symbol_cache: SharedSymbolCache) -> Self {
2024 Self::with_symbol_cache_generation(symbol_cache, None)
2025 }
2026
2027 pub fn with_symbol_cache_generation(
2029 symbol_cache: SharedSymbolCache,
2030 symbol_cache_generation: Option<u64>,
2031 ) -> Self {
2032 Self {
2033 cache: HashMap::new(),
2034 symbol_cache,
2035 symbol_cache_generation,
2036 capture_source: false,
2037 dynamic_languages: false,
2038 }
2039 }
2040
2041 pub fn with_source_capture(mut self) -> Self {
2044 self.capture_source = true;
2045 self
2046 }
2047
2048 pub fn with_dynamic_languages(mut self, dynamic_languages: bool) -> Self {
2049 self.dynamic_languages = dynamic_languages;
2050 self
2051 }
2052
2053 pub fn parse_source(path: &Path, source: &str, lang: LangId) -> Result<Tree, AftError> {
2059 #[cfg(any(test, feature = "test-support"))]
2060 work_counters::TREE_PARSES.with(|count| count.set(count.get() + 1));
2061 parse_source_with_cached_parser(path, source, lang).inspect_err(|_| {
2062 crate::slog_error!("parse failed for {}", path.display());
2063 })
2064 }
2065
2066 pub fn symbol_cache_len(&self) -> usize {
2068 self.symbol_cache
2069 .read()
2070 .map(|cache| cache.len())
2071 .unwrap_or(0)
2072 }
2073
2074 #[cfg(any(test, feature = "test-support"))]
2075 pub fn parse_tree_cache_len(&self) -> usize {
2076 self.cache.len()
2077 }
2078
2079 pub fn symbol_cache(&self) -> SharedSymbolCache {
2081 Arc::clone(&self.symbol_cache)
2082 }
2083
2084 pub fn parse(&mut self, path: &Path) -> Result<(&Tree, LangId), AftError> {
2087 let lang = language_for_extension(path)
2088 .or_else(|| {
2089 self.dynamic_languages
2090 .then(|| detect_language_any(path, true))
2091 .flatten()
2092 })
2093 .ok_or_else(|| AftError::InvalidRequest {
2094 message: format!(
2095 "unsupported file extension: {}",
2096 path.extension()
2097 .and_then(|e| e.to_str())
2098 .unwrap_or("<none>")
2099 ),
2100 })?;
2101
2102 let canon = path.to_path_buf();
2103 let current_mtime = crate::bounded_io::metadata(path)
2104 .and_then(|m| m.modified())
2105 .map_err(|e| AftError::FileNotFound {
2106 path: format!("{}: {}", path.display(), e),
2107 })?;
2108
2109 let needs_reparse = match self.cache.get(&canon) {
2113 Some(cached) => !cached_file_is_fresh(
2114 path,
2115 cached.mtime,
2116 cached.size,
2117 cached.content_hash,
2118 current_mtime,
2119 ),
2120 None => true,
2121 };
2122
2123 if needs_reparse {
2124 #[cfg(any(test, feature = "test-support"))]
2125 work_counters::FILE_PARSE_READS.with(|count| count.set(count.get() + 1));
2126 #[cfg(any(test, feature = "test-support"))]
2127 work_counters::TREE_SOURCE_READS.with(|count| count.set(count.get() + 1));
2128 let source = read_source(path).map_err(|e| AftError::FileNotFound {
2129 path: format!("{}: {}", path.display(), e),
2130 })?;
2131
2132 let (tree, lang) = parse_resolved_source(path, &source, lang)?;
2133 #[cfg(any(test, feature = "test-support"))]
2134 work_counters::TREE_PARSES.with(|count| count.set(count.get() + 1));
2135
2136 self.cache.insert(
2137 canon.clone(),
2138 CachedTree {
2139 mtime: current_mtime,
2140 size: source.len() as u64,
2141 content_hash: content_hash_for_source(&source),
2142 tree,
2143 lang,
2144 source: self.capture_source.then(|| captured_source(source)),
2145 },
2146 );
2147 }
2148
2149 let cached = self.cache.get(&canon).ok_or_else(|| AftError::ParseError {
2150 message: format!("parser cache missing entry for {}", path.display()),
2151 })?;
2152 Ok((&cached.tree, cached.lang))
2153 }
2154
2155 pub fn parse_source_text(
2161 &mut self,
2162 path: &Path,
2163 source: &str,
2164 ) -> Result<(&Tree, LangId), AftError> {
2165 let lang = language_for_extension(path).ok_or_else(|| AftError::InvalidRequest {
2166 message: format!(
2167 "unsupported file extension: {}",
2168 path.extension()
2169 .and_then(|e| e.to_str())
2170 .unwrap_or("<none>")
2171 ),
2172 })?;
2173 let size = source.len() as u64;
2174 let content_hash = content_hash_for_source(source);
2175 let reusable = size <= cache_freshness::CONTENT_HASH_SIZE_CAP
2176 && self
2177 .cache
2178 .get(path)
2179 .is_some_and(|cached| cached.size == size && cached.content_hash == content_hash);
2180 if !reusable {
2181 let (tree, lang) = parse_resolved_source(path, source, lang)?;
2182 #[cfg(any(test, feature = "test-support"))]
2183 work_counters::TREE_PARSES.with(|count| count.set(count.get() + 1));
2184 self.cache.insert(
2185 path.to_path_buf(),
2186 CachedTree {
2187 mtime: SystemTime::UNIX_EPOCH,
2191 size,
2192 content_hash,
2193 tree,
2194 lang,
2195 source: self
2196 .capture_source
2197 .then(|| captured_source(source.to_string())),
2198 },
2199 );
2200 }
2201 let cached = self.cache.get(path).ok_or_else(|| AftError::ParseError {
2202 message: format!("parser cache missing entry for {}", path.display()),
2203 })?;
2204 Ok((&cached.tree, cached.lang))
2205 }
2206
2207 pub fn parse_cloned(&mut self, path: &Path) -> Result<(Tree, LangId), AftError> {
2212 let (tree, lang) = self.parse(path)?;
2213 Ok((tree.clone(), lang))
2214 }
2215
2216 pub fn parse_snapshot(&mut self, path: &Path) -> Result<ParsedFile, AftError> {
2217 self.capture_source = true;
2218 if self
2219 .cache
2220 .get(path)
2221 .is_some_and(|cached| cached.source.is_none())
2222 {
2223 self.evict_parse_tree(path);
2224 }
2225 let (_, lang) = self.parse(path)?;
2226 let cached = &self.cache[path];
2227 let modules = (lang == LangId::Rust).then(|| {
2230 Arc::new(rust_modules(
2231 cached.tree.root_node(),
2232 cached.source.as_deref().expect("source capture enabled"),
2233 ))
2234 });
2235 Ok(ParsedFile {
2236 source: Arc::clone(cached.source.as_ref().expect("source capture enabled")),
2237 tree: cached.tree.clone(),
2238 lang,
2239 modules,
2240 mtime: cached.mtime,
2241 size: cached.size,
2242 content_hash: cached.content_hash,
2243 })
2244 }
2245
2246 pub fn extract_symbols_from_snapshot(
2248 &mut self,
2249 path: &Path,
2250 parsed: &ParsedFile,
2251 ) -> Result<Arc<Vec<Symbol>>, AftError> {
2252 let cached = self
2253 .symbol_cache
2254 .read()
2255 .map_err(|_| AftError::ParseError {
2256 message: "symbol cache lock poisoned".into(),
2257 })?
2258 .entries
2259 .get(path)
2260 .cloned();
2261 let symbols = match cached {
2262 Some(cached)
2263 if cached.size == parsed.size
2264 && cached.content_hash == parsed.content_hash
2265 && (cached.mtime == parsed.mtime
2266 || parsed.content_hash != cache_freshness::zero_hash()) =>
2267 {
2268 cached.symbols
2269 }
2270 _ => Arc::new(extract_symbols_from_tree(
2271 &parsed.source,
2272 &parsed.tree,
2273 parsed.lang,
2274 )?),
2275 };
2276 let modules = parsed.modules.clone();
2277 let mut cache = self
2278 .symbol_cache
2279 .write()
2280 .map_err(|_| AftError::ParseError {
2281 message: "symbol cache lock poisoned".into(),
2282 })?;
2283 if self
2284 .symbol_cache_generation
2285 .is_none_or(|generation| cache.generation == generation)
2286 {
2287 cache.insert_shared(
2288 path.to_path_buf(),
2289 parsed.mtime,
2290 parsed.size,
2291 parsed.content_hash,
2292 Arc::clone(&symbols),
2293 modules,
2294 Some(parsed.tree.root_node().has_error()),
2295 );
2296 }
2297 Ok(symbols)
2298 }
2299
2300 pub fn cached_has_error(&self, path: &Path) -> Option<bool> {
2304 let current_mtime = crate::bounded_io::metadata(path)
2305 .and_then(|metadata| metadata.modified())
2306 .ok()?;
2307 let cached = self.symbol_cache.read().ok()?.entries.get(path)?.clone();
2308 let has_error = cached.has_error?;
2309 cached_file_is_fresh(
2310 path,
2311 cached.mtime,
2312 cached.size,
2313 cached.content_hash,
2314 current_mtime,
2315 )
2316 .then_some(has_error)
2317 }
2318
2319 pub fn cached_outline(&self, path: &Path) -> Option<CachedOutline> {
2322 let current_mtime = crate::bounded_io::metadata(path)
2323 .and_then(|metadata| metadata.modified())
2324 .ok()?;
2325 let cached = self.symbol_cache.read().ok()?.entries.get(path)?.clone();
2326 let (Some(has_error), Some(facts)) = (cached.has_error, cached.outline_facts) else {
2327 return None;
2328 };
2329 cached_file_is_fresh(
2330 path,
2331 cached.mtime,
2332 cached.size,
2333 cached.content_hash,
2334 current_mtime,
2335 )
2336 .then_some(CachedOutline {
2337 symbols: cached.symbols,
2338 modules: cached.modules,
2339 has_error,
2340 facts,
2341 })
2342 }
2343
2344 pub fn store_outline_facts(
2349 &self,
2350 path: &Path,
2351 parsed: &ParsedFile,
2352 facts: Arc<outline_facts::OutlineParseFacts>,
2353 ) {
2354 let Ok(mut cache) = self.symbol_cache.write() else {
2355 return;
2356 };
2357 if self
2358 .symbol_cache_generation
2359 .is_some_and(|generation| cache.generation != generation)
2360 {
2361 return;
2362 }
2363 if let Some(entry) = cache.entries.get_mut(path) {
2364 if entry.mtime == parsed.mtime
2365 && entry.size == parsed.size
2366 && entry.content_hash == parsed.content_hash
2367 {
2368 let previous_bytes = entry
2369 .outline_facts
2370 .as_deref()
2371 .map_or(0, |facts| facts.estimated_bytes());
2372 let next_bytes = facts.estimated_bytes();
2373 entry.outline_facts = Some(facts);
2374 cache.entry_bytes = cache
2375 .entry_bytes
2376 .saturating_sub(previous_bytes)
2377 .saturating_add(next_bytes);
2378 }
2379 }
2380 }
2381
2382 pub fn extract_rust_outline(
2386 &mut self,
2387 path: &Path,
2388 ) -> Result<(Arc<Vec<Symbol>>, Arc<Vec<RustModule>>), AftError> {
2389 let symbols = self.extract_symbols_shared(path)?;
2390 let modules = self
2391 .symbol_cache
2392 .read()
2393 .map_err(|_| AftError::ParseError {
2394 message: "symbol cache lock poisoned".into(),
2395 })?
2396 .entries
2397 .get(path)
2398 .filter(|entry| Arc::ptr_eq(&entry.symbols, &symbols))
2399 .and_then(|entry| entry.modules.clone());
2400 if let Some(modules) = modules {
2401 return Ok((symbols, modules));
2402 }
2403 let parsed = self.parse_snapshot(path)?;
2404 let symbols = self.extract_symbols_from_snapshot(path, &parsed)?;
2405 Ok((
2406 symbols,
2407 parsed.modules.expect("Rust outline requires Rust source"),
2408 ))
2409 }
2410
2411 test_support_visibility! {
2412 fn parse_with_source(
2424 &mut self,
2425 path: &Path,
2426 source: &str,
2427 current_mtime: std::time::SystemTime,
2428 size: u64,
2429 content_hash: blake3::Hash,
2430 ) -> Result<(&Tree, LangId), AftError> {
2431 let lang = language_for_extension(path)
2432 .or_else(|| {
2433 self.dynamic_languages
2434 .then(|| detect_language_any(path, true))
2435 .flatten()
2436 })
2437 .ok_or_else(|| AftError::InvalidRequest {
2438 message: format!(
2439 "unsupported file extension: {}",
2440 path.extension()
2441 .and_then(|e| e.to_str())
2442 .unwrap_or("<none>")
2443 ),
2444 })?;
2445
2446 let canon = path.to_path_buf();
2447 let needs_reparse = match self.cache.get(&canon) {
2448 Some(cached) => !cached_file_is_fresh(
2449 path,
2450 cached.mtime,
2451 cached.size,
2452 cached.content_hash,
2453 current_mtime,
2454 ),
2455 None => true,
2456 };
2457
2458 if needs_reparse {
2459 let (tree, lang) = parse_resolved_source(path, source, lang)?;
2460 #[cfg(any(test, feature = "test-support"))]
2461 work_counters::TREE_PARSES.with(|count| count.set(count.get() + 1));
2462
2463 self.cache.insert(
2464 canon.clone(),
2465 CachedTree {
2466 mtime: current_mtime,
2467 size,
2468 content_hash,
2469 tree,
2470 lang,
2471 source: self
2472 .capture_source
2473 .then(|| captured_source(source.to_owned())),
2474 },
2475 );
2476 }
2477
2478 let cached = self.cache.get(&canon).ok_or_else(|| AftError::ParseError {
2479 message: format!("parser cache missing entry for {}", path.display()),
2480 })?;
2481 Ok((&cached.tree, cached.lang))
2482 }
2483 }
2484
2485 pub fn extract_symbols(&mut self, path: &Path) -> Result<Vec<Symbol>, AftError> {
2489 self.extract_symbols_with_cache_status(path)
2490 .map(|(symbols, _)| symbols)
2491 }
2492
2493 pub fn extract_symbols_with_cache_status(
2494 &mut self,
2495 path: &Path,
2496 ) -> Result<(Vec<Symbol>, bool), AftError> {
2497 let (symbols, changed, hit) = self.extract_symbols_shared_inner(path)?;
2498 #[cfg(any(test, feature = "test-support"))]
2499 if hit {
2500 work_counters::CACHED_SYMBOL_COPIES.with(|count| count.set(count.get() + 1));
2501 }
2502 let _ = hit;
2503 #[cfg(any(test, feature = "test-support"))]
2504 if Arc::strong_count(&symbols) > 1 {
2505 work_counters::OWNED_SYMBOL_COPIES.with(|count| count.set(count.get() + 1));
2506 }
2507 Ok((Arc::unwrap_or_clone(symbols), changed))
2508 }
2509
2510 pub fn extract_symbols_shared(&mut self, path: &Path) -> Result<Arc<Vec<Symbol>>, AftError> {
2512 self.extract_symbols_shared_inner(path)
2513 .map(|(symbols, _, _)| symbols)
2514 }
2515
2516 fn extract_symbols_shared_inner(
2517 &mut self,
2518 path: &Path,
2519 ) -> Result<(Arc<Vec<Symbol>>, bool, bool), AftError> {
2520 for attempt in 0..=3 {
2523 let canon = path.to_path_buf();
2524 let current_mtime = crate::bounded_io::metadata(path)
2525 .and_then(|m| m.modified())
2526 .map_err(|e| AftError::FileNotFound {
2527 path: format!("{}: {}", path.display(), e),
2528 })?;
2529 if !self.dynamic_languages && language_for_extension(path).is_none() {
2532 return Err(AftError::InvalidRequest {
2533 message: format!(
2534 "unsupported file extension: {}",
2535 path.extension()
2536 .and_then(|ext| ext.to_str())
2537 .unwrap_or("<none>")
2538 ),
2539 });
2540 }
2541
2542 let cached = if attempt < 3 {
2545 self.symbol_cache
2546 .read()
2547 .map_err(|_| AftError::ParseError {
2548 message: "symbol cache lock poisoned".to_string(),
2549 })?
2550 .entries
2551 .get(&canon)
2552 .cloned()
2553 } else {
2554 None
2555 };
2556 if let Some(cached) = cached {
2557 if cached_file_is_fresh(
2558 path,
2559 cached.mtime,
2560 cached.size,
2561 cached.content_hash,
2562 current_mtime,
2563 ) {
2564 if cached.mtime != current_mtime {
2565 #[cfg(any(test, feature = "test-support"))]
2566 CACHE_REFRESH_TEST_BARRIERS.with(|slot| {
2567 if let Some((arrived, released)) = slot.borrow_mut().take() {
2568 arrived.wait();
2569 released.wait();
2570 }
2571 });
2572 #[cfg(any(test, feature = "test-support"))]
2573 CACHE_REFRESH_TEST_MUTATOR.with(|slot| {
2574 if let Some(mutator) = slot.borrow_mut().as_mut() {
2575 mutator();
2576 }
2577 });
2578 let mut cache =
2579 self.symbol_cache
2580 .write()
2581 .map_err(|_| AftError::ParseError {
2582 message: "symbol cache lock poisoned".to_string(),
2583 })?;
2584 if let Some(entry) = cache.entries.get_mut(&canon) {
2585 if entry.mtime == cached.mtime
2586 && entry.size == cached.size
2587 && entry.content_hash == cached.content_hash
2588 {
2589 entry.mtime = current_mtime;
2590 } else {
2591 drop(cache);
2594 continue;
2595 }
2596 } else {
2597 drop(cache);
2598 continue;
2599 }
2600 }
2601 return Ok((cached.symbols, false, true));
2602 }
2603 }
2604
2605 let source = read_source(path).map_err(|e| AftError::FileNotFound {
2606 path: format!("{}: {}", path.display(), e),
2607 })?;
2608 let size = source.len() as u64;
2609 let content_hash = content_hash_for_source(&source);
2610
2611 let (symbols, modules, has_error) = {
2612 let (tree, lang) =
2615 self.parse_with_source(path, &source, current_mtime, size, content_hash)?;
2616 let mut symbols = extract_symbols_from_tree(&source, tree, lang)?;
2617 if lang == LangId::Rust {
2618 complete_rust_trait_members(
2619 &mut symbols,
2620 crate::callgraph::rust_trait_members(&source, tree.root_node(), Direct),
2621 );
2622 }
2623 (
2624 Arc::new(symbols),
2625 (lang == LangId::Rust)
2626 .then(|| Arc::new(rust_modules(tree.root_node(), &source))),
2627 Some(tree.root_node().has_error()),
2628 )
2629 };
2630
2631 let mut symbol_cache = self
2636 .symbol_cache
2637 .write()
2638 .map_err(|_| AftError::ParseError {
2639 message: "symbol cache lock poisoned".to_string(),
2640 })?;
2641 let cache_changed = if let Some(generation) = self.symbol_cache_generation {
2642 symbol_cache.generation == generation
2643 && symbol_cache.insert_shared(
2644 canon,
2645 current_mtime,
2646 size,
2647 content_hash,
2648 Arc::clone(&symbols),
2649 modules,
2650 has_error,
2651 )
2652 } else {
2653 symbol_cache.insert_shared(
2654 canon,
2655 current_mtime,
2656 size,
2657 content_hash,
2658 Arc::clone(&symbols),
2659 modules,
2660 has_error,
2661 )
2662 };
2663
2664 return Ok((symbols, cache_changed, false));
2665 }
2666 unreachable!("the uncached final attempt returns")
2667 }
2668
2669 pub fn evict_parse_tree(&mut self, path: &Path) {
2675 self.cache.remove(path);
2676 }
2677
2678 pub fn invalidate_symbols(&mut self, path: &Path) {
2680 if let Ok(mut symbol_cache) = self.symbol_cache.write() {
2681 symbol_cache.invalidate(path);
2682 }
2683 self.evict_parse_tree(path);
2684 }
2685}
2686
2687pub fn extract_symbols_from_tree(
2692 source: &str,
2693 tree: &Tree,
2694 lang: LangId,
2695) -> Result<Vec<Symbol>, AftError> {
2696 extract_symbols_from_tree_with(source, tree, lang, Direct)
2697}
2698
2699pub fn extract_symbols_from_tree_with<'tree>(
2703 source: &str,
2704 tree: &'tree Tree,
2705 lang: LangId,
2706 nav: impl Nav<'tree>,
2707) -> Result<Vec<Symbol>, AftError> {
2708 let mut symbols = extract_symbols_from_tree_unbounded(source, tree, lang, nav)?;
2709 for symbol in &mut symbols {
2710 if let Some(signature) = symbol.signature.as_mut() {
2711 truncate_signature(signature);
2712 }
2713 }
2714 Ok(symbols)
2715}
2716
2717pub fn truncate_signature(signature: &mut String) {
2720 if signature.len() <= MAX_SIGNATURE_BYTES {
2721 return;
2722 }
2723 let mut end = MAX_SIGNATURE_BYTES;
2724 while !signature.is_char_boundary(end) {
2725 end -= 1;
2726 }
2727 signature.truncate(end);
2728 signature.push('…');
2729}
2730
2731fn extract_symbols_from_tree_unbounded<'tree>(
2732 source: &str,
2733 tree: &'tree Tree,
2734 lang: LangId,
2735 nav: impl Nav<'tree>,
2736) -> Result<Vec<Symbol>, AftError> {
2737 let root = tree.root_node();
2738
2739 if lang == LangId::Rust {
2740 return extract_rs_symbols(source, &root, nav);
2741 }
2742 if lang == LangId::Html {
2743 return extract_html_symbols(source, &root);
2744 }
2745 if lang == LangId::Markdown {
2746 return extract_md_symbols(source, &root);
2747 }
2748 if lang == LangId::Vue {
2749 return extract_vue_symbols(source, &root);
2750 }
2751 if lang == LangId::Json {
2752 return extract_json_symbols(source, &root);
2753 }
2754 if lang == LangId::Yaml {
2755 return extract_yaml_symbols(source, &root);
2756 }
2757 if lang == LangId::Toml {
2758 return extract_toml_symbols(source, &root);
2759 }
2760 if lang == LangId::Luau {
2761 return Ok(crate::luau::declarations(source, root)
2762 .into_iter()
2763 .map(|declaration| luau_symbol(source, declaration))
2764 .collect());
2765 }
2766
2767 let query = cached_query_for(lang)?.ok_or_else(|| AftError::InvalidRequest {
2768 message: format!("no query patterns implemented for {:?} yet", lang),
2769 })?;
2770
2771 match lang {
2772 LangId::TypeScript | LangId::Tsx => extract_ts_symbols(source, &root, query, nav),
2773 LangId::JavaScript => extract_js_symbols(source, &root, query, nav),
2774 LangId::Python => extract_py_symbols(source, &root, query, nav),
2775 LangId::Go => extract_go_symbols(source, &root, query),
2776 LangId::C => extract_c_symbols(source, &root, query),
2777 LangId::Cpp | LangId::Cuda | LangId::Metal => {
2778 extract_cpp_symbols(source, &root, query, lang)
2779 }
2780 LangId::Zig => extract_zig_symbols(source, &root, query),
2781 LangId::CSharp => extract_csharp_symbols(source, &root, query),
2782 LangId::Bash => extract_bash_symbols(source, &root, query),
2783 LangId::Solidity => extract_solidity_symbols(source, &root, query),
2784 LangId::Scss => extract_scss_symbols(source, &root, query),
2785 LangId::Scala => extract_scala_symbols(source, &root, query),
2786 LangId::Java => extract_java_symbols(source, &root, query),
2787 LangId::Ruby => extract_ruby_symbols(source, &root, query),
2788 LangId::Kotlin => extract_kotlin_symbols(source, &root, query),
2789 LangId::Swift => extract_swift_symbols(source, &root, query),
2790 LangId::Php => extract_php_symbols(source, &root, query),
2791 LangId::Lua => extract_lua_symbols(source, &root, query),
2792 LangId::Perl => extract_perl_symbols(source, &root, query),
2793 LangId::Pascal => extract_pascal_symbols(source, &root, query),
2794 LangId::R => extract_r_symbols(source, &root, query),
2795 LangId::Groovy => extract_groovy_symbols(source, &root, query),
2796 LangId::ObjC => extract_objc_symbols(source, &root, query),
2797 LangId::Luau => Err(AftError::InvalidRequest {
2798 message: format!("no query patterns implemented for {:?} yet", lang),
2799 }),
2800 LangId::Rust
2801 | LangId::Html
2802 | LangId::Markdown
2803 | LangId::Vue
2804 | LangId::Json
2805 | LangId::Yaml
2806 | LangId::Toml => unreachable!("handled before query lookup"),
2807 }
2808}
2809
2810pub fn node_range(node: &Node) -> Range {
2812 let start = node.start_position();
2813 let end = node.end_position();
2814 Range {
2815 start_line: start.row as u32,
2816 start_col: start.column as u32,
2817 end_line: end.row as u32,
2818 end_col: end.column as u32,
2819 }
2820}
2821
2822pub fn node_range_with_decorators(node: &Node, source: &str, lang: LangId) -> Range {
2828 node_range_with_decorators_with(node, source, lang, Direct)
2829}
2830
2831pub fn node_range_with_decorators_with<'tree>(
2834 node: &Node<'tree>,
2835 source: &str,
2836 lang: LangId,
2837 nav: impl Nav<'tree>,
2838) -> Range {
2839 if matches!(lang, LangId::Python) {
2840 if let Some(parent) = nav.parent(*node) {
2841 if nav.kind(parent) == "decorated_definition" {
2842 return node_range(&parent);
2843 }
2844 }
2845 }
2846
2847 if matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
2855 if let Some(parent) = nav.parent(*node) {
2856 if nav.kind(parent) == "export_statement" {
2857 return node_range_with_decorators_inner(&parent, source, lang, nav);
2858 }
2859 }
2860 }
2861
2862 node_range_with_decorators_inner(node, source, lang, nav)
2863}
2864
2865fn node_range_with_decorators_inner<'tree>(
2869 node: &Node<'tree>,
2870 source: &str,
2871 lang: LangId,
2872 nav: impl Nav<'tree>,
2873) -> Range {
2874 let mut range = node_range(node);
2875
2876 let mut current = *node;
2877 while let Some(prev) = nav.prev_sibling(current) {
2878 let kind = nav.kind(prev);
2879 let should_include = match lang {
2880 LangId::Rust => {
2881 kind == "attribute_item"
2883 || (kind == "line_comment"
2885 && node_text(source, &prev).starts_with("///"))
2886 || (kind == "block_comment"
2888 && node_text(source, &prev).starts_with("/**"))
2889 }
2890 LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
2891 kind == "decorator"
2893 || (kind == "comment"
2896 && node_text(source, &prev).starts_with("/**")
2897 && is_adjacent_line(&prev, ¤t, source))
2898 }
2899 LangId::Go
2900 | LangId::C
2901 | LangId::Cpp
2902 | LangId::Cuda
2903 | LangId::Metal
2904 | LangId::ObjC
2905 | LangId::Zig
2906 | LangId::CSharp
2907 | LangId::Bash
2908 | LangId::Pascal => {
2909 kind == "comment" && is_adjacent_line(&prev, ¤t, source)
2911 }
2912 LangId::Solidity
2913 | LangId::Scss
2914 | LangId::Scala
2915 | LangId::Java
2916 | LangId::Kotlin
2917 | LangId::Swift
2918 | LangId::Php
2919 | LangId::Groovy => {
2920 let text = node_text(source, &prev);
2922 (kind == "comment" || kind == "line_comment" || kind == "block_comment")
2923 && (text.starts_with("///") || text.starts_with("/**"))
2924 && is_adjacent_line(&prev, ¤t, source)
2925 }
2926 LangId::Ruby | LangId::Lua | LangId::R => {
2927 let text = node_text(source, &prev);
2929 kind == "comment"
2930 && (text.starts_with('#') || text.starts_with("---"))
2931 && is_adjacent_line(&prev, ¤t, source)
2932 }
2933 LangId::Perl | LangId::Luau => false,
2934 LangId::Python => {
2935 false
2937 }
2938 LangId::Html
2939 | LangId::Markdown
2940 | LangId::Vue
2941 | LangId::Json
2942 | LangId::Yaml
2943 | LangId::Toml => false,
2944 };
2945
2946 if should_include {
2947 range.start_line = prev.start_position().row as u32;
2948 range.start_col = prev.start_position().column as u32;
2949 current = prev;
2950 } else {
2951 break;
2952 }
2953 }
2954
2955 range
2956}
2957
2958fn is_adjacent_line(upper: &Node, lower: &Node, source: &str) -> bool {
2960 let upper_end = upper.end_position().row;
2961 let lower_start = lower.start_position().row;
2962
2963 if lower_start == 0 || lower_start <= upper_end {
2964 return true;
2965 }
2966
2967 let gap_start = upper.end_byte().min(source.len());
2974 let gap_end = lower.start_byte().clamp(gap_start, source.len());
2975 let gap = &source[gap_start..gap_end];
2976 #[cfg(any(test, feature = "test-support"))]
2977 ADJACENT_LINE_BYTES_SCANNED.with(|bytes| bytes.set(bytes.get() + gap.len()));
2978 let mut rows = gap.split('\n');
2979 rows.next();
2980 let mut rows = rows.peekable();
2981 while let Some(row) = rows.next() {
2982 if rows.peek().is_some() && row.trim().is_empty() {
2983 return false;
2984 }
2985 }
2986 true
2987}
2988
2989#[cfg(any(test, feature = "test-support"))]
2990thread_local! {
2991 pub static ADJACENT_LINE_BYTES_SCANNED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2994}
2995
2996pub fn node_text<'a>(source: &'a str, node: &Node) -> &'a str {
2998 source.get(node.byte_range()).unwrap_or("")
2999}
3000
3001fn lexical_declaration_has_function_value(node: &Node) -> bool {
3006 let mut pending: Vec<Node> = node.children(&mut node.walk()).collect();
3007 while let Some(child) = pending.pop() {
3008 if matches!(
3009 child.kind(),
3010 "arrow_function" | "function_expression" | "generator_function"
3011 ) {
3012 return true;
3013 }
3014 pending.extend(child.children(&mut child.walk()));
3015 }
3016 false
3017}
3018
3019fn variable_declarator_has_function_value(node: &Node) -> bool {
3020 node.child_by_field_name("value").is_some_and(|value| {
3021 matches!(
3022 value.kind(),
3023 "arrow_function" | "function_expression" | "generator_function"
3024 )
3025 })
3026}
3027
3028test_support_visibility! {
3029struct ExportIndex {
3037 #[cfg(any(test, feature = "test-support"))]
3038 pub ranges: Vec<std::ops::Range<usize>>,
3039 #[cfg(not(any(test, feature = "test-support")))]
3040 ranges: Vec<std::ops::Range<usize>>,
3041 #[cfg(any(test, feature = "test-support"))]
3042 pub names: HashSet<String>,
3043 #[cfg(not(any(test, feature = "test-support")))]
3044 names: HashSet<String>,
3045}
3046}
3047
3048test_support_visibility! {
3049fn collect_exports<'tree>(source: &str, root: &Node<'tree>, nav: impl Nav<'tree>) -> ExportIndex {
3050 let mut ranges = Vec::new();
3051 let names = walk_export_statements(source, root, nav, |node| ranges.push(node.byte_range()));
3052 ranges.sort_by(|a, b| a.start.cmp(&b.start).then(b.end.cmp(&a.end)));
3057 let mut outermost: Vec<std::ops::Range<usize>> = Vec::with_capacity(ranges.len());
3058 for range in ranges {
3059 if outermost
3060 .last()
3061 .is_some_and(|last| last.start <= range.start && range.end <= last.end)
3062 {
3063 continue;
3064 }
3065 outermost.push(range);
3066 }
3067 ExportIndex {
3068 ranges: outermost,
3069 names,
3070 }
3071}
3072}
3073
3074test_support_visibility! {
3075fn is_exported(node: &Node, export_ranges: &[std::ops::Range<usize>]) -> bool {
3082 let r = node.byte_range();
3083 let candidates = export_ranges.partition_point(|er| er.start <= r.start);
3084 #[cfg(any(test, feature = "test-support"))]
3085 EXPORT_RANGE_COMPARISONS.with(|count| count.set(count.get() + 1));
3086 candidates
3087 .checked_sub(1)
3088 .is_some_and(|index| r.end <= export_ranges[index].end)
3089}
3090}
3091
3092#[cfg(any(test, feature = "test-support"))]
3093thread_local! {
3094 pub static EXPORT_RANGE_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3096}
3097
3098#[cfg(any(test, feature = "test-support"))]
3101pub fn collect_exported_symbol_names(source: &str, root: &Node) -> HashSet<String> {
3102 walk_export_statements(source, root, Direct, |_| {})
3103}
3104
3105fn walk_export_statements<'tree>(
3114 source: &str,
3115 root: &Node<'tree>,
3116 nav: impl Nav<'tree>,
3117 mut on_export: impl FnMut(&Node),
3118) -> HashSet<String> {
3119 let mut exported = HashSet::new();
3120 nav.walk(*root, |node, kind| {
3121 if kind == "export_statement" {
3122 on_export(&node);
3123 collect_names_from_export_statement(source, &node, &mut exported);
3124 }
3125 true
3126 });
3127 exported
3128}
3129
3130fn collect_names_from_export_statement(source: &str, node: &Node, exported: &mut HashSet<String>) {
3131 let mut cursor = node.walk();
3132 if !cursor.goto_first_child() {
3133 return;
3134 }
3135
3136 let mut saw_default = false;
3137 loop {
3138 let child = cursor.node();
3139 match child.kind() {
3140 "default" => saw_default = true,
3141 "export_clause" => collect_names_from_export_clause(source, &child, exported),
3142 "identifier" | "type_identifier" | "property_identifier" if saw_default => {
3143 exported.insert(node_text(source, &child).to_string());
3144 return;
3145 }
3146 _ => {}
3147 }
3148 if !cursor.goto_next_sibling() {
3149 break;
3150 }
3151 }
3152}
3153
3154fn collect_names_from_export_clause(source: &str, node: &Node, exported: &mut HashSet<String>) {
3155 let mut cursor = node.walk();
3156 if !cursor.goto_first_child() {
3157 return;
3158 }
3159
3160 loop {
3161 let child = cursor.node();
3162 if child.kind() == "export_specifier" {
3163 if let Some(exported_name) = last_identifier_text(source, &child) {
3164 exported.insert(exported_name);
3165 }
3166 }
3167 if !cursor.goto_next_sibling() {
3168 break;
3169 }
3170 }
3171}
3172
3173fn last_identifier_text(source: &str, node: &Node) -> Option<String> {
3174 let mut cursor = node.walk();
3175 if !cursor.goto_first_child() {
3176 return None;
3177 }
3178
3179 let mut last = None;
3180 loop {
3181 let child = cursor.node();
3182 if matches!(
3183 child.kind(),
3184 "identifier"
3185 | "type_identifier"
3186 | "property_identifier"
3187 | "shorthand_property_identifier"
3188 ) {
3189 last = Some(node_text(source, &child).to_string());
3190 }
3191 if !cursor.goto_next_sibling() {
3192 break;
3193 }
3194 }
3195 last
3196}
3197
3198fn mark_named_exports(symbols: &mut [Symbol], exported_names: &HashSet<String>) {
3199 for symbol in symbols {
3200 if symbol.scope_chain.is_empty()
3201 && symbol.parent.is_none()
3202 && exported_names.contains(&symbol.name)
3203 {
3204 symbol.exported = true;
3205 }
3206 }
3207}
3208
3209test_support_visibility! {
3210fn extract_signature(source: &str, node: &Node) -> String {
3212 let text = node_text(source, node);
3213 let first_line = text.lines().next().unwrap_or(text);
3214 let trimmed = first_line.trim_end();
3216 let trimmed = trimmed.strip_suffix('{').unwrap_or(trimmed).trim_end();
3217 trimmed.to_string()
3218}
3219}
3220
3221fn push_default_export_symbol<'tree>(
3222 symbols: &mut Vec<Symbol>,
3223 source: &str,
3224 lang: LangId,
3225 body_node: Node<'tree>,
3226 def_node: Node<'tree>,
3227 nav: impl Nav<'tree>,
3228) {
3229 let kind = if body_node.kind() == "class" {
3230 SymbolKind::Class
3231 } else {
3232 SymbolKind::Function
3233 };
3234
3235 symbols.push(Symbol {
3236 name: "default".to_string(),
3237 kind,
3238 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3239 signature: Some(extract_signature(source, &def_node)),
3240 scope_chain: vec![],
3241 exported: true,
3242 parent: None,
3243 });
3244}
3245
3246fn node_contains_descendant_kind(node: &Node, kind: &str) -> bool {
3247 let mut cursor = node.walk();
3248 loop {
3249 if cursor.node().kind() == kind {
3250 return true;
3251 }
3252 if cursor.goto_first_child() {
3253 continue;
3254 }
3255 loop {
3256 if cursor.goto_next_sibling() {
3257 break;
3258 }
3259 if !cursor.goto_parent() {
3260 return false;
3261 }
3262 }
3263 }
3264}
3265
3266fn push_ts_member_symbol<'tree>(
3267 symbols: &mut Vec<Symbol>,
3268 source: &str,
3269 name_node: Node<'tree>,
3270 def_node: Node<'tree>,
3271 parent_name: &str,
3272 kind: SymbolKind,
3273 nav: impl Nav<'tree>,
3274) {
3275 symbols.push(Symbol {
3276 name: node_text(source, &name_node).to_string(),
3277 kind,
3278 range: node_range_with_decorators_with(&def_node, source, LangId::TypeScript, nav),
3279 signature: Some(extract_signature(source, &def_node)),
3280 scope_chain: vec![parent_name.to_string()],
3281 exported: false,
3282 parent: Some(parent_name.to_string()),
3283 });
3284}
3285
3286fn extract_ts_symbols<'tree>(
3288 source: &str,
3289 root: &Node<'tree>,
3290 query: &Query,
3291 nav: impl Nav<'tree>,
3292) -> Result<Vec<Symbol>, AftError> {
3293 let lang = LangId::TypeScript;
3294 let capture_names = query.capture_names();
3295
3296 let ExportIndex {
3297 ranges: export_ranges,
3298 names: exported_names,
3299 } = collect_exports(source, root, nav);
3300
3301 let mut symbols = Vec::new();
3302 let mut variable_names = VariableNameIndex::default();
3303 let mut cursor = QueryCursor::new();
3304 let mut matches = cursor.matches(query, *root, source.as_bytes());
3305
3306 while let Some(m) = {
3307 matches.advance();
3308 matches.get()
3309 } {
3310 let mut fn_name_node = None;
3312 let mut fn_def_node = None;
3313 let mut arrow_name_node = None;
3314 let mut arrow_def_node = None;
3315 let mut arrow_decl_node = None;
3316 let mut class_name_node = None;
3317 let mut class_def_node = None;
3318 let mut method_class_name_node = None;
3319 let mut method_name_node = None;
3320 let mut method_def_node = None;
3321 let mut class_property_class_name_node = None;
3322 let mut class_property_name_node = None;
3323 let mut class_property_def_node = None;
3324 let mut interface_name_node = None;
3325 let mut interface_def_node = None;
3326 let mut interface_member_interface_name_node = None;
3327 let mut interface_member_name_node = None;
3328 let mut interface_member_def_node = None;
3329 let mut interface_property_interface_name_node = None;
3330 let mut interface_property_name_node = None;
3331 let mut interface_property_def_node = None;
3332 let mut object_property_object_name_node = None;
3333 let mut object_property_name_node = None;
3334 let mut object_property_value_node = None;
3335 let mut object_property_def_node = None;
3336 let mut enum_name_node = None;
3337 let mut enum_def_node = None;
3338 let mut type_alias_name_node = None;
3339 let mut type_alias_def_node = None;
3340 let mut var_name_node = None;
3341 let mut var_def_node = None;
3342 let mut var_decl_node = None;
3343 let mut default_body_node = None;
3344 let mut default_def_node = None;
3345
3346 for cap in m.captures {
3347 let Some(&name) = capture_names.get(cap.index as usize) else {
3348 continue;
3349 };
3350 match name {
3351 "fn.name" => fn_name_node = Some(cap.node),
3352 "fn.def" => fn_def_node = Some(cap.node),
3353 "arrow.name" => arrow_name_node = Some(cap.node),
3354 "arrow.def" => arrow_def_node = Some(cap.node),
3355 "arrow.decl" => arrow_decl_node = Some(cap.node),
3356 "class.name" => class_name_node = Some(cap.node),
3357 "class.def" => class_def_node = Some(cap.node),
3358 "method.class_name" => method_class_name_node = Some(cap.node),
3359 "method.name" => method_name_node = Some(cap.node),
3360 "method.def" => method_def_node = Some(cap.node),
3361 "class_property.class_name" => class_property_class_name_node = Some(cap.node),
3362 "class_property.name" => class_property_name_node = Some(cap.node),
3363 "class_property.def" => class_property_def_node = Some(cap.node),
3364 "interface.name" => interface_name_node = Some(cap.node),
3365 "interface.def" => interface_def_node = Some(cap.node),
3366 "interface_member.interface_name" => {
3367 interface_member_interface_name_node = Some(cap.node)
3368 }
3369 "interface_member.name" => interface_member_name_node = Some(cap.node),
3370 "interface_member.def" => interface_member_def_node = Some(cap.node),
3371 "interface_property.interface_name" => {
3372 interface_property_interface_name_node = Some(cap.node)
3373 }
3374 "interface_property.name" => interface_property_name_node = Some(cap.node),
3375 "interface_property.def" => interface_property_def_node = Some(cap.node),
3376 "object_property.object_name" => object_property_object_name_node = Some(cap.node),
3377 "object_property.name" => object_property_name_node = Some(cap.node),
3378 "object_property.value" => object_property_value_node = Some(cap.node),
3379 "object_property.def" => object_property_def_node = Some(cap.node),
3380 "enum.name" => enum_name_node = Some(cap.node),
3381 "enum.def" => enum_def_node = Some(cap.node),
3382 "type_alias.name" => type_alias_name_node = Some(cap.node),
3383 "type_alias.def" => type_alias_def_node = Some(cap.node),
3384 "var.name" => var_name_node = Some(cap.node),
3385 "var.def" => var_def_node = Some(cap.node),
3386 "var.decl" => var_decl_node = Some(cap.node),
3387 "default.body" => default_body_node = Some(cap.node),
3388 "default.def" => default_def_node = Some(cap.node),
3389 _ => {}
3390 }
3391 }
3392
3393 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
3395 symbols.push(Symbol {
3396 name: node_text(source, &name_node).to_string(),
3397 kind: SymbolKind::Function,
3398 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3399 signature: Some(extract_signature(source, &def_node)),
3400 scope_chain: vec![],
3401 exported: is_exported(&def_node, &export_ranges),
3402 parent: None,
3403 });
3404 }
3405
3406 if let (Some(name_node), Some(def_node)) = (arrow_name_node, arrow_def_node) {
3408 let range_node = arrow_decl_node.unwrap_or(def_node);
3409 symbols.push(Symbol {
3410 name: node_text(source, &name_node).to_string(),
3411 kind: SymbolKind::Function,
3412 range: node_range_with_decorators_with(&range_node, source, lang, nav),
3413 signature: Some(extract_signature(source, &def_node)),
3414 scope_chain: vec![],
3415 exported: is_exported(&def_node, &export_ranges),
3416 parent: None,
3417 });
3418 }
3419
3420 if let (Some(body_node), Some(def_node)) = (default_body_node, default_def_node) {
3422 push_default_export_symbol(&mut symbols, source, lang, body_node, def_node, nav);
3423 }
3424
3425 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
3427 symbols.push(Symbol {
3428 name: node_text(source, &name_node).to_string(),
3429 kind: SymbolKind::Class,
3430 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3431 signature: Some(extract_signature(source, &def_node)),
3432 scope_chain: vec![],
3433 exported: is_exported(&def_node, &export_ranges),
3434 parent: None,
3435 });
3436 }
3437
3438 if let (Some(class_name_node), Some(name_node), Some(def_node)) =
3440 (method_class_name_node, method_name_node, method_def_node)
3441 {
3442 let class_name = node_text(source, &class_name_node).to_string();
3443 symbols.push(Symbol {
3444 name: node_text(source, &name_node).to_string(),
3445 kind: SymbolKind::Method,
3446 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3447 signature: Some(extract_signature(source, &def_node)),
3448 scope_chain: vec![class_name.clone()],
3449 exported: false, parent: Some(class_name),
3451 });
3452 }
3453
3454 if let (Some(class_name_node), Some(name_node), Some(def_node)) = (
3456 class_property_class_name_node,
3457 class_property_name_node,
3458 class_property_def_node,
3459 ) {
3460 let class_name = node_text(source, &class_name_node);
3461 push_ts_member_symbol(
3462 &mut symbols,
3463 source,
3464 name_node,
3465 def_node,
3466 class_name,
3467 SymbolKind::Method,
3468 nav,
3469 );
3470 }
3471
3472 if let (Some(name_node), Some(def_node)) = (interface_name_node, interface_def_node) {
3474 symbols.push(Symbol {
3475 name: node_text(source, &name_node).to_string(),
3476 kind: SymbolKind::Interface,
3477 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3478 signature: Some(extract_signature(source, &def_node)),
3479 scope_chain: vec![],
3480 exported: is_exported(&def_node, &export_ranges),
3481 parent: None,
3482 });
3483 }
3484
3485 if let (Some(interface_name_node), Some(name_node), Some(def_node)) = (
3487 interface_member_interface_name_node,
3488 interface_member_name_node,
3489 interface_member_def_node,
3490 ) {
3491 let interface_name = node_text(source, &interface_name_node);
3492 push_ts_member_symbol(
3493 &mut symbols,
3494 source,
3495 name_node,
3496 def_node,
3497 interface_name,
3498 SymbolKind::Method,
3499 nav,
3500 );
3501 }
3502
3503 if let (Some(interface_name_node), Some(name_node), Some(def_node)) = (
3505 interface_property_interface_name_node,
3506 interface_property_name_node,
3507 interface_property_def_node,
3508 ) {
3509 if node_contains_descendant_kind(&def_node, "function_type") {
3510 let interface_name = node_text(source, &interface_name_node);
3511 push_ts_member_symbol(
3512 &mut symbols,
3513 source,
3514 name_node,
3515 def_node,
3516 interface_name,
3517 SymbolKind::Method,
3518 nav,
3519 );
3520 }
3521 }
3522
3523 if let (Some(object_name_node), Some(name_node), Some(def_node)) = (
3525 object_property_object_name_node,
3526 object_property_name_node,
3527 object_property_def_node,
3528 ) {
3529 let object_name = node_text(source, &object_name_node);
3530 let property_name = node_text(source, &name_node);
3531 push_ts_member_symbol(
3532 &mut symbols,
3533 source,
3534 name_node,
3535 def_node,
3536 object_name,
3537 SymbolKind::Method,
3538 nav,
3539 );
3540
3541 if let Some(value_node) = object_property_value_node {
3543 if let Some(function_name_node) = value_node.child_by_field_name("name") {
3544 if node_text(source, &function_name_node) != property_name {
3545 push_ts_member_symbol(
3546 &mut symbols,
3547 source,
3548 function_name_node,
3549 value_node,
3550 object_name,
3551 SymbolKind::Function,
3552 nav,
3553 );
3554 }
3555 }
3556 }
3557 }
3558
3559 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
3561 symbols.push(Symbol {
3562 name: node_text(source, &name_node).to_string(),
3563 kind: SymbolKind::Enum,
3564 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3565 signature: Some(extract_signature(source, &def_node)),
3566 scope_chain: vec![],
3567 exported: is_exported(&def_node, &export_ranges),
3568 parent: None,
3569 });
3570 }
3571
3572 if let (Some(name_node), Some(def_node)) = (type_alias_name_node, type_alias_def_node) {
3574 symbols.push(Symbol {
3575 name: node_text(source, &name_node).to_string(),
3576 kind: SymbolKind::TypeAlias,
3577 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3578 signature: Some(extract_signature(source, &def_node)),
3579 scope_chain: vec![],
3580 exported: is_exported(&def_node, &export_ranges),
3581 parent: None,
3582 });
3583 }
3584
3585 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
3587 let is_top_level = nav
3589 .parent(def_node)
3590 .map(|p| p.kind() == "program" || p.kind() == "export_statement")
3591 .unwrap_or(false);
3592 let range_node = var_decl_node.unwrap_or(def_node);
3593 let is_function_like = if range_node.kind() == "variable_declarator" {
3594 variable_declarator_has_function_value(&range_node)
3595 } else {
3596 lexical_declaration_has_function_value(&def_node)
3597 };
3598 let name = node_text(source, &name_node);
3599 if variable_names.should_capture(&symbols, name, is_top_level && !is_function_like) {
3600 symbols.push(Symbol {
3601 name: name.to_string(),
3602 kind: SymbolKind::Variable,
3603 range: node_range_with_decorators_with(&range_node, source, lang, nav),
3604 signature: Some(extract_signature(source, &def_node)),
3605 scope_chain: vec![],
3606 exported: is_exported(&def_node, &export_ranges),
3607 parent: None,
3608 });
3609 }
3610 }
3611 }
3612
3613 mark_named_exports(&mut symbols, &exported_names);
3614
3615 dedup_symbols(&mut symbols);
3617 Ok(symbols)
3618}
3619
3620#[derive(Default)]
3622struct VariableNameIndex {
3623 names: HashSet<String>,
3624 indexed: usize,
3625}
3626
3627#[cfg(any(test, feature = "test-support"))]
3628thread_local! {
3629 pub static VARIABLE_NAME_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3630 pub static LEGACY_VARIABLE_NAMES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3631}
3632
3633impl VariableNameIndex {
3634 fn should_capture(&mut self, symbols: &[Symbol], name: &str, eligible: bool) -> bool {
3635 #[cfg(any(test, feature = "test-support"))]
3636 if LEGACY_VARIABLE_NAMES.with(|legacy| legacy.get()) {
3637 return Self::legacy_capture(symbols, name, eligible);
3638 }
3639 if !eligible {
3641 return false;
3642 }
3643 for symbol in &symbols[self.indexed..] {
3646 #[cfg(any(test, feature = "test-support"))]
3647 VARIABLE_NAME_WORK.with(|work| work.set(work.get() + 1));
3648 self.names.insert(symbol.name.clone());
3649 }
3650 self.indexed = symbols.len();
3651 #[cfg(any(test, feature = "test-support"))]
3652 VARIABLE_NAME_WORK.with(|work| work.set(work.get() + 1));
3653 !self.names.contains(name)
3654 }
3655
3656 #[cfg(any(test, feature = "test-support"))]
3657 fn legacy_capture(symbols: &[Symbol], name: &str, eligible: bool) -> bool {
3658 let captured = symbols.iter().any(|symbol| {
3659 VARIABLE_NAME_WORK.with(|work| work.set(work.get() + 1));
3660 symbol.name == name
3661 });
3662 eligible && !captured
3663 }
3664}
3665
3666fn extract_js_symbols<'tree>(
3668 source: &str,
3669 root: &Node<'tree>,
3670 query: &Query,
3671 nav: impl Nav<'tree>,
3672) -> Result<Vec<Symbol>, AftError> {
3673 let lang = LangId::JavaScript;
3674 let capture_names = query.capture_names();
3675
3676 let ExportIndex {
3677 ranges: export_ranges,
3678 names: exported_names,
3679 } = collect_exports(source, root, nav);
3680
3681 let mut symbols = Vec::new();
3682 let mut variable_names = VariableNameIndex::default();
3683 let mut cursor = QueryCursor::new();
3684 let mut matches = cursor.matches(query, *root, source.as_bytes());
3685
3686 while let Some(m) = {
3687 matches.advance();
3688 matches.get()
3689 } {
3690 let mut fn_name_node = None;
3691 let mut fn_def_node = None;
3692 let mut arrow_name_node = None;
3693 let mut arrow_def_node = None;
3694 let mut arrow_decl_node = None;
3695 let mut class_name_node = None;
3696 let mut class_def_node = None;
3697 let mut method_class_name_node = None;
3698 let mut method_name_node = None;
3699 let mut method_def_node = None;
3700 let mut default_body_node = None;
3701 let mut default_def_node = None;
3702 let mut var_name_node = None;
3703 let mut var_def_node = None;
3704 let mut var_decl_node = None;
3705
3706 for cap in m.captures {
3707 let Some(&name) = capture_names.get(cap.index as usize) else {
3708 continue;
3709 };
3710 match name {
3711 "fn.name" => fn_name_node = Some(cap.node),
3712 "fn.def" => fn_def_node = Some(cap.node),
3713 "arrow.name" => arrow_name_node = Some(cap.node),
3714 "arrow.def" => arrow_def_node = Some(cap.node),
3715 "arrow.decl" => arrow_decl_node = Some(cap.node),
3716 "class.name" => class_name_node = Some(cap.node),
3717 "class.def" => class_def_node = Some(cap.node),
3718 "method.class_name" => method_class_name_node = Some(cap.node),
3719 "method.name" => method_name_node = Some(cap.node),
3720 "method.def" => method_def_node = Some(cap.node),
3721 "default.body" => default_body_node = Some(cap.node),
3722 "default.def" => default_def_node = Some(cap.node),
3723 "var.name" => var_name_node = Some(cap.node),
3724 "var.def" => var_def_node = Some(cap.node),
3725 "var.decl" => var_decl_node = Some(cap.node),
3726 _ => {}
3727 }
3728 }
3729
3730 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
3731 symbols.push(Symbol {
3732 name: node_text(source, &name_node).to_string(),
3733 kind: SymbolKind::Function,
3734 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3735 signature: Some(extract_signature(source, &def_node)),
3736 scope_chain: vec![],
3737 exported: is_exported(&def_node, &export_ranges),
3738 parent: None,
3739 });
3740 }
3741
3742 if let (Some(name_node), Some(def_node)) = (arrow_name_node, arrow_def_node) {
3743 let range_node = arrow_decl_node.unwrap_or(def_node);
3744 symbols.push(Symbol {
3745 name: node_text(source, &name_node).to_string(),
3746 kind: SymbolKind::Function,
3747 range: node_range_with_decorators_with(&range_node, source, lang, nav),
3748 signature: Some(extract_signature(source, &def_node)),
3749 scope_chain: vec![],
3750 exported: is_exported(&def_node, &export_ranges),
3751 parent: None,
3752 });
3753 }
3754
3755 if let (Some(body_node), Some(def_node)) = (default_body_node, default_def_node) {
3756 push_default_export_symbol(&mut symbols, source, lang, body_node, def_node, nav);
3757 }
3758
3759 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
3760 symbols.push(Symbol {
3761 name: node_text(source, &name_node).to_string(),
3762 kind: SymbolKind::Class,
3763 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3764 signature: Some(extract_signature(source, &def_node)),
3765 scope_chain: vec![],
3766 exported: is_exported(&def_node, &export_ranges),
3767 parent: None,
3768 });
3769 }
3770
3771 if let (Some(class_name_node), Some(name_node), Some(def_node)) =
3772 (method_class_name_node, method_name_node, method_def_node)
3773 {
3774 let class_name = node_text(source, &class_name_node).to_string();
3775 symbols.push(Symbol {
3776 name: node_text(source, &name_node).to_string(),
3777 kind: SymbolKind::Method,
3778 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3779 signature: Some(extract_signature(source, &def_node)),
3780 scope_chain: vec![class_name.clone()],
3781 exported: false,
3782 parent: Some(class_name),
3783 });
3784 }
3785
3786 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
3792 let is_top_level = nav
3793 .parent(def_node)
3794 .map(|p| p.kind() == "program" || p.kind() == "export_statement")
3795 .unwrap_or(false);
3796 let range_node = var_decl_node.unwrap_or(def_node);
3797 let is_function_like = if range_node.kind() == "variable_declarator" {
3798 variable_declarator_has_function_value(&range_node)
3799 } else {
3800 lexical_declaration_has_function_value(&def_node)
3801 };
3802 let name = node_text(source, &name_node);
3803 if variable_names.should_capture(&symbols, name, is_top_level && !is_function_like) {
3804 symbols.push(Symbol {
3805 name: name.to_string(),
3806 kind: SymbolKind::Variable,
3807 range: node_range_with_decorators_with(&range_node, source, lang, nav),
3808 signature: Some(extract_signature(source, &def_node)),
3809 scope_chain: vec![],
3810 exported: is_exported(&def_node, &export_ranges),
3811 parent: None,
3812 });
3813 }
3814 }
3815 }
3816
3817 mark_named_exports(&mut symbols, &exported_names);
3818 dedup_symbols(&mut symbols);
3819 Ok(symbols)
3820}
3821
3822fn py_scope_chain<'tree>(node: &Node<'tree>, source: &str, nav: impl Nav<'tree>) -> Vec<String> {
3825 let mut chain = Vec::new();
3826 let mut current = nav.parent(*node);
3827 while let Some(parent) = current {
3828 if nav.kind(parent) == "class_definition" {
3829 if let Some(name_node) = parent.child_by_field_name("name") {
3830 chain.push(node_text(source, &name_node).to_string());
3831 }
3832 }
3833 current = nav.parent(parent);
3834 }
3835 chain.reverse();
3836 chain
3837}
3838
3839fn extract_py_symbols<'tree>(
3841 source: &str,
3842 root: &Node<'tree>,
3843 query: &Query,
3844 nav: impl Nav<'tree>,
3845) -> Result<Vec<Symbol>, AftError> {
3846 let lang = LangId::Python;
3847 let capture_names = query.capture_names();
3848
3849 let mut symbols = Vec::new();
3850 let mut cursor = QueryCursor::new();
3851 let mut matches = cursor.matches(query, *root, source.as_bytes());
3852
3853 let mut decorated_fn_lines = std::collections::HashSet::new();
3855
3856 {
3858 let mut cursor2 = QueryCursor::new();
3859 let mut matches2 = cursor2.matches(query, *root, source.as_bytes());
3860 while let Some(m) = {
3861 matches2.advance();
3862 matches2.get()
3863 } {
3864 let mut dec_def_node = None;
3865 let mut dec_decorator_node = None;
3866
3867 for cap in m.captures {
3868 let Some(&name) = capture_names.get(cap.index as usize) else {
3869 continue;
3870 };
3871 match name {
3872 "dec.def" => dec_def_node = Some(cap.node),
3873 "dec.decorator" => dec_decorator_node = Some(cap.node),
3874 _ => {}
3875 }
3876 }
3877
3878 if let (Some(def_node), Some(_dec_node)) = (dec_def_node, dec_decorator_node) {
3879 let mut child_cursor = def_node.walk();
3881 if child_cursor.goto_first_child() {
3882 loop {
3883 let child = child_cursor.node();
3884 if child.kind() == "function_definition"
3885 || child.kind() == "class_definition"
3886 {
3887 decorated_fn_lines.insert(child.start_position().row);
3888 }
3889 if !child_cursor.goto_next_sibling() {
3890 break;
3891 }
3892 }
3893 }
3894 }
3895 }
3896 }
3897
3898 while let Some(m) = {
3899 matches.advance();
3900 matches.get()
3901 } {
3902 let mut fn_name_node = None;
3903 let mut fn_def_node = None;
3904 let mut class_name_node = None;
3905 let mut class_def_node = None;
3906
3907 for cap in m.captures {
3908 let Some(&name) = capture_names.get(cap.index as usize) else {
3909 continue;
3910 };
3911 match name {
3912 "fn.name" => fn_name_node = Some(cap.node),
3913 "fn.def" => fn_def_node = Some(cap.node),
3914 "class.name" => class_name_node = Some(cap.node),
3915 "class.def" => class_def_node = Some(cap.node),
3916 _ => {}
3917 }
3918 }
3919
3920 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
3922 let scope = py_scope_chain(&def_node, source, nav);
3923 let is_method = !scope.is_empty();
3924 let name = node_text(source, &name_node).to_string();
3925 let kind = if is_method {
3927 SymbolKind::Method
3928 } else {
3929 SymbolKind::Function
3930 };
3931
3932 let sig = if decorated_fn_lines.contains(&def_node.start_position().row) {
3934 let mut sig_parts = Vec::new();
3936 let mut parent = nav.parent(def_node);
3937 while let Some(p) = parent {
3938 if p.kind() == "decorated_definition" {
3939 let mut dc = p.walk();
3941 if dc.goto_first_child() {
3942 loop {
3943 if dc.node().kind() == "decorator" {
3944 sig_parts.push(node_text(source, &dc.node()).to_string());
3945 }
3946 if !dc.goto_next_sibling() {
3947 break;
3948 }
3949 }
3950 }
3951 break;
3952 }
3953 parent = nav.parent(p);
3954 }
3955 sig_parts.push(extract_signature(source, &def_node));
3956 Some(sig_parts.join("\n"))
3957 } else {
3958 Some(extract_signature(source, &def_node))
3959 };
3960
3961 symbols.push(Symbol {
3962 name,
3963 kind,
3964 range: node_range_with_decorators_with(&def_node, source, lang, nav),
3965 signature: sig,
3966 scope_chain: scope.clone(),
3967 exported: false, parent: scope.last().cloned(),
3969 });
3970 }
3971
3972 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
3974 let scope = py_scope_chain(&def_node, source, nav);
3975
3976 let sig = if decorated_fn_lines.contains(&def_node.start_position().row) {
3978 let mut sig_parts = Vec::new();
3979 let mut parent = nav.parent(def_node);
3980 while let Some(p) = parent {
3981 if p.kind() == "decorated_definition" {
3982 let mut dc = p.walk();
3983 if dc.goto_first_child() {
3984 loop {
3985 if dc.node().kind() == "decorator" {
3986 sig_parts.push(node_text(source, &dc.node()).to_string());
3987 }
3988 if !dc.goto_next_sibling() {
3989 break;
3990 }
3991 }
3992 }
3993 break;
3994 }
3995 parent = nav.parent(p);
3996 }
3997 sig_parts.push(extract_signature(source, &def_node));
3998 Some(sig_parts.join("\n"))
3999 } else {
4000 Some(extract_signature(source, &def_node))
4001 };
4002
4003 symbols.push(Symbol {
4004 name: node_text(source, &name_node).to_string(),
4005 kind: SymbolKind::Class,
4006 range: node_range_with_decorators_with(&def_node, source, lang, nav),
4007 signature: sig,
4008 scope_chain: scope.clone(),
4009 exported: false,
4010 parent: scope.last().cloned(),
4011 });
4012 }
4013 }
4014
4015 dedup_symbols(&mut symbols);
4016 Ok(symbols)
4017}
4018
4019test_support_visibility! {
4020fn rust_mod_scope_chain<'tree>(
4021 node: &Node<'tree>,
4022 source: &str,
4023 nav: impl Nav<'tree>,
4024) -> Vec<String> {
4025 let mut scopes = Vec::new();
4026 let mut current = nav.parent(*node);
4027
4028 while let Some(parent) = current {
4029 if nav.kind(parent) == "mod_item" {
4030 if let Some(name_node) = parent.child_by_field_name("name") {
4031 scopes.push(node_text(source, &name_node).to_string());
4032 }
4033 }
4034 current = nav.parent(parent);
4035 }
4036
4037 scopes.reverse();
4038 scopes
4039}
4040}
4041
4042pub const RUST_ENTRY_POINT_ATTRIBUTES: &[&str] = &[
4047 "tauri::command",
4048 "wasm_bindgen",
4049 "no_mangle",
4050 "export_name",
4051 "ctor",
4052 "dtor",
4053];
4054
4055#[derive(Debug, Clone, PartialEq, Eq)]
4056pub struct RustAttributeEntryPoint {
4057 pub name: String,
4058 pub scoped_name: String,
4059 pub attribute: &'static str,
4060}
4061
4062pub fn rust_attribute_entry_points<'a>(
4064 source: &str,
4065 root: Node<'a>,
4066) -> Vec<RustAttributeEntryPoint> {
4067 rust_attribute_entry_points_with(source, root, Direct)
4068}
4069
4070pub fn rust_attribute_entry_points_with<'tree>(
4072 source: &str,
4073 root: Node<'tree>,
4074 nav: impl Nav<'tree>,
4075) -> Vec<RustAttributeEntryPoint> {
4076 let bare_command_imported = rust_file_imports_tauri_command(source, root, nav);
4077 let mut function_nodes = Vec::new();
4078 nav.walk(root, |node, kind| {
4079 if kind == "function_item" {
4080 function_nodes.push(node);
4081 }
4082 true
4083 });
4084
4085 let mut entry_points = BTreeMap::new();
4086 for function_node in function_nodes {
4087 let Some(attribute) = rust_entry_point_attribute_for_function(
4088 source,
4089 &function_node,
4090 bare_command_imported,
4091 nav,
4092 ) else {
4093 continue;
4094 };
4095 let Some((name, scoped_name)) = rust_function_identity(source, &function_node, nav) else {
4096 continue;
4097 };
4098 entry_points
4099 .entry(scoped_name.clone())
4100 .or_insert(RustAttributeEntryPoint {
4101 name,
4102 scoped_name,
4103 attribute,
4104 });
4105 }
4106
4107 entry_points.into_values().collect()
4108}
4109
4110fn rust_function_identity<'tree>(
4111 source: &str,
4112 function_node: &Node<'tree>,
4113 nav: impl Nav<'tree>,
4114) -> Option<(String, String)> {
4115 let name_node = function_node.child_by_field_name("name")?;
4116 let name = node_text(source, &name_node).to_string();
4117 let declaration_list_owner = rust_function_declaration_list_owner(function_node, nav);
4118
4119 match declaration_list_owner.map(|owner| nav.kind(owner)) {
4120 Some("impl_item") => {
4121 let scope_name = rust_impl_scope_name(declaration_list_owner.as_ref().unwrap(), source);
4122 let scoped_name = if scope_name.is_empty() {
4123 name.clone()
4124 } else {
4125 format!("{scope_name}::{name}")
4126 };
4127 Some((name, scoped_name))
4128 }
4129 Some(owner_kind) if owner_kind != "mod_item" => None,
4130 _ => {
4131 let scope_chain = rust_mod_scope_chain(function_node, source, nav);
4132 let scoped_name = if scope_chain.is_empty() {
4133 name.clone()
4134 } else {
4135 format!("{}::{name}", scope_chain.join("::"))
4136 };
4137 Some((name, scoped_name))
4138 }
4139 }
4140}
4141
4142test_support_visibility! {
4143fn rust_function_declaration_list_owner<'tree>(
4144 function_node: &Node<'tree>,
4145 nav: impl Nav<'tree>,
4146) -> Option<Node<'tree>> {
4147 nav.parent(*function_node)
4148 .filter(|parent| nav.kind(*parent) == "declaration_list")
4149 .and_then(|parent| nav.parent(parent))
4150}
4151}
4152
4153test_support_visibility! {
4154fn rust_impl_scope_name(impl_node: &Node, source: &str) -> String {
4155 let mut type_names: Vec<String> = Vec::new();
4156 let mut child_cursor = impl_node.walk();
4157 if child_cursor.goto_first_child() {
4158 loop {
4159 let child = child_cursor.node();
4160 if child.kind() == "type_identifier" || child.kind() == "generic_type" {
4161 type_names.push(node_text(source, &child).to_string());
4162 }
4163 if !child_cursor.goto_next_sibling() {
4164 break;
4165 }
4166 }
4167 }
4168
4169 if type_names.len() >= 2 {
4170 format!("{} for {}", type_names[0], type_names[1])
4171 } else if type_names.len() == 1 {
4172 type_names[0].clone()
4173 } else {
4174 String::new()
4175 }
4176}
4177}
4178
4179fn rust_entry_point_attribute_for_function<'tree>(
4180 source: &str,
4181 function_node: &Node<'tree>,
4182 bare_command_imported: bool,
4183 nav: impl Nav<'tree>,
4184) -> Option<&'static str> {
4185 let mut current = *function_node;
4186 while let Some(prev) = nav.prev_sibling(current) {
4187 let kind = nav.kind(prev);
4188 match kind {
4189 "attribute_item" => {
4190 if let Some(attribute) =
4191 rust_entry_point_attribute_from_node(source, &prev, bare_command_imported)
4192 {
4193 return Some(attribute);
4194 }
4195 current = prev;
4196 }
4197 "line_comment" if node_text(source, &prev).starts_with("///") => {
4198 current = prev;
4199 }
4200 "block_comment" if node_text(source, &prev).starts_with("/**") => {
4201 current = prev;
4202 }
4203 _ => break,
4204 }
4205 }
4206
4207 None
4208}
4209
4210fn rust_entry_point_attribute_from_node(
4211 source: &str,
4212 attribute_node: &Node,
4213 bare_command_imported: bool,
4214) -> Option<&'static str> {
4215 let text = node_text(source, attribute_node);
4216 let path = rust_attribute_path(text)?;
4217 rust_entry_point_attribute_for_path(path, bare_command_imported)
4218}
4219
4220fn rust_attribute_path(attribute_text: &str) -> Option<&str> {
4221 let inner = attribute_text
4222 .trim()
4223 .strip_prefix("#[")?
4224 .strip_suffix(']')?
4225 .trim();
4226 let effective = inner
4227 .strip_prefix("unsafe(")
4228 .and_then(|wrapped| wrapped.strip_suffix(')'))
4229 .map(str::trim)
4230 .unwrap_or(inner);
4231 effective
4232 .split(|ch: char| matches!(ch, '(' | '=' | ','))
4233 .next()
4234 .map(str::trim)
4235 .filter(|path| !path.is_empty())
4236}
4237
4238fn rust_entry_point_attribute_for_path(
4239 path: &str,
4240 bare_command_imported: bool,
4241) -> Option<&'static str> {
4242 let compact = path
4243 .chars()
4244 .filter(|ch| !ch.is_whitespace())
4245 .collect::<String>();
4246 if compact == "tauri::command" {
4247 return Some("tauri::command");
4248 }
4249 if compact == "command" && bare_command_imported {
4250 return Some("tauri::command");
4251 }
4252
4253 let last_segment = compact.rsplit("::").next().unwrap_or(compact.as_str());
4254 RUST_ENTRY_POINT_ATTRIBUTES
4255 .iter()
4256 .copied()
4257 .find(|attribute| *attribute != "tauri::command" && *attribute == last_segment)
4258}
4259
4260fn rust_file_imports_tauri_command<'tree>(
4261 source: &str,
4262 root: Node<'tree>,
4263 nav: impl Nav<'tree>,
4264) -> bool {
4265 let mut imported = false;
4267 nav.walk(root, |node, kind| {
4268 imported |= kind == "use_declaration"
4269 && rust_use_declaration_imports_tauri_command(node_text(source, &node));
4270 !imported
4271 });
4272 imported
4273}
4274
4275fn rust_use_declaration_imports_tauri_command(use_text: &str) -> bool {
4276 let compact = use_text
4277 .chars()
4278 .filter(|ch| !ch.is_whitespace())
4279 .collect::<String>();
4280 let Some(use_index) = compact.find("use") else {
4281 return false;
4282 };
4283 let path = compact[use_index + "use".len()..].trim_end_matches(';');
4284 if path == "tauri::command" {
4285 return true;
4286 }
4287
4288 let Some(inner) = path
4289 .strip_prefix("tauri::{")
4290 .and_then(|inner| inner.strip_suffix('}'))
4291 else {
4292 return false;
4293 };
4294
4295 split_rust_use_items(inner)
4296 .into_iter()
4297 .any(|item| item == "command" || item == "commandascommand")
4298}
4299
4300fn split_rust_use_items(inner: &str) -> Vec<&str> {
4301 let mut items = Vec::new();
4302 let mut depth = 0usize;
4303 let mut start = 0usize;
4304 for (idx, ch) in inner.char_indices() {
4305 match ch {
4306 '{' => depth += 1,
4307 '}' => depth = depth.saturating_sub(1),
4308 ',' if depth == 0 => {
4309 items.push(inner[start..idx].trim());
4310 start = idx + ch.len_utf8();
4311 }
4312 _ => {}
4313 }
4314 }
4315 if start <= inner.len() {
4316 let tail = inner[start..].trim();
4317 if !tail.is_empty() {
4318 items.push(tail);
4319 }
4320 }
4321 items
4322}
4323
4324thread_local! {
4325 static RUST_MACRO_BODY_PARSER: RefCell<Option<Parser>> = const { RefCell::new(None) };
4329}
4330
4331pub fn complete_rust_trait_members(
4335 symbols: &mut Vec<Symbol>,
4336 members: impl IntoIterator<Item = Symbol>,
4337) {
4338 let mut members = members.into_iter().collect::<Vec<_>>();
4341 members.sort_by_key(|member| (member.range.start_line, member.range.start_col));
4342 for mut member in members {
4343 if member.kind != SymbolKind::Method
4344 || !symbols.iter().any(|owner| {
4345 owner.kind == SymbolKind::Interface
4346 && member.parent.as_deref() == Some(owner.name.as_str())
4347 && (owner.range.start_line, owner.range.start_col)
4348 <= (member.range.start_line, member.range.start_col)
4349 && (member.range.end_line, member.range.end_col)
4350 <= (owner.range.end_line, owner.range.end_col)
4351 })
4352 {
4353 continue;
4354 }
4355 member.scope_chain = member.parent.iter().cloned().collect();
4358 if symbols.iter().any(|existing| {
4359 existing.kind == member.kind
4360 && existing.name == member.name
4361 && existing.range == member.range
4362 && existing.scope_chain == member.scope_chain
4363 }) {
4364 continue;
4365 }
4366 symbols.push(member);
4367 }
4368}
4369
4370test_support_visibility! {
4371fn rust_impl_parent_name(impl_target: &str) -> String {
4375 let base_type = impl_target.split('<').next().unwrap_or(impl_target).trim();
4376 base_type
4377 .rsplit("::")
4378 .next()
4379 .unwrap_or(base_type)
4380 .to_string()
4381}
4382}
4383
4384test_support_visibility! {
4385fn extract_rs_symbols<'tree>(
4394 source: &str,
4395 root: &Node<'tree>,
4396 nav: impl Nav<'tree>,
4397) -> Result<Vec<Symbol>, AftError> {
4398 let mut symbols = Vec::new();
4399 let mut macro_bodies = Vec::new();
4400 extract_rs_symbols_from_root(source, *root, &mut symbols, &mut macro_bodies, nav);
4401
4402 let mut found_macro_symbols = false;
4406 while let Some(body) = macro_bodies.pop() {
4407 let Some(tree) = parse_rust_macro_body(source, body) else {
4408 continue;
4409 };
4410 let before = symbols.len();
4411 extract_rs_symbols_from_root(
4412 source,
4413 tree.root_node(),
4414 &mut symbols,
4415 &mut macro_bodies,
4416 Direct,
4417 );
4418 found_macro_symbols |= symbols.len() > before;
4419 }
4420
4421 if found_macro_symbols {
4422 symbols.sort_by_key(|symbol| (symbol.range.start_line, symbol.range.start_col));
4425 }
4426 dedup_symbols(&mut symbols);
4427 Ok(symbols)
4428}
4429}
4430
4431fn rust_token_tree_interior(source: &str, token_tree: &Node) -> Option<tree_sitter::Range> {
4434 let open = token_tree.child(0)?;
4435 let last = u32::try_from(token_tree.child_count().checked_sub(1)?).ok()?;
4436 let close = token_tree.child(last)?;
4437 if open.id() == close.id() || !matches!(open.kind(), "{" | "(" | "[") {
4438 return None;
4439 }
4440 let start_byte = open.end_byte();
4441 let end_byte = close.start_byte();
4442 if source.get(start_byte..end_byte)?.trim().is_empty() {
4443 return None;
4444 }
4445 Some(tree_sitter::Range {
4446 start_byte,
4447 end_byte,
4448 start_point: open.end_position(),
4449 end_point: close.start_position(),
4450 })
4451}
4452
4453fn parse_rust_macro_body(source: &str, body: tree_sitter::Range) -> Option<Tree> {
4460 RUST_MACRO_BODY_PARSER.with(|slot| {
4461 let mut slot = slot.borrow_mut();
4462 if slot.is_none() {
4463 let mut parser = Parser::new();
4464 parser.set_language(&grammar_for(LangId::Rust).ok()?).ok()?;
4465 *slot = Some(parser);
4466 }
4467 let parser = slot.as_mut()?;
4468 parser.set_included_ranges(&[body]).ok()?;
4469 let tree = parser.parse(source, None)?;
4470 if tree.root_node().has_error() {
4471 return None;
4472 }
4473 Some(tree)
4474 })
4475}
4476
4477fn extract_rs_symbols_from_root<'tree>(
4480 source: &str,
4481 root: Node<'tree>,
4482 symbols: &mut Vec<Symbol>,
4483 macro_bodies: &mut Vec<tree_sitter::Range>,
4484 nav: impl Nav<'tree>,
4485) {
4486 let lang = LangId::Rust;
4487 let is_pub = |node: &Node| -> bool {
4488 let mut child_cursor = node.walk();
4489 if child_cursor.goto_first_child() {
4490 loop {
4491 if child_cursor.node().kind() == "visibility_modifier" {
4492 return true;
4493 }
4494 if !child_cursor.goto_next_sibling() {
4495 break;
4496 }
4497 }
4498 }
4499 false
4500 };
4501
4502 let symbol_name = |node: &Node<'_>| -> Option<String> {
4506 let name_node = node.child_by_field_name("name")?;
4507 if name_node.kind() == "metavariable" {
4508 return None;
4509 }
4510 Some(node_text(source, &name_node).to_string())
4511 };
4512
4513 let item_symbol = |node: Node<'tree>, kind: SymbolKind| -> Option<Symbol> {
4514 let name = symbol_name(&node)?;
4515 Some(Symbol {
4516 name,
4517 kind,
4518 range: node_range_with_decorators_with(&node, source, lang, nav),
4519 signature: Some(extract_signature(source, &node)),
4520 scope_chain: Vec::new(),
4521 exported: is_pub(&node),
4522 parent: None,
4523 })
4524 };
4525
4526 nav.walk(root, |node, kind| {
4528 match kind {
4529 "macro_definition" => {
4530 let mut rule_cursor = node.walk();
4531 for rule in node.children(&mut rule_cursor) {
4532 if rule.kind() != "macro_rule" {
4533 continue;
4534 }
4535 if let Some(body) = rule
4536 .child_by_field_name("right")
4537 .and_then(|right| rust_token_tree_interior(source, &right))
4538 {
4539 macro_bodies.push(body);
4540 }
4541 }
4542 }
4543 "macro_invocation"
4547 if nav.parent(node).is_some_and(|parent| {
4548 matches!(nav.kind(parent), "source_file" | "declaration_list")
4549 }) =>
4550 {
4551 let body = node
4552 .child_by_field_name("macro")
4553 .and_then(|name| name.next_sibling())
4554 .and_then(|bang| bang.next_sibling())
4555 .filter(|tree| tree.kind() == "token_tree")
4556 .and_then(|tree| rust_token_tree_interior(source, &tree));
4557 if let Some(body) = body {
4558 macro_bodies.push(body);
4559 }
4560 }
4561 "function_item" => {
4562 let declaration_list_owner = nav
4563 .parent(node)
4564 .filter(|parent| nav.kind(*parent) == "declaration_list")
4565 .and_then(|parent| nav.parent(parent));
4566 let in_non_module_declaration_list =
4567 declaration_list_owner.is_some_and(|owner| nav.kind(owner) != "mod_item");
4568
4569 if !in_non_module_declaration_list {
4570 if let Some(name) = symbol_name(&node) {
4571 let scope_chain = rust_mod_scope_chain(&node, source, nav);
4572 symbols.push(Symbol {
4573 name,
4574 kind: SymbolKind::Function,
4575 range: node_range_with_decorators_with(&node, source, lang, nav),
4576 signature: Some(extract_signature(source, &node)),
4577 scope_chain: scope_chain.clone(),
4578 exported: is_pub(&node),
4579 parent: scope_chain.last().cloned(),
4580 });
4581 }
4582 }
4583 }
4584 "struct_item" => {
4585 if let Some(symbol) = item_symbol(node, SymbolKind::Struct) {
4586 symbols.push(symbol);
4587 }
4588 }
4589 "enum_item" => {
4590 if let Some(symbol) = item_symbol(node, SymbolKind::Enum) {
4591 symbols.push(symbol);
4592 }
4593 }
4594 "trait_item" => {
4595 if let Some(symbol) = item_symbol(node, SymbolKind::Interface) {
4596 symbols.push(symbol);
4597 }
4598 }
4599 "impl_item" => {
4600 let mut type_names = Vec::new();
4601 let mut child_cursor = node.walk();
4602 if child_cursor.goto_first_child() {
4603 loop {
4604 let child = child_cursor.node();
4605 if child.kind() == "type_identifier" || child.kind() == "generic_type" {
4606 type_names.push(node_text(source, &child).to_string());
4607 }
4608 if !child_cursor.goto_next_sibling() {
4609 break;
4610 }
4611 }
4612 }
4613
4614 let scope_name = if type_names.len() >= 2 {
4615 format!("{} for {}", type_names[0], type_names[1])
4616 } else {
4617 type_names.first().cloned().unwrap_or_default()
4618 };
4619 let parent_name = type_names
4620 .last()
4621 .map(|name| rust_impl_parent_name(name))
4622 .unwrap_or_default();
4623
4624 let mut child_cursor = node.walk();
4625 if child_cursor.goto_first_child() {
4626 loop {
4627 let child = child_cursor.node();
4628 if child.kind() == "declaration_list" {
4629 let mut method_cursor = child.walk();
4630 if method_cursor.goto_first_child() {
4631 loop {
4632 let method = method_cursor.node();
4633 if method.kind() == "function_item" {
4634 if let Some(name) = symbol_name(&method) {
4635 symbols.push(Symbol {
4636 name,
4637 kind: SymbolKind::Method,
4638 range: node_range_with_decorators_with(
4639 &method, source, lang, nav,
4640 ),
4641 signature: Some(extract_signature(source, &method)),
4642 scope_chain: if scope_name.is_empty() {
4643 Vec::new()
4644 } else {
4645 vec![scope_name.clone()]
4646 },
4647 exported: is_pub(&method),
4648 parent: if parent_name.is_empty() {
4649 None
4650 } else {
4651 Some(parent_name.clone())
4652 },
4653 });
4654 }
4655 }
4656 if !method_cursor.goto_next_sibling() {
4657 break;
4658 }
4659 }
4660 }
4661 }
4662 if !child_cursor.goto_next_sibling() {
4663 break;
4664 }
4665 }
4666 }
4667 }
4668 _ => {}
4669 }
4670 true
4671 });
4672}
4673
4674fn extract_go_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
4678 let lang = LangId::Go;
4679 let capture_names = query.capture_names();
4680
4681 let is_go_exported = |name: &str| -> bool {
4682 name.chars()
4683 .next()
4684 .map(|c| c.is_uppercase())
4685 .unwrap_or(false)
4686 };
4687
4688 let mut symbols = Vec::new();
4689 let mut cursor = QueryCursor::new();
4690 let mut matches = cursor.matches(query, *root, source.as_bytes());
4691
4692 while let Some(m) = {
4693 matches.advance();
4694 matches.get()
4695 } {
4696 let mut fn_name_node = None;
4697 let mut fn_def_node = None;
4698 let mut method_name_node = None;
4699 let mut method_def_node = None;
4700 let mut type_name_node = None;
4701 let mut type_body_node = None;
4702 let mut type_def_node = None;
4703
4704 for cap in m.captures {
4705 let Some(&name) = capture_names.get(cap.index as usize) else {
4706 continue;
4707 };
4708 match name {
4709 "fn.name" => fn_name_node = Some(cap.node),
4710 "fn.def" => fn_def_node = Some(cap.node),
4711 "method.name" => method_name_node = Some(cap.node),
4712 "method.def" => method_def_node = Some(cap.node),
4713 "type.name" => type_name_node = Some(cap.node),
4714 "type.body" => type_body_node = Some(cap.node),
4715 "type.def" => type_def_node = Some(cap.node),
4716 _ => {}
4717 }
4718 }
4719
4720 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
4722 let name = node_text(source, &name_node).to_string();
4723 symbols.push(Symbol {
4724 exported: is_go_exported(&name),
4725 name,
4726 kind: SymbolKind::Function,
4727 range: node_range_with_decorators(&def_node, source, lang),
4728 signature: Some(extract_signature(source, &def_node)),
4729 scope_chain: vec![],
4730 parent: None,
4731 });
4732 }
4733
4734 if let (Some(name_node), Some(def_node)) = (method_name_node, method_def_node) {
4736 let name = node_text(source, &name_node).to_string();
4737
4738 let receiver_type = extract_go_receiver_type(&def_node, source);
4740 let scope_chain = if let Some(ref rt) = receiver_type {
4741 vec![rt.clone()]
4742 } else {
4743 vec![]
4744 };
4745
4746 symbols.push(Symbol {
4747 exported: is_go_exported(&name),
4748 name,
4749 kind: SymbolKind::Method,
4750 range: node_range_with_decorators(&def_node, source, lang),
4751 signature: Some(extract_signature(source, &def_node)),
4752 scope_chain,
4753 parent: receiver_type,
4754 });
4755 }
4756
4757 if let (Some(name_node), Some(body_node), Some(def_node)) =
4759 (type_name_node, type_body_node, type_def_node)
4760 {
4761 let name = node_text(source, &name_node).to_string();
4762 let def_node = def_node
4765 .parent()
4766 .filter(|parent| {
4767 parent.kind() == "type_declaration" && {
4768 let mut cursor = parent.walk();
4769 let ungrouped = !parent
4770 .children(&mut cursor)
4771 .any(|child| child.kind() == "(");
4772 ungrouped
4773 }
4774 })
4775 .unwrap_or(def_node);
4776 let kind = match body_node.kind() {
4777 "struct_type" => SymbolKind::Struct,
4778 "interface_type" => SymbolKind::Interface,
4779 _ => SymbolKind::TypeAlias,
4780 };
4781
4782 symbols.push(Symbol {
4783 exported: is_go_exported(&name),
4784 name,
4785 kind,
4786 range: node_range_with_decorators(&def_node, source, lang),
4787 signature: Some(extract_signature(source, &def_node)),
4788 scope_chain: vec![],
4789 parent: None,
4790 });
4791 }
4792 }
4793
4794 for declaration in root.named_children(&mut root.walk()) {
4797 if !matches!(declaration.kind(), "var_declaration" | "const_declaration") {
4798 continue;
4799 }
4800 let mut stack = vec![declaration];
4801 while let Some(spec) = stack.pop() {
4802 if matches!(spec.kind(), "var_spec" | "const_spec") {
4803 for name_node in spec.children_by_field_name("name", &mut spec.walk()) {
4804 let name = node_text(source, &name_node).to_string();
4805 if name == "_" {
4806 continue;
4807 }
4808 symbols.push(Symbol {
4809 exported: is_go_exported(&name),
4810 name,
4811 kind: SymbolKind::Variable,
4812 range: node_range_with_decorators(&spec, source, lang),
4813 signature: Some(extract_signature(source, &spec)),
4814 scope_chain: vec![],
4815 parent: None,
4816 });
4817 }
4818 } else {
4819 stack.extend(spec.named_children(&mut spec.walk()));
4820 }
4821 }
4822 }
4823 dedup_symbols(&mut symbols);
4824 Ok(symbols)
4825}
4826
4827fn extract_go_receiver_type(method_node: &Node, source: &str) -> Option<String> {
4830 let mut child_cursor = method_node.walk();
4832 if child_cursor.goto_first_child() {
4833 loop {
4834 let child = child_cursor.node();
4835 if child.kind() == "parameter_list" {
4836 return find_type_identifier_recursive(&child, source);
4838 }
4839 if !child_cursor.goto_next_sibling() {
4840 break;
4841 }
4842 }
4843 }
4844 None
4845}
4846
4847fn split_scope_text(text: &str, separator: &str) -> Vec<String> {
4848 text.split(separator)
4849 .map(str::trim)
4850 .filter(|segment| !segment.is_empty())
4851 .map(ToString::to_string)
4852 .collect()
4853}
4854
4855fn last_scope_segment(text: &str, separator: &str) -> String {
4856 split_scope_text(text, separator)
4857 .pop()
4858 .unwrap_or_else(|| text.trim().to_string())
4859}
4860
4861fn zig_container_scope_chain(node: &Node, source: &str) -> Vec<String> {
4862 let mut chain = Vec::new();
4863 let mut current = node.parent();
4864
4865 while let Some(parent) = current {
4866 if matches!(
4867 parent.kind(),
4868 "struct_declaration" | "enum_declaration" | "union_declaration" | "opaque_declaration"
4869 ) {
4870 if let Some(container) = parent.parent() {
4871 if container.kind() == "variable_declaration" {
4872 let mut cursor = container.walk();
4873 if cursor.goto_first_child() {
4874 loop {
4875 let child = cursor.node();
4876 if child.kind() == "identifier" {
4877 chain.push(node_text(source, &child).to_string());
4878 break;
4879 }
4880 if !cursor.goto_next_sibling() {
4881 break;
4882 }
4883 }
4884 }
4885 }
4886 }
4887 }
4888 current = parent.parent();
4889 }
4890
4891 chain.reverse();
4892 chain
4893}
4894
4895fn csharp_scope_chain(node: &Node, source: &str) -> Vec<String> {
4896 let mut chain = Vec::new();
4897 let mut current = node.parent();
4898
4899 while let Some(parent) = current {
4900 match parent.kind() {
4901 "namespace_declaration" | "file_scoped_namespace_declaration" => {
4902 if let Some(name_node) = parent.child_by_field_name("name") {
4903 chain.push(node_text(source, &name_node).to_string());
4904 }
4905 }
4906 "class_declaration"
4907 | "interface_declaration"
4908 | "struct_declaration"
4909 | "record_declaration" => {
4910 if let Some(name_node) = parent.child_by_field_name("name") {
4911 chain.push(node_text(source, &name_node).to_string());
4912 }
4913 }
4914 _ => {}
4915 }
4916 current = parent.parent();
4917 }
4918
4919 chain.reverse();
4920 chain
4921}
4922
4923fn cpp_parent_scope_chain(node: &Node, source: &str) -> Vec<String> {
4924 let mut chain = Vec::new();
4925 let mut current = node.parent();
4926
4927 while let Some(parent) = current {
4928 match parent.kind() {
4929 "namespace_definition" => {
4930 if let Some(name_node) = parent.child_by_field_name("name") {
4931 chain.push(node_text(source, &name_node).to_string());
4932 }
4933 }
4934 "class_specifier" | "struct_specifier" => {
4935 if let Some(name_node) = parent.child_by_field_name("name") {
4936 chain.push(last_scope_segment(node_text(source, &name_node), "::"));
4937 }
4938 }
4939 _ => {}
4940 }
4941 current = parent.parent();
4942 }
4943
4944 chain.reverse();
4945 chain
4946}
4947
4948fn template_signature(source: &str, template_node: &Node, item_node: &Node) -> String {
4949 format!(
4950 "{}\n{}",
4951 extract_signature(source, template_node),
4952 extract_signature(source, item_node)
4953 )
4954}
4955
4956fn extract_c_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
4958 let lang = LangId::C;
4959 let capture_names = query.capture_names();
4960
4961 let mut symbols = Vec::new();
4962 let mut cursor = QueryCursor::new();
4963 let mut matches = cursor.matches(query, *root, source.as_bytes());
4964
4965 while let Some(m) = {
4966 matches.advance();
4967 matches.get()
4968 } {
4969 let mut fn_name_node = None;
4970 let mut fn_def_node = None;
4971 let mut struct_name_node = None;
4972 let mut struct_def_node = None;
4973 let mut enum_name_node = None;
4974 let mut enum_def_node = None;
4975 let mut type_name_node = None;
4976 let mut type_def_node = None;
4977 let mut macro_name_node = None;
4978 let mut macro_def_node = None;
4979
4980 for cap in m.captures {
4981 let Some(&name) = capture_names.get(cap.index as usize) else {
4982 continue;
4983 };
4984 match name {
4985 "fn.name" => fn_name_node = Some(cap.node),
4986 "fn.def" => fn_def_node = Some(cap.node),
4987 "struct.name" => struct_name_node = Some(cap.node),
4988 "struct.def" => struct_def_node = Some(cap.node),
4989 "enum.name" => enum_name_node = Some(cap.node),
4990 "enum.def" => enum_def_node = Some(cap.node),
4991 "type.name" => type_name_node = Some(cap.node),
4992 "type.def" => type_def_node = Some(cap.node),
4993 "macro.name" => macro_name_node = Some(cap.node),
4994 "macro.def" => macro_def_node = Some(cap.node),
4995 _ => {}
4996 }
4997 }
4998
4999 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
5000 symbols.push(Symbol {
5001 name: node_text(source, &name_node).to_string(),
5002 kind: SymbolKind::Function,
5003 range: node_range_with_decorators(&def_node, source, lang),
5004 signature: Some(extract_signature(source, &def_node)),
5005 scope_chain: vec![],
5006 exported: false,
5007 parent: None,
5008 });
5009 }
5010
5011 if let (Some(name_node), Some(def_node)) = (struct_name_node, struct_def_node) {
5012 symbols.push(Symbol {
5013 name: node_text(source, &name_node).to_string(),
5014 kind: SymbolKind::Struct,
5015 range: node_range_with_decorators(&def_node, source, lang),
5016 signature: Some(extract_signature(source, &def_node)),
5017 scope_chain: vec![],
5018 exported: false,
5019 parent: None,
5020 });
5021 }
5022
5023 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
5024 symbols.push(Symbol {
5025 name: node_text(source, &name_node).to_string(),
5026 kind: SymbolKind::Enum,
5027 range: node_range_with_decorators(&def_node, source, lang),
5028 signature: Some(extract_signature(source, &def_node)),
5029 scope_chain: vec![],
5030 exported: false,
5031 parent: None,
5032 });
5033 }
5034
5035 if let (Some(name_node), Some(def_node)) = (type_name_node, type_def_node) {
5036 symbols.push(Symbol {
5037 name: node_text(source, &name_node).to_string(),
5038 kind: SymbolKind::TypeAlias,
5039 range: node_range_with_decorators(&def_node, source, lang),
5040 signature: Some(extract_signature(source, &def_node)),
5041 scope_chain: vec![],
5042 exported: false,
5043 parent: None,
5044 });
5045 }
5046
5047 if let (Some(name_node), Some(def_node)) = (macro_name_node, macro_def_node) {
5048 symbols.push(Symbol {
5049 name: node_text(source, &name_node).to_string(),
5050 kind: SymbolKind::Variable,
5051 range: node_range(&def_node),
5052 signature: Some(extract_signature(source, &def_node)),
5053 scope_chain: vec![],
5054 exported: false,
5055 parent: None,
5056 });
5057 }
5058 }
5059
5060 dedup_symbols(&mut symbols);
5061 Ok(symbols)
5062}
5063
5064fn cpp_function_kind(source: &str, definition: &Node, lang: LangId) -> SymbolKind {
5065 let is_cuda_kernel = lang == LangId::Cuda
5066 && node_text(source, definition)
5067 .split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
5068 .any(|token| token == "__global__");
5069 if is_cuda_kernel {
5070 SymbolKind::Kernel
5071 } else {
5072 SymbolKind::Function
5073 }
5074}
5075
5076fn extract_cpp_symbols(
5078 source: &str,
5079 root: &Node,
5080 query: &Query,
5081 lang: LangId,
5082) -> Result<Vec<Symbol>, AftError> {
5083 let capture_names = query.capture_names();
5084
5085 let mut type_names = HashSet::new();
5086 {
5087 let mut cursor = QueryCursor::new();
5088 let mut matches = cursor.matches(query, *root, source.as_bytes());
5089 while let Some(m) = {
5090 matches.advance();
5091 matches.get()
5092 } {
5093 for cap in m.captures {
5094 let Some(&name) = capture_names.get(cap.index as usize) else {
5095 continue;
5096 };
5097 match name {
5098 "class.name"
5099 | "struct.name"
5100 | "template.class.name"
5101 | "template.struct.name" => {
5102 type_names.insert(last_scope_segment(node_text(source, &cap.node), "::"));
5103 }
5104 _ => {}
5105 }
5106 }
5107 }
5108 }
5109
5110 let mut symbols = Vec::new();
5111 let mut cursor = QueryCursor::new();
5112 let mut matches = cursor.matches(query, *root, source.as_bytes());
5113
5114 while let Some(m) = {
5115 matches.advance();
5116 matches.get()
5117 } {
5118 let mut fn_name_node = None;
5119 let mut fn_def_node = None;
5120 let mut method_name_node = None;
5121 let mut method_def_node = None;
5122 let mut qual_scope_node = None;
5123 let mut qual_name_node = None;
5124 let mut qual_def_node = None;
5125 let mut class_name_node = None;
5126 let mut class_def_node = None;
5127 let mut struct_name_node = None;
5128 let mut struct_def_node = None;
5129 let mut enum_name_node = None;
5130 let mut enum_def_node = None;
5131 let mut namespace_name_node = None;
5132 let mut namespace_def_node = None;
5133 let mut template_class_name_node = None;
5134 let mut template_class_def_node = None;
5135 let mut template_class_item_node = None;
5136 let mut template_struct_name_node = None;
5137 let mut template_struct_def_node = None;
5138 let mut template_struct_item_node = None;
5139 let mut template_fn_name_node = None;
5140 let mut template_fn_def_node = None;
5141 let mut template_fn_item_node = None;
5142 let mut template_qual_scope_node = None;
5143 let mut template_qual_name_node = None;
5144 let mut template_qual_def_node = None;
5145 let mut template_qual_item_node = None;
5146
5147 for cap in m.captures {
5148 let Some(&name) = capture_names.get(cap.index as usize) else {
5149 continue;
5150 };
5151 match name {
5152 "fn.name" => fn_name_node = Some(cap.node),
5153 "fn.def" => fn_def_node = Some(cap.node),
5154 "method.name" => method_name_node = Some(cap.node),
5155 "method.def" => method_def_node = Some(cap.node),
5156 "qual.scope" => qual_scope_node = Some(cap.node),
5157 "qual.name" => qual_name_node = Some(cap.node),
5158 "qual.def" => qual_def_node = Some(cap.node),
5159 "class.name" => class_name_node = Some(cap.node),
5160 "class.def" => class_def_node = Some(cap.node),
5161 "struct.name" => struct_name_node = Some(cap.node),
5162 "struct.def" => struct_def_node = Some(cap.node),
5163 "enum.name" => enum_name_node = Some(cap.node),
5164 "enum.def" => enum_def_node = Some(cap.node),
5165 "namespace.name" => namespace_name_node = Some(cap.node),
5166 "namespace.def" => namespace_def_node = Some(cap.node),
5167 "template.class.name" => template_class_name_node = Some(cap.node),
5168 "template.class.def" => template_class_def_node = Some(cap.node),
5169 "template.class.item" => template_class_item_node = Some(cap.node),
5170 "template.struct.name" => template_struct_name_node = Some(cap.node),
5171 "template.struct.def" => template_struct_def_node = Some(cap.node),
5172 "template.struct.item" => template_struct_item_node = Some(cap.node),
5173 "template.fn.name" => template_fn_name_node = Some(cap.node),
5174 "template.fn.def" => template_fn_def_node = Some(cap.node),
5175 "template.fn.item" => template_fn_item_node = Some(cap.node),
5176 "template.qual.scope" => template_qual_scope_node = Some(cap.node),
5177 "template.qual.name" => template_qual_name_node = Some(cap.node),
5178 "template.qual.def" => template_qual_def_node = Some(cap.node),
5179 "template.qual.item" => template_qual_item_node = Some(cap.node),
5180 _ => {}
5181 }
5182 }
5183
5184 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
5185 let in_template = def_node
5186 .parent()
5187 .map(|parent| parent.kind() == "template_declaration")
5188 .unwrap_or(false);
5189 if !in_template {
5190 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5191 symbols.push(Symbol {
5192 name: node_text(source, &name_node).to_string(),
5193 kind: cpp_function_kind(source, &def_node, lang),
5194 range: node_range_with_decorators(&def_node, source, lang),
5195 signature: Some(extract_signature(source, &def_node)),
5196 scope_chain: scope_chain.clone(),
5197 exported: false,
5198 parent: scope_chain.last().cloned(),
5199 });
5200 }
5201 }
5202
5203 if let (Some(name_node), Some(def_node)) = (method_name_node, method_def_node) {
5204 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5205 symbols.push(Symbol {
5206 name: node_text(source, &name_node).to_string(),
5207 kind: SymbolKind::Method,
5208 range: node_range_with_decorators(&def_node, source, lang),
5209 signature: Some(extract_signature(source, &def_node)),
5210 scope_chain: scope_chain.clone(),
5211 exported: false,
5212 parent: scope_chain.last().cloned(),
5213 });
5214 }
5215
5216 if let (Some(scope_node), Some(name_node), Some(def_node)) =
5217 (qual_scope_node, qual_name_node, qual_def_node)
5218 {
5219 let in_template = def_node
5220 .parent()
5221 .map(|parent| parent.kind() == "template_declaration")
5222 .unwrap_or(false);
5223 if !in_template {
5224 let scope_text = node_text(source, &scope_node);
5225 let scope_chain = split_scope_text(scope_text, "::");
5226 let parent = scope_chain.last().cloned();
5227 let kind = if parent
5228 .as_ref()
5229 .map(|segment| type_names.contains(segment))
5230 .unwrap_or(false)
5231 {
5232 SymbolKind::Method
5233 } else {
5234 SymbolKind::Function
5235 };
5236
5237 symbols.push(Symbol {
5238 name: node_text(source, &name_node).to_string(),
5239 kind,
5240 range: node_range_with_decorators(&def_node, source, lang),
5241 signature: Some(extract_signature(source, &def_node)),
5242 scope_chain,
5243 exported: false,
5244 parent,
5245 });
5246 }
5247 }
5248
5249 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
5250 let in_template = def_node
5251 .parent()
5252 .map(|parent| parent.kind() == "template_declaration")
5253 .unwrap_or(false);
5254 if !in_template {
5255 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5256 let name = last_scope_segment(node_text(source, &name_node), "::");
5257 symbols.push(Symbol {
5258 name: name.clone(),
5259 kind: SymbolKind::Class,
5260 range: node_range_with_decorators(&def_node, source, lang),
5261 signature: Some(extract_signature(source, &def_node)),
5262 scope_chain: scope_chain.clone(),
5263 exported: false,
5264 parent: scope_chain.last().cloned(),
5265 });
5266 }
5267 }
5268
5269 if let (Some(name_node), Some(def_node)) = (struct_name_node, struct_def_node) {
5270 let in_template = def_node
5271 .parent()
5272 .map(|parent| parent.kind() == "template_declaration")
5273 .unwrap_or(false);
5274 if !in_template {
5275 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5276 let name = last_scope_segment(node_text(source, &name_node), "::");
5277 symbols.push(Symbol {
5278 name: name.clone(),
5279 kind: SymbolKind::Struct,
5280 range: node_range_with_decorators(&def_node, source, lang),
5281 signature: Some(extract_signature(source, &def_node)),
5282 scope_chain: scope_chain.clone(),
5283 exported: false,
5284 parent: scope_chain.last().cloned(),
5285 });
5286 }
5287 }
5288
5289 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
5290 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5291 let name = last_scope_segment(node_text(source, &name_node), "::");
5292 symbols.push(Symbol {
5293 name: name.clone(),
5294 kind: SymbolKind::Enum,
5295 range: node_range_with_decorators(&def_node, source, lang),
5296 signature: Some(extract_signature(source, &def_node)),
5297 scope_chain: scope_chain.clone(),
5298 exported: false,
5299 parent: scope_chain.last().cloned(),
5300 });
5301 }
5302
5303 if let (Some(name_node), Some(def_node)) = (namespace_name_node, namespace_def_node) {
5304 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5305 symbols.push(Symbol {
5306 name: node_text(source, &name_node).to_string(),
5307 kind: SymbolKind::TypeAlias,
5308 range: node_range_with_decorators(&def_node, source, lang),
5309 signature: Some(extract_signature(source, &def_node)),
5310 scope_chain: scope_chain.clone(),
5311 exported: false,
5312 parent: scope_chain.last().cloned(),
5313 });
5314 }
5315
5316 if let (Some(name_node), Some(def_node), Some(item_node)) = (
5317 template_class_name_node,
5318 template_class_def_node,
5319 template_class_item_node,
5320 ) {
5321 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5322 let name = last_scope_segment(node_text(source, &name_node), "::");
5323 symbols.push(Symbol {
5324 name: name.clone(),
5325 kind: SymbolKind::Class,
5326 range: node_range_with_decorators(&def_node, source, lang),
5327 signature: Some(template_signature(source, &def_node, &item_node)),
5328 scope_chain: scope_chain.clone(),
5329 exported: false,
5330 parent: scope_chain.last().cloned(),
5331 });
5332 }
5333
5334 if let (Some(name_node), Some(def_node), Some(item_node)) = (
5335 template_struct_name_node,
5336 template_struct_def_node,
5337 template_struct_item_node,
5338 ) {
5339 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5340 let name = last_scope_segment(node_text(source, &name_node), "::");
5341 symbols.push(Symbol {
5342 name: name.clone(),
5343 kind: SymbolKind::Struct,
5344 range: node_range_with_decorators(&def_node, source, lang),
5345 signature: Some(template_signature(source, &def_node, &item_node)),
5346 scope_chain: scope_chain.clone(),
5347 exported: false,
5348 parent: scope_chain.last().cloned(),
5349 });
5350 }
5351
5352 if let (Some(name_node), Some(def_node), Some(item_node)) = (
5353 template_fn_name_node,
5354 template_fn_def_node,
5355 template_fn_item_node,
5356 ) {
5357 let scope_chain = cpp_parent_scope_chain(&def_node, source);
5358 symbols.push(Symbol {
5359 name: node_text(source, &name_node).to_string(),
5360 kind: SymbolKind::Function,
5361 range: node_range_with_decorators(&def_node, source, lang),
5362 signature: Some(template_signature(source, &def_node, &item_node)),
5363 scope_chain: scope_chain.clone(),
5364 exported: false,
5365 parent: scope_chain.last().cloned(),
5366 });
5367 }
5368
5369 if let (Some(scope_node), Some(name_node), Some(def_node), Some(item_node)) = (
5370 template_qual_scope_node,
5371 template_qual_name_node,
5372 template_qual_def_node,
5373 template_qual_item_node,
5374 ) {
5375 let scope_chain = split_scope_text(node_text(source, &scope_node), "::");
5376 let parent = scope_chain.last().cloned();
5377 let kind = if parent
5378 .as_ref()
5379 .map(|segment| type_names.contains(segment))
5380 .unwrap_or(false)
5381 {
5382 SymbolKind::Method
5383 } else {
5384 SymbolKind::Function
5385 };
5386
5387 symbols.push(Symbol {
5388 name: node_text(source, &name_node).to_string(),
5389 kind,
5390 range: node_range_with_decorators(&def_node, source, lang),
5391 signature: Some(template_signature(source, &def_node, &item_node)),
5392 scope_chain,
5393 exported: false,
5394 parent,
5395 });
5396 }
5397 }
5398
5399 dedup_symbols(&mut symbols);
5400 Ok(symbols)
5401}
5402
5403fn extract_zig_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
5405 let lang = LangId::Zig;
5406 let capture_names = query.capture_names();
5407
5408 let mut symbols = Vec::new();
5409 let mut variable_names = VariableNameIndex::default();
5410 let mut cursor = QueryCursor::new();
5411 let mut matches = cursor.matches(query, *root, source.as_bytes());
5412
5413 while let Some(m) = {
5414 matches.advance();
5415 matches.get()
5416 } {
5417 let mut fn_name_node = None;
5418 let mut fn_def_node = None;
5419 let mut struct_name_node = None;
5420 let mut struct_def_node = None;
5421 let mut enum_name_node = None;
5422 let mut enum_def_node = None;
5423 let mut union_name_node = None;
5424 let mut union_def_node = None;
5425 let mut const_name_node = None;
5426 let mut const_def_node = None;
5427 let mut test_name_node = None;
5428 let mut test_def_node = None;
5429
5430 for cap in m.captures {
5431 let Some(&name) = capture_names.get(cap.index as usize) else {
5432 continue;
5433 };
5434 match name {
5435 "fn.name" => fn_name_node = Some(cap.node),
5436 "fn.def" => fn_def_node = Some(cap.node),
5437 "struct.name" => struct_name_node = Some(cap.node),
5438 "struct.def" => struct_def_node = Some(cap.node),
5439 "enum.name" => enum_name_node = Some(cap.node),
5440 "enum.def" => enum_def_node = Some(cap.node),
5441 "union.name" => union_name_node = Some(cap.node),
5442 "union.def" => union_def_node = Some(cap.node),
5443 "const.name" => const_name_node = Some(cap.node),
5444 "const.def" => const_def_node = Some(cap.node),
5445 "test.name" => test_name_node = Some(cap.node),
5446 "test.def" => test_def_node = Some(cap.node),
5447 _ => {}
5448 }
5449 }
5450
5451 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
5452 let scope_chain = zig_container_scope_chain(&def_node, source);
5453 let kind = if scope_chain.is_empty() {
5454 SymbolKind::Function
5455 } else {
5456 SymbolKind::Method
5457 };
5458 symbols.push(Symbol {
5459 name: node_text(source, &name_node).to_string(),
5460 kind,
5461 range: node_range_with_decorators(&def_node, source, lang),
5462 signature: Some(extract_signature(source, &def_node)),
5463 scope_chain: scope_chain.clone(),
5464 exported: false,
5465 parent: scope_chain.last().cloned(),
5466 });
5467 }
5468
5469 if let (Some(name_node), Some(def_node)) = (struct_name_node, struct_def_node) {
5470 symbols.push(Symbol {
5471 name: node_text(source, &name_node).to_string(),
5472 kind: SymbolKind::Struct,
5473 range: node_range_with_decorators(&def_node, source, lang),
5474 signature: Some(extract_signature(source, &def_node)),
5475 scope_chain: vec![],
5476 exported: false,
5477 parent: None,
5478 });
5479 }
5480
5481 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
5482 symbols.push(Symbol {
5483 name: node_text(source, &name_node).to_string(),
5484 kind: SymbolKind::Enum,
5485 range: node_range_with_decorators(&def_node, source, lang),
5486 signature: Some(extract_signature(source, &def_node)),
5487 scope_chain: vec![],
5488 exported: false,
5489 parent: None,
5490 });
5491 }
5492
5493 if let (Some(name_node), Some(def_node)) = (union_name_node, union_def_node) {
5494 symbols.push(Symbol {
5495 name: node_text(source, &name_node).to_string(),
5496 kind: SymbolKind::TypeAlias,
5497 range: node_range_with_decorators(&def_node, source, lang),
5498 signature: Some(extract_signature(source, &def_node)),
5499 scope_chain: vec![],
5500 exported: false,
5501 parent: None,
5502 });
5503 }
5504
5505 if let (Some(name_node), Some(def_node)) = (const_name_node, const_def_node) {
5506 let signature = extract_signature(source, &def_node);
5507 let is_container = signature.contains("= struct")
5508 || signature.contains("= enum")
5509 || signature.contains("= union")
5510 || signature.contains("= opaque");
5511 let is_const = signature.trim_start().starts_with("const ");
5512 let name = node_text(source, &name_node);
5513 if variable_names.should_capture(&symbols, name, is_const && !is_container) {
5514 symbols.push(Symbol {
5515 name: name.to_string(),
5516 kind: SymbolKind::Variable,
5517 range: node_range_with_decorators(&def_node, source, lang),
5518 signature: Some(signature),
5519 scope_chain: vec![],
5520 exported: false,
5521 parent: None,
5522 });
5523 }
5524 }
5525
5526 if let (Some(name_node), Some(def_node)) = (test_name_node, test_def_node) {
5527 let scope_chain = zig_container_scope_chain(&def_node, source);
5528 symbols.push(Symbol {
5529 name: node_text(source, &name_node).trim_matches('"').to_string(),
5530 kind: SymbolKind::Function,
5531 range: node_range_with_decorators(&def_node, source, lang),
5532 signature: Some(extract_signature(source, &def_node)),
5533 scope_chain: scope_chain.clone(),
5534 exported: false,
5535 parent: scope_chain.last().cloned(),
5536 });
5537 }
5538 }
5539
5540 dedup_symbols(&mut symbols);
5541 Ok(symbols)
5542}
5543
5544fn extract_csharp_symbols(
5546 source: &str,
5547 root: &Node,
5548 query: &Query,
5549) -> Result<Vec<Symbol>, AftError> {
5550 let lang = LangId::CSharp;
5551 let capture_names = query.capture_names();
5552
5553 let mut symbols = Vec::new();
5554 let mut cursor = QueryCursor::new();
5555 let mut matches = cursor.matches(query, *root, source.as_bytes());
5556
5557 while let Some(m) = {
5558 matches.advance();
5559 matches.get()
5560 } {
5561 let mut class_name_node = None;
5562 let mut class_def_node = None;
5563 let mut interface_name_node = None;
5564 let mut interface_def_node = None;
5565 let mut struct_name_node = None;
5566 let mut struct_def_node = None;
5567 let mut enum_name_node = None;
5568 let mut enum_def_node = None;
5569 let mut method_name_node = None;
5570 let mut method_def_node = None;
5571 let mut property_name_node = None;
5572 let mut property_def_node = None;
5573 let mut namespace_name_node = None;
5574 let mut namespace_def_node = None;
5575
5576 for cap in m.captures {
5577 let Some(&name) = capture_names.get(cap.index as usize) else {
5578 continue;
5579 };
5580 match name {
5581 "class.name" => class_name_node = Some(cap.node),
5582 "class.def" => class_def_node = Some(cap.node),
5583 "interface.name" => interface_name_node = Some(cap.node),
5584 "interface.def" => interface_def_node = Some(cap.node),
5585 "struct.name" => struct_name_node = Some(cap.node),
5586 "struct.def" => struct_def_node = Some(cap.node),
5587 "enum.name" => enum_name_node = Some(cap.node),
5588 "enum.def" => enum_def_node = Some(cap.node),
5589 "method.name" => method_name_node = Some(cap.node),
5590 "method.def" => method_def_node = Some(cap.node),
5591 "property.name" => property_name_node = Some(cap.node),
5592 "property.def" => property_def_node = Some(cap.node),
5593 "namespace.name" => namespace_name_node = Some(cap.node),
5594 "namespace.def" => namespace_def_node = Some(cap.node),
5595 _ => {}
5596 }
5597 }
5598
5599 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
5600 let scope_chain = csharp_scope_chain(&def_node, source);
5601 symbols.push(Symbol {
5602 name: node_text(source, &name_node).to_string(),
5603 kind: SymbolKind::Class,
5604 range: node_range_with_decorators(&def_node, source, lang),
5605 signature: Some(extract_signature(source, &def_node)),
5606 scope_chain: scope_chain.clone(),
5607 exported: false,
5608 parent: scope_chain.last().cloned(),
5609 });
5610 }
5611
5612 if let (Some(name_node), Some(def_node)) = (interface_name_node, interface_def_node) {
5613 let scope_chain = csharp_scope_chain(&def_node, source);
5614 symbols.push(Symbol {
5615 name: node_text(source, &name_node).to_string(),
5616 kind: SymbolKind::Interface,
5617 range: node_range_with_decorators(&def_node, source, lang),
5618 signature: Some(extract_signature(source, &def_node)),
5619 scope_chain: scope_chain.clone(),
5620 exported: false,
5621 parent: scope_chain.last().cloned(),
5622 });
5623 }
5624
5625 if let (Some(name_node), Some(def_node)) = (struct_name_node, struct_def_node) {
5626 let scope_chain = csharp_scope_chain(&def_node, source);
5627 symbols.push(Symbol {
5628 name: node_text(source, &name_node).to_string(),
5629 kind: SymbolKind::Struct,
5630 range: node_range_with_decorators(&def_node, source, lang),
5631 signature: Some(extract_signature(source, &def_node)),
5632 scope_chain: scope_chain.clone(),
5633 exported: false,
5634 parent: scope_chain.last().cloned(),
5635 });
5636 }
5637
5638 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
5639 let scope_chain = csharp_scope_chain(&def_node, source);
5640 symbols.push(Symbol {
5641 name: node_text(source, &name_node).to_string(),
5642 kind: SymbolKind::Enum,
5643 range: node_range_with_decorators(&def_node, source, lang),
5644 signature: Some(extract_signature(source, &def_node)),
5645 scope_chain: scope_chain.clone(),
5646 exported: false,
5647 parent: scope_chain.last().cloned(),
5648 });
5649 }
5650
5651 if let (Some(name_node), Some(def_node)) = (method_name_node, method_def_node) {
5652 let scope_chain = csharp_scope_chain(&def_node, source);
5653 symbols.push(Symbol {
5654 name: node_text(source, &name_node).to_string(),
5655 kind: SymbolKind::Method,
5656 range: node_range_with_decorators(&def_node, source, lang),
5657 signature: Some(extract_signature(source, &def_node)),
5658 scope_chain: scope_chain.clone(),
5659 exported: false,
5660 parent: scope_chain.last().cloned(),
5661 });
5662 }
5663
5664 if let (Some(name_node), Some(def_node)) = (property_name_node, property_def_node) {
5665 let scope_chain = csharp_scope_chain(&def_node, source);
5666 symbols.push(Symbol {
5667 name: node_text(source, &name_node).to_string(),
5668 kind: SymbolKind::Variable,
5669 range: node_range_with_decorators(&def_node, source, lang),
5670 signature: Some(extract_signature(source, &def_node)),
5671 scope_chain: scope_chain.clone(),
5672 exported: false,
5673 parent: scope_chain.last().cloned(),
5674 });
5675 }
5676
5677 if let (Some(name_node), Some(def_node)) = (namespace_name_node, namespace_def_node) {
5678 let scope_chain = csharp_scope_chain(&def_node, source);
5679 symbols.push(Symbol {
5680 name: node_text(source, &name_node).to_string(),
5681 kind: SymbolKind::TypeAlias,
5682 range: node_range_with_decorators(&def_node, source, lang),
5683 signature: Some(extract_signature(source, &def_node)),
5684 scope_chain: scope_chain.clone(),
5685 exported: false,
5686 parent: scope_chain.last().cloned(),
5687 });
5688 }
5689 }
5690
5691 dedup_symbols(&mut symbols);
5692 Ok(symbols)
5693}
5694
5695fn find_type_identifier_recursive(node: &Node, source: &str) -> Option<String> {
5699 let mut cursor = node.walk();
5700 loop {
5701 if cursor.node().kind() == "type_identifier" {
5702 return Some(node_text(source, &cursor.node()).to_string());
5703 }
5704 if cursor.goto_first_child() {
5705 continue;
5706 }
5707 while !cursor.goto_next_sibling() {
5710 if !cursor.goto_parent() {
5711 return None;
5712 }
5713 }
5714 }
5715}
5716
5717fn extract_bash_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
5721 let lang = LangId::Bash;
5722 let capture_names = query.capture_names();
5723
5724 let mut symbols = Vec::new();
5725 let mut cursor = QueryCursor::new();
5726 let mut matches = cursor.matches(query, *root, source.as_bytes());
5727
5728 while let Some(m) = {
5729 matches.advance();
5730 matches.get()
5731 } {
5732 let mut fn_name_node = None;
5733 let mut fn_def_node = None;
5734
5735 for cap in m.captures {
5736 let Some(&name) = capture_names.get(cap.index as usize) else {
5737 continue;
5738 };
5739 match name {
5740 "fn.name" => fn_name_node = Some(cap.node),
5741 "fn.def" => fn_def_node = Some(cap.node),
5742 _ => {}
5743 }
5744 }
5745
5746 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
5747 symbols.push(Symbol {
5748 name: node_text(source, &name_node).to_string(),
5749 kind: SymbolKind::Function,
5750 range: node_range_with_decorators(&def_node, source, lang),
5751 signature: Some(extract_signature(source, &def_node)),
5752 scope_chain: vec![],
5753 exported: false,
5754 parent: None,
5755 });
5756 }
5757 }
5758
5759 Ok(symbols)
5760}
5761
5762fn extract_pascal_symbols(
5763 source: &str,
5764 root: &Node,
5765 query: &Query,
5766) -> Result<Vec<Symbol>, AftError> {
5767 let lang = LangId::Pascal;
5768 let capture_names = query.capture_names();
5769
5770 let mut symbols = Vec::new();
5771 let mut cursor = QueryCursor::new();
5772 let mut matches = cursor.matches(query, *root, source.as_bytes());
5773
5774 while let Some(m) = {
5775 matches.advance();
5776 matches.get()
5777 } {
5778 let mut program_name_node = None;
5779 let mut program_def_node = None;
5780 let mut unit_name_node = None;
5781 let mut unit_def_node = None;
5782 let mut type_name_node = None;
5783 let mut type_def_node = None;
5784 let mut const_name_node = None;
5785 let mut const_def_node = None;
5786 let mut var_name_node = None;
5787 let mut var_def_node = None;
5788 let mut proc_name_node = None;
5789 let mut proc_def_node = None;
5790
5791 for cap in m.captures {
5792 let Some(&name) = capture_names.get(cap.index as usize) else {
5793 continue;
5794 };
5795 match name {
5796 "program.name" => program_name_node = Some(cap.node),
5797 "program.def" => program_def_node = Some(cap.node),
5798 "unit.name" => unit_name_node = Some(cap.node),
5799 "unit.def" => unit_def_node = Some(cap.node),
5800 "type.name" => type_name_node = Some(cap.node),
5801 "type.def" => type_def_node = Some(cap.node),
5802 "const.name" => const_name_node = Some(cap.node),
5803 "const.def" => const_def_node = Some(cap.node),
5804 "var.name" => var_name_node = Some(cap.node),
5805 "var.def" => var_def_node = Some(cap.node),
5806 "proc.name" => proc_name_node = Some(cap.node),
5807 "proc.def" => proc_def_node = Some(cap.node),
5808 _ => {}
5809 }
5810 }
5811
5812 if let (Some(name_node), Some(def_node)) = (program_name_node, program_def_node) {
5813 symbols.push(Symbol {
5814 name: node_text(source, &name_node).to_string(),
5815 kind: SymbolKind::Class,
5816 range: node_range_with_decorators(&def_node, source, lang),
5817 signature: Some(extract_signature(source, &def_node)),
5818 scope_chain: vec![],
5819 exported: true,
5820 parent: None,
5821 });
5822 }
5823
5824 if let (Some(name_node), Some(def_node)) = (unit_name_node, unit_def_node) {
5825 symbols.push(Symbol {
5826 name: node_text(source, &name_node).to_string(),
5827 kind: SymbolKind::Class,
5828 range: node_range_with_decorators(&def_node, source, lang),
5829 signature: Some(extract_signature(source, &def_node)),
5830 scope_chain: vec![],
5831 exported: true,
5832 parent: None,
5833 });
5834 }
5835
5836 if let (Some(name_node), Some(def_node)) = (type_name_node, type_def_node) {
5837 let kind = pascal_type_kind(&def_node, source);
5838 symbols.push(Symbol {
5839 name: node_text(source, &name_node).to_string(),
5840 kind,
5841 range: node_range_with_decorators(&def_node, source, lang),
5842 signature: Some(extract_signature(source, &def_node)),
5843 scope_chain: vec![],
5844 exported: true,
5845 parent: None,
5846 });
5847 }
5848
5849 if let (Some(name_node), Some(def_node)) = (const_name_node, const_def_node) {
5850 symbols.push(Symbol {
5851 name: node_text(source, &name_node).to_string(),
5852 kind: SymbolKind::Variable,
5853 range: node_range_with_decorators(&def_node, source, lang),
5854 signature: Some(extract_signature(source, &def_node)),
5855 scope_chain: vec![],
5856 exported: true,
5857 parent: None,
5858 });
5859 }
5860
5861 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
5862 symbols.push(Symbol {
5863 name: node_text(source, &name_node).to_string(),
5864 kind: SymbolKind::Variable,
5865 range: node_range_with_decorators(&def_node, source, lang),
5866 signature: Some(extract_signature(source, &def_node)),
5867 scope_chain: vec![],
5868 exported: true,
5869 parent: None,
5870 });
5871 }
5872
5873 if let (Some(name_node), Some(def_node)) = (proc_name_node, proc_def_node) {
5874 if def_node.kind() == "declProc" {
5875 if let Some(parent) = def_node.parent() {
5876 if parent.kind() == "defProc" {
5877 continue;
5878 }
5879 }
5880 }
5881
5882 let (name, scope_chain) = extract_pascal_name_and_scope(&name_node, &def_node, source);
5883 let kind = if scope_chain.is_empty() {
5884 SymbolKind::Function
5885 } else {
5886 SymbolKind::Method
5887 };
5888
5889 symbols.push(Symbol {
5890 name,
5891 kind,
5892 range: node_range_with_decorators(&def_node, source, lang),
5893 signature: Some(extract_signature(source, &def_node)),
5894 parent: scope_chain.last().cloned(),
5895 scope_chain,
5896 exported: true,
5897 });
5898 }
5899 }
5900
5901 dedup_symbols(&mut symbols);
5902 Ok(symbols)
5903}
5904
5905fn pascal_type_kind(node: &Node, _source: &str) -> SymbolKind {
5906 let mut cursor = node.walk();
5907 for child in node.children(&mut cursor) {
5908 if child.kind() == "declClass" {
5909 let mut child_cursor = child.walk();
5910 for grandchild in child.children(&mut child_cursor) {
5911 if grandchild.kind() == "kRecord" {
5912 return SymbolKind::Struct;
5913 }
5914 }
5915 return SymbolKind::Class;
5916 }
5917 if child.kind() == "declIntf" {
5918 return SymbolKind::Interface;
5919 }
5920 if child.kind() == "type" {
5921 let mut child_cursor = child.walk();
5922 for grandchild in child.children(&mut child_cursor) {
5923 if grandchild.kind() == "declEnum" {
5924 return SymbolKind::Enum;
5925 }
5926 }
5927 }
5928 }
5929 SymbolKind::TypeAlias
5930}
5931
5932fn extract_pascal_name_and_scope(
5933 name_node: &Node,
5934 def_node: &Node,
5935 source: &str,
5936) -> (String, Vec<String>) {
5937 let mut scope_chain = Vec::new();
5938 let mut name = node_text(source, name_node).to_string();
5939
5940 if name_node.kind() == "genericDot" {
5941 let mut cursor = name_node.walk();
5942 let idents: Vec<Node> = name_node
5943 .children(&mut cursor)
5944 .filter(|c| c.kind() == "identifier")
5945 .collect();
5946 if idents.len() >= 2 {
5947 let class_name = node_text(source, &idents[0]).to_string();
5948 scope_chain.push(class_name);
5949 name = node_text(source, &idents[1]).to_string();
5950 }
5951 }
5952
5953 let mut current = def_node.parent();
5954 while let Some(parent) = current {
5955 if parent.kind() == "declType" {
5956 if let Some(type_name_node) = parent.child_by_field_name("name").or_else(|| {
5957 let mut cursor = parent.walk();
5958 let mut found = None;
5959 for child in parent.children(&mut cursor) {
5960 if child.kind() == "identifier" {
5961 found = Some(child);
5962 break;
5963 }
5964 }
5965 found
5966 }) {
5967 scope_chain.insert(0, node_text(source, &type_name_node).to_string());
5968 }
5969 }
5970 current = parent.parent();
5971 }
5972
5973 (name, scope_chain)
5974}
5975
5976fn solidity_scope_chain(node: &Node, source: &str) -> Vec<String> {
5979 let mut chain = Vec::new();
5980 let mut current = node.parent();
5981
5982 while let Some(parent) = current {
5983 match parent.kind() {
5984 "contract_declaration" | "library_declaration" | "interface_declaration" => {
5985 if let Some(name_node) = parent.child_by_field_name("name") {
5986 chain.push(node_text(source, &name_node).to_string());
5987 }
5988 }
5989 _ => {}
5990 }
5991 current = parent.parent();
5992 }
5993
5994 chain.reverse();
5995 chain
5996}
5997
5998fn extract_solidity_symbols(
5999 source: &str,
6000 root: &Node,
6001 query: &Query,
6002) -> Result<Vec<Symbol>, AftError> {
6003 let lang = LangId::Solidity;
6004 let capture_names = query.capture_names();
6005
6006 let mut symbols = Vec::new();
6007 let mut cursor = QueryCursor::new();
6008 let mut matches = cursor.matches(query, *root, source.as_bytes());
6009
6010 while let Some(m) = {
6011 matches.advance();
6012 matches.get()
6013 } {
6014 let mut contract_name_node = None;
6015 let mut contract_def_node = None;
6016 let mut library_name_node = None;
6017 let mut library_def_node = None;
6018 let mut interface_name_node = None;
6019 let mut interface_def_node = None;
6020 let mut fn_name_node = None;
6021 let mut fn_def_node = None;
6022 let mut modifier_name_node = None;
6023 let mut modifier_def_node = None;
6024 let mut constructor_def_node = None;
6025 let mut fallback_receive_def_node = None;
6026 let mut event_name_node = None;
6027 let mut event_def_node = None;
6028 let mut error_name_node = None;
6029 let mut error_def_node = None;
6030 let mut struct_name_node = None;
6031 let mut struct_def_node = None;
6032 let mut enum_name_node = None;
6033 let mut enum_def_node = None;
6034 let mut var_name_node = None;
6035 let mut var_def_node = None;
6036
6037 for cap in m.captures {
6038 let Some(&name) = capture_names.get(cap.index as usize) else {
6039 continue;
6040 };
6041 match name {
6042 "contract.name" => contract_name_node = Some(cap.node),
6043 "contract.def" => contract_def_node = Some(cap.node),
6044 "library.name" => library_name_node = Some(cap.node),
6045 "library.def" => library_def_node = Some(cap.node),
6046 "interface.name" => interface_name_node = Some(cap.node),
6047 "interface.def" => interface_def_node = Some(cap.node),
6048 "fn.name" => fn_name_node = Some(cap.node),
6049 "fn.def" => fn_def_node = Some(cap.node),
6050 "modifier.name" => modifier_name_node = Some(cap.node),
6051 "modifier.def" => modifier_def_node = Some(cap.node),
6052 "constructor.def" => constructor_def_node = Some(cap.node),
6053 "fallback_receive.def" => fallback_receive_def_node = Some(cap.node),
6054 "event.name" => event_name_node = Some(cap.node),
6055 "event.def" => event_def_node = Some(cap.node),
6056 "error.name" => error_name_node = Some(cap.node),
6057 "error.def" => error_def_node = Some(cap.node),
6058 "struct.name" => struct_name_node = Some(cap.node),
6059 "struct.def" => struct_def_node = Some(cap.node),
6060 "enum.name" => enum_name_node = Some(cap.node),
6061 "enum.def" => enum_def_node = Some(cap.node),
6062 "var.name" => var_name_node = Some(cap.node),
6063 "var.def" => var_def_node = Some(cap.node),
6064 _ => {}
6065 }
6066 }
6067
6068 if let (Some(name_node), Some(def_node)) = (contract_name_node, contract_def_node) {
6070 symbols.push(Symbol {
6071 name: node_text(source, &name_node).to_string(),
6072 kind: SymbolKind::Class,
6073 range: node_range_with_decorators(&def_node, source, lang),
6074 signature: Some(extract_signature(source, &def_node)),
6075 scope_chain: vec![],
6076 exported: true,
6077 parent: None,
6078 });
6079 }
6080
6081 if let (Some(name_node), Some(def_node)) = (library_name_node, library_def_node) {
6083 symbols.push(Symbol {
6084 name: node_text(source, &name_node).to_string(),
6085 kind: SymbolKind::Class,
6086 range: node_range_with_decorators(&def_node, source, lang),
6087 signature: Some(extract_signature(source, &def_node)),
6088 scope_chain: vec![],
6089 exported: true,
6090 parent: None,
6091 });
6092 }
6093
6094 if let (Some(name_node), Some(def_node)) = (interface_name_node, interface_def_node) {
6096 symbols.push(Symbol {
6097 name: node_text(source, &name_node).to_string(),
6098 kind: SymbolKind::Interface,
6099 range: node_range_with_decorators(&def_node, source, lang),
6100 signature: Some(extract_signature(source, &def_node)),
6101 scope_chain: vec![],
6102 exported: true,
6103 parent: None,
6104 });
6105 }
6106
6107 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
6109 let scope_chain = solidity_scope_chain(&def_node, source);
6110 let kind = if scope_chain.is_empty() {
6111 SymbolKind::Function
6112 } else {
6113 SymbolKind::Method
6114 };
6115 symbols.push(Symbol {
6116 name: node_text(source, &name_node).to_string(),
6117 kind,
6118 range: node_range_with_decorators(&def_node, source, lang),
6119 signature: Some(extract_signature(source, &def_node)),
6120 parent: scope_chain.last().cloned(),
6121 scope_chain,
6122 exported: true,
6123 });
6124 }
6125
6126 if let (Some(name_node), Some(def_node)) = (modifier_name_node, modifier_def_node) {
6128 let scope_chain = solidity_scope_chain(&def_node, source);
6129 symbols.push(Symbol {
6130 name: node_text(source, &name_node).to_string(),
6131 kind: SymbolKind::Method,
6132 range: node_range_with_decorators(&def_node, source, lang),
6133 signature: Some(extract_signature(source, &def_node)),
6134 parent: scope_chain.last().cloned(),
6135 scope_chain,
6136 exported: true,
6137 });
6138 }
6139
6140 if let Some(def_node) = constructor_def_node {
6142 let scope_chain = solidity_scope_chain(&def_node, source);
6143 symbols.push(Symbol {
6144 name: "constructor".to_string(),
6145 kind: SymbolKind::Method,
6146 range: node_range_with_decorators(&def_node, source, lang),
6147 signature: Some(extract_signature(source, &def_node)),
6148 parent: scope_chain.last().cloned(),
6149 scope_chain,
6150 exported: true,
6151 });
6152 }
6153
6154 if let Some(def_node) = fallback_receive_def_node {
6156 let scope_chain = solidity_scope_chain(&def_node, source);
6157 let signature = extract_signature(source, &def_node);
6158 let name = if signature.trim_start().starts_with("receive") {
6159 "receive"
6160 } else {
6161 "fallback"
6162 };
6163 symbols.push(Symbol {
6164 name: name.to_string(),
6165 kind: SymbolKind::Method,
6166 range: node_range_with_decorators(&def_node, source, lang),
6167 signature: Some(signature),
6168 parent: scope_chain.last().cloned(),
6169 scope_chain,
6170 exported: true,
6171 });
6172 }
6173
6174 if let (Some(name_node), Some(def_node)) = (event_name_node, event_def_node) {
6176 let scope_chain = solidity_scope_chain(&def_node, source);
6177 symbols.push(Symbol {
6178 name: node_text(source, &name_node).to_string(),
6179 kind: SymbolKind::Function,
6180 range: node_range_with_decorators(&def_node, source, lang),
6181 signature: Some(extract_signature(source, &def_node)),
6182 parent: scope_chain.last().cloned(),
6183 scope_chain,
6184 exported: true,
6185 });
6186 }
6187
6188 if let (Some(name_node), Some(def_node)) = (error_name_node, error_def_node) {
6190 let scope_chain = solidity_scope_chain(&def_node, source);
6191 symbols.push(Symbol {
6192 name: node_text(source, &name_node).to_string(),
6193 kind: SymbolKind::TypeAlias,
6194 range: node_range_with_decorators(&def_node, source, lang),
6195 signature: Some(extract_signature(source, &def_node)),
6196 parent: scope_chain.last().cloned(),
6197 scope_chain,
6198 exported: true,
6199 });
6200 }
6201
6202 if let (Some(name_node), Some(def_node)) = (struct_name_node, struct_def_node) {
6204 let scope_chain = solidity_scope_chain(&def_node, source);
6205 symbols.push(Symbol {
6206 name: node_text(source, &name_node).to_string(),
6207 kind: SymbolKind::Struct,
6208 range: node_range_with_decorators(&def_node, source, lang),
6209 signature: Some(extract_signature(source, &def_node)),
6210 parent: scope_chain.last().cloned(),
6211 scope_chain,
6212 exported: true,
6213 });
6214 }
6215
6216 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
6218 let scope_chain = solidity_scope_chain(&def_node, source);
6219 symbols.push(Symbol {
6220 name: node_text(source, &name_node).to_string(),
6221 kind: SymbolKind::Enum,
6222 range: node_range_with_decorators(&def_node, source, lang),
6223 signature: Some(extract_signature(source, &def_node)),
6224 parent: scope_chain.last().cloned(),
6225 scope_chain,
6226 exported: true,
6227 });
6228 }
6229
6230 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
6232 let scope_chain = solidity_scope_chain(&def_node, source);
6233 symbols.push(Symbol {
6234 name: node_text(source, &name_node).to_string(),
6235 kind: SymbolKind::Variable,
6236 range: node_range_with_decorators(&def_node, source, lang),
6237 signature: Some(extract_signature(source, &def_node)),
6238 parent: scope_chain.last().cloned(),
6239 scope_chain,
6240 exported: true,
6241 });
6242 }
6243 }
6244
6245 dedup_symbols(&mut symbols);
6246 Ok(symbols)
6247}
6248
6249fn extract_r_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
6250 let lang = LangId::R;
6251 let capture_names = query.capture_names();
6252
6253 let mut symbols = Vec::new();
6254 let mut cursor = QueryCursor::new();
6255 let mut matches = cursor.matches(query, *root, source.as_bytes());
6256
6257 while let Some(m) = {
6258 matches.advance();
6259 matches.get()
6260 } {
6261 let mut assign_node = None;
6262 let mut function_node = None;
6263
6264 for cap in m.captures {
6265 let Some(&name) = capture_names.get(cap.index as usize) else {
6266 continue;
6267 };
6268 match name {
6269 "assign.def" => assign_node = Some(cap.node),
6270 "function.def" => function_node = Some(cap.node),
6271 _ => {}
6272 }
6273 }
6274
6275 if let Some(def_node) = function_node {
6276 if let Some(symbol) = r_rightward_function_assignment_symbol(source, &def_node, lang) {
6277 symbols.push(symbol);
6278 }
6279 continue;
6280 }
6281
6282 let Some(def_node) = assign_node else {
6283 continue;
6284 };
6285 let Some(assignment) = r_assignment_parts(source, &def_node) else {
6286 continue;
6287 };
6288 let Some(name_node) = r_assignment_name_node(&assignment) else {
6289 continue;
6290 };
6291 if name_node.kind() != "identifier" {
6292 continue;
6293 }
6294
6295 let value_is_function = r_node_contains_kind(&assignment.value, "function_definition");
6296 if !value_is_function && !r_is_top_level_assignment(&def_node) {
6297 continue;
6298 }
6299
6300 symbols.push(Symbol {
6301 name: node_text(source, &name_node).to_string(),
6302 kind: if value_is_function {
6303 SymbolKind::Function
6304 } else {
6305 SymbolKind::Variable
6306 },
6307 range: node_range_with_decorators(&def_node, source, lang),
6308 signature: Some(extract_signature(source, &def_node)),
6309 scope_chain: vec![],
6310 exported: true,
6311 parent: None,
6312 });
6313 }
6314
6315 dedup_symbols(&mut symbols);
6316 Ok(symbols)
6317}
6318
6319fn extract_groovy_symbols(
6320 source: &str,
6321 root: &Node,
6322 query: &Query,
6323) -> Result<Vec<Symbol>, AftError> {
6324 let lang = LangId::Groovy;
6325 let capture_names = query.capture_names();
6326 let mut symbols = Vec::new();
6327 let mut cursor = QueryCursor::new();
6328 let mut matches = cursor.matches(query, *root, source.as_bytes());
6329
6330 while let Some(m) = {
6331 matches.advance();
6332 matches.get()
6333 } {
6334 let mut class_name_node = None;
6335 let mut class_def_node = None;
6336 let mut interface_name_node = None;
6337 let mut interface_def_node = None;
6338 let mut trait_name_node = None;
6339 let mut trait_def_node = None;
6340 let mut enum_name_node = None;
6341 let mut enum_def_node = None;
6342 let mut fn_name_node = None;
6343 let mut fn_def_node = None;
6344 let mut var_name_node = None;
6345 let mut var_def_node = None;
6346 let mut pipeline_def_node = None;
6347
6348 for cap in m.captures {
6349 let Some(&name) = capture_names.get(cap.index as usize) else {
6350 continue;
6351 };
6352 match name {
6353 "class.name" => class_name_node = Some(cap.node),
6354 "class.def" => class_def_node = Some(cap.node),
6355 "interface.name" => interface_name_node = Some(cap.node),
6356 "interface.def" => interface_def_node = Some(cap.node),
6357 "trait.name" => trait_name_node = Some(cap.node),
6358 "trait.def" => trait_def_node = Some(cap.node),
6359 "enum.name" => enum_name_node = Some(cap.node),
6360 "enum.def" => enum_def_node = Some(cap.node),
6361 "fn.name" => fn_name_node = Some(cap.node),
6362 "fn.def" => fn_def_node = Some(cap.node),
6363 "var.name" => var_name_node = Some(cap.node),
6364 "var.def" => var_def_node = Some(cap.node),
6365 "pipeline.def" => pipeline_def_node = Some(cap.node),
6366 _ => {}
6367 }
6368 }
6369
6370 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
6371 push_captured_symbol(
6372 &mut symbols,
6373 source,
6374 lang,
6375 name_node,
6376 def_node,
6377 SymbolKind::Class,
6378 groovy_scope_chain(&def_node, source),
6379 true,
6380 );
6381 }
6382 if let (Some(name_node), Some(def_node)) = (interface_name_node, interface_def_node) {
6383 push_captured_symbol(
6384 &mut symbols,
6385 source,
6386 lang,
6387 name_node,
6388 def_node,
6389 SymbolKind::Interface,
6390 groovy_scope_chain(&def_node, source),
6391 true,
6392 );
6393 }
6394 if let (Some(name_node), Some(def_node)) = (trait_name_node, trait_def_node) {
6395 push_captured_symbol(
6396 &mut symbols,
6397 source,
6398 lang,
6399 name_node,
6400 def_node,
6401 SymbolKind::Interface,
6402 groovy_scope_chain(&def_node, source),
6403 true,
6404 );
6405 }
6406 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
6407 push_captured_symbol(
6408 &mut symbols,
6409 source,
6410 lang,
6411 name_node,
6412 def_node,
6413 SymbolKind::Enum,
6414 groovy_scope_chain(&def_node, source),
6415 true,
6416 );
6417 }
6418 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
6419 let scope_chain = groovy_scope_chain(&def_node, source);
6420 let kind = if scope_chain.is_empty() {
6421 SymbolKind::Function
6422 } else {
6423 SymbolKind::Method
6424 };
6425 push_captured_symbol(
6426 &mut symbols,
6427 source,
6428 lang,
6429 name_node,
6430 def_node,
6431 kind,
6432 scope_chain,
6433 true,
6434 );
6435 }
6436 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
6437 push_captured_symbol(
6438 &mut symbols,
6439 source,
6440 lang,
6441 name_node,
6442 def_node,
6443 SymbolKind::Variable,
6444 groovy_scope_chain(&def_node, source),
6445 true,
6446 );
6447 }
6448 if let Some(def_node) = pipeline_def_node {
6449 symbols.push(Symbol {
6450 name: "pipeline".to_string(),
6451 kind: SymbolKind::Function,
6452 range: node_range_with_decorators(&def_node, source, lang),
6453 signature: Some(extract_signature(source, &def_node)),
6454 scope_chain: vec![],
6455 exported: true,
6456 parent: None,
6457 });
6458 }
6459 }
6460
6461 collect_groovy_task_symbols(source, root, &mut symbols);
6462 dedup_symbols(&mut symbols);
6463 Ok(symbols)
6464}
6465
6466fn r_rightward_function_assignment_symbol(
6467 source: &str,
6468 function_node: &Node,
6469 lang: LangId,
6470) -> Option<Symbol> {
6471 let body = function_node.child_by_field_name("body")?;
6472 let assignment = r_assignment_parts(source, &body)?;
6473 if !matches!(assignment.operator.as_str(), "->" | "->>") {
6474 return None;
6475 }
6476 let function_text = node_text(source, function_node);
6477 let name = r_rightward_assignment_name_from_text(function_text).or_else(|| {
6478 let name_node = assignment.right;
6479 (name_node.kind() == "identifier").then(|| node_text(source, &name_node).to_string())
6480 })?;
6481
6482 let signature = r_rightward_function_signature(source, function_node, &name);
6483
6484 Some(Symbol {
6485 name,
6486 kind: SymbolKind::Function,
6487 range: node_range_with_decorators(function_node, source, lang),
6488 signature: Some(signature),
6489 scope_chain: vec![],
6490 exported: true,
6491 parent: None,
6492 })
6493}
6494
6495fn r_rightward_function_signature(source: &str, function_node: &Node, name: &str) -> String {
6496 let signature = extract_signature(source, function_node);
6497 if signature.contains(name) {
6498 signature
6499 } else {
6500 format!("{signature} -> {name}")
6501 }
6502}
6503
6504fn r_rightward_assignment_name_from_text(text: &str) -> Option<String> {
6505 let (_, after) = text.rsplit_once("->>").or_else(|| text.rsplit_once("->"))?;
6506 let trimmed = after.trim_start();
6507 let name: String = trimmed
6508 .chars()
6509 .take_while(|ch| ch.is_alphanumeric() || *ch == '_' || *ch == '.')
6510 .collect();
6511 (!name.is_empty()).then_some(name)
6512}
6513
6514struct RAssignmentParts<'tree> {
6515 operator: String,
6516 left: Node<'tree>,
6517 right: Node<'tree>,
6518 value: Node<'tree>,
6519}
6520
6521fn r_assignment_name_node<'tree>(assignment: &RAssignmentParts<'tree>) -> Option<Node<'tree>> {
6522 match assignment.operator.as_str() {
6523 "<-" | "=" | "<<-" => Some(assignment.left),
6524 "->" | "->>" => Some(assignment.right),
6525 _ => None,
6526 }
6527}
6528
6529fn r_assignment_parts<'tree>(source: &str, node: &Node<'tree>) -> Option<RAssignmentParts<'tree>> {
6530 if node.kind() != "binary_operator" {
6531 return None;
6532 }
6533
6534 let mut operator = None;
6535 let mut operator_index = None;
6536 for index in 0..node.child_count() {
6537 let child = node.child(index as u32)?;
6538 let text = node_text(source, &child).trim();
6539 if matches!(text, "<-" | "=" | "<<-" | "->" | "->>") {
6540 operator = Some(text.to_string());
6541 operator_index = Some(index);
6542 break;
6543 }
6544 }
6545
6546 let operator = operator?;
6547 let operator_index = operator_index?;
6548
6549 let left = r_nearest_named_child_before(node, operator_index)
6550 .or_else(|| node.child_by_field_name("lhs"))
6551 .or_else(|| node.child_by_field_name("left"))?;
6552 let right = r_nearest_named_child_after(node, operator_index)
6553 .or_else(|| node.child_by_field_name("rhs"))
6554 .or_else(|| node.child_by_field_name("right"))?;
6555
6556 let value = match operator.as_str() {
6557 "<-" | "=" | "<<-" => right,
6558 "->" | "->>" => left,
6559 _ => return None,
6560 };
6561
6562 Some(RAssignmentParts {
6563 operator,
6564 left,
6565 right,
6566 value,
6567 })
6568}
6569
6570fn r_nearest_named_child_before<'tree>(node: &Node<'tree>, index: usize) -> Option<Node<'tree>> {
6571 (0..index)
6572 .rev()
6573 .filter_map(|child_index| node.child(child_index as u32))
6574 .find(|child| child.is_named())
6575}
6576
6577fn r_nearest_named_child_after<'tree>(node: &Node<'tree>, index: usize) -> Option<Node<'tree>> {
6578 ((index + 1)..node.child_count())
6579 .filter_map(|child_index| node.child(child_index as u32))
6580 .find(|child| child.is_named())
6581}
6582
6583fn r_node_contains_kind(node: &Node, kind: &str) -> bool {
6587 let mut pending = vec![*node];
6588 while let Some(node) = pending.pop() {
6589 if node.kind() == kind {
6590 return true;
6591 }
6592 pending.extend(node.children(&mut node.walk()));
6593 }
6594 false
6595}
6596
6597fn r_is_top_level_assignment(node: &Node) -> bool {
6598 let mut current = node.parent();
6599 while let Some(parent) = current {
6600 match parent.kind() {
6601 "program" => return true,
6602 "braced_expression" | "function_definition" => return false,
6603 _ => current = parent.parent(),
6604 }
6605 }
6606 false
6607}
6608
6609fn extract_objc_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
6610 let lang = LangId::ObjC;
6611 let capture_names = query.capture_names();
6612
6613 let mut symbols = Vec::new();
6614 let mut cursor = QueryCursor::new();
6615 let mut matches = cursor.matches(query, *root, source.as_bytes());
6616
6617 while let Some(m) = {
6618 matches.advance();
6619 matches.get()
6620 } {
6621 for cap in m.captures {
6622 let Some(&name) = capture_names.get(cap.index as usize) else {
6623 continue;
6624 };
6625
6626 let def_node = cap.node;
6627 match name {
6628 "class.def" => {
6629 if let Some(symbol_name) = objc_container_name(source, &def_node) {
6630 let scope_chain = objc_scope_chain(&def_node, source);
6631 symbols.push(Symbol {
6632 name: symbol_name,
6633 kind: SymbolKind::Class,
6634 range: node_range_with_decorators(&def_node, source, lang),
6635 signature: Some(extract_signature(source, &def_node)),
6636 parent: scope_chain.last().cloned(),
6637 scope_chain,
6638 exported: false,
6639 });
6640 }
6641 }
6642 "interface.def" => {
6643 if let Some(symbol_name) = objc_container_name(source, &def_node) {
6644 let scope_chain = objc_scope_chain(&def_node, source);
6645 symbols.push(Symbol {
6646 name: symbol_name,
6647 kind: SymbolKind::Interface,
6648 range: node_range_with_decorators(&def_node, source, lang),
6649 signature: Some(extract_signature(source, &def_node)),
6650 parent: scope_chain.last().cloned(),
6651 scope_chain,
6652 exported: false,
6653 });
6654 }
6655 }
6656 "method.def" => {
6657 if let Some(symbol_name) = objc_method_selector(source, &def_node) {
6658 let scope_chain = objc_scope_chain(&def_node, source);
6659 symbols.push(Symbol {
6660 name: symbol_name,
6661 kind: SymbolKind::Method,
6662 range: node_range_with_decorators(&def_node, source, lang),
6663 signature: Some(extract_signature(source, &def_node)),
6664 parent: scope_chain.last().cloned(),
6665 scope_chain,
6666 exported: false,
6667 });
6668 }
6669 }
6670 "property.def" => {
6671 if let Some(symbol_name) = objc_property_name(source, &def_node) {
6672 let scope_chain = objc_scope_chain(&def_node, source);
6673 symbols.push(Symbol {
6674 name: symbol_name,
6675 kind: SymbolKind::Variable,
6676 range: node_range_with_decorators(&def_node, source, lang),
6677 signature: Some(extract_signature(source, &def_node)),
6678 parent: scope_chain.last().cloned(),
6679 scope_chain,
6680 exported: false,
6681 });
6682 }
6683 }
6684 "fn.def" => {
6685 if let Some(symbol_name) = objc_function_name(source, &def_node) {
6686 let scope_chain = objc_scope_chain(&def_node, source);
6687 symbols.push(Symbol {
6688 name: symbol_name,
6689 kind: SymbolKind::Function,
6690 range: node_range_with_decorators(&def_node, source, lang),
6691 signature: Some(extract_signature(source, &def_node)),
6692 parent: scope_chain.last().cloned(),
6693 scope_chain,
6694 exported: false,
6695 });
6696 }
6697 }
6698 "type.def" => {
6699 if let Some(symbol_name) = objc_typedef_name(source, &def_node) {
6700 let scope_chain = objc_scope_chain(&def_node, source);
6701 symbols.push(Symbol {
6702 name: symbol_name,
6703 kind: SymbolKind::TypeAlias,
6704 range: node_range_with_decorators(&def_node, source, lang),
6705 signature: Some(extract_signature(source, &def_node)),
6706 parent: scope_chain.last().cloned(),
6707 scope_chain,
6708 exported: false,
6709 });
6710 }
6711 }
6712 _ => {}
6713 }
6714 }
6715 }
6716
6717 dedup_symbols(&mut symbols);
6718 Ok(symbols)
6719}
6720
6721fn objc_container_name(source: &str, node: &Node) -> Option<String> {
6722 objc_first_direct_identifier(source, node)
6723}
6724
6725fn objc_method_selector(source: &str, node: &Node) -> Option<String> {
6726 let mut bare_selector = None;
6727 let mut keyword_segments = Vec::new();
6728 let mut cursor = node.walk();
6729
6730 let direct_named_children = node.named_children(&mut cursor).collect::<Vec<_>>();
6731 for (index, child) in direct_named_children.iter().enumerate() {
6732 match child.kind() {
6733 "identifier" => {
6734 let next_kind = direct_named_children.get(index + 1).map(|next| next.kind());
6735 if next_kind == Some("method_parameter") {
6736 keyword_segments.push(format!(
6737 "{}:",
6738 node_text(source, child).trim_end_matches(':')
6739 ));
6740 } else {
6741 bare_selector.get_or_insert_with(|| node_text(source, child).to_string());
6742 }
6743 }
6744 "keyword_declarator" => {
6745 if let Some(segment) = objc_first_direct_identifier(source, child) {
6746 keyword_segments.push(format!("{}:", segment.trim_end_matches(':')));
6747 }
6748 }
6749 _ => {}
6750 }
6751 }
6752
6753 if keyword_segments.is_empty() {
6754 bare_selector
6755 } else {
6756 Some(keyword_segments.join(""))
6757 }
6758}
6759
6760fn objc_property_name(source: &str, node: &Node) -> Option<String> {
6761 find_child_by_kind(*node, "atomic_declaration")
6762 .as_ref()
6763 .and_then(|declaration| objc_declarator_name(source, declaration))
6764 .or_else(|| objc_declarator_name(source, node))
6765}
6766
6767fn objc_function_name(source: &str, node: &Node) -> Option<String> {
6768 node.child_by_field_name("declarator")
6769 .as_ref()
6770 .and_then(|declarator| objc_declarator_name(source, declarator))
6771}
6772
6773fn objc_typedef_name(source: &str, node: &Node) -> Option<String> {
6774 node.child_by_field_name("declarator")
6775 .as_ref()
6776 .and_then(|declarator| objc_declarator_name(source, declarator))
6777}
6778
6779fn objc_scope_chain(node: &Node, source: &str) -> Vec<String> {
6780 let mut scopes = Vec::new();
6781 let mut current = node.parent();
6782 while let Some(parent) = current {
6783 if matches!(
6784 parent.kind(),
6785 "class_interface" | "class_implementation" | "protocol_declaration"
6786 ) {
6787 if let Some(name) = objc_container_name(source, &parent) {
6788 scopes.push(name);
6789 }
6790 }
6791 current = parent.parent();
6792 }
6793 scopes.reverse();
6794 scopes
6795}
6796
6797fn objc_first_direct_identifier(source: &str, node: &Node) -> Option<String> {
6798 let mut cursor = node.walk();
6799 if !cursor.goto_first_child() {
6800 return None;
6801 }
6802
6803 loop {
6804 let child = cursor.node();
6805 if child.kind() == "identifier" {
6806 return Some(node_text(source, &child).to_string());
6807 }
6808 if !cursor.goto_next_sibling() {
6809 break;
6810 }
6811 }
6812
6813 None
6814}
6815
6816fn objc_declarator_name(source: &str, node: &Node) -> Option<String> {
6821 let mut pending = vec![*node];
6822 while let Some(node) = pending.pop() {
6823 if matches!(
6824 node.kind(),
6825 "identifier" | "field_identifier" | "type_identifier"
6826 ) {
6827 return Some(node_text(source, &node).to_string());
6828 }
6829 let declarator = node.child_by_field_name("declarator");
6834 for child_index in 0..node.child_count() {
6835 if let Some(child) = node.child(child_index as u32) {
6836 if child.is_named() && Some(child) != declarator {
6837 pending.push(child);
6838 }
6839 }
6840 }
6841 pending.extend(declarator);
6842 }
6843 None
6844}
6845
6846fn toml_key_text(source: &str, key: &Node) -> String {
6847 let raw = node_text(source, key).trim();
6848 if raw.len() >= 2
6849 && ((raw.starts_with('"') && raw.ends_with('"'))
6850 || (raw.starts_with('\'') && raw.ends_with('\'')))
6851 {
6852 raw[1..raw.len() - 1].to_string()
6853 } else {
6854 raw.to_string()
6855 }
6856}
6857
6858fn toml_pair_symbol(source: &str, pair: &Node, section: Option<&str>) -> Option<Symbol> {
6859 let key = pair.child_by_field_name("key").or_else(|| {
6860 let mut cursor = pair.walk();
6861 let first = pair.named_children(&mut cursor).next();
6862 first
6863 })?;
6864 let name = toml_key_text(source, &key);
6865 if name.is_empty() {
6866 return None;
6867 }
6868
6869 let scope_chain = section
6870 .map(|name| vec![name.to_string()])
6871 .unwrap_or_default();
6872 Some(Symbol {
6873 name,
6874 kind: SymbolKind::Variable,
6875 range: node_range_with_decorators(pair, source, LangId::Toml),
6876 signature: None,
6877 scope_chain,
6878 exported: false,
6879 parent: section.map(str::to_string),
6880 })
6881}
6882
6883fn toml_table_name(source: &str, table: &Node) -> Option<String> {
6884 let first_line = node_text(source, table).lines().next()?.trim();
6885 let name = first_line
6886 .strip_prefix("[[")
6887 .and_then(|line| line.strip_suffix("]]"))
6888 .or_else(|| {
6889 first_line
6890 .strip_prefix('[')
6891 .and_then(|line| line.strip_suffix(']'))
6892 })?
6893 .trim();
6894 (!name.is_empty()).then(|| name.to_string())
6895}
6896
6897fn toml_table_range(source: &str, table: &Node) -> Range {
6898 let start = table.start_position();
6899 let text = node_text(source, table).trim_end();
6900 let mut lines = text.lines();
6901 let line_count = lines.clone().count().max(1);
6902 let end_col = lines.next_back().map(str::len).unwrap_or_default();
6903 Range {
6904 start_line: start.row as u32,
6905 start_col: start.column as u32,
6906 end_line: start.row as u32 + line_count as u32 - 1,
6907 end_col: end_col as u32,
6908 }
6909}
6910
6911fn extract_toml_symbols(source: &str, root: &Node) -> Result<Vec<Symbol>, AftError> {
6912 let mut symbols = Vec::new();
6913 let mut cursor = root.walk();
6914 for child in root.named_children(&mut cursor) {
6915 match child.kind() {
6916 "pair" => {
6917 if let Some(symbol) = toml_pair_symbol(source, &child, None) {
6918 symbols.push(symbol);
6919 }
6920 }
6921 "table" | "table_array_element" => {
6922 let Some(name) = toml_table_name(source, &child) else {
6923 continue;
6924 };
6925 symbols.push(Symbol {
6926 name: name.clone(),
6927 kind: SymbolKind::Variable,
6928 range: toml_table_range(source, &child),
6929 signature: None,
6930 scope_chain: Vec::new(),
6931 exported: false,
6932 parent: None,
6933 });
6934
6935 let mut table_cursor = child.walk();
6936 for item in child.named_children(&mut table_cursor) {
6937 if item.kind() == "pair" {
6938 if let Some(symbol) = toml_pair_symbol(source, &item, Some(&name)) {
6939 symbols.push(symbol);
6940 }
6941 }
6942 }
6943 }
6944 _ => {}
6945 }
6946 }
6947 Ok(symbols)
6948}
6949
6950pub fn json_document_value<'a>(root: &Node<'a>) -> Option<Node<'a>> {
6956 let mut cursor = root.walk();
6957 let value = root
6958 .named_children(&mut cursor)
6959 .find(|child| child.kind() != "comment");
6960 value
6961}
6962
6963fn extract_json_symbols(source: &str, root: &Node) -> Result<Vec<Symbol>, AftError> {
6964 let Some(value) = json_document_value(root) else {
6965 return Ok(Vec::new());
6966 };
6967
6968 if value.kind() != "object" {
6969 return Ok(Vec::new());
6970 }
6971
6972 let mut symbols = Vec::new();
6973 let mut cursor = value.walk();
6974 for child in value.named_children(&mut cursor) {
6975 if child.kind() != "pair" {
6976 continue;
6977 }
6978 let Some(key_node) = child.child_by_field_name("key") else {
6979 continue;
6980 };
6981 let name = node_text(source, &key_node).trim_matches('"').to_string();
6982 if name.is_empty() {
6983 continue;
6984 }
6985 symbols.push(Symbol {
6986 name,
6987 kind: SymbolKind::Variable,
6988 range: node_range_with_decorators(&child, source, LangId::Json),
6989 signature: None,
6990 scope_chain: vec![],
6991 exported: false,
6992 parent: None,
6993 });
6994 }
6995
6996 Ok(symbols)
6997}
6998
6999fn yaml_scalar_text(source: &str, node: &Node) -> String {
7001 node_text(source, node)
7002 .trim()
7003 .trim_matches('"')
7004 .trim_matches('\'')
7005 .to_string()
7006}
7007
7008fn yaml_find_mapping<'a>(node: &Node<'a>) -> Option<Node<'a>> {
7014 let mut current = *node;
7015 loop {
7016 match current.kind() {
7017 "block_mapping" | "flow_mapping" => return Some(current),
7018 "document" | "block_node" | "flow_node" => {
7019 let mut cursor = current.walk();
7020 let next = current
7021 .named_children(&mut cursor)
7022 .find(|child| !matches!(child.kind(), "tag" | "anchor"));
7023 match next {
7024 Some(inner) => current = inner,
7025 None => return None,
7026 }
7027 }
7028 _ => return None,
7029 }
7030 }
7031}
7032
7033fn yaml_get<'a>(mapping: &Node<'a>, source: &str, key: &str) -> Option<Node<'a>> {
7035 let mut cursor = mapping.walk();
7036 for pair in mapping.named_children(&mut cursor) {
7037 if pair.kind() != "block_mapping_pair" && pair.kind() != "flow_pair" {
7038 continue;
7039 }
7040 let Some(key_node) = pair.child_by_field_name("key") else {
7041 continue;
7042 };
7043 if yaml_scalar_text(source, &key_node) == key {
7044 return pair.child_by_field_name("value");
7045 }
7046 }
7047 None
7048}
7049
7050fn yaml_unwrap<'a>(node: &Node<'a>) -> Node<'a> {
7055 let mut current = *node;
7056 while current.kind() == "block_node" || current.kind() == "flow_node" {
7057 let mut cursor = current.walk();
7058 let next = current
7059 .named_children(&mut cursor)
7060 .find(|child| !matches!(child.kind(), "tag" | "anchor"));
7061 match next {
7062 Some(inner) => current = inner,
7063 None => break,
7064 }
7065 }
7066 current
7067}
7068
7069fn yaml_flatten_value(source: &str, node: &Node) -> String {
7070 let node = &yaml_unwrap(node);
7071 match node.kind() {
7072 "block_sequence" | "flow_sequence" => {
7073 let mut items = Vec::new();
7074 let mut cursor = node.walk();
7075 for child in node.named_children(&mut cursor) {
7076 let value = if child.kind() == "block_sequence_item" {
7078 child.named_child(0)
7079 } else {
7080 Some(child)
7081 };
7082 if let Some(v) = value {
7083 let v = yaml_unwrap(&v);
7084 if v.kind() != "block_mapping" && v.kind() != "flow_mapping" {
7086 let text = yaml_scalar_text(source, &v);
7087 if !text.is_empty() {
7088 items.push(text);
7089 }
7090 }
7091 }
7092 }
7093 items.join(",")
7094 }
7095 "block_mapping" | "flow_mapping" => String::new(),
7099 _ => yaml_scalar_text(source, node),
7100 }
7101}
7102
7103fn yaml_collect_values(
7110 source: &str,
7111 node: &Node,
7112 keys: &[&str],
7113 out: &mut Vec<String>,
7114 cap: usize,
7115) {
7116 let mut pending: Vec<Node> = node.named_children(&mut node.walk()).collect();
7118 pending.reverse();
7119 while let Some(child) = pending.pop() {
7120 if out.len() >= cap {
7121 return;
7122 }
7123 if child.kind() == "block_mapping_pair" || child.kind() == "flow_pair" {
7124 if let Some(key_node) = child.child_by_field_name("key") {
7125 let key_text = yaml_scalar_text(source, &key_node);
7126 if keys.contains(&key_text.as_str()) {
7127 if let Some(value_node) = child.child_by_field_name("value") {
7128 let value_text = yaml_flatten_value(source, &value_node);
7129 if !value_text.is_empty() && out.len() < cap {
7130 out.push(format!("{}={}", key_text, value_text));
7131 }
7132 }
7133 }
7134 }
7135 }
7136 let start = pending.len();
7137 pending.extend(child.named_children(&mut child.walk()));
7138 pending[start..].reverse();
7139 }
7140}
7141
7142fn yaml_collect_named_items(
7150 source: &str,
7151 node: &Node,
7152 parent_key: &str,
7153 label: &str,
7154 out: &mut Vec<String>,
7155 cap: usize,
7156) {
7157 let mut pending: Vec<Node> = node.named_children(&mut node.walk()).collect();
7159 pending.reverse();
7160 while let Some(child) = pending.pop() {
7161 if (child.kind() == "block_mapping_pair" || child.kind() == "flow_pair")
7162 && child
7163 .child_by_field_name("key")
7164 .map(|k| yaml_scalar_text(source, &k))
7165 .as_deref()
7166 == Some(parent_key)
7167 {
7168 if let Some(seq) = child.child_by_field_name("value") {
7169 let seq = yaml_unwrap(&seq);
7170 let mut names = Vec::new();
7171 let mut seq_cursor = seq.walk();
7172 for item in seq.named_children(&mut seq_cursor) {
7173 let value = if item.kind() == "block_sequence_item" {
7174 item.named_child(0)
7175 } else {
7176 Some(item)
7177 };
7178 if let Some(v) = value {
7179 if let Some(map) = yaml_find_mapping(&v) {
7180 if let Some(name_node) = yaml_get(&map, source, "name") {
7181 let n = yaml_scalar_text(source, &name_node);
7182 if !n.is_empty() && names.len() < 16 {
7183 names.push(n);
7184 }
7185 }
7186 }
7187 }
7188 }
7189 if !names.is_empty() && out.len() < cap {
7190 out.push(format!("{}={}", label, names.join(",")));
7191 }
7192 }
7193 }
7194 let start = pending.len();
7195 pending.extend(child.named_children(&mut child.walk()));
7196 pending[start..].reverse();
7197 }
7198}
7199
7200fn yaml_k8s_resource_symbol(source: &str, doc: &Node, mapping: &Node) -> Option<Symbol> {
7204 let api_version =
7205 yaml_get(mapping, source, "apiVersion").map(|n| yaml_scalar_text(source, &n))?;
7206 let kind = yaml_get(mapping, source, "kind").map(|n| yaml_scalar_text(source, &n))?;
7207 if api_version.is_empty() || kind.is_empty() {
7208 return None;
7209 }
7210
7211 let (name, namespace) = match yaml_get(mapping, source, "metadata") {
7212 Some(meta) => match yaml_find_mapping(&meta) {
7213 Some(meta_map) => {
7214 let name = yaml_get(&meta_map, source, "name")
7218 .map(|n| yaml_scalar_text(source, &n))
7219 .filter(|s| !s.is_empty())
7220 .or_else(|| {
7221 yaml_get(&meta_map, source, "generateName")
7222 .map(|n| yaml_scalar_text(source, &n))
7223 .filter(|s| !s.is_empty())
7224 });
7225 (
7226 name,
7227 yaml_get(&meta_map, source, "namespace").map(|n| yaml_scalar_text(source, &n)),
7228 )
7229 }
7230 None => (None, None),
7231 },
7232 None => (None, None),
7233 };
7234
7235 let res_name = name.clone().filter(|s| !s.is_empty());
7236 let sym_name = match (&namespace, &res_name) {
7237 (Some(ns), Some(n)) if !ns.is_empty() => format!("{}/{}/{}", ns, kind, n),
7238 (_, Some(n)) => format!("{}/{}", kind, n),
7239 _ => kind.clone(),
7240 };
7241
7242 let mut sig = format!("apiVersion={} kind={}", api_version, kind);
7243 if let Some(ns) = namespace.as_ref().filter(|s| !s.is_empty()) {
7244 sig.push_str(&format!(" namespace={}", ns));
7245 }
7246 if let Some(n) = res_name.as_ref() {
7247 sig.push_str(&format!(" name={}", n));
7248 }
7249 let mut extras = Vec::new();
7253 yaml_collect_values(
7254 source,
7255 mapping,
7256 &[
7257 "image",
7258 "containerPort",
7259 "port",
7260 "targetPort",
7261 "cpu",
7262 "memory",
7263 "storage",
7264 "verbs",
7265 "resources",
7266 "apiGroups",
7267 "mountPath",
7268 "replicas",
7269 "entrypoint",
7271 "command",
7272 "args",
7273 "schedule",
7274 ],
7275 &mut extras,
7276 24,
7277 );
7278 yaml_collect_named_items(source, mapping, "env", "env", &mut extras, 24);
7281 yaml_collect_named_items(source, mapping, "templates", "templates", &mut extras, 24);
7282 if !extras.is_empty() {
7283 sig.push(' ');
7284 sig.push_str(&extras.join(" "));
7285 }
7286
7287 Some(Symbol {
7288 name: sym_name,
7289 kind: SymbolKind::Class,
7290 range: node_range(doc),
7291 signature: Some(sig),
7292 scope_chain: vec![],
7293 exported: true,
7294 parent: None,
7295 })
7296}
7297
7298fn yaml_generic_keys(source: &str, mapping: &Node, symbols: &mut Vec<Symbol>) {
7301 let mut cursor = mapping.walk();
7302 for pair in mapping.named_children(&mut cursor) {
7303 if pair.kind() != "block_mapping_pair" && pair.kind() != "flow_pair" {
7304 continue;
7305 }
7306 let Some(key_node) = pair.child_by_field_name("key") else {
7307 continue;
7308 };
7309 let name = yaml_scalar_text(source, &key_node);
7310 if name.is_empty() {
7311 continue;
7312 }
7313 symbols.push(Symbol {
7314 name,
7315 kind: SymbolKind::Variable,
7316 range: node_range(&pair),
7317 signature: None,
7318 scope_chain: vec![],
7319 exported: false,
7320 parent: None,
7321 });
7322 }
7323}
7324
7325fn extract_yaml_symbols(source: &str, root: &Node) -> Result<Vec<Symbol>, AftError> {
7331 let mut symbols = Vec::new();
7332 let mut cursor = root.walk();
7333 for doc in root.named_children(&mut cursor) {
7334 if doc.kind() != "document" {
7335 continue;
7336 }
7337 let Some(mapping) = yaml_find_mapping(&doc) else {
7338 continue;
7339 };
7340 if let Some(symbol) = yaml_k8s_resource_symbol(source, &doc, &mapping) {
7341 symbols.push(symbol);
7342 } else {
7343 yaml_generic_keys(source, &mapping, &mut symbols);
7344 }
7345 }
7346 Ok(symbols)
7347}
7348
7349fn scala_scope_chain(node: &Node, source: &str) -> Vec<String> {
7350 let mut chain = Vec::new();
7351 let mut current = node.parent();
7352
7353 while let Some(parent) = current {
7354 match parent.kind() {
7355 "class_definition" | "object_definition" | "enum_definition" | "trait_definition" => {
7356 if let Some(name_node) = parent.child_by_field_name("name") {
7357 chain.push(node_text(source, &name_node).to_string());
7358 }
7359 }
7360 _ => {}
7361 }
7362 current = parent.parent();
7363 }
7364
7365 chain.reverse();
7366 chain
7367}
7368
7369fn extract_scala_symbols(
7370 source: &str,
7371 root: &Node,
7372 query: &Query,
7373) -> Result<Vec<Symbol>, AftError> {
7374 let lang = LangId::Scala;
7375 let capture_names = query.capture_names();
7376
7377 let mut symbols = Vec::new();
7378 let mut cursor = QueryCursor::new();
7379 let mut matches = cursor.matches(query, *root, source.as_bytes());
7380
7381 while let Some(m) = {
7382 matches.advance();
7383 matches.get()
7384 } {
7385 let mut class_name_node = None;
7386 let mut class_def_node = None;
7387 let mut object_name_node = None;
7388 let mut object_def_node = None;
7389 let mut enum_name_node = None;
7390 let mut enum_def_node = None;
7391 let mut trait_name_node = None;
7392 let mut trait_def_node = None;
7393 let mut fn_name_node = None;
7394 let mut fn_def_node = None;
7395 let mut val_name_node = None;
7396 let mut val_def_node = None;
7397 let mut var_name_node = None;
7398 let mut var_def_node = None;
7399 let mut type_name_node = None;
7400 let mut type_def_node = None;
7401
7402 for cap in m.captures {
7403 let Some(&name) = capture_names.get(cap.index as usize) else {
7404 continue;
7405 };
7406 match name {
7407 "class.name" => class_name_node = Some(cap.node),
7408 "class.def" => class_def_node = Some(cap.node),
7409 "object.name" => object_name_node = Some(cap.node),
7410 "object.def" => object_def_node = Some(cap.node),
7411 "enum.name" => enum_name_node = Some(cap.node),
7412 "enum.def" => enum_def_node = Some(cap.node),
7413 "trait.name" => trait_name_node = Some(cap.node),
7414 "trait.def" => trait_def_node = Some(cap.node),
7415 "fn.name" => fn_name_node = Some(cap.node),
7416 "fn.def" => fn_def_node = Some(cap.node),
7417 "val.name" => val_name_node = Some(cap.node),
7418 "val.def" => val_def_node = Some(cap.node),
7419 "var.name" => var_name_node = Some(cap.node),
7420 "var.def" => var_def_node = Some(cap.node),
7421 "given.name" => val_name_node = Some(cap.node),
7422 "given.def" => val_def_node = Some(cap.node),
7423 "type.name" => type_name_node = Some(cap.node),
7424 "type.def" => type_def_node = Some(cap.node),
7425 _ => {}
7426 }
7427 }
7428
7429 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
7430 symbols.push(Symbol {
7431 name: node_text(source, &name_node).to_string(),
7432 kind: SymbolKind::Class,
7433 range: node_range_with_decorators(&def_node, source, lang),
7434 signature: Some(extract_signature(source, &def_node)),
7435 scope_chain: scala_scope_chain(&def_node, source),
7436 exported: true,
7437 parent: scala_scope_chain(&def_node, source).last().cloned(),
7438 });
7439 }
7440
7441 if let (Some(name_node), Some(def_node)) = (object_name_node, object_def_node) {
7442 symbols.push(Symbol {
7443 name: node_text(source, &name_node).to_string(),
7444 kind: SymbolKind::Class,
7445 range: node_range_with_decorators(&def_node, source, lang),
7446 signature: Some(extract_signature(source, &def_node)),
7447 scope_chain: scala_scope_chain(&def_node, source),
7448 exported: true,
7449 parent: scala_scope_chain(&def_node, source).last().cloned(),
7450 });
7451 }
7452
7453 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
7454 symbols.push(Symbol {
7455 name: node_text(source, &name_node).to_string(),
7456 kind: SymbolKind::Enum,
7457 range: node_range_with_decorators(&def_node, source, lang),
7458 signature: Some(extract_signature(source, &def_node)),
7459 scope_chain: scala_scope_chain(&def_node, source),
7460 exported: true,
7461 parent: scala_scope_chain(&def_node, source).last().cloned(),
7462 });
7463 }
7464
7465 if let (Some(name_node), Some(def_node)) = (trait_name_node, trait_def_node) {
7466 symbols.push(Symbol {
7467 name: node_text(source, &name_node).to_string(),
7468 kind: SymbolKind::Interface,
7469 range: node_range_with_decorators(&def_node, source, lang),
7470 signature: Some(extract_signature(source, &def_node)),
7471 scope_chain: scala_scope_chain(&def_node, source),
7472 exported: true,
7473 parent: scala_scope_chain(&def_node, source).last().cloned(),
7474 });
7475 }
7476
7477 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
7478 let scope_chain = scala_scope_chain(&def_node, source);
7479 let kind = if scope_chain.is_empty() {
7480 SymbolKind::Function
7481 } else {
7482 SymbolKind::Method
7483 };
7484 symbols.push(Symbol {
7485 name: node_text(source, &name_node).to_string(),
7486 kind,
7487 range: node_range_with_decorators(&def_node, source, lang),
7488 signature: Some(extract_signature(source, &def_node)),
7489 parent: scope_chain.last().cloned(),
7490 scope_chain,
7491 exported: true,
7492 });
7493 }
7494
7495 if let (Some(name_node), Some(def_node)) = (val_name_node, val_def_node) {
7496 let scope_chain = scala_scope_chain(&def_node, source);
7497 symbols.push(Symbol {
7498 name: node_text(source, &name_node).to_string(),
7499 kind: SymbolKind::Variable,
7500 range: node_range_with_decorators(&def_node, source, lang),
7501 signature: Some(extract_signature(source, &def_node)),
7502 parent: scope_chain.last().cloned(),
7503 scope_chain,
7504 exported: true,
7505 });
7506 }
7507
7508 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
7509 let scope_chain = scala_scope_chain(&def_node, source);
7510 symbols.push(Symbol {
7511 name: node_text(source, &name_node).to_string(),
7512 kind: SymbolKind::Variable,
7513 range: node_range_with_decorators(&def_node, source, lang),
7514 signature: Some(extract_signature(source, &def_node)),
7515 parent: scope_chain.last().cloned(),
7516 scope_chain,
7517 exported: true,
7518 });
7519 }
7520
7521 if let (Some(name_node), Some(def_node)) = (type_name_node, type_def_node) {
7522 let scope_chain = scala_scope_chain(&def_node, source);
7523 symbols.push(Symbol {
7524 name: node_text(source, &name_node).to_string(),
7525 kind: SymbolKind::TypeAlias,
7526 range: node_range_with_decorators(&def_node, source, lang),
7527 signature: Some(extract_signature(source, &def_node)),
7528 parent: scope_chain.last().cloned(),
7529 scope_chain,
7530 exported: true,
7531 });
7532 }
7533 }
7534
7535 dedup_symbols(&mut symbols);
7536 Ok(symbols)
7537}
7538
7539fn child_text_by_field_or_kind(
7540 node: &Node,
7541 source: &str,
7542 field_name: &str,
7543 kinds: &[&str],
7544) -> Option<String> {
7545 if let Some(name_node) = node.child_by_field_name(field_name) {
7546 return Some(node_text(source, &name_node).to_string());
7547 }
7548
7549 let mut cursor = node.walk();
7550 if !cursor.goto_first_child() {
7551 return None;
7552 }
7553
7554 loop {
7555 let child = cursor.node();
7556 if kinds.contains(&child.kind()) {
7557 return Some(node_text(source, &child).to_string());
7558 }
7559 if !cursor.goto_next_sibling() {
7560 break;
7561 }
7562 }
7563
7564 None
7565}
7566
7567fn push_captured_symbol(
7568 symbols: &mut Vec<Symbol>,
7569 source: &str,
7570 lang: LangId,
7571 name_node: Node,
7572 def_node: Node,
7573 kind: SymbolKind,
7574 scope_chain: Vec<String>,
7575 exported: bool,
7576) {
7577 symbols.push(Symbol {
7578 name: node_text(source, &name_node).to_string(),
7579 kind,
7580 range: node_range_with_decorators(&def_node, source, lang),
7581 signature: Some(extract_signature(source, &def_node)),
7582 parent: scope_chain.last().cloned(),
7583 scope_chain,
7584 exported,
7585 });
7586}
7587
7588fn range_spanning_nodes(start_node: &Node, end_node: &Node) -> Range {
7589 let start = start_node.start_position();
7590 let end = end_node.end_position();
7591 Range {
7592 start_line: start.row as u32,
7593 start_col: start.column as u32,
7594 end_line: end.row as u32,
7595 end_col: end.column as u32,
7596 }
7597}
7598
7599fn extract_signature_between(source: &str, start_node: &Node, end_node: &Node) -> String {
7600 let start = start_node.start_byte();
7601 let end = end_node.end_byte();
7602 let text = source.get(start..end).unwrap_or_default();
7603 let first_line = text.lines().next().unwrap_or(text);
7604 let trimmed = first_line.trim_end();
7605 let trimmed = trimmed.strip_suffix('{').unwrap_or(trimmed).trim_end();
7606 trimmed.to_string()
7607}
7608
7609fn groovy_scope_chain(node: &Node, source: &str) -> Vec<String> {
7610 let mut chain = Vec::new();
7611 let mut current = node.parent();
7612
7613 while let Some(parent) = current {
7614 if matches!(
7615 parent.kind(),
7616 "class_declaration"
7617 | "interface_declaration"
7618 | "trait_declaration"
7619 | "enum_declaration"
7620 | "record_declaration"
7621 | "annotation_type_declaration"
7622 ) {
7623 if let Some(name_node) = parent.child_by_field_name("name") {
7624 chain.push(node_text(source, &name_node).to_string());
7625 }
7626 }
7627 current = parent.parent();
7628 }
7629
7630 chain.reverse();
7631 chain
7632}
7633
7634fn groovy_keyword_task_symbol(
7638 source: &str,
7639 keyword_stmt: Node,
7640 declaration: Node,
7641) -> Option<Symbol> {
7642 if keyword_stmt.kind() != "expression_statement" || declaration.kind() != "command_chain" {
7643 return None;
7644 }
7645
7646 let keyword = keyword_stmt.named_child(0)?;
7647 if keyword.kind() != "identifier" || node_text(source, &keyword) != "task" {
7648 return None;
7649 }
7650
7651 let name_node = declaration.child_by_field_name("receiver")?;
7652 if name_node.kind() != "identifier" {
7653 return None;
7654 }
7655
7656 let body_node = declaration.child_by_field_name("argument")?;
7657 if body_node.kind() != "closure" {
7658 return None;
7659 }
7660
7661 Some(Symbol {
7662 name: node_text(source, &name_node).to_string(),
7663 kind: SymbolKind::Function,
7664 range: range_spanning_nodes(&keyword_stmt, &declaration),
7665 signature: Some(extract_signature_between(
7666 source,
7667 &keyword_stmt,
7668 &declaration,
7669 )),
7670 scope_chain: vec![],
7671 exported: true,
7672 parent: None,
7673 })
7674}
7675
7676fn groovy_registered_task_symbol(
7680 source: &str,
7681 invocation_stmt: Node,
7682 closure_stmt: Node,
7683) -> Option<Symbol> {
7684 if invocation_stmt.kind() != "expression_statement"
7685 || closure_stmt.kind() != "expression_statement"
7686 {
7687 return None;
7688 }
7689
7690 let invocation = invocation_stmt.named_child(0)?;
7691 if invocation.kind() != "method_invocation" {
7692 return None;
7693 }
7694
7695 let function = invocation.child_by_field_name("function")?;
7696 if function.kind() != "field_access" {
7697 return None;
7698 }
7699
7700 let object = function.child_by_field_name("object")?;
7701 let field = function.child_by_field_name("field")?;
7702 if node_text(source, &object) != "tasks" || node_text(source, &field) != "register" {
7703 return None;
7704 }
7705
7706 let arguments = invocation.child_by_field_name("arguments")?;
7707 let name_node = arguments.named_child(0)?;
7708 if name_node.kind() != "string_literal" {
7709 return None;
7710 }
7711
7712 let closure = closure_stmt.named_child(0)?;
7713 if closure.kind() != "closure" {
7714 return None;
7715 }
7716
7717 Some(Symbol {
7718 name: string_content(source, &name_node)?,
7719 kind: SymbolKind::Function,
7720 range: range_spanning_nodes(&invocation_stmt, &closure_stmt),
7721 signature: Some(extract_signature_between(
7722 source,
7723 &invocation_stmt,
7724 &closure_stmt,
7725 )),
7726 scope_chain: vec![],
7727 exported: true,
7728 parent: None,
7729 })
7730}
7731
7732fn collect_groovy_task_symbols(source: &str, root: &Node, symbols: &mut Vec<Symbol>) {
7733 let children: Vec<Node> = root.named_children(&mut root.walk()).collect();
7734 let mut index = 0;
7735 while index + 1 < children.len() {
7736 if let Some(symbol) =
7737 groovy_keyword_task_symbol(source, children[index], children[index + 1])
7738 {
7739 symbols.push(symbol);
7740 index += 2;
7741 continue;
7742 }
7743
7744 if let Some(symbol) =
7745 groovy_registered_task_symbol(source, children[index], children[index + 1])
7746 {
7747 symbols.push(symbol);
7748 index += 2;
7749 continue;
7750 }
7751
7752 index += 1;
7753 }
7754}
7755
7756fn java_scope_chain(node: &Node, source: &str) -> Vec<String> {
7757 let mut chain = Vec::new();
7758 let mut current = node.parent();
7759
7760 while let Some(parent) = current {
7761 if matches!(
7762 parent.kind(),
7763 "class_declaration"
7764 | "interface_declaration"
7765 | "annotation_type_declaration"
7766 | "enum_declaration"
7767 | "record_declaration"
7768 ) {
7769 if let Some(name_node) = parent.child_by_field_name("name") {
7770 chain.push(node_text(source, &name_node).to_string());
7771 }
7772 }
7773 current = parent.parent();
7774 }
7775
7776 chain.reverse();
7777 chain
7778}
7779
7780fn extract_java_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
7781 let lang = LangId::Java;
7782 let capture_names = query.capture_names();
7783 let mut symbols = Vec::new();
7784 let mut cursor = QueryCursor::new();
7785 let mut matches = cursor.matches(query, *root, source.as_bytes());
7786
7787 while let Some(m) = {
7788 matches.advance();
7789 matches.get()
7790 } {
7791 let mut class_name_node = None;
7792 let mut class_def_node = None;
7793 let mut interface_name_node = None;
7794 let mut interface_def_node = None;
7795 let mut enum_name_node = None;
7796 let mut enum_def_node = None;
7797 let mut struct_name_node = None;
7798 let mut struct_def_node = None;
7799 let mut fn_name_node = None;
7800 let mut fn_def_node = None;
7801 let mut var_name_node = None;
7802 let mut var_def_node = None;
7803
7804 for cap in m.captures {
7805 let Some(&name) = capture_names.get(cap.index as usize) else {
7806 continue;
7807 };
7808 match name {
7809 "class.name" => class_name_node = Some(cap.node),
7810 "class.def" => class_def_node = Some(cap.node),
7811 "interface.name" => interface_name_node = Some(cap.node),
7812 "interface.def" => interface_def_node = Some(cap.node),
7813 "enum.name" => enum_name_node = Some(cap.node),
7814 "enum.def" => enum_def_node = Some(cap.node),
7815 "struct.name" => struct_name_node = Some(cap.node),
7816 "struct.def" => struct_def_node = Some(cap.node),
7817 "fn.name" => fn_name_node = Some(cap.node),
7818 "fn.def" => fn_def_node = Some(cap.node),
7819 "var.name" => var_name_node = Some(cap.node),
7820 "var.def" => var_def_node = Some(cap.node),
7821 _ => {}
7822 }
7823 }
7824
7825 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
7826 push_captured_symbol(
7827 &mut symbols,
7828 source,
7829 lang,
7830 name_node,
7831 def_node,
7832 SymbolKind::Class,
7833 java_scope_chain(&def_node, source),
7834 true,
7835 );
7836 }
7837 if let (Some(name_node), Some(def_node)) = (interface_name_node, interface_def_node) {
7838 push_captured_symbol(
7839 &mut symbols,
7840 source,
7841 lang,
7842 name_node,
7843 def_node,
7844 SymbolKind::Interface,
7845 java_scope_chain(&def_node, source),
7846 true,
7847 );
7848 }
7849 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
7850 push_captured_symbol(
7851 &mut symbols,
7852 source,
7853 lang,
7854 name_node,
7855 def_node,
7856 SymbolKind::Enum,
7857 java_scope_chain(&def_node, source),
7858 true,
7859 );
7860 }
7861 if let (Some(name_node), Some(def_node)) = (struct_name_node, struct_def_node) {
7862 push_captured_symbol(
7863 &mut symbols,
7864 source,
7865 lang,
7866 name_node,
7867 def_node,
7868 SymbolKind::Struct,
7869 java_scope_chain(&def_node, source),
7870 true,
7871 );
7872 }
7873 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
7874 let scope_chain = java_scope_chain(&def_node, source);
7875 let kind = if scope_chain.is_empty() {
7876 SymbolKind::Function
7877 } else {
7878 SymbolKind::Method
7879 };
7880 push_captured_symbol(
7881 &mut symbols,
7882 source,
7883 lang,
7884 name_node,
7885 def_node,
7886 kind,
7887 scope_chain,
7888 true,
7889 );
7890 }
7891 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
7892 push_captured_symbol(
7893 &mut symbols,
7894 source,
7895 lang,
7896 name_node,
7897 def_node,
7898 SymbolKind::Variable,
7899 java_scope_chain(&def_node, source),
7900 true,
7901 );
7902 }
7903 }
7904
7905 dedup_symbols(&mut symbols);
7906 Ok(symbols)
7907}
7908
7909fn ruby_scope_chain(node: &Node, source: &str) -> Vec<String> {
7910 let mut chain = Vec::new();
7911 let mut current = node.parent();
7912
7913 while let Some(parent) = current {
7914 if matches!(parent.kind(), "class" | "module") {
7915 if let Some(name_node) = parent.child_by_field_name("name") {
7916 chain.push(node_text(source, &name_node).to_string());
7917 }
7918 }
7919 current = parent.parent();
7920 }
7921
7922 chain.reverse();
7923 chain
7924}
7925
7926fn extract_ruby_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
7927 let lang = LangId::Ruby;
7928 let capture_names = query.capture_names();
7929 let mut symbols = Vec::new();
7930 let mut cursor = QueryCursor::new();
7931 let mut matches = cursor.matches(query, *root, source.as_bytes());
7932
7933 while let Some(m) = {
7934 matches.advance();
7935 matches.get()
7936 } {
7937 let mut module_name_node = None;
7938 let mut module_def_node = None;
7939 let mut class_name_node = None;
7940 let mut class_def_node = None;
7941 let mut fn_name_node = None;
7942 let mut fn_def_node = None;
7943 let mut var_name_node = None;
7944 let mut var_def_node = None;
7945
7946 for cap in m.captures {
7947 let Some(&name) = capture_names.get(cap.index as usize) else {
7948 continue;
7949 };
7950 match name {
7951 "module.name" => module_name_node = Some(cap.node),
7952 "module.def" => module_def_node = Some(cap.node),
7953 "class.name" => class_name_node = Some(cap.node),
7954 "class.def" => class_def_node = Some(cap.node),
7955 "fn.name" => fn_name_node = Some(cap.node),
7956 "fn.def" => fn_def_node = Some(cap.node),
7957 "var.name" => var_name_node = Some(cap.node),
7958 "var.def" => var_def_node = Some(cap.node),
7959 _ => {}
7960 }
7961 }
7962
7963 if let (Some(name_node), Some(def_node)) = (module_name_node, module_def_node) {
7964 push_captured_symbol(
7965 &mut symbols,
7966 source,
7967 lang,
7968 name_node,
7969 def_node,
7970 SymbolKind::Class,
7971 ruby_scope_chain(&def_node, source),
7972 true,
7973 );
7974 }
7975 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
7976 push_captured_symbol(
7977 &mut symbols,
7978 source,
7979 lang,
7980 name_node,
7981 def_node,
7982 SymbolKind::Class,
7983 ruby_scope_chain(&def_node, source),
7984 true,
7985 );
7986 }
7987 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
7988 let scope_chain = ruby_scope_chain(&def_node, source);
7989 let kind = if scope_chain.is_empty() {
7990 SymbolKind::Function
7991 } else {
7992 SymbolKind::Method
7993 };
7994 push_captured_symbol(
7995 &mut symbols,
7996 source,
7997 lang,
7998 name_node,
7999 def_node,
8000 kind,
8001 scope_chain,
8002 true,
8003 );
8004 }
8005 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
8006 push_captured_symbol(
8007 &mut symbols,
8008 source,
8009 lang,
8010 name_node,
8011 def_node,
8012 SymbolKind::Variable,
8013 ruby_scope_chain(&def_node, source),
8014 true,
8015 );
8016 }
8017 }
8018
8019 dedup_symbols(&mut symbols);
8020 Ok(symbols)
8021}
8022
8023fn kotlin_scope_chain(node: &Node, source: &str) -> Vec<String> {
8024 let mut chain = Vec::new();
8025 let mut current = node.parent();
8026
8027 while let Some(parent) = current {
8028 if matches!(parent.kind(), "class_declaration" | "object_declaration") {
8029 if let Some(name) =
8030 child_text_by_field_or_kind(&parent, source, "name", &["type_identifier"])
8031 {
8032 chain.push(name);
8033 }
8034 }
8035 current = parent.parent();
8036 }
8037
8038 chain.reverse();
8039 chain
8040}
8041
8042fn extract_kotlin_symbols(
8043 source: &str,
8044 root: &Node,
8045 query: &Query,
8046) -> Result<Vec<Symbol>, AftError> {
8047 let lang = LangId::Kotlin;
8048 let capture_names = query.capture_names();
8049 let mut symbols = Vec::new();
8050 let mut cursor = QueryCursor::new();
8051 let mut matches = cursor.matches(query, *root, source.as_bytes());
8052
8053 while let Some(m) = {
8054 matches.advance();
8055 matches.get()
8056 } {
8057 let mut class_name_node = None;
8058 let mut class_def_node = None;
8059 let mut object_name_node = None;
8060 let mut object_def_node = None;
8061 let mut fn_name_node = None;
8062 let mut fn_def_node = None;
8063 let mut var_name_node = None;
8064 let mut var_def_node = None;
8065 let mut type_name_node = None;
8066 let mut type_def_node = None;
8067
8068 for cap in m.captures {
8069 let Some(&name) = capture_names.get(cap.index as usize) else {
8070 continue;
8071 };
8072 match name {
8073 "class.name" => class_name_node = Some(cap.node),
8074 "class.def" => class_def_node = Some(cap.node),
8075 "object.name" => object_name_node = Some(cap.node),
8076 "object.def" => object_def_node = Some(cap.node),
8077 "fn.name" => fn_name_node = Some(cap.node),
8078 "fn.def" => fn_def_node = Some(cap.node),
8079 "var.name" => var_name_node = Some(cap.node),
8080 "var.def" => var_def_node = Some(cap.node),
8081 "type.name" => type_name_node = Some(cap.node),
8082 "type.def" => type_def_node = Some(cap.node),
8083 _ => {}
8084 }
8085 }
8086
8087 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
8088 push_captured_symbol(
8089 &mut symbols,
8090 source,
8091 lang,
8092 name_node,
8093 def_node,
8094 SymbolKind::Class,
8095 kotlin_scope_chain(&def_node, source),
8096 true,
8097 );
8098 }
8099 if let (Some(name_node), Some(def_node)) = (object_name_node, object_def_node) {
8100 push_captured_symbol(
8101 &mut symbols,
8102 source,
8103 lang,
8104 name_node,
8105 def_node,
8106 SymbolKind::Class,
8107 kotlin_scope_chain(&def_node, source),
8108 true,
8109 );
8110 }
8111 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
8112 let scope_chain = kotlin_scope_chain(&def_node, source);
8113 let kind = if scope_chain.is_empty() {
8114 SymbolKind::Function
8115 } else {
8116 SymbolKind::Method
8117 };
8118 push_captured_symbol(
8119 &mut symbols,
8120 source,
8121 lang,
8122 name_node,
8123 def_node,
8124 kind,
8125 scope_chain,
8126 true,
8127 );
8128 }
8129 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
8130 push_captured_symbol(
8131 &mut symbols,
8132 source,
8133 lang,
8134 name_node,
8135 def_node,
8136 SymbolKind::Variable,
8137 kotlin_scope_chain(&def_node, source),
8138 true,
8139 );
8140 }
8141 if let (Some(name_node), Some(def_node)) = (type_name_node, type_def_node) {
8142 push_captured_symbol(
8143 &mut symbols,
8144 source,
8145 lang,
8146 name_node,
8147 def_node,
8148 SymbolKind::TypeAlias,
8149 kotlin_scope_chain(&def_node, source),
8150 true,
8151 );
8152 }
8153 }
8154
8155 dedup_symbols(&mut symbols);
8156 Ok(symbols)
8157}
8158
8159fn swift_scope_chain(node: &Node, source: &str) -> Vec<String> {
8160 let mut chain = Vec::new();
8161 let mut current = node.parent();
8162
8163 while let Some(parent) = current {
8164 if matches!(parent.kind(), "class_declaration" | "protocol_declaration") {
8165 if let Some(name_node) = parent.child_by_field_name("name") {
8166 chain.push(node_text(source, &name_node).to_string());
8167 }
8168 }
8169 current = parent.parent();
8170 }
8171
8172 chain.reverse();
8173 chain
8174}
8175
8176fn swift_type_kind(source: &str, node: &Node) -> SymbolKind {
8177 match node
8178 .child_by_field_name("declaration_kind")
8179 .map(|kind_node| node_text(source, &kind_node))
8180 {
8181 Some("struct") => SymbolKind::Struct,
8182 Some("enum") => SymbolKind::Enum,
8183 _ => SymbolKind::Class,
8184 }
8185}
8186
8187fn extract_swift_symbols(
8188 source: &str,
8189 root: &Node,
8190 query: &Query,
8191) -> Result<Vec<Symbol>, AftError> {
8192 let lang = LangId::Swift;
8193 let capture_names = query.capture_names();
8194 let mut symbols = Vec::new();
8195 let mut cursor = QueryCursor::new();
8196 let mut matches = cursor.matches(query, *root, source.as_bytes());
8197
8198 while let Some(m) = {
8199 matches.advance();
8200 matches.get()
8201 } {
8202 let mut class_name_node = None;
8203 let mut class_def_node = None;
8204 let mut interface_name_node = None;
8205 let mut interface_def_node = None;
8206 let mut fn_name_node = None;
8207 let mut fn_def_node = None;
8208 let mut var_name_node = None;
8209 let mut var_def_node = None;
8210 let mut type_name_node = None;
8211 let mut type_def_node = None;
8212
8213 for cap in m.captures {
8214 let Some(&name) = capture_names.get(cap.index as usize) else {
8215 continue;
8216 };
8217 match name {
8218 "class.name" => class_name_node = Some(cap.node),
8219 "class.def" => class_def_node = Some(cap.node),
8220 "interface.name" => interface_name_node = Some(cap.node),
8221 "interface.def" => interface_def_node = Some(cap.node),
8222 "fn.name" => fn_name_node = Some(cap.node),
8223 "fn.def" => fn_def_node = Some(cap.node),
8224 "var.name" => var_name_node = Some(cap.node),
8225 "var.def" => var_def_node = Some(cap.node),
8226 "type.name" => type_name_node = Some(cap.node),
8227 "type.def" => type_def_node = Some(cap.node),
8228 _ => {}
8229 }
8230 }
8231
8232 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
8233 let kind = swift_type_kind(source, &def_node);
8234 push_captured_symbol(
8235 &mut symbols,
8236 source,
8237 lang,
8238 name_node,
8239 def_node,
8240 kind,
8241 swift_scope_chain(&def_node, source),
8242 true,
8243 );
8244 }
8245 if let (Some(name_node), Some(def_node)) = (interface_name_node, interface_def_node) {
8246 push_captured_symbol(
8247 &mut symbols,
8248 source,
8249 lang,
8250 name_node,
8251 def_node,
8252 SymbolKind::Interface,
8253 swift_scope_chain(&def_node, source),
8254 true,
8255 );
8256 }
8257 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
8258 let scope_chain = swift_scope_chain(&def_node, source);
8259 let kind = if scope_chain.is_empty() {
8260 SymbolKind::Function
8261 } else {
8262 SymbolKind::Method
8263 };
8264 push_captured_symbol(
8265 &mut symbols,
8266 source,
8267 lang,
8268 name_node,
8269 def_node,
8270 kind,
8271 scope_chain,
8272 true,
8273 );
8274 }
8275 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
8276 push_captured_symbol(
8277 &mut symbols,
8278 source,
8279 lang,
8280 name_node,
8281 def_node,
8282 SymbolKind::Variable,
8283 swift_scope_chain(&def_node, source),
8284 true,
8285 );
8286 }
8287 if let (Some(name_node), Some(def_node)) = (type_name_node, type_def_node) {
8288 push_captured_symbol(
8289 &mut symbols,
8290 source,
8291 lang,
8292 name_node,
8293 def_node,
8294 SymbolKind::TypeAlias,
8295 swift_scope_chain(&def_node, source),
8296 true,
8297 );
8298 }
8299 }
8300
8301 dedup_symbols(&mut symbols);
8302 Ok(symbols)
8303}
8304
8305fn php_scope_chain(node: &Node, source: &str) -> Vec<String> {
8306 let mut chain = Vec::new();
8307 let mut current = node.parent();
8308
8309 while let Some(parent) = current {
8310 match parent.kind() {
8311 "namespace_definition"
8312 | "class_declaration"
8313 | "interface_declaration"
8314 | "trait_declaration"
8315 | "enum_declaration" => {
8316 if let Some(name_node) = parent.child_by_field_name("name") {
8317 chain.push(node_text(source, &name_node).to_string());
8318 }
8319 }
8320 _ => {}
8321 }
8322 current = parent.parent();
8323 }
8324
8325 chain.reverse();
8326 chain
8327}
8328
8329fn extract_scss_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
8330 let lang = LangId::Scss;
8331 let capture_names = query.capture_names();
8332 let mut symbols = Vec::new();
8333 let mut cursor = QueryCursor::new();
8334 let mut matches = cursor.matches(query, *root, source.as_bytes());
8335
8336 while let Some(m) = {
8337 matches.advance();
8338 matches.get()
8339 } {
8340 let mut mixin_name_node = None;
8341 let mut mixin_def_node = None;
8342 let mut fn_name_node = None;
8343 let mut fn_def_node = None;
8344 let mut var_name_node = None;
8345 let mut var_def_node = None;
8346 let mut selector_name_node = None;
8347 let mut selector_def_node = None;
8348
8349 for cap in m.captures {
8350 let Some(&name) = capture_names.get(cap.index as usize) else {
8351 continue;
8352 };
8353 match name {
8354 "mixin.name" => mixin_name_node = Some(cap.node),
8355 "mixin.def" => mixin_def_node = Some(cap.node),
8356 "fn.name" => fn_name_node = Some(cap.node),
8357 "fn.def" => fn_def_node = Some(cap.node),
8358 "var.name" => var_name_node = Some(cap.node),
8359 "var.def" => var_def_node = Some(cap.node),
8360 "selector.name" => selector_name_node = Some(cap.node),
8361 "selector.def" => selector_def_node = Some(cap.node),
8362 _ => {}
8363 }
8364 }
8365
8366 if let (Some(name_node), Some(def_node)) = (mixin_name_node, mixin_def_node) {
8367 push_captured_symbol(
8368 &mut symbols,
8369 source,
8370 lang,
8371 name_node,
8372 def_node,
8373 SymbolKind::Function,
8374 vec![],
8375 true,
8376 );
8377 }
8378 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
8379 push_captured_symbol(
8380 &mut symbols,
8381 source,
8382 lang,
8383 name_node,
8384 def_node,
8385 SymbolKind::Function,
8386 vec![],
8387 true,
8388 );
8389 }
8390 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
8391 if !node_text(source, &name_node).starts_with('$') {
8392 continue;
8393 }
8394 push_captured_symbol(
8395 &mut symbols,
8396 source,
8397 lang,
8398 name_node,
8399 def_node,
8400 SymbolKind::Variable,
8401 vec![],
8402 true,
8403 );
8404 }
8405 if let (Some(name_node), Some(def_node)) = (selector_name_node, selector_def_node) {
8406 push_captured_symbol(
8407 &mut symbols,
8408 source,
8409 lang,
8410 name_node,
8411 def_node,
8412 SymbolKind::Class,
8413 vec![],
8414 true,
8415 );
8416 }
8417 }
8418
8419 Ok(symbols)
8420}
8421
8422fn extract_php_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
8423 let lang = LangId::Php;
8424 let capture_names = query.capture_names();
8425 let mut symbols = Vec::new();
8426 let mut cursor = QueryCursor::new();
8427 let mut matches = cursor.matches(query, *root, source.as_bytes());
8428
8429 while let Some(m) = {
8430 matches.advance();
8431 matches.get()
8432 } {
8433 let mut namespace_name_node = None;
8434 let mut namespace_def_node = None;
8435 let mut class_name_node = None;
8436 let mut class_def_node = None;
8437 let mut interface_name_node = None;
8438 let mut interface_def_node = None;
8439 let mut trait_name_node = None;
8440 let mut trait_def_node = None;
8441 let mut enum_name_node = None;
8442 let mut enum_def_node = None;
8443 let mut fn_name_node = None;
8444 let mut fn_def_node = None;
8445 let mut var_name_node = None;
8446 let mut var_def_node = None;
8447
8448 for cap in m.captures {
8449 let Some(&name) = capture_names.get(cap.index as usize) else {
8450 continue;
8451 };
8452 match name {
8453 "namespace.name" => namespace_name_node = Some(cap.node),
8454 "namespace.def" => namespace_def_node = Some(cap.node),
8455 "class.name" => class_name_node = Some(cap.node),
8456 "class.def" => class_def_node = Some(cap.node),
8457 "interface.name" => interface_name_node = Some(cap.node),
8458 "interface.def" => interface_def_node = Some(cap.node),
8459 "trait.name" => trait_name_node = Some(cap.node),
8460 "trait.def" => trait_def_node = Some(cap.node),
8461 "enum.name" => enum_name_node = Some(cap.node),
8462 "enum.def" => enum_def_node = Some(cap.node),
8463 "fn.name" => fn_name_node = Some(cap.node),
8464 "fn.def" => fn_def_node = Some(cap.node),
8465 "var.name" => var_name_node = Some(cap.node),
8466 "var.def" => var_def_node = Some(cap.node),
8467 _ => {}
8468 }
8469 }
8470
8471 if let (Some(name_node), Some(def_node)) = (namespace_name_node, namespace_def_node) {
8472 push_captured_symbol(
8473 &mut symbols,
8474 source,
8475 lang,
8476 name_node,
8477 def_node,
8478 SymbolKind::Class,
8479 php_scope_chain(&def_node, source),
8480 true,
8481 );
8482 }
8483 if let (Some(name_node), Some(def_node)) = (class_name_node, class_def_node) {
8484 push_captured_symbol(
8485 &mut symbols,
8486 source,
8487 lang,
8488 name_node,
8489 def_node,
8490 SymbolKind::Class,
8491 php_scope_chain(&def_node, source),
8492 true,
8493 );
8494 }
8495 if let (Some(name_node), Some(def_node)) = (interface_name_node, interface_def_node) {
8496 push_captured_symbol(
8497 &mut symbols,
8498 source,
8499 lang,
8500 name_node,
8501 def_node,
8502 SymbolKind::Interface,
8503 php_scope_chain(&def_node, source),
8504 true,
8505 );
8506 }
8507 if let (Some(name_node), Some(def_node)) = (trait_name_node, trait_def_node) {
8508 push_captured_symbol(
8509 &mut symbols,
8510 source,
8511 lang,
8512 name_node,
8513 def_node,
8514 SymbolKind::Interface,
8515 php_scope_chain(&def_node, source),
8516 true,
8517 );
8518 }
8519 if let (Some(name_node), Some(def_node)) = (enum_name_node, enum_def_node) {
8520 push_captured_symbol(
8521 &mut symbols,
8522 source,
8523 lang,
8524 name_node,
8525 def_node,
8526 SymbolKind::Enum,
8527 php_scope_chain(&def_node, source),
8528 true,
8529 );
8530 }
8531 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
8532 let scope_chain = php_scope_chain(&def_node, source);
8533 let kind = if scope_chain.is_empty() || def_node.kind() == "function_definition" {
8534 SymbolKind::Function
8535 } else {
8536 SymbolKind::Method
8537 };
8538 push_captured_symbol(
8539 &mut symbols,
8540 source,
8541 lang,
8542 name_node,
8543 def_node,
8544 kind,
8545 scope_chain,
8546 true,
8547 );
8548 }
8549 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
8550 push_captured_symbol(
8551 &mut symbols,
8552 source,
8553 lang,
8554 name_node,
8555 def_node,
8556 SymbolKind::Variable,
8557 php_scope_chain(&def_node, source),
8558 true,
8559 );
8560 }
8561 }
8562
8563 dedup_symbols(&mut symbols);
8564 Ok(symbols)
8565}
8566
8567fn lua_scope_chain(node: &Node, source: &str) -> Vec<String> {
8568 let mut chain = Vec::new();
8569
8570 if node.kind() == "function_declaration" {
8571 if let Some(name_node) = node.child_by_field_name("name") {
8572 match name_node.kind() {
8573 "dot_index_expression" | "method_index_expression" => {
8574 if let Some(table_node) = name_node.child_by_field_name("table") {
8575 chain.push(node_text(source, &table_node).to_string());
8576 }
8577 }
8578 _ => {}
8579 }
8580 }
8581 }
8582
8583 chain
8584}
8585
8586pub fn luau_symbol(source: &str, declaration: crate::luau::Declaration<'_>) -> Symbol {
8587 let mut symbols = Vec::new();
8588 push_captured_symbol(
8589 &mut symbols,
8590 source,
8591 LangId::Luau,
8592 declaration.name,
8593 declaration.definition,
8594 declaration.kind,
8595 declaration.parent.into_iter().collect(),
8596 declaration.exported,
8597 );
8598 symbols.remove(0)
8599}
8600
8601fn extract_lua_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
8602 let lang = LangId::Lua;
8603 let capture_names = query.capture_names();
8604 let mut symbols = Vec::new();
8605 let mut cursor = QueryCursor::new();
8606 let mut matches = cursor.matches(query, *root, source.as_bytes());
8607
8608 while let Some(m) = {
8609 matches.advance();
8610 matches.get()
8611 } {
8612 let mut fn_name_node = None;
8613 let mut fn_def_node = None;
8614 let mut var_name_node = None;
8615 let mut var_def_node = None;
8616
8617 for cap in m.captures {
8618 let Some(&name) = capture_names.get(cap.index as usize) else {
8619 continue;
8620 };
8621 match name {
8622 "fn.name" => fn_name_node = Some(cap.node),
8623 "fn.def" => fn_def_node = Some(cap.node),
8624 "var.name" => var_name_node = Some(cap.node),
8625 "var.def" => var_def_node = Some(cap.node),
8626 _ => {}
8627 }
8628 }
8629
8630 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
8631 let scope_chain = lua_scope_chain(&def_node, source);
8632 let kind = if scope_chain.is_empty() {
8633 SymbolKind::Function
8634 } else {
8635 SymbolKind::Method
8636 };
8637 push_captured_symbol(
8638 &mut symbols,
8639 source,
8640 lang,
8641 name_node,
8642 def_node,
8643 kind,
8644 scope_chain,
8645 true,
8646 );
8647 }
8648 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
8649 push_captured_symbol(
8650 &mut symbols,
8651 source,
8652 lang,
8653 name_node,
8654 def_node,
8655 SymbolKind::Variable,
8656 vec![],
8657 true,
8658 );
8659 }
8660 }
8661
8662 dedup_symbols(&mut symbols);
8663 Ok(symbols)
8664}
8665
8666fn perl_package_name(source: &str, node: &Node) -> Option<String> {
8667 let mut cursor = node.walk();
8668 if !cursor.goto_first_child() {
8669 return None;
8670 }
8671
8672 loop {
8673 let child = cursor.node();
8674 if child.kind() == "package" {
8675 return Some(node_text(source, &child).to_string());
8676 }
8677 if !cursor.goto_next_sibling() {
8678 break;
8679 }
8680 }
8681
8682 None
8683}
8684
8685fn perl_scope_chain(node: &Node, source: &str) -> Vec<String> {
8686 let mut chain = Vec::new();
8687 let mut current = node.parent();
8688
8689 while let Some(parent) = current {
8690 if parent.kind() == "package_statement" {
8691 if let Some(name) = perl_package_name(source, &parent) {
8692 chain.push(name);
8693 }
8694 }
8695 current = parent.parent();
8696 }
8697
8698 if chain.is_empty() && node.kind() != "package_statement" {
8699 let mut sibling = node.prev_sibling();
8700 while let Some(prev) = sibling {
8701 if prev.kind() == "package_statement" {
8702 if let Some(name) = perl_package_name(source, &prev) {
8703 chain.push(name);
8704 }
8705 break;
8706 }
8707 sibling = prev.prev_sibling();
8708 }
8709 }
8710
8711 chain.reverse();
8712 chain
8713}
8714
8715fn extract_perl_symbols(source: &str, root: &Node, query: &Query) -> Result<Vec<Symbol>, AftError> {
8716 let lang = LangId::Perl;
8717 let capture_names = query.capture_names();
8718 let mut symbols = Vec::new();
8719 let mut cursor = QueryCursor::new();
8720 let mut matches = cursor.matches(query, *root, source.as_bytes());
8721
8722 while let Some(m) = {
8723 matches.advance();
8724 matches.get()
8725 } {
8726 let mut package_name_node = None;
8727 let mut package_def_node = None;
8728 let mut fn_name_node = None;
8729 let mut fn_def_node = None;
8730 let mut var_name_node = None;
8731 let mut var_def_node = None;
8732 let mut const_pragma_node = None;
8733 let mut const_name_node = None;
8734 let mut const_def_node = None;
8735
8736 for cap in m.captures {
8737 let Some(&name) = capture_names.get(cap.index as usize) else {
8738 continue;
8739 };
8740 match name {
8741 "package.name" => package_name_node = Some(cap.node),
8742 "package.def" => package_def_node = Some(cap.node),
8743 "fn.name" => fn_name_node = Some(cap.node),
8744 "fn.def" => fn_def_node = Some(cap.node),
8745 "var.name" => var_name_node = Some(cap.node),
8746 "var.def" => var_def_node = Some(cap.node),
8747 "const.pragma" => const_pragma_node = Some(cap.node),
8748 "const.name" => const_name_node = Some(cap.node),
8749 "const.def" => const_def_node = Some(cap.node),
8750 _ => {}
8751 }
8752 }
8753
8754 if let (Some(pragma_node), Some(name_node), Some(def_node)) =
8759 (const_pragma_node, const_name_node, const_def_node)
8760 {
8761 if node_text(source, &pragma_node) == "constant" {
8762 var_name_node = Some(name_node);
8763 var_def_node = Some(def_node);
8764 }
8765 }
8766
8767 if let (Some(name_node), Some(def_node)) = (package_name_node, package_def_node) {
8768 push_captured_symbol(
8769 &mut symbols,
8770 source,
8771 lang,
8772 name_node,
8773 def_node,
8774 SymbolKind::Class,
8775 vec![],
8776 true,
8777 );
8778 }
8779 if let (Some(name_node), Some(def_node)) = (fn_name_node, fn_def_node) {
8780 let scope_chain = perl_scope_chain(&def_node, source);
8781 let kind = if scope_chain.is_empty() {
8782 SymbolKind::Function
8783 } else {
8784 SymbolKind::Method
8785 };
8786 push_captured_symbol(
8787 &mut symbols,
8788 source,
8789 lang,
8790 name_node,
8791 def_node,
8792 kind,
8793 scope_chain,
8794 true,
8795 );
8796 }
8797 if let (Some(name_node), Some(def_node)) = (var_name_node, var_def_node) {
8798 push_captured_symbol(
8799 &mut symbols,
8800 source,
8801 lang,
8802 name_node,
8803 def_node,
8804 SymbolKind::Variable,
8805 perl_scope_chain(&def_node, source),
8806 true,
8807 );
8808 }
8809 }
8810
8811 dedup_symbols(&mut symbols);
8812 Ok(symbols)
8813}
8814
8815fn extract_vue_symbols(source: &str, root: &Node) -> Result<Vec<Symbol>, AftError> {
8816 let mut symbols = Vec::new();
8817 collect_vue_sections(source, root, &mut symbols, true);
8818 dedup_symbols(&mut symbols);
8819 Ok(symbols)
8820}
8821
8822fn collect_vue_sections(
8828 source: &str,
8829 node: &Node,
8830 symbols: &mut Vec<Symbol>,
8831 allow_sections: bool,
8832) {
8833 fn push_children<'tree>(
8836 pending: &mut Vec<(Node<'tree>, bool)>,
8837 parent: Node<'tree>,
8838 allow_sections: bool,
8839 ) {
8840 let start = pending.len();
8841 pending.extend(
8842 parent
8843 .children(&mut parent.walk())
8844 .map(|child| (child, allow_sections)),
8845 );
8846 pending[start..].reverse();
8847 }
8848
8849 let mut pending = Vec::new();
8850 push_children(&mut pending, *node, allow_sections);
8851 while let Some((child, allow_sections)) = pending.pop() {
8852 if let Some(section_name) = vue_section_name(&child) {
8853 if allow_sections {
8854 symbols.push(Symbol {
8855 name: section_name.to_string(),
8856 kind: SymbolKind::Heading,
8857 range: node_range(&child),
8858 signature: vue_opening_tag_signature(source, &child),
8859 scope_chain: vec![],
8860 exported: false,
8861 parent: None,
8862 });
8863 }
8864 } else {
8865 push_children(
8866 &mut pending,
8867 child,
8868 allow_sections && child.kind() == "document",
8869 );
8870 }
8871 }
8872}
8873
8874fn vue_section_name(node: &Node) -> Option<&'static str> {
8875 match node.kind() {
8876 "template_element" => Some("template"),
8877 "script_element" => Some("script"),
8878 "style_element" => Some("style"),
8879 _ => None,
8880 }
8881}
8882
8883fn vue_opening_tag_signature(source: &str, node: &Node) -> Option<String> {
8884 find_child_by_kind(*node, "start_tag")
8885 .or_else(|| find_child_by_kind(*node, "script_start_tag"))
8886 .or_else(|| find_child_by_kind(*node, "style_start_tag"))
8887 .or_else(|| find_child_by_kind(*node, "template_start_tag"))
8888 .map(|tag| node_text(source, &tag).trim().to_string())
8889}
8890
8891#[cfg(any(test, feature = "test-support"))]
8892thread_local! {
8893 pub static HEADING_COLUMN_LINE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
8894}
8895
8896test_support_visibility! {
8897fn source_line_end_cols(source: &str) -> Vec<u32> {
8898 source
8899 .lines()
8900 .map(|line| {
8901 #[cfg(any(test, feature = "test-support"))]
8902 HEADING_COLUMN_LINE_VISITS.with(|visits| visits.set(visits.get() + 1));
8903 line.len() as u32
8904 })
8905 .collect()
8906}
8907}
8908
8909fn extract_html_symbols(source: &str, root: &Node) -> Result<Vec<Symbol>, AftError> {
8910 let mut headings = Vec::new();
8911 collect_html_headings(source, root, &mut headings);
8912
8913 let end_cols = source_line_end_cols(source);
8914 let total_lines = end_cols.len() as u32;
8915
8916 for i in 0..headings.len() {
8920 let level = headings[i].level;
8921 let section_end = headings[i + 1..]
8922 .iter()
8923 .find(|heading| heading.level <= level)
8924 .map(|heading| heading.symbol.range.start_line.saturating_sub(1))
8925 .unwrap_or_else(|| total_lines.saturating_sub(1))
8926 .max(headings[i].symbol.range.start_line);
8927 headings[i].symbol.range.end_line = section_end;
8928 if section_end != headings[i].symbol.range.start_line {
8929 headings[i].symbol.range.end_col =
8930 end_cols.get(section_end as usize).copied().unwrap_or(0);
8931 }
8932 }
8933
8934 let mut scope_stack: Vec<(u8, String)> = Vec::new(); for heading in &mut headings {
8937 while scope_stack
8939 .last()
8940 .is_some_and(|(level, _)| *level >= heading.level)
8941 {
8942 scope_stack.pop();
8943 }
8944 heading.symbol.scope_chain = scope_stack.iter().map(|(_, name)| name.clone()).collect();
8945 heading.symbol.parent = scope_stack.last().map(|(_, name)| name.clone());
8946 scope_stack.push((heading.level, heading.symbol.name.clone()));
8947 }
8948
8949 Ok(headings.into_iter().map(|heading| heading.symbol).collect())
8950}
8951
8952struct HtmlHeading {
8954 level: u8,
8955 symbol: Symbol,
8956 anchor_id: Option<String>,
8957}
8958
8959fn collect_html_headings(source: &str, node: &Node, headings: &mut Vec<HtmlHeading>) {
8964 let mut cursor = node.walk();
8965 if !cursor.goto_first_child() {
8966 return;
8967 }
8968
8969 loop {
8970 let child = cursor.node();
8971 if child.kind() == "element" {
8972 if let Some(start_tag) = child
8974 .child_by_field_name("start_tag")
8975 .or_else(|| child.child(0).filter(|c| c.kind() == "start_tag"))
8976 {
8977 if let Some(tag_name_node) = start_tag
8978 .child_by_field_name("tag_name")
8979 .or_else(|| start_tag.child(1).filter(|c| c.kind() == "tag_name"))
8980 {
8981 let tag_name = node_text(source, &tag_name_node).to_lowercase();
8982 if let Some(level) = match tag_name.as_str() {
8983 "h1" => Some(1u8),
8984 "h2" => Some(2),
8985 "h3" => Some(3),
8986 "h4" => Some(4),
8987 "h5" => Some(5),
8988 "h6" => Some(6),
8989 _ => None,
8990 } {
8991 let text = extract_element_text(source, &child).trim().to_string();
8993 if !text.is_empty() {
8994 let range = node_range(&child);
8995 let signature = format!("<h{}> {}", level, text);
8996 headings.push(HtmlHeading {
8997 level,
8998 anchor_id: html_heading_anchor_id(source, &start_tag),
8999 symbol: Symbol {
9000 name: text,
9001 kind: SymbolKind::Heading,
9002 range,
9003 signature: Some(signature),
9004 scope_chain: vec![], exported: false,
9006 parent: None, },
9008 });
9009 }
9010 }
9011 }
9012 }
9013 }
9014 if cursor.goto_first_child() {
9017 continue;
9018 }
9019 while !cursor.goto_next_sibling() {
9022 if !cursor.goto_parent() || cursor.node().id() == node.id() {
9023 return;
9024 }
9025 }
9026 }
9027}
9028
9029fn extract_html_heading_anchors(source: &str, root: &Node) -> Vec<crate::language::HeadingAnchor> {
9030 let mut headings = Vec::new();
9031 collect_html_headings(source, root, &mut headings);
9032 headings
9033 .into_iter()
9034 .filter_map(|heading| {
9035 heading.anchor_id.map(|id| crate::language::HeadingAnchor {
9036 start_line: heading.symbol.range.start_line,
9037 start_col: heading.symbol.range.start_col,
9038 id,
9039 })
9040 })
9041 .collect()
9042}
9043
9044fn html_heading_anchor_id(source: &str, start_tag: &Node) -> Option<String> {
9045 for expected_name in ["id", "name"] {
9046 let mut cursor = start_tag.walk();
9047 for attribute in start_tag.named_children(&mut cursor) {
9048 if attribute.kind() != "attribute" {
9049 continue;
9050 }
9051 let Some(name_node) = attribute
9052 .child_by_field_name("name")
9053 .or_else(|| find_child_by_kind(attribute, "attribute_name"))
9054 else {
9055 continue;
9056 };
9057 if !node_text(source, &name_node).eq_ignore_ascii_case(expected_name) {
9058 continue;
9059 }
9060 let Some(value_node) = attribute
9061 .child_by_field_name("value")
9062 .or_else(|| find_child_by_kind(attribute, "quoted_attribute_value"))
9063 .or_else(|| find_child_by_kind(attribute, "attribute_value"))
9064 else {
9065 continue;
9066 };
9067 let raw_value = node_text(source, &value_node).trim();
9068 let value = raw_value
9069 .strip_prefix('"')
9070 .and_then(|value| value.strip_suffix('"'))
9071 .or_else(|| {
9072 raw_value
9073 .strip_prefix('\'')
9074 .and_then(|value| value.strip_suffix('\''))
9075 })
9076 .unwrap_or(raw_value)
9077 .trim();
9078 if !value.is_empty() {
9079 return Some(value.to_string());
9080 }
9081 }
9082 }
9083 None
9084}
9085
9086fn extract_element_text(source: &str, node: &Node) -> String {
9091 let mut text = String::new();
9092 let mut cursor = node.walk();
9093 if !cursor.goto_first_child() {
9094 return text;
9095 }
9096 loop {
9097 let child = cursor.node();
9098 match child.kind() {
9099 "text" => {
9100 text.push_str(node_text(source, &child));
9101 }
9102 "element" if cursor.goto_first_child() => continue,
9103 _ => {}
9104 }
9105 while !cursor.goto_next_sibling() {
9108 if !cursor.goto_parent() || cursor.node().id() == node.id() {
9109 return text;
9110 }
9111 }
9112 }
9113}
9114
9115struct RawHeading {
9116 name: String,
9117 level: u8,
9118 range: Range,
9119}
9120
9121fn parse_atx_heading(source: &str, node: &Node) -> Option<(String, u8)> {
9122 let mut heading_level = 1;
9123 let mut heading_name = String::new();
9124 let mut cursor = node.walk();
9125 if cursor.goto_first_child() {
9126 loop {
9127 let child = cursor.node();
9128 let kind = child.kind();
9129 if kind.starts_with("atx_h") && kind.ends_with("_marker") {
9130 heading_level = kind
9131 .strip_prefix("atx_h")
9132 .and_then(|s| s.strip_suffix("_marker"))
9133 .and_then(|s| s.parse::<u8>().ok())
9134 .unwrap_or(1);
9135 } else if kind == "inline" {
9136 heading_name = node_text(source, &child).trim().to_string();
9137 }
9138 if !cursor.goto_next_sibling() {
9139 break;
9140 }
9141 }
9142 }
9143 if heading_name.is_empty() {
9144 None
9145 } else {
9146 Some((heading_name, heading_level))
9147 }
9148}
9149
9150fn parse_setext_heading(source: &str, node: &Node) -> Option<(String, u8)> {
9151 let mut heading_level = 1;
9152 let mut heading_name = String::new();
9153 let mut cursor = node.walk();
9154 if cursor.goto_first_child() {
9155 loop {
9156 let child = cursor.node();
9157 let kind = child.kind();
9158 if kind.starts_with("setext_h") && kind.ends_with("_underline") {
9159 heading_level = kind
9160 .strip_prefix("setext_h")
9161 .and_then(|s| s.strip_suffix("_underline"))
9162 .and_then(|s| s.parse::<u8>().ok())
9163 .unwrap_or(1);
9164 } else if kind == "paragraph" {
9165 heading_name = node_text(source, &child).trim().to_string();
9166 }
9167 if !cursor.goto_next_sibling() {
9168 break;
9169 }
9170 }
9171 }
9172 if heading_name.is_empty() {
9173 None
9174 } else {
9175 Some((heading_name, heading_level))
9176 }
9177}
9178
9179fn collect_headings(source: &str, node: &Node, headings: &mut Vec<RawHeading>) {
9184 let mut cursor = node.walk();
9185 loop {
9186 let current = cursor.node();
9187 let kind = current.kind();
9188 let heading = if kind == "atx_heading" {
9189 Some(parse_atx_heading(source, ¤t))
9190 } else if kind == "setext_heading" {
9191 Some(parse_setext_heading(source, ¤t))
9192 } else {
9193 None
9194 };
9195 match heading {
9196 Some(parsed) => {
9197 if let Some((name, level)) = parsed {
9198 headings.push(RawHeading {
9199 name,
9200 level,
9201 range: node_range(¤t),
9202 });
9203 }
9204 }
9205 None if cursor.goto_first_child() => continue,
9206 None => {}
9207 }
9208 while !cursor.goto_next_sibling() {
9211 if !cursor.goto_parent() {
9212 return;
9213 }
9214 }
9215 }
9216}
9217
9218fn extract_md_symbols(source: &str, root: &Node) -> Result<Vec<Symbol>, AftError> {
9222 let mut raw_headings = Vec::new();
9223 collect_headings(source, root, &mut raw_headings);
9224
9225 let mut symbols = Vec::new();
9226 let end_cols = source_line_end_cols(source);
9227 let total_lines = end_cols.len() as u32;
9228
9229 let mut active_headings: Vec<Option<String>> = vec![None; 7];
9230
9231 for i in 0..raw_headings.len() {
9232 let h = &raw_headings[i];
9233 let level = h.level as usize;
9234
9235 let mut scope_chain = Vec::new();
9237 for l in 1..level {
9238 if let Some(ref name) = active_headings[l] {
9239 scope_chain.push(name.clone());
9240 }
9241 }
9242
9243 active_headings[level] = Some(h.name.clone());
9245 for l in (level + 1)..7 {
9246 active_headings[l] = None;
9247 }
9248
9249 let start_line = h.range.start_line;
9251 let start_col = h.range.start_col;
9252
9253 let mut end_line = total_lines.saturating_sub(1);
9255 let mut end_col = if total_lines > 0 {
9256 end_cols.get(end_line as usize).copied().unwrap_or(0)
9257 } else {
9258 0
9259 };
9260
9261 for j in (i + 1)..raw_headings.len() {
9262 if raw_headings[j].level <= h.level {
9263 let next_start_line = raw_headings[j].range.start_line;
9265 end_line = next_start_line.saturating_sub(1).max(start_line);
9266 end_col = end_cols.get(end_line as usize).copied().unwrap_or(0);
9267 break;
9268 }
9269 }
9270
9271 let signature = format!("{} {}", "#".repeat((h.level as usize).min(6)), h.name);
9272
9273 symbols.push(Symbol {
9274 name: h.name.clone(),
9275 kind: SymbolKind::Heading,
9276 range: Range {
9277 start_line,
9278 start_col,
9279 end_line,
9280 end_col,
9281 },
9282 signature: Some(signature),
9283 scope_chain: scope_chain.clone(),
9284 exported: false,
9285 parent: scope_chain.last().cloned(),
9286 });
9287 }
9288
9289 Ok(symbols)
9290}
9291
9292test_support_visibility! {
9293fn dedup_symbols(symbols: &mut Vec<Symbol>) {
9297 let keep: Vec<bool> = {
9300 let mut seen = std::collections::HashSet::with_capacity(symbols.len());
9301 symbols
9302 .iter()
9303 .map(|s| seen.insert((s.name.as_str(), &s.kind, s.range.start_line)))
9304 .collect()
9305 };
9306 let mut keep = keep.into_iter();
9307 symbols.retain(|_| keep.next().unwrap_or(true));
9308}
9309}
9310
9311pub struct TreeSitterProvider {
9314 symbol_cache: SharedSymbolCache,
9315}
9316
9317pub fn list_symbols_shared(
9320 provider: &dyn crate::language::LanguageProvider,
9321 file: &Path,
9322 dynamic_languages: bool,
9323) -> Result<Arc<Vec<Symbol>>, AftError> {
9324 if let Some(provider) = provider.as_any().downcast_ref::<TreeSitterProvider>() {
9325 FileParser::with_symbol_cache(provider.symbol_cache())
9326 .with_dynamic_languages(dynamic_languages)
9327 .extract_symbols_shared(file)
9328 } else {
9329 provider.list_symbols(file).map(Arc::new)
9330 }
9331}
9332
9333#[derive(Debug, Clone)]
9334struct ReExportTarget {
9335 file: PathBuf,
9336 symbol_name: String,
9337}
9338
9339impl TreeSitterProvider {
9340 pub fn new() -> Self {
9342 Self::with_symbol_cache(Arc::new(RwLock::new(SymbolCache::new())))
9343 }
9344
9345 pub fn with_symbol_cache(symbol_cache: SharedSymbolCache) -> Self {
9347 Self { symbol_cache }
9348 }
9349
9350 pub fn symbol_cache_len(&self) -> usize {
9352 self.symbol_cache
9353 .read()
9354 .map(|cache| cache.len())
9355 .unwrap_or(0)
9356 }
9357
9358 pub fn symbol_cache(&self) -> SharedSymbolCache {
9360 Arc::clone(&self.symbol_cache)
9361 }
9362
9363 fn resolve_symbol_inner(
9364 &self,
9365 parser: &mut FileParser,
9366 file: &Path,
9367 name: &str,
9368 depth: usize,
9369 visited: &mut HashSet<(PathBuf, String)>,
9370 ) -> Result<Vec<SymbolMatch>, AftError> {
9371 if depth > MAX_REEXPORT_DEPTH {
9372 return Ok(Vec::new());
9373 }
9374
9375 let canonical_file = std::fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf());
9376 if !visited.insert((canonical_file, name.to_string())) {
9377 return Ok(Vec::new());
9378 }
9379
9380 let symbols = parser.extract_symbols_shared(file)?;
9381 let local_matches = symbol_matches_in_file(file, &symbols, name);
9382 if !local_matches.is_empty() {
9383 return Ok(local_matches);
9384 }
9385
9386 if !matches!(
9389 detect_language(file),
9390 Some(LangId::TypeScript | LangId::Tsx | LangId::JavaScript)
9391 ) {
9392 return Ok(Vec::new());
9393 }
9394
9395 let parsed = self.read_parsed_file(parser, file)?;
9398 if name == "default" {
9399 let default_matches = self.resolve_local_default_export(&parsed, file, &symbols)?;
9400 if !default_matches.is_empty() {
9401 return Ok(default_matches);
9402 }
9403 }
9404
9405 let reexport_targets = self.collect_reexport_targets(&parsed, file, name)?;
9406 let mut matches = Vec::new();
9407 let mut seen = HashSet::new();
9408 for target in reexport_targets {
9409 for resolved in self.resolve_symbol_inner(
9410 parser,
9411 &target.file,
9412 &target.symbol_name,
9413 depth + 1,
9414 visited,
9415 )? {
9416 let key = format!(
9417 "{}:{}:{}:{}:{}:{}",
9418 resolved.file,
9419 resolved.symbol.name,
9420 resolved.symbol.range.start_line,
9421 resolved.symbol.range.start_col,
9422 resolved.symbol.range.end_line,
9423 resolved.symbol.range.end_col
9424 );
9425 if seen.insert(key) {
9426 matches.push(resolved);
9427 }
9428 }
9429 }
9430
9431 Ok(matches)
9432 }
9433
9434 fn collect_reexport_targets(
9435 &self,
9436 (source, tree, lang): &(String, Tree, LangId),
9437 file: &Path,
9438 requested_name: &str,
9439 ) -> Result<Vec<ReExportTarget>, AftError> {
9440 let (source, lang) = (source.as_str(), *lang);
9441 if !matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
9442 return Ok(Vec::new());
9443 }
9444
9445 let mut targets = Vec::new();
9446 let root = tree.root_node();
9447 let from_dir = file.parent().unwrap_or_else(|| Path::new("."));
9448
9449 let mut cursor = root.walk();
9450 if !cursor.goto_first_child() {
9451 return Ok(targets);
9452 }
9453
9454 loop {
9455 let node = cursor.node();
9456 if node.kind() == "export_statement" {
9457 let Some(source_node) = node.child_by_field_name("source") else {
9458 if let Some(export_clause) = find_child_by_kind(node, "export_clause") {
9459 if let Some(symbol_name) =
9460 resolve_export_clause_name(&source, &export_clause, requested_name)
9461 {
9462 targets.push(ReExportTarget {
9463 file: file.to_path_buf(),
9464 symbol_name,
9465 });
9466 }
9467 }
9468 if !cursor.goto_next_sibling() {
9469 break;
9470 }
9471 continue;
9472 };
9473
9474 let Some(module_path) = string_content(&source, &source_node) else {
9475 if !cursor.goto_next_sibling() {
9476 break;
9477 }
9478 continue;
9479 };
9480
9481 let Some(target_file) = resolve_module_path(from_dir, &module_path) else {
9482 if !cursor.goto_next_sibling() {
9483 break;
9484 }
9485 continue;
9486 };
9487
9488 if let Some(export_clause) = find_child_by_kind(node, "export_clause") {
9489 if let Some(symbol_name) =
9490 resolve_export_clause_name(&source, &export_clause, requested_name)
9491 {
9492 targets.push(ReExportTarget {
9493 file: target_file,
9494 symbol_name,
9495 });
9496 }
9497 } else if export_statement_has_wildcard(&source, &node) {
9498 targets.push(ReExportTarget {
9499 file: target_file,
9500 symbol_name: requested_name.to_string(),
9501 });
9502 }
9503 }
9504
9505 if !cursor.goto_next_sibling() {
9506 break;
9507 }
9508 }
9509
9510 Ok(targets)
9511 }
9512
9513 fn resolve_local_default_export(
9514 &self,
9515 (source, tree, lang): &(String, Tree, LangId),
9516 file: &Path,
9517 symbols: &[Symbol],
9518 ) -> Result<Vec<SymbolMatch>, AftError> {
9519 let (source, lang) = (source.as_str(), *lang);
9520 if !matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
9521 return Ok(Vec::new());
9522 }
9523
9524 let root = tree.root_node();
9525 let mut matches = Vec::new();
9526 let mut seen = HashSet::new();
9527
9528 let mut cursor = root.walk();
9529 if !cursor.goto_first_child() {
9530 return Ok(matches);
9531 }
9532
9533 loop {
9534 let node = cursor.node();
9535 if node.kind() == "export_statement"
9536 && node.child_by_field_name("source").is_none()
9537 && node_contains_token(&source, &node, "default")
9538 {
9539 if let Some(target_name) = default_export_target_name(&source, &node) {
9540 for symbol_match in symbol_matches_in_file(file, symbols, &target_name) {
9541 let key = format!(
9542 "{}:{}:{}:{}:{}:{}",
9543 symbol_match.file,
9544 symbol_match.symbol.name,
9545 symbol_match.symbol.range.start_line,
9546 symbol_match.symbol.range.start_col,
9547 symbol_match.symbol.range.end_line,
9548 symbol_match.symbol.range.end_col
9549 );
9550 if seen.insert(key) {
9551 matches.push(symbol_match);
9552 }
9553 }
9554 }
9555 }
9556
9557 if !cursor.goto_next_sibling() {
9558 break;
9559 }
9560 }
9561
9562 Ok(matches)
9563 }
9564
9565 fn read_parsed_file(
9566 &self,
9567 parser: &mut FileParser,
9568 file: &Path,
9569 ) -> Result<(String, Tree, LangId), AftError> {
9570 #[cfg(any(test, feature = "test-support"))]
9571 work_counters::PARSED_FILE_READS.with(|count| count.set(count.get() + 1));
9572 let current_mtime = crate::bounded_io::metadata(file)
9573 .and_then(|m| m.modified())
9574 .map_err(|e| AftError::FileNotFound {
9575 path: format!("{}: {}", file.display(), e),
9576 })?;
9577 let source =
9578 crate::bounded_io::read_to_string(file).map_err(|e| AftError::FileNotFound {
9579 path: format!("{}: {}", file.display(), e),
9580 })?;
9581 let size = source.len() as u64;
9582 let content_hash = content_hash_for_source(&source);
9583 let (tree, lang) =
9584 parser.parse_with_source(file, &source, current_mtime, size, content_hash)?;
9585 Ok((source, tree.clone(), lang))
9586 }
9587}
9588
9589fn symbol_matches_in_file(file: &Path, symbols: &[Symbol], name: &str) -> Vec<SymbolMatch> {
9590 symbols
9591 .iter()
9592 .filter(|symbol| symbol_query_matches(symbol, name))
9593 .cloned()
9594 .map(|symbol| SymbolMatch {
9595 file: file.display().to_string(),
9596 symbol,
9597 })
9598 .collect()
9599}
9600
9601fn symbol_query_matches(symbol: &Symbol, query: &str) -> bool {
9602 if symbol.name == query {
9603 return true;
9604 }
9605
9606 if !query.contains('.') && !query.contains("::") {
9607 return false;
9608 }
9609
9610 let mut parts = symbol
9611 .scope_chain
9612 .iter()
9613 .filter(|part| !part.is_empty())
9614 .map(String::as_str)
9615 .collect::<Vec<_>>();
9616 if parts.is_empty() {
9617 return false;
9618 }
9619 parts.push(symbol.name.as_str());
9620
9621 parts.join(".") == query || parts.join("::") == query
9622}
9623
9624fn string_content(source: &str, node: &Node) -> Option<String> {
9625 let text = node_text(source, node);
9626 if text.len() < 2 {
9627 return None;
9628 }
9629
9630 Some(
9631 text.trim_start_matches(|c| c == '\'' || c == '"')
9632 .trim_end_matches(|c| c == '\'' || c == '"')
9633 .to_string(),
9634 )
9635}
9636
9637fn find_child_by_kind<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
9638 let mut cursor = node.walk();
9639 if !cursor.goto_first_child() {
9640 return None;
9641 }
9642
9643 loop {
9644 let child = cursor.node();
9645 if child.kind() == kind {
9646 return Some(child);
9647 }
9648 if !cursor.goto_next_sibling() {
9649 break;
9650 }
9651 }
9652
9653 None
9654}
9655
9656fn resolve_export_clause_name(
9657 source: &str,
9658 export_clause: &Node,
9659 requested_name: &str,
9660) -> Option<String> {
9661 let mut cursor = export_clause.walk();
9662 if !cursor.goto_first_child() {
9663 return None;
9664 }
9665
9666 loop {
9667 let child = cursor.node();
9668 if child.kind() == "export_specifier" {
9669 let (source_name, exported_name) = export_specifier_names(source, &child)?;
9670 if exported_name == requested_name {
9671 return Some(source_name);
9672 }
9673 }
9674
9675 if !cursor.goto_next_sibling() {
9676 break;
9677 }
9678 }
9679
9680 None
9681}
9682
9683fn export_specifier_names(source: &str, specifier: &Node) -> Option<(String, String)> {
9684 let source_name = specifier
9685 .child_by_field_name("name")
9686 .map(|node| node_text(source, &node).to_string());
9687 let alias_name = specifier
9688 .child_by_field_name("alias")
9689 .map(|node| node_text(source, &node).to_string());
9690
9691 if let Some(source_name) = source_name {
9692 let exported_name = alias_name.unwrap_or_else(|| source_name.clone());
9693 return Some((source_name, exported_name));
9694 }
9695
9696 let mut names = Vec::new();
9697 let mut cursor = specifier.walk();
9698 if cursor.goto_first_child() {
9699 loop {
9700 let child = cursor.node();
9701 let child_text = node_text(source, &child).trim();
9702 if matches!(
9703 child.kind(),
9704 "identifier" | "type_identifier" | "property_identifier"
9705 ) || child_text == "default"
9706 {
9707 names.push(child_text.to_string());
9708 }
9709 if !cursor.goto_next_sibling() {
9710 break;
9711 }
9712 }
9713 }
9714
9715 match names.as_slice() {
9716 [name] => Some((name.clone(), name.clone())),
9717 [source_name, exported_name, ..] => Some((source_name.clone(), exported_name.clone())),
9718 _ => None,
9719 }
9720}
9721
9722fn export_statement_has_wildcard(source: &str, node: &Node) -> bool {
9723 let mut cursor = node.walk();
9724 if !cursor.goto_first_child() {
9725 return false;
9726 }
9727
9728 loop {
9729 if node_text(source, &cursor.node()).trim() == "*" {
9730 return true;
9731 }
9732 if !cursor.goto_next_sibling() {
9733 break;
9734 }
9735 }
9736
9737 false
9738}
9739
9740fn node_contains_token(source: &str, node: &Node, token: &str) -> bool {
9741 let mut cursor = node.walk();
9742 if !cursor.goto_first_child() {
9743 return false;
9744 }
9745
9746 loop {
9747 if node_text(source, &cursor.node()).trim() == token {
9748 return true;
9749 }
9750 if !cursor.goto_next_sibling() {
9751 break;
9752 }
9753 }
9754
9755 false
9756}
9757
9758fn default_export_target_name(source: &str, export_stmt: &Node) -> Option<String> {
9759 if let Some(value_node) = export_stmt.child_by_field_name("value") {
9760 if let Some(name) = default_export_node_name(source, &value_node) {
9761 return Some(name);
9762 }
9763 }
9764
9765 if let Some(declaration_node) = export_stmt.child_by_field_name("declaration") {
9766 if let Some(name) = default_export_node_name(source, &declaration_node) {
9767 return Some(name);
9768 }
9769 }
9770
9771 let mut cursor = export_stmt.walk();
9772 if !cursor.goto_first_child() {
9773 return None;
9774 }
9775
9776 loop {
9777 let child = cursor.node();
9778 if let Some(name) = default_export_node_name(source, &child) {
9779 return Some(name);
9780 }
9781
9782 if !cursor.goto_next_sibling() {
9783 break;
9784 }
9785 }
9786
9787 None
9788}
9789
9790fn default_export_node_name(source: &str, node: &Node) -> Option<String> {
9791 match node.kind() {
9792 "function_declaration"
9793 | "generator_function_declaration"
9794 | "function_expression"
9795 | "generator_function"
9796 | "class_declaration"
9797 | "class" => node
9798 .child_by_field_name("name")
9799 .map(|name_node| node_text(source, &name_node).to_string())
9800 .or_else(|| Some("default".to_string())),
9801 "interface_declaration" | "enum_declaration" | "type_alias_declaration" => node
9802 .child_by_field_name("name")
9803 .map(|name_node| node_text(source, &name_node).to_string()),
9804 "lexical_declaration" => lexical_declaration_name(source, node),
9805 "identifier" | "type_identifier" => {
9806 let text = node_text(source, node);
9807 (text != "export" && text != "default").then(|| text.to_string())
9808 }
9809 _ => None,
9810 }
9811}
9812
9813fn lexical_declaration_name(source: &str, node: &Node) -> Option<String> {
9814 let mut cursor = node.walk();
9815 if !cursor.goto_first_child() {
9816 return None;
9817 }
9818
9819 loop {
9820 let child = cursor.node();
9821 if child.kind() == "variable_declarator" {
9822 if let Some(name_node) = child.child_by_field_name("name") {
9823 return Some(node_text(source, &name_node).to_string());
9824 }
9825 }
9826 if !cursor.goto_next_sibling() {
9827 break;
9828 }
9829 }
9830
9831 None
9832}
9833
9834impl crate::language::LanguageProvider for TreeSitterProvider {
9835 fn resolve_symbol(&self, file: &Path, name: &str) -> Result<Vec<SymbolMatch>, AftError> {
9836 let mut parser = FileParser::with_symbol_cache(self.symbol_cache());
9837 let matches = self.resolve_symbol_inner(&mut parser, file, name, 0, &mut HashSet::new())?;
9838
9839 if matches.is_empty() {
9840 Err(AftError::SymbolNotFound {
9841 name: name.to_string(),
9842 file: file.display().to_string(),
9843 })
9844 } else {
9845 Ok(matches)
9846 }
9847 }
9848
9849 fn list_symbols(&self, file: &Path) -> Result<Vec<Symbol>, AftError> {
9850 let mut parser = FileParser::with_symbol_cache(self.symbol_cache());
9851 parser.extract_symbols(file)
9852 }
9853
9854 fn heading_anchors(
9855 &self,
9856 file: &Path,
9857 ) -> Result<Vec<crate::language::HeadingAnchor>, AftError> {
9858 if detect_language(file) != Some(LangId::Html) {
9859 return Ok(Vec::new());
9860 }
9861 let mut parser = FileParser::with_symbol_cache(self.symbol_cache());
9862 let (source, tree, _) = self.read_parsed_file(&mut parser, file)?;
9863 Ok(extract_html_heading_anchors(&source, &tree.root_node()))
9864 }
9865
9866 fn as_any(&self) -> &dyn std::any::Any {
9867 self
9868 }
9869}
9870#[cfg(any(test, feature = "test-support"))]
9871pub mod work_counters {
9872 use std::cell::Cell;
9873
9874 thread_local! {
9875 pub static TREE_PARSES: Cell<usize> = const { Cell::new(0) };
9877 pub static GRAMMAR_LOADS: Cell<usize> = const { Cell::new(0) };
9879 pub static PARSED_FILE_READS: Cell<usize> = const { Cell::new(0) };
9881 pub static TREE_SOURCE_READS: Cell<usize> = const { Cell::new(0) };
9883 pub static CACHED_SYMBOL_COPIES: Cell<usize> = const { Cell::new(0) };
9885 pub static FILE_PARSE_READS: Cell<usize> = const { Cell::new(0) };
9886 pub static SOURCE_READS: Cell<usize> = const { Cell::new(0) };
9887 pub static OWNED_SYMBOL_COPIES: Cell<usize> = const { Cell::new(0) };
9888 pub static RUST_MODULE_SCANS: Cell<usize> = const { Cell::new(0) };
9889 pub static CACHED_PARSER_PARSES: Cell<usize> = const { Cell::new(0) };
9892 }
9893
9894 pub fn cached_parser_parses() -> usize {
9895 CACHED_PARSER_PARSES.with(Cell::get)
9896 }
9897
9898 pub fn tree_parses() -> usize {
9899 TREE_PARSES.with(Cell::get)
9900 }
9901
9902 pub fn grammar_loads() -> usize {
9903 GRAMMAR_LOADS.with(Cell::get)
9904 }
9905}