1use crate::calls::extract_type_references;
4use crate::imports::{parse_imports, specifier_imported_name, specifier_local_name};
5use crate::parser::{grammar_for, LangId};
6use serde::{Deserialize, Serialize};
7use std::collections::{hash_map::Entry, BTreeMap, BTreeSet, HashMap};
8use std::path::Path;
9use std::sync::OnceLock;
10
11#[derive(Default)]
12pub struct FactParsers {
13 parsers: HashMap<LangId, tree_sitter::Parser>,
14}
15
16impl FactParsers {
17 pub fn parse_source(&mut self, lang: LangId, source: &str) -> Option<tree_sitter::Tree> {
18 if crate::parser::markdown_too_deep_to_parse(lang, source) {
20 return None;
21 }
22 let parser = match self.parsers.entry(lang) {
23 Entry::Occupied(entry) => entry.into_mut(),
24 Entry::Vacant(entry) => {
25 let grammar = grammar_for(lang).ok()?;
26 let mut parser = tree_sitter::Parser::new();
27 if parser.set_language(&grammar).is_err() {
28 return None;
29 }
30 entry.insert(parser)
31 }
32 };
33
34 parser.parse(source, None)
35 }
36}
37
38pub const RUST_MACRO_REF_SHAPE_CALL: &str = "call";
39pub const RUST_MACRO_REF_SHAPE_METHOD: &str = "method";
40pub const RUST_MACRO_REF_SHAPE_STRUCT: &str = "struct";
41pub const TOP_LEVEL_SYMBOL: &str = "<top-level>";
42#[derive(Debug, Default)]
43pub struct FileAnalysis {
44 pub oversized: bool,
45 pub freshness: Option<crate::cache_freshness::FileFreshness>,
46 pub rust_api: Option<RustApiFacts>,
47 pub go_dispatch: Option<GoDispatchFacts>,
48 pub raw_imports: Vec<RawImportContribution>,
49 pub rust_imports: Vec<RawImportContribution>,
50 pub raw_reexports: Vec<RawReexportContribution>,
51 pub attribute_entry_points: Vec<String>,
52 pub macro_token_refs: Vec<MacroTokenRefContribution>,
53 pub cfg_test_ranges: Vec<RustCfgTestRange>,
54 pub cfg_test_module_files: Vec<String>,
55 pub globs_parent_module: bool,
56 pub trait_impl_methods: Vec<String>,
57 pub type_ref_names: BTreeSet<String>,
58}
59
60#[derive(Debug, Default, Serialize, Deserialize)]
69pub struct StoredFileFacts {
70 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
72 pub not_text: bool,
73 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
74 pub type_ref_names: BTreeSet<String>,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub js: Option<StoredJsFacts>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub rust: Option<StoredRustFacts>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub go: Option<GoDispatchFacts>,
82}
83
84#[derive(Debug, Default, Serialize, Deserialize)]
87pub struct StoredJsFacts {
88 #[serde(default, skip_serializing_if = "Vec::is_empty")]
89 pub raw_imports: Vec<RawImportContribution>,
90 #[serde(default, skip_serializing_if = "Vec::is_empty")]
91 pub raw_reexports: Vec<RawReexportContribution>,
92}
93
94#[derive(Debug, Default, Serialize, Deserialize)]
96pub struct StoredRustFacts {
97 #[serde(default, skip_serializing_if = "Vec::is_empty")]
98 pub imports: Vec<RawImportContribution>,
99 #[serde(default, skip_serializing_if = "Vec::is_empty")]
100 pub raw_reexports: Vec<RawReexportContribution>,
101 pub api: RustApiFacts,
104 #[serde(default, skip_serializing_if = "Vec::is_empty")]
105 pub attribute_entry_points: Vec<String>,
106 #[serde(default, skip_serializing_if = "Vec::is_empty")]
107 pub macro_token_refs: Vec<MacroTokenRefContribution>,
108 #[serde(default, skip_serializing_if = "Vec::is_empty")]
109 pub cfg_test_ranges: Vec<RustCfgTestRange>,
110 #[serde(default, skip_serializing_if = "Vec::is_empty")]
111 pub cfg_test_modules: Vec<RustCfgTestModule>,
112 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
113 pub globs_parent_module: bool,
114 #[serde(default, skip_serializing_if = "Vec::is_empty")]
115 pub trait_impl_methods: Vec<String>,
116}
117
118impl StoredFileFacts {
119 pub fn read_for(lang: LangId) -> bool {
121 supports_type_refs(lang)
122 }
123
124 pub fn encode_for_record(source: &[u8], lang: LangId, tree: &tree_sitter::Tree) -> Vec<u8> {
128 let facts = match std::str::from_utf8(source) {
129 Ok(source) => Self::extract(source, lang, Some(tree)),
130 Err(_) => Self {
131 not_text: true,
132 ..Self::default()
133 },
134 };
135 serde_json::to_vec(&facts).unwrap_or_default()
136 }
137
138 pub fn decode(bytes: &[u8]) -> Result<Self, String> {
144 serde_json::from_slice(bytes).map_err(|error| error.to_string())
145 }
146
147 pub fn extract(source: &str, lang: LangId, tree: Option<&tree_sitter::Tree>) -> Self {
150 if !Self::read_for(lang) {
151 return Self::default();
152 }
153 let type_ref_names = tree
154 .map(|tree| extract_type_references(source, tree.root_node(), lang))
155 .unwrap_or_default();
156 let js = matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript).then(|| {
159 StoredJsFacts {
160 raw_imports: tree
161 .map(|tree| raw_imports_from_tree(source, tree, lang))
162 .unwrap_or_default(),
163 raw_reexports: tree
164 .map(|tree| ts_raw_reexport_contributions(source, tree.root_node()))
165 .unwrap_or_default(),
166 }
167 });
168 let rust = (lang == LangId::Rust).then(|| {
169 let api = tree
172 .map(|tree| rust_api_facts(source, tree.root_node(), ""))
173 .unwrap_or_default();
174 let attribute_entry_points = tree
175 .map(|tree| {
176 let mut roots = BTreeSet::new();
177 for entry in
178 crate::parser::rust_attribute_entry_points(source, tree.root_node())
179 {
180 roots.insert(entry.name);
181 roots.insert(entry.scoped_name);
182 }
183 roots.extend(rust_serde_function_references(
184 source,
185 tree.root_node(),
186 api.items.as_slice(),
187 ));
188 roots.into_iter().collect()
189 })
190 .unwrap_or_default();
191 StoredRustFacts {
192 imports: tree
193 .map(|tree| rust_raw_import_contributions(source, tree))
194 .unwrap_or_default(),
195 raw_reexports: rust_raw_reexport_contributions(source),
196 attribute_entry_points,
197 macro_token_refs: tree
198 .map(|tree| rust_macro_token_refs(source, tree.root_node()))
199 .unwrap_or_default(),
200 cfg_test_ranges: tree
201 .map(|tree| rust_cfg_test_ranges(source, tree.root_node()))
202 .unwrap_or_default(),
203 cfg_test_modules: tree
204 .map(|tree| rust_cfg_test_modules(source, tree.root_node()))
205 .unwrap_or_default(),
206 globs_parent_module: tree
207 .is_some_and(|tree| rust_globs_parent_module(source, tree.root_node())),
208 trait_impl_methods: tree
209 .map(|tree| rust_trait_impl_methods(source, tree.root_node()))
210 .unwrap_or_default(),
211 api,
212 }
213 });
214 let go = (lang == LangId::Go).then(|| {
215 tree.map(|tree| go_dispatch_facts(source, tree.root_node()))
216 .unwrap_or_default()
217 });
218 Self {
219 not_text: false,
220 type_ref_names,
221 js,
222 rust,
223 go,
224 }
225 }
226
227 pub fn into_analysis(
232 self,
233 lang: LangId,
234 file: &Path,
235 relative_file: &str,
236 has_oxc_file: bool,
237 ) -> FileAnalysis {
238 if self.not_text || !Self::read_for(lang) {
239 return FileAnalysis::default();
240 }
241 let needs_ts_raw_facts =
242 matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) && !has_oxc_file;
243 let js = self.js.unwrap_or_default();
244 let rust = (lang == LangId::Rust).then(|| {
245 let mut rust = self.rust.unwrap_or_default();
246 for module in &mut rust.api.modules {
247 if module.file.is_some() {
248 let mut nested = module.scope.clone();
249 nested.push(module.name.clone());
250 module.file = Some(rust_module_file(
251 relative_file,
252 &nested,
253 module.path_override.as_deref(),
254 ));
255 }
256 }
257 rust
258 });
259 let go_dispatch = (lang == LangId::Go).then(|| {
260 let mut facts = self.go.unwrap_or_default();
261 facts.module = go_module_dir(file, relative_file);
262 facts
263 });
264 let raw_reexports = if needs_ts_raw_facts {
265 js.raw_reexports
266 } else {
267 rust.as_ref()
268 .map(|rust| rust.raw_reexports.clone())
269 .unwrap_or_default()
270 };
271 let Some(rust) = rust else {
272 return FileAnalysis {
273 go_dispatch,
274 raw_imports: if needs_ts_raw_facts {
275 js.raw_imports
276 } else {
277 Vec::new()
278 },
279 raw_reexports,
280 type_ref_names: self.type_ref_names,
281 ..FileAnalysis::default()
282 };
283 };
284 FileAnalysis {
285 oversized: false,
286 freshness: None,
287 go_dispatch,
288 raw_imports: Vec::new(),
289 raw_reexports,
290 cfg_test_module_files: rust_cfg_test_module_files_for(
291 relative_file,
292 &rust.cfg_test_modules,
293 ),
294 rust_api: Some(rust.api),
295 rust_imports: rust.imports,
296 attribute_entry_points: rust.attribute_entry_points,
297 macro_token_refs: rust.macro_token_refs,
298 cfg_test_ranges: rust.cfg_test_ranges,
299 globs_parent_module: rust.globs_parent_module,
300 trait_impl_methods: rust.trait_impl_methods,
301 type_ref_names: self.type_ref_names,
302 }
303 }
304}
305
306pub fn go_module_dir(file: &Path, relative_file: &str) -> String {
310 let mut module = String::new();
311 let mut relative = Path::new(relative_file).parent().unwrap_or(Path::new(""));
312 let mut absolute = file.parent().unwrap_or(Path::new(""));
313 loop {
314 if absolute.join("go.mod").is_file() {
315 module = relative.to_string_lossy().replace('\\', "/");
316 break;
317 }
318 let (Some(next_relative), Some(next_absolute)) = (relative.parent(), absolute.parent())
319 else {
320 break;
321 };
322 relative = next_relative;
323 absolute = next_absolute;
324 }
325 module
326}
327
328#[derive(Debug, Clone)]
329pub struct RustMacroToken<'a> {
330 pub text: &'a str,
331 pub kind: &'a str,
332 pub line: u32,
333}
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
336pub struct RustCfgTestRange {
337 pub start_line: u32,
338 pub end_line: u32,
339}
340
341impl RustCfgTestRange {
342 pub fn contains(self, line: u32) -> bool {
343 self.start_line <= line && line <= self.end_line
344 }
345}
346
347pub fn rust_globs_parent_module(source: &str, root: tree_sitter::Node) -> bool {
350 let mut cursor = root.walk();
351 let globs = root.children(&mut cursor).any(|node| {
352 node.kind() == "use_declaration"
353 && node_text(source, node)
354 .chars()
355 .filter(|ch| !ch.is_whitespace())
356 .collect::<String>()
357 .ends_with("usesuper::*;")
358 });
359 globs
360}
361
362pub fn rust_serde_function_references(
369 source: &str,
370 root: tree_sitter::Node,
371 items: &[RustApiItem],
372) -> Vec<String> {
373 static SERDE_FUNCTION_ATTRIBUTE: OnceLock<regex::Regex> = OnceLock::new();
374 let pattern = SERDE_FUNCTION_ATTRIBUTE.get_or_init(|| {
375 regex::Regex::new(
376 r#"\b(?:deserialize_with|serialize_with|default|skip_serializing_if)\s*=\s*"([A-Za-z_][A-Za-z0-9_:]*)""#,
377 )
378 .expect("serde function attribute pattern compiles")
379 });
380 let identities = items
381 .iter()
382 .filter(|item| item.owner.is_none())
383 .map(rust_qualified_item_name)
384 .collect::<BTreeSet<_>>();
385 pattern
386 .captures_iter(source)
387 .filter_map(|captures| captures.get(1))
388 .map(|path| {
389 let scope = root
390 .descendant_for_byte_range(path.start(), path.end())
391 .map(|node| rust_mod_scope_chain(&node, source))
392 .unwrap_or_default();
393 rust_serde_root_identity(path.as_str(), &scope, &identities)
394 })
395 .collect()
396}
397
398pub fn rust_serde_root_identity(
406 path: &str,
407 scope: &[String],
408 identities: &BTreeSet<String>,
409) -> String {
410 let mut segments = rust_path_segments(path);
411 let short = segments.last().cloned().unwrap_or_default();
412 let mut scope = scope.to_vec();
413 let mut anchored = false;
414 while let Some(first) = segments.first().map(String::as_str) {
415 match first {
416 "self" => {}
417 "super" => {
418 scope.pop();
419 }
420 "crate" => scope.clear(),
421 _ => break,
422 }
423 segments.remove(0);
424 anchored = true;
425 }
426 loop {
427 let candidate = scope
428 .iter()
429 .chain(&segments)
430 .cloned()
431 .collect::<Vec<_>>()
432 .join("::");
433 if identities.contains(&candidate) {
434 return candidate;
435 }
436 if anchored || scope.pop().is_none() {
437 break;
438 }
439 }
440 if !anchored && segments.len() == 1 {
441 let suffix = format!("::{short}");
442 let mut matches = identities
443 .iter()
444 .filter(|identity| identity.ends_with(&suffix));
445 if let (Some(only), None) = (matches.next(), matches.next()) {
446 return only.clone();
447 }
448 }
449 short
450}
451
452pub fn rust_trait_impl_methods(source: &str, root: tree_sitter::Node) -> Vec<String> {
455 let mut names = BTreeSet::new();
456 let mut stack = vec![root];
457 while let Some(node) = stack.pop() {
458 if node.kind() == "impl_item" && node.child_by_field_name("trait").is_some() {
459 if let Some(body) = node.child_by_field_name("body") {
460 let mut cursor = body.walk();
461 for item in body.children(&mut cursor) {
462 if item.kind() == "function_item" {
463 if let Some(name) = item.child_by_field_name("name") {
464 names.insert(node_text(source, name).to_string());
465 }
466 }
467 }
468 }
469 continue;
470 }
471 let mut cursor = node.walk();
472 stack.extend(node.children(&mut cursor));
473 }
474 names.into_iter().collect()
475}
476
477pub fn rust_path_segments(path: &str) -> Vec<String> {
478 path.split("::")
479 .map(str::trim)
480 .filter(|segment| !segment.is_empty())
481 .map(str::to_string)
482 .collect()
483}
484
485pub fn macro_scoped_symbol(path: &[String], name: &str) -> String {
486 if path.is_empty() {
487 name.to_string()
488 } else {
489 format!("{}::{name}", path.join("::"))
490 }
491}
492
493pub fn raw_imports_from_tree(
494 source: &str,
495 tree: &tree_sitter::Tree,
496 lang: LangId,
497) -> Vec<RawImportContribution> {
498 parse_imports(source, tree, lang)
499 .imports
500 .into_iter()
501 .map(|import| RawImportContribution {
502 source: import.module_path,
503 names: import.names,
504 default_import: import.default_import,
505 namespace_import: import.namespace_import,
506 })
507 .collect()
508}
509
510pub fn rust_raw_import_contributions(
511 source: &str,
512 tree: &tree_sitter::Tree,
513) -> Vec<RawImportContribution> {
514 parse_imports(source, tree, LangId::Rust)
515 .imports
516 .into_iter()
517 .map(|import| RawImportContribution {
518 source: crate::imports::rust_use_tree(&import),
519 names: import.names,
520 default_import: None,
521 namespace_import: None,
522 })
523 .collect()
524}
525
526pub fn rust_cfg_test_ranges(source: &str, root: tree_sitter::Node) -> Vec<RustCfgTestRange> {
532 let mut ranges = Vec::new();
533 let mut stack = vec![(root, false)];
537 while let Some((node, parent_is_block)) = stack.pop() {
538 let in_function_body = parent_is_block
539 && !matches!(
540 node.kind(),
541 "attribute_item" | "inner_attribute_item" | "line_comment" | "block_comment"
542 );
543 let item = matches!(
544 node.kind(),
545 "mod_item"
546 | "function_item"
547 | "impl_item"
548 | "struct_item"
549 | "enum_item"
550 | "union_item"
551 | "trait_item"
552 | "type_item"
553 | "const_item"
554 | "static_item"
555 );
556 if (in_function_body || item) && rust_node_has_cfg_test_attribute(source, node) {
557 ranges.push(RustCfgTestRange {
558 start_line: rust_item_start_line(node),
562 end_line: node.end_position().row as u32 + 1,
563 });
564 }
565
566 let mut cursor = node.walk();
567 if cursor.goto_first_child() {
568 let is_block = node.kind() == "block";
569 loop {
570 stack.push((cursor.node(), is_block));
571 if !cursor.goto_next_sibling() {
572 break;
573 }
574 }
575 }
576 }
577 ranges.sort_by_key(|range| (range.start_line, range.end_line));
578 ranges.dedup();
579 ranges
580}
581
582pub fn rust_item_start_line(node: tree_sitter::Node<'_>) -> u32 {
583 let mut first = node;
584 while let Some(previous) = first.prev_sibling() {
585 if !matches!(
586 previous.kind(),
587 "attribute_item" | "line_comment" | "block_comment"
588 ) {
589 break;
590 }
591 first = previous;
592 }
593 first.start_position().row as u32 + 1
594}
595
596#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
599pub enum RustCfgTestModule {
600 Path(String),
601 Name(String),
602}
603
604pub fn rust_cfg_test_modules(source: &str, root: tree_sitter::Node) -> Vec<RustCfgTestModule> {
607 let mut modules = Vec::new();
608 let mut cursor = root.walk();
609 for node in root.children(&mut cursor) {
610 if node.kind() != "mod_item"
613 || node.child_by_field_name("body").is_some()
614 || !rust_node_has_cfg_test_attribute(source, node)
615 {
616 continue;
617 }
618 if let Some(path) = rust_path_attribute_value(source, node) {
619 modules.push(RustCfgTestModule::Path(path));
620 continue;
621 }
622 let Some(name) = node
623 .child_by_field_name("name")
624 .map(|name| node_text(source, name).to_string())
625 else {
626 continue;
627 };
628 modules.push(RustCfgTestModule::Name(name));
629 }
630 modules
631}
632
633pub fn rust_cfg_test_module_files_for(
636 relative_file: &str,
637 modules: &[RustCfgTestModule],
638) -> Vec<String> {
639 let normalized = relative_file.replace('\\', "/");
640 let (dir, file_name) = normalized
641 .rsplit_once('/')
642 .map_or(("", normalized.as_str()), |(dir, name)| (dir, name));
643 let module_dir = match file_name.strip_suffix(".rs") {
646 Some("mod" | "lib" | "main") | None => dir.to_string(),
647 Some(stem) if dir.is_empty() => stem.to_string(),
648 Some(stem) => format!("{dir}/{stem}"),
649 };
650 let join = |base: &str, rest: &str| {
651 if base.is_empty() {
652 rest.to_string()
653 } else {
654 format!("{base}/{rest}")
655 }
656 };
657
658 let mut files = Vec::new();
659 for module in modules {
660 match module {
661 RustCfgTestModule::Path(path) => {
662 files.push(normalize_relative_segments(&join(dir, path)));
665 }
666 RustCfgTestModule::Name(name) => {
667 files.push(join(&module_dir, &format!("{name}.rs")));
668 files.push(join(&module_dir, &format!("{name}/mod.rs")));
669 }
670 }
671 }
672 files
673}
674
675pub fn rust_path_attribute_value(source: &str, node: tree_sitter::Node<'_>) -> Option<String> {
677 let mut previous = node.prev_sibling();
678 while let Some(attribute) = previous {
679 match attribute.kind() {
680 "attribute_item" => {
681 let text = &source[attribute.byte_range()];
682 let inner = text
683 .trim()
684 .strip_prefix("#[")
685 .and_then(|inner| inner.strip_suffix(']'))
686 .map(str::trim);
687 if let Some(value) = inner
688 .and_then(|inner| inner.strip_prefix("path"))
689 .map(str::trim_start)
690 .and_then(|rest| rest.strip_prefix('='))
691 .map(str::trim)
692 .and_then(|rest| rest.strip_prefix('"'))
693 .and_then(|rest| rest.strip_suffix('"'))
694 {
695 return Some(value.replace('\\', "/"));
696 }
697 previous = attribute.prev_sibling();
698 }
699 "line_comment" | "block_comment" => previous = attribute.prev_sibling(),
700 _ => break,
701 }
702 }
703 None
704}
705
706pub fn normalize_relative_segments(path: &str) -> String {
708 let mut segments: Vec<&str> = Vec::new();
709 for segment in path.split(['/', '\\']) {
712 match segment {
713 "" | "." => {}
714 ".." => {
715 segments.pop();
716 }
717 other => segments.push(other),
718 }
719 }
720 segments.join("/")
721}
722
723pub fn rust_node_has_cfg_test_attribute(source: &str, node: tree_sitter::Node<'_>) -> bool {
724 let mut previous = node.prev_sibling();
725 while let Some(attribute) = previous {
726 match attribute.kind() {
727 "attribute_item" => {
728 if rust_attribute_requires_test(source, attribute) {
729 return true;
730 }
731 previous = attribute.prev_sibling();
732 }
733 "line_comment" | "block_comment" => previous = attribute.prev_sibling(),
734 _ => break,
735 }
736 }
737 false
738}
739
740pub fn rust_children_cfg_test_gated<'t>(
745 source: &str,
746 parent: tree_sitter::Node<'t>,
747) -> Vec<(tree_sitter::Node<'t>, bool)> {
748 let mut children = Vec::new();
749 let mut run_requires_test = false;
752 let mut cursor = parent.walk();
753 for node in parent.children(&mut cursor) {
754 if node.is_named() {
755 children.push((node, run_requires_test));
756 }
757 match node.kind() {
758 "attribute_item" => {
759 run_requires_test = run_requires_test || rust_attribute_requires_test(source, node);
760 }
761 "line_comment" | "block_comment" => {}
762 _ => run_requires_test = false,
763 }
764 }
765 children
766}
767
768pub fn rust_attribute_requires_test(source: &str, attribute: tree_sitter::Node<'_>) -> bool {
770 let compact = source[attribute.byte_range()]
771 .chars()
772 .filter(|ch| !ch.is_whitespace())
773 .collect::<String>();
774 compact
775 .strip_prefix("#[cfg(")
776 .and_then(|inner| inner.strip_suffix(")]"))
777 .is_some_and(cfg_predicate_requires_test)
778}
779
780pub fn cfg_predicate_requires_test(predicate: &str) -> bool {
781 if predicate == "test" {
782 return true;
783 }
784 if let Some(inner) = predicate
785 .strip_prefix("all(")
786 .and_then(|inner| inner.strip_suffix(')'))
787 {
788 return split_cfg_predicates(inner)
789 .into_iter()
790 .any(cfg_predicate_requires_test);
791 }
792 if let Some(inner) = predicate
793 .strip_prefix("any(")
794 .and_then(|inner| inner.strip_suffix(')'))
795 {
796 let predicates = split_cfg_predicates(inner);
797 return !predicates.is_empty() && predicates.into_iter().all(cfg_predicate_requires_test);
798 }
799 false
800}
801
802pub fn split_cfg_predicates(input: &str) -> Vec<&str> {
803 let mut parts = Vec::new();
804 let mut depth = 0usize;
805 let mut start = 0usize;
806 for (index, ch) in input.char_indices() {
807 match ch {
808 '(' => depth += 1,
809 ')' => depth = depth.saturating_sub(1),
810 ',' if depth == 0 => {
811 parts.push(input[start..index].trim());
812 start = index + ch.len_utf8();
813 }
814 _ => {}
815 }
816 }
817 let tail = input[start..].trim();
818 if !tail.is_empty() {
819 parts.push(tail);
820 }
821 parts
822}
823
824pub fn rust_macro_token_refs(
825 source: &str,
826 root: tree_sitter::Node,
827) -> Vec<MacroTokenRefContribution> {
828 let mut refs = BTreeSet::new();
829 let mut scope_stack = Vec::new();
830 collect_rust_macro_token_refs(source, root, &mut scope_stack, &mut refs);
831 let mut functions: BTreeMap<String, Vec<tree_sitter::Node>> = BTreeMap::new();
834 let mut stack = vec![root];
835 while let Some(node) = stack.pop() {
836 if node.kind() == "function_item" {
837 if let Some(name) = rust_function_symbol_name(source, &node) {
838 functions.entry(name).or_default().push(node);
839 }
840 }
841 let mut cursor = node.walk();
842 stack.extend(node.named_children(&mut cursor));
843 }
844 for (caller_symbol, variants) in functions {
845 for node in variants {
846 for (full, _, line, _, _) in rust_function_body_calls(source, node) {
847 if full.contains('.') || full.ends_with('!') {
848 continue;
849 }
850 let mut path = rust_path_segments(&full);
851 let Some(name) = path.pop() else {
852 continue;
853 };
854 refs.insert(MacroTokenRefContribution {
855 caller_symbol: caller_symbol.clone(),
856 name,
857 line,
858 path: macro_ref_path(path),
859 shape: RUST_MACRO_REF_SHAPE_CALL.into(),
860 });
861 }
862 }
863 }
864 refs.into_iter().collect()
865}
866
867pub fn rust_function_body_calls(
877 source: &str,
878 function: tree_sitter::Node,
879) -> Vec<crate::calls::CallTuple> {
880 let (calls, facts) = crate::calls::extract_rust_calls_with_macro_facts(
881 source,
882 function,
883 function.start_byte(),
884 function.end_byte(),
885 );
886 if facts.bodies.is_empty() {
887 return calls;
888 }
889
890 let owner = |start: usize, end: usize| {
892 facts
893 .bodies
894 .iter()
895 .filter(|body| body.byte_start <= start && end <= body.byte_end)
896 .min_by_key(|body| body.byte_end - body.byte_start)
897 .map(|body| body.name.as_str())
898 };
899
900 let mut direct_invocations = Vec::new();
901 let mut template_invocations: BTreeMap<&str, Vec<String>> = BTreeMap::new();
902 for (full, _, _, start, end) in &calls {
903 let Some(path) = full.strip_suffix('!') else {
904 continue;
905 };
906 let name = path.rsplit("::").next().unwrap_or(path).trim().to_string();
910 match owner(*start, *end) {
911 Some(macro_name) => template_invocations
912 .entry(macro_name)
913 .or_default()
914 .push(name),
915 None => direct_invocations.push(name),
916 }
917 }
918
919 let mut invoked = BTreeSet::new();
920 let mut pending = direct_invocations;
921 while let Some(name) = pending.pop() {
922 if !invoked.insert(name.clone()) {
923 continue;
924 }
925 if let Some(nested) = template_invocations.get(name.as_str()) {
926 pending.extend(nested.iter().cloned());
927 }
928 }
929 let unresolved_invocation = facts.bodies.iter().any(|body| {
938 invoked.contains(&body.name)
939 && rust_template_token_tree(function, body.byte_start - 1, body.byte_end + 1)
940 .is_none_or(|tree| {
941 tree.has_error() || rust_token_tree_invokes_metavariable_macro(tree)
942 })
943 });
944 if unresolved_invocation {
945 return calls;
946 }
947 calls
948 .into_iter()
949 .filter(|(_, _, _, start, end)| {
950 owner(*start, *end).is_none_or(|macro_name| invoked.contains(macro_name))
951 })
952 .collect()
953}
954
955pub fn rust_template_token_tree(
959 root: tree_sitter::Node<'_>,
960 start: usize,
961 end: usize,
962) -> Option<tree_sitter::Node<'_>> {
963 let mut stack = vec![root];
964 while let Some(node) = stack.pop() {
965 let range = node.byte_range();
966 if range.start > start || range.end < end {
967 continue;
968 }
969 if node.kind() == "token_tree" && range.start == start && range.end == end {
970 return Some(node);
971 }
972 let mut cursor = node.walk();
973 stack.extend(node.children(&mut cursor));
974 }
975 None
976}
977
978pub fn rust_token_tree_invokes_metavariable_macro(token_tree: tree_sitter::Node<'_>) -> bool {
982 let mut stack = vec![token_tree];
983 while let Some(node) = stack.pop() {
984 let mut cursor = node.walk();
985 let tokens = node
988 .children(&mut cursor)
989 .filter(|child| !child.is_extra())
990 .collect::<Vec<_>>();
991 for (index, token) in tokens.iter().enumerate() {
992 if token.child_count() > 0 {
993 stack.push(*token);
994 }
995 if token.kind() != "metavariable" {
996 continue;
997 }
998 let mut next = index + 1;
1002 let mut name_end = token.end_byte();
1003 while let Some(part) = tokens
1004 .get(next)
1005 .filter(|part| part.kind() == "identifier" && part.start_byte() == name_end)
1006 {
1007 name_end = part.end_byte();
1008 next += 1;
1009 }
1010 if tokens.get(next).is_some_and(|bang| bang.kind() == "!") {
1011 return true;
1012 }
1013 }
1014 }
1015 false
1016}
1017
1018pub fn collect_rust_macro_token_refs(
1028 source: &str,
1029 root: tree_sitter::Node,
1030 scope_stack: &mut Vec<String>,
1031 refs: &mut BTreeSet<MacroTokenRefContribution>,
1032) {
1033 enum Step<'tree> {
1034 Enter(tree_sitter::Node<'tree>),
1035 Leave(usize),
1037 }
1038 let mut pending = vec![Step::Enter(root)];
1039 while let Some(step) = pending.pop() {
1040 let node = match step {
1041 Step::Enter(node) => node,
1042 Step::Leave(scope_len) => {
1043 scope_stack.truncate(scope_len);
1044 continue;
1045 }
1046 };
1047 pending.push(Step::Leave(scope_stack.len()));
1048 if node.kind() == "function_item" {
1049 if let Some(symbol) = rust_function_symbol_name(source, &node) {
1050 scope_stack.push(symbol);
1051 }
1052 }
1053
1054 if node.kind() == "macro_invocation" {
1055 if let Some(token_tree) = find_child_by_kind(node, "token_tree") {
1056 let caller_symbol = scope_stack
1057 .last()
1058 .cloned()
1059 .unwrap_or_else(|| TOP_LEVEL_SYMBOL.to_string());
1060 let mut tokens = Vec::new();
1061 collect_rust_macro_tokens(source, token_tree, &mut tokens);
1062 let mut shadowed = BTreeSet::new();
1063 for token in &tokens {
1064 if rust_macro_token_is_identifier(token)
1065 && crate::calls::rust_name_is_shadowed_at(node, source, token.text)
1066 {
1067 shadowed.insert(token.text.to_string());
1068 }
1069 }
1070 let mut binding = false;
1071 for token in &tokens {
1072 if token.text == "let" {
1073 binding = true;
1074 } else if token.text == "=" {
1075 binding = false;
1076 } else if binding && rust_macro_token_is_identifier(token) {
1077 shadowed.insert(token.text.to_string());
1078 }
1079 }
1080 extract_rust_macro_token_refs(&tokens, &caller_symbol, &shadowed, refs);
1081 }
1082 }
1083
1084 let start = pending.len();
1085 let mut cursor = node.walk();
1086 pending.extend(node.children(&mut cursor).map(Step::Enter));
1087 pending[start..].reverse();
1088 }
1089}
1090
1091pub fn collect_rust_macro_tokens<'a>(
1096 source: &'a str,
1097 root: tree_sitter::Node,
1098 tokens: &mut Vec<RustMacroToken<'a>>,
1099) {
1100 let mut cursor = root.walk();
1101 loop {
1102 let node = cursor.node();
1103 if !rust_macro_token_node_is_opaque(node.kind()) {
1104 if node.child_count() == 0 {
1105 let text = node_text(source, node).trim();
1106 if !text.is_empty() {
1107 tokens.push(RustMacroToken {
1108 text,
1109 kind: node.kind(),
1110 line: node.start_position().row as u32 + 1,
1111 });
1112 }
1113 } else if cursor.goto_first_child() {
1114 continue;
1115 }
1116 }
1117 while !cursor.goto_next_sibling() {
1120 if !cursor.goto_parent() {
1121 return;
1122 }
1123 }
1124 }
1125}
1126
1127pub fn rust_macro_token_node_is_opaque(kind: &str) -> bool {
1128 matches!(
1129 kind,
1130 "string_literal" | "raw_string_literal" | "char_literal" | "line_comment" | "block_comment"
1131 )
1132}
1133
1134pub fn extract_rust_macro_token_refs(
1135 tokens: &[RustMacroToken<'_>],
1136 caller_symbol: &str,
1137 shadowed: &BTreeSet<String>,
1138 refs: &mut BTreeSet<MacroTokenRefContribution>,
1139) {
1140 for index in 0..tokens.len() {
1141 let token = &tokens[index];
1142 if !rust_macro_token_is_identifier(token) || rust_macro_token_is_keyword(token.text) {
1143 continue;
1144 }
1145 if index > 0 && tokens[index - 1].text == "." {
1146 continue;
1147 }
1148 if tokens.get(index + 1).is_some_and(|next| next.text == "!") {
1149 continue;
1150 }
1151
1152 let path = rust_macro_path_before(tokens, index);
1153 let next = rust_macro_next_after_optional_turbofish(tokens, index + 1);
1154 if index > 0
1158 && tokens[index - 1].text == "("
1159 && tokens
1160 .get(next)
1161 .is_some_and(|next| matches!(next.text, ")" | ","))
1162 && !shadowed.contains(token.text)
1163 {
1164 refs.insert(MacroTokenRefContribution {
1165 caller_symbol: caller_symbol.to_string(),
1166 line: token.line,
1167 name: token.text.to_string(),
1168 path: macro_ref_path(path.clone()),
1169 shape: RUST_MACRO_REF_SHAPE_CALL.into(),
1170 });
1171 }
1172 if tokens.get(next).is_some_and(|next| next.text == "(") {
1173 let shape = if path
1174 .last()
1175 .is_some_and(|segment| rust_macro_name_is_upper_camel(segment))
1176 {
1177 RUST_MACRO_REF_SHAPE_METHOD
1178 } else {
1179 RUST_MACRO_REF_SHAPE_CALL
1180 };
1181 refs.insert(MacroTokenRefContribution {
1182 caller_symbol: caller_symbol.to_string(),
1183 line: token.line,
1184 name: token.text.to_string(),
1185 path: macro_ref_path(path),
1186 shape: shape.to_string(),
1187 });
1188 continue;
1189 }
1190
1191 if rust_macro_name_is_upper_camel(token.text)
1192 && tokens.get(index + 1).is_some_and(|next| next.text == "{")
1193 {
1194 refs.insert(MacroTokenRefContribution {
1195 caller_symbol: caller_symbol.to_string(),
1196 line: token.line,
1197 name: token.text.to_string(),
1198 path: macro_ref_path(path),
1199 shape: RUST_MACRO_REF_SHAPE_STRUCT.to_string(),
1200 });
1201 }
1202 }
1203}
1204
1205pub fn rust_macro_path_before(tokens: &[RustMacroToken<'_>], index: usize) -> Vec<String> {
1206 let mut segments = Vec::new();
1207 let mut cursor = index;
1208 while cursor >= 2
1209 && tokens[cursor - 1].text == "::"
1210 && rust_macro_token_is_path_segment(&tokens[cursor - 2])
1211 {
1212 segments.push(tokens[cursor - 2].text.to_string());
1213 cursor -= 2;
1214 }
1215 segments.reverse();
1216 segments
1217}
1218
1219pub fn rust_macro_next_after_optional_turbofish(
1220 tokens: &[RustMacroToken<'_>],
1221 index: usize,
1222) -> usize {
1223 if tokens.get(index).is_none_or(|token| token.text != "::")
1224 || tokens.get(index + 1).is_none_or(|token| token.text != "<")
1225 {
1226 return index;
1227 }
1228
1229 let mut depth = 0usize;
1230 let mut cursor = index + 1;
1231 while let Some(token) = tokens.get(cursor) {
1232 match token.text {
1233 "<" => depth += 1,
1234 ">" => {
1235 depth = depth.saturating_sub(1);
1236 if depth == 0 {
1237 return cursor + 1;
1238 }
1239 }
1240 _ => {}
1241 }
1242 cursor += 1;
1243 }
1244 index
1245}
1246
1247pub fn macro_ref_path(path: Vec<String>) -> Option<Vec<String>> {
1248 (!path.is_empty()).then_some(path)
1249}
1250
1251pub fn rust_macro_token_is_identifier(token: &RustMacroToken<'_>) -> bool {
1252 matches!(token.kind, "identifier" | "type_identifier")
1253 || rust_macro_text_is_identifier(token.text)
1254}
1255
1256pub fn rust_macro_token_is_path_segment(token: &RustMacroToken<'_>) -> bool {
1257 rust_macro_token_is_identifier(token)
1258 && (!rust_macro_token_is_keyword(token.text)
1259 || matches!(token.text, "crate" | "self" | "super"))
1260}
1261
1262pub fn rust_macro_text_is_identifier(text: &str) -> bool {
1263 let mut chars = text.chars();
1264 let Some(first) = chars.next() else {
1265 return false;
1266 };
1267 (first == '_' || first.is_ascii_alphabetic())
1268 && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
1269}
1270
1271pub fn rust_macro_name_is_upper_camel(name: &str) -> bool {
1272 name.chars().next().is_some_and(char::is_uppercase)
1273}
1274
1275pub fn rust_macro_token_is_keyword(text: &str) -> bool {
1276 matches!(
1277 text,
1278 "as" | "async"
1279 | "await"
1280 | "break"
1281 | "const"
1282 | "continue"
1283 | "crate"
1284 | "dyn"
1285 | "else"
1286 | "enum"
1287 | "extern"
1288 | "false"
1289 | "fn"
1290 | "for"
1291 | "if"
1292 | "impl"
1293 | "in"
1294 | "let"
1295 | "loop"
1296 | "match"
1297 | "mod"
1298 | "move"
1299 | "mut"
1300 | "pub"
1301 | "ref"
1302 | "return"
1303 | "self"
1304 | "Self"
1305 | "static"
1306 | "struct"
1307 | "super"
1308 | "trait"
1309 | "true"
1310 | "type"
1311 | "unsafe"
1312 | "use"
1313 | "where"
1314 | "while"
1315 )
1316}
1317
1318pub fn rust_function_symbol_name(
1319 source: &str,
1320 function_node: &tree_sitter::Node<'_>,
1321) -> Option<String> {
1322 let name_node = function_node.child_by_field_name("name")?;
1323 let name = node_text(source, name_node).to_string();
1324 let declaration_list_owner = rust_function_declaration_list_owner(function_node);
1325
1326 match declaration_list_owner.as_ref().map(tree_sitter::Node::kind) {
1327 Some("impl_item") => {
1328 let scope_name = rust_impl_scope_name(declaration_list_owner.as_ref().unwrap(), source);
1329 if scope_name.is_empty() {
1330 Some(name)
1331 } else {
1332 Some(format!("{scope_name}::{name}"))
1333 }
1334 }
1335 Some(owner_kind) if owner_kind != "mod_item" => None,
1336 _ => {
1337 let scope_chain = rust_mod_scope_chain(function_node, source);
1338 if scope_chain.is_empty() {
1339 Some(name)
1340 } else {
1341 Some(format!("{}::{name}", scope_chain.join("::")))
1342 }
1343 }
1344 }
1345}
1346
1347pub fn rust_function_declaration_list_owner<'a>(
1348 function_node: &tree_sitter::Node<'a>,
1349) -> Option<tree_sitter::Node<'a>> {
1350 function_node
1351 .parent()
1352 .filter(|parent| parent.kind() == "declaration_list")
1353 .and_then(|parent| parent.parent())
1354}
1355
1356pub fn rust_mod_scope_chain(node: &tree_sitter::Node<'_>, source: &str) -> Vec<String> {
1357 let mut scopes = Vec::new();
1358 let mut current = node.parent();
1359 while let Some(parent) = current {
1360 if parent.kind() == "mod_item" {
1361 if let Some(name_node) = parent.child_by_field_name("name") {
1362 scopes.push(node_text(source, name_node).to_string());
1363 }
1364 }
1365 current = parent.parent();
1366 }
1367 scopes.reverse();
1368 scopes
1369}
1370
1371pub fn rust_impl_scope_name(impl_node: &tree_sitter::Node<'_>, source: &str) -> String {
1372 let Some(self_type) = impl_node.child_by_field_name("type") else {
1373 return String::new();
1374 };
1375 let self_name = node_text(source, self_type);
1376 match impl_node.child_by_field_name("trait") {
1377 Some(trait_type) => format!("{} for {self_name}", node_text(source, trait_type)),
1378 None => self_name.to_string(),
1379 }
1380}
1381
1382pub fn ts_raw_reexport_contributions(
1383 source: &str,
1384 root: tree_sitter::Node,
1385) -> Vec<RawReexportContribution> {
1386 let mut reexports = Vec::new();
1387 let mut cursor = root.walk();
1388 if !cursor.goto_first_child() {
1389 return reexports;
1390 }
1391
1392 loop {
1393 let node = cursor.node();
1394 if node.kind() == "export_statement" {
1395 if let Some(module_path) = export_source_module(source, node) {
1396 let line = (node.start_position().row + 1) as u32;
1397 let raw_export = node_text(source, node).trim();
1398 for specifier in ts_reexport_specifiers(raw_export) {
1399 reexports.push(RawReexportContribution {
1400 language: "ts".to_string(),
1401 source: module_path.clone(),
1402 kind: "named".to_string(),
1403 imported: Some(specifier.imported),
1404 exported: Some(specifier.exported),
1405 line,
1406 });
1407 }
1408 if raw_export.contains('*') {
1409 if let Some(namespace_export) = ts_namespace_reexport_name(raw_export) {
1410 reexports.push(RawReexportContribution {
1411 language: "ts".to_string(),
1412 source: module_path.clone(),
1413 kind: "namespace".to_string(),
1414 imported: Some("*".to_string()),
1415 exported: Some(namespace_export),
1416 line,
1417 });
1418 } else {
1419 reexports.push(RawReexportContribution {
1420 language: "ts".to_string(),
1421 source: module_path.clone(),
1422 kind: "star".to_string(),
1423 imported: Some("*".to_string()),
1424 exported: None,
1425 line,
1426 });
1427 }
1428 }
1429 }
1430 }
1431
1432 if !cursor.goto_next_sibling() {
1433 break;
1434 }
1435 }
1436
1437 reexports
1438}
1439
1440pub fn rust_raw_reexport_contributions(source: &str) -> Vec<RawReexportContribution> {
1441 rust_pub_use_statements(source)
1442 .into_iter()
1443 .flat_map(|(statement, line)| {
1444 rust_reexport_specifiers(&statement)
1445 .into_iter()
1446 .map(move |specifier| RawReexportContribution {
1447 language: "rust".to_string(),
1448 source: specifier.module_path.join("::"),
1449 kind: if specifier.imported == "*" {
1450 "star".to_string()
1451 } else {
1452 "named".to_string()
1453 },
1454 imported: Some(specifier.imported),
1455 exported: Some(specifier.exported),
1456 line,
1457 })
1458 })
1459 .collect()
1460}
1461
1462#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1463pub struct RustApiFacts {
1464 #[serde(default)]
1465 pub receiver_references: BTreeSet<String>,
1466 #[serde(default)]
1467 pub initializers: Vec<RustInitializer>,
1468 #[serde(default)]
1469 pub initializer_references: Vec<MacroTokenRefContribution>,
1470 pub items: Vec<RustApiItem>,
1471 pub modules: Vec<RustApiModule>,
1472 pub uses: Vec<RustApiUse>,
1473}
1474
1475#[derive(Debug, Clone, Serialize, Deserialize)]
1476pub struct RustInitializer {
1477 pub name: String,
1478 pub range: RustCfgTestRange,
1479}
1480
1481#[derive(Debug, Clone, Serialize, Deserialize)]
1482pub struct RustApiItem {
1483 pub name: String,
1484 pub scope: Vec<String>,
1485 pub public: bool,
1486 pub line: u32,
1487 pub owner: Option<String>,
1488 pub trait_name: Option<String>,
1489}
1490
1491pub fn rust_qualified_item_name(item: &RustApiItem) -> String {
1492 let mut parts = item.scope.clone();
1493 if let Some(owner) = &item.owner {
1494 parts.push(match &item.trait_name {
1495 Some(trait_name) => format!("{trait_name} for {owner}"),
1496 None => owner.clone(),
1497 });
1498 }
1499 parts.push(item.name.clone());
1500 parts.join("::")
1501}
1502
1503#[derive(Debug, Clone, Serialize, Deserialize)]
1504pub struct RustApiModule {
1505 pub scope: Vec<String>,
1506 pub name: String,
1507 pub public: bool,
1508 pub file: Option<String>,
1509 #[serde(default, skip_serializing_if = "Option::is_none")]
1510 pub path_override: Option<String>,
1511}
1512
1513#[derive(Debug, Clone, Serialize, Deserialize)]
1514pub struct RustApiUse {
1515 pub scope: Vec<String>,
1516 pub path: Vec<String>,
1517 pub alias: String,
1518 pub public: bool,
1519 pub line: u32,
1520}
1521
1522pub fn rust_unrestricted_pub(source: &str, node: tree_sitter::Node) -> bool {
1523 find_child_by_kind(node, "visibility_modifier")
1524 .is_some_and(|visibility| node_text(source, visibility).trim() == "pub")
1525}
1526
1527pub fn rust_api_facts(source: &str, root: tree_sitter::Node, file: &str) -> RustApiFacts {
1528 let mut facts = RustApiFacts::default();
1529 rust_collect_api_facts(source, root, file, &[], &mut facts, 0);
1530 let mut owners = Vec::new();
1531 let mut stack = vec![root];
1532 while let Some(node) = stack.pop() {
1533 let owner = match node.kind() {
1534 "function_item" => rust_function_symbol_name(source, &node),
1535 "static_item" | "const_item" => node.child_by_field_name("name").map(|name| {
1536 macro_scoped_symbol(
1537 &rust_mod_scope_chain(&node, source),
1538 node_text(source, name),
1539 )
1540 }),
1541 _ => None,
1542 };
1543 if let Some(owner) = owner {
1544 owners.push((node.start_byte(), node.end_byte(), owner.clone()));
1545 if matches!(node.kind(), "static_item" | "const_item") {
1546 facts.initializers.push(RustInitializer {
1547 name: owner,
1548 range: RustCfgTestRange {
1549 start_line: rust_item_start_line(node),
1550 end_line: node.end_position().row as u32 + 1,
1551 },
1552 });
1553 }
1554 }
1555 let mut cursor = node.walk();
1556 stack.extend(node.named_children(&mut cursor));
1557 }
1558 facts.initializer_references = crate::calls::extract_rust_value_references(source, root)
1559 .into_iter()
1560 .map(|(full, name, line, start, end)| {
1561 let mut path = rust_path_segments(&full);
1562 path.pop();
1563 let caller_symbol = owners
1564 .iter()
1565 .filter(|(a, b, _)| *a <= start && *b >= end)
1566 .min_by_key(|(a, b, _)| b - a)
1567 .map(|(_, _, name)| name.clone())
1568 .unwrap_or_else(|| "<top-level>".into());
1569 MacroTokenRefContribution {
1570 caller_symbol,
1571 name,
1572 line,
1573 path: macro_ref_path(path),
1574 shape: "call".into(),
1575 }
1576 })
1577 .collect();
1578 facts
1579}
1580
1581pub const MAX_RUST_API_NESTING: usize = 64;
1588
1589pub fn rust_collect_api_facts(
1593 source: &str,
1594 root: tree_sitter::Node,
1595 file: &str,
1596 scope: &[String],
1597 facts: &mut RustApiFacts,
1598 depth: usize,
1599) {
1600 if depth > MAX_RUST_API_NESTING {
1601 return;
1602 }
1603 let gated = rust_children_cfg_test_gated(source, root);
1604 for (node, gated) in gated {
1605 if gated {
1606 continue;
1607 }
1608 if !matches!(node.kind(), "impl_item" | "mod_item") {
1611 facts
1612 .receiver_references
1613 .extend(extract_type_references(source, node, LangId::Rust));
1614 }
1615 let name = node
1616 .child_by_field_name("name")
1617 .map(|name| node_text(source, name).to_string());
1618 let public = rust_unrestricted_pub(source, node);
1619 match node.kind() {
1620 "mod_item" => {
1621 let Some(name) = name else {
1622 continue;
1623 };
1624 let body = node.child_by_field_name("body");
1625 let path_override = rust_path_attribute_value(source, node);
1626 let mut nested = scope.to_vec();
1627 nested.push(name.clone());
1628 let module_file = body
1629 .is_none()
1630 .then(|| rust_module_file(file, &nested, path_override.as_deref()));
1631 facts.modules.push(RustApiModule {
1632 scope: scope.to_vec(),
1633 name,
1634 public,
1635 file: module_file,
1636 path_override,
1637 });
1638 if let Some(body) = body {
1639 rust_collect_api_facts(source, body, file, &nested, facts, depth + 1);
1640 }
1641 }
1642 "use_declaration" => {
1643 let text = node_text(source, node);
1644 let Some((_, path)) = text.split_once("use ") else {
1645 continue;
1646 };
1647 rust_api_use_paths(
1648 path.trim().trim_end_matches(';'),
1649 &[],
1650 &mut |path, alias| {
1651 facts.uses.push(RustApiUse {
1652 scope: scope.to_vec(),
1653 path,
1654 alias,
1655 public,
1656 line: node.start_position().row as u32 + 1,
1657 });
1658 },
1659 );
1660 }
1661 "impl_item" => {
1662 let owner = node
1663 .child_by_field_name("type")
1664 .map(|ty| rust_api_type_path(node_text(source, ty)));
1665 let trait_name = node
1666 .child_by_field_name("trait")
1667 .map(|ty| rust_api_type_path(node_text(source, ty)));
1668 if let Some(body) = node.child_by_field_name("body") {
1669 let mut cursor = body.walk();
1670 for method in body
1671 .named_children(&mut cursor)
1672 .filter(|item| item.kind() == "function_item")
1673 {
1674 if rust_node_has_cfg_test_attribute(source, method) {
1675 continue;
1676 }
1677 if let Some(name) = method.child_by_field_name("name") {
1678 facts.items.push(RustApiItem {
1679 name: node_text(source, name).to_string(),
1680 scope: scope.to_vec(),
1681 public: rust_unrestricted_pub(source, method)
1682 || trait_name.is_some(),
1683 line: method.start_position().row as u32 + 1,
1684 owner: owner.clone(),
1685 trait_name: trait_name.clone(),
1686 });
1687 }
1688 }
1689 }
1690 }
1691 "function_item" | "struct_item" | "enum_item" | "trait_item" | "type_item"
1692 | "const_item" | "static_item" => {
1693 if let Some(name) = name {
1694 facts.items.push(RustApiItem {
1695 name,
1696 scope: scope.to_vec(),
1697 public,
1698 line: node.start_position().row as u32 + 1,
1699 owner: None,
1700 trait_name: None,
1701 });
1702 }
1703 }
1704 "macro_invocation" => {
1705 if let Some(tokens) = find_child_by_kind(node, "token_tree") {
1708 rust_collect_api_macro_items(source, tokens, file, scope, facts, depth + 1);
1709 }
1710 if let Some(name) = node.child_by_field_name("macro") {
1711 let mut cursor = root.walk();
1712 for definition in root
1713 .named_children(&mut cursor)
1714 .filter(|n| n.kind() == "macro_definition")
1715 {
1716 if definition
1717 .child_by_field_name("name")
1718 .is_some_and(|n| node_text(source, n) == node_text(source, name))
1719 {
1720 let mut cursor = definition.walk();
1721 for rule in definition
1722 .named_children(&mut cursor)
1723 .filter(|n| n.kind() == "macro_rule")
1724 {
1725 if let (Some(left), Some(right), Some(input)) = (
1726 rule.child_by_field_name("left"),
1727 rule.child_by_field_name("right"),
1728 find_child_by_kind(node, "token_tree"),
1729 ) {
1730 if let Some(expanded) = rust_api_macro_expansion(
1731 node_text(source, left),
1732 node_text(source, right),
1733 node_text(source, input),
1734 ) {
1735 rust_collect_api_macro_text(
1736 &expanded,
1737 right.start_position().row,
1738 file,
1739 scope,
1740 facts,
1741 depth + 1,
1742 );
1743 }
1744 }
1745 }
1746 }
1747 }
1748 }
1749 }
1750 _ => {}
1751 }
1752 }
1753}
1754
1755pub fn rust_module_file(file: &str, nested: &[String], path_override: Option<&str>) -> String {
1759 let base = Path::new(file);
1760 let dir = base.parent().unwrap_or(Path::new(""));
1761 let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("");
1762 let dir = if matches!(stem, "lib" | "main" | "mod") {
1763 dir.to_path_buf()
1764 } else {
1765 dir.join(stem)
1766 };
1767 if let Some(path) = path_override {
1768 normalize_relative_segments(
1769 &base
1770 .parent()
1771 .unwrap_or(Path::new(""))
1772 .join(path)
1773 .to_string_lossy(),
1774 )
1775 } else {
1776 dir.join(nested.join("/"))
1777 .with_extension("rs")
1778 .to_string_lossy()
1779 .replace('\\', "/")
1780 }
1781}
1782
1783pub fn rust_collect_api_macro_items(
1784 source: &str,
1785 tokens: tree_sitter::Node,
1786 file: &str,
1787 scope: &[String],
1788 facts: &mut RustApiFacts,
1789 depth: usize,
1790) {
1791 let text = node_text(source, tokens);
1792 if text.len() < 2 {
1793 return;
1794 }
1795 rust_collect_api_macro_text(
1796 &text[1..text.len() - 1],
1797 tokens.start_position().row,
1798 file,
1799 scope,
1800 facts,
1801 depth,
1802 );
1803}
1804
1805pub fn rust_api_macro_expansion(pattern: &str, template: &str, input: &str) -> Option<String> {
1809 let interior = |text: &str| {
1810 text.get(1..text.len().checked_sub(1)?)
1811 .map(str::trim)
1812 .map(str::to_string)
1813 };
1814 let pattern = interior(pattern)?;
1815 let input = interior(input)?;
1816 let mut template = interior(template)?;
1817 if !pattern.contains('$') {
1818 return (pattern == input).then_some(template);
1819 }
1820 let patterns = split_cfg_predicates(&pattern);
1821 let inputs = split_cfg_predicates(&input);
1822 if patterns.len() != inputs.len() {
1823 return None;
1824 }
1825 for (pattern, input) in patterns.into_iter().zip(inputs) {
1826 let (name, kind) = pattern.trim().strip_prefix('$')?.split_once(':')?;
1827 if !matches!(kind.trim(), "ident" | "path")
1828 || !name.chars().all(|ch| ch.is_alphanumeric() || ch == '_')
1829 {
1830 return None;
1831 }
1832 if !input
1833 .trim()
1834 .chars()
1835 .all(|ch| ch.is_alphanumeric() || ch == '_' || ch == ':')
1836 {
1837 return None;
1838 }
1839 template = template.replace(&format!("${}", name.trim()), input.trim());
1840 }
1841 (!template.contains('$')).then_some(template)
1842}
1843
1844pub fn rust_collect_api_macro_text(
1845 interior: &str,
1846 row: usize,
1847 file: &str,
1848 scope: &[String],
1849 facts: &mut RustApiFacts,
1850 depth: usize,
1851) {
1852 if interior.contains('$') {
1853 return;
1854 }
1855 let padded = format!("{}{}", "\n".repeat(row), interior);
1856 let mut analyzer = FactParsers::default();
1857 if let Some(tree) = analyzer.parse_source(LangId::Rust, &padded) {
1858 if !tree.root_node().has_error() {
1859 rust_collect_api_facts(&padded, tree.root_node(), file, scope, facts, depth);
1860 }
1861 }
1862}
1863
1864pub fn rust_api_type_path(text: &str) -> String {
1865 text.split('<').next().unwrap_or(text).trim().to_string()
1866}
1867
1868pub const MAX_RUST_USE_GROUP_NESTING: usize = 64;
1875
1876pub fn rust_api_use_paths(
1877 text: &str,
1878 prefix: &[String],
1879 emit: &mut impl FnMut(Vec<String>, String),
1880) {
1881 rust_api_use_paths_at(text, prefix, emit, 0);
1882}
1883
1884pub fn rust_api_use_paths_at(
1886 text: &str,
1887 prefix: &[String],
1888 emit: &mut impl FnMut(Vec<String>, String),
1889 depth: usize,
1890) {
1891 let text = text.trim();
1892 if let Some(open) = text.find('{') {
1893 if depth >= MAX_RUST_USE_GROUP_NESTING {
1894 return;
1895 }
1896 let mut prefix = prefix.to_vec();
1897 prefix.extend(rust_path_segments(text[..open].trim_end_matches(':')));
1898 let inner = text[open + 1..].trim_end_matches('}');
1899 let mut depth_in_group = 0;
1900 let mut start = 0;
1901 for (index, ch) in inner.char_indices() {
1902 match ch {
1903 '{' => depth_in_group += 1,
1904 '}' => depth_in_group -= 1,
1905 ',' if depth_in_group == 0 => {
1906 rust_api_use_paths_at(&inner[start..index], &prefix, emit, depth + 1);
1907 start = index + 1;
1908 }
1909 _ => {}
1910 }
1911 }
1912 rust_api_use_paths_at(&inner[start..], &prefix, emit, depth + 1);
1913 } else if !text.is_empty() {
1914 let (path, alias) = text
1915 .split_once(" as ")
1916 .map(|(path, alias)| (path.trim(), Some(alias.trim())))
1917 .unwrap_or((text, None));
1918 let mut segments = prefix.to_vec();
1919 segments.extend(rust_path_segments(path));
1920 if segments.last().is_some_and(|s| s == "self") {
1921 segments.pop();
1922 }
1923 if let Some(name) = alias.or_else(|| segments.last().map(String::as_str)) {
1924 emit(segments.clone(), name.to_string());
1925 }
1926 }
1927}
1928
1929#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1930pub struct GoDispatchFacts {
1931 #[serde(default)]
1932 pub module: String,
1933 pub methods: Vec<GoMethodFact>,
1934 pub interfaces: Vec<Vec<String>>,
1935 pub used_types: BTreeSet<String>,
1936 #[serde(default)]
1937 pub live_methods: BTreeSet<String>,
1938}
1939
1940#[derive(Debug, Clone, Serialize, Deserialize)]
1941pub struct GoMethodFact {
1942 pub receiver: String,
1943 pub name: String,
1944 pub signature: String,
1945}
1946
1947pub fn go_dispatch_facts(source: &str, root: tree_sitter::Node) -> GoDispatchFacts {
1948 let mut facts = GoDispatchFacts::default();
1949 let mut stack = vec![root];
1950 while let Some(node) = stack.pop() {
1951 if node.kind() == "method_declaration" {
1952 if let (Some(receiver), Some(name)) = (
1953 node.child_by_field_name("receiver"),
1954 node.child_by_field_name("name"),
1955 ) {
1956 let mut cursor = receiver.walk();
1957 if let Some(parameter) = receiver.named_children(&mut cursor).next() {
1958 if let Some(ty) = parameter.child_by_field_name("type") {
1959 facts.methods.push(GoMethodFact {
1960 receiver: node_text(source, ty).trim_start_matches('*').to_string(),
1961 name: node_text(source, name).to_string(),
1962 signature: go_method_signature(source, node),
1963 });
1964 }
1965 }
1966 let mut cursor = node.walk();
1967 stack.extend(
1968 node.named_children(&mut cursor)
1969 .filter(|child| child.id() != receiver.id()),
1970 );
1971 continue;
1972 }
1973 }
1974 if node.kind() == "interface_type" {
1975 let mut cursor = node.walk();
1976 let methods = node
1977 .named_children(&mut cursor)
1978 .filter(|child| child.kind() == "method_elem")
1979 .map(|method| go_method_signature(source, method))
1980 .collect::<Vec<_>>();
1981 let mut cursor = node.walk();
1985 if !methods.is_empty()
1986 && !node
1987 .named_children(&mut cursor)
1988 .any(|child| child.kind() == "type_elem")
1989 {
1990 facts.interfaces.push(methods);
1991 }
1992 continue;
1993 }
1994 if node.kind() == "type_identifier"
1995 && !node.parent().is_some_and(|parent| {
1996 parent.kind() == "type_spec"
1997 && parent
1998 .child_by_field_name("name")
1999 .is_some_and(|name| name.id() == node.id())
2000 })
2001 {
2002 facts.used_types.insert(node_text(source, node).to_string());
2003 }
2004 let mut cursor = node.walk();
2005 stack.extend(node.named_children(&mut cursor));
2006 }
2007 facts
2008}
2009
2010pub fn go_method_signature(source: &str, method: tree_sitter::Node) -> String {
2011 let name = method
2012 .child_by_field_name("name")
2013 .map(|name| node_text(source, name))
2014 .unwrap_or("");
2015 let parameters = method
2016 .child_by_field_name("parameters")
2017 .map(|node| go_signature_types(source, node))
2018 .unwrap_or_default();
2019 let result = method
2020 .child_by_field_name("result")
2021 .map(|node| go_signature_types(source, node))
2022 .unwrap_or_default();
2023 format!("{name}({parameters})({result})")
2024}
2025
2026pub fn go_signature_types(source: &str, node: tree_sitter::Node) -> String {
2027 if node.kind() != "parameter_list" {
2028 return node_text(source, node)
2029 .split_whitespace()
2030 .collect::<String>();
2031 }
2032 let mut types = Vec::new();
2033 let mut cursor = node.walk();
2034 for parameter in node.named_children(&mut cursor) {
2035 let Some(ty) = parameter.child_by_field_name("type") else {
2036 continue;
2037 };
2038 let mut cursor = parameter.walk();
2039 let count = parameter
2040 .named_children(&mut cursor)
2041 .filter(|child| child.kind() == "identifier")
2042 .count()
2043 .max(1);
2044 let ty = format!(
2045 "{}{}",
2046 if parameter.kind() == "variadic_parameter_declaration" {
2047 "..."
2048 } else {
2049 ""
2050 },
2051 node_text(source, ty).split_whitespace().collect::<String>()
2052 );
2053 types.extend(std::iter::repeat_n(ty, count));
2054 }
2055 types.join(",")
2056}
2057
2058pub fn ts_reexport_specifiers(raw_export: &str) -> Vec<ReexportSpecifier> {
2059 let Some(start) = raw_export.find('{').map(|index| index + 1) else {
2060 return Vec::new();
2061 };
2062 let Some(end) = raw_export[start..].find('}').map(|index| start + index) else {
2063 return Vec::new();
2064 };
2065
2066 raw_export[start..end]
2067 .split(',')
2068 .filter_map(|specifier| {
2069 let specifier = specifier.trim();
2070 if specifier.is_empty() {
2071 return None;
2072 }
2073 let imported = specifier_imported_name(specifier).trim();
2074 let exported = specifier_local_name(specifier).trim();
2075 if imported.is_empty() || exported.is_empty() {
2076 return None;
2077 }
2078 Some(ReexportSpecifier {
2079 imported: imported.to_string(),
2080 exported: exported.to_string(),
2081 })
2082 })
2083 .collect()
2084}
2085
2086pub fn ts_namespace_reexport_name(raw_export: &str) -> Option<String> {
2087 let after_star = raw_export.split_once('*')?.1.trim_start();
2088 let after_as = after_star.strip_prefix("as")?.trim_start();
2089 let name = after_as
2090 .split_whitespace()
2091 .next()?
2092 .trim_matches(|ch: char| ch == '{' || ch == '}' || ch == ';' || ch == ',');
2093 (!name.is_empty()).then(|| name.to_string())
2094}
2095
2096pub fn rust_pub_use_statements(source: &str) -> Vec<(String, u32)> {
2097 let mut statements = Vec::new();
2098 let mut current = String::new();
2099 let mut start_line = 0u32;
2100
2101 for (index, line) in source.lines().enumerate() {
2102 let trimmed = line.trim();
2103 if current.is_empty() {
2104 if !(trimmed.starts_with("pub use ") || trimmed.starts_with("pub(crate) use ")) {
2105 continue;
2106 }
2107 start_line = (index + 1) as u32;
2108 }
2109
2110 current.push(' ');
2111 current.push_str(trimmed);
2112 if trimmed.ends_with(';') {
2113 statements.push((current.trim().to_string(), start_line));
2114 current.clear();
2115 }
2116 }
2117
2118 statements
2119}
2120
2121pub fn rust_reexport_specifiers(statement: &str) -> Vec<RustReexportSpecifier> {
2122 let statement = statement
2123 .trim()
2124 .trim_end_matches(';')
2125 .strip_prefix("pub(crate) use ")
2126 .or_else(|| {
2127 statement
2128 .trim()
2129 .trim_end_matches(';')
2130 .strip_prefix("pub use ")
2131 })
2132 .unwrap_or("")
2133 .trim();
2134 if statement.is_empty() {
2135 return Vec::new();
2136 }
2137
2138 if let Some((module_path, grouped)) = statement.split_once("::{") {
2139 let grouped = grouped.trim_end_matches('}');
2140 return grouped
2141 .split(',')
2142 .filter_map(|specifier| rust_reexport_specifier(module_path.trim(), specifier.trim()))
2143 .collect();
2144 }
2145
2146 let Some((module_path, imported)) = statement.rsplit_once("::") else {
2147 return Vec::new();
2148 };
2149 rust_reexport_specifier(module_path.trim(), imported.trim())
2150 .into_iter()
2151 .collect()
2152}
2153
2154pub fn rust_reexport_specifier(
2155 module_path: &str,
2156 specifier: &str,
2157) -> Option<RustReexportSpecifier> {
2158 if specifier.is_empty() {
2159 return None;
2160 }
2161 let (imported, exported) = specifier
2162 .split_once(" as ")
2163 .map(|(imported, exported)| (imported.trim(), exported.trim()))
2164 .unwrap_or((specifier.trim(), specifier.trim()));
2165 if imported.is_empty() || exported.is_empty() {
2166 return None;
2167 }
2168 Some(RustReexportSpecifier {
2169 module_path: rust_normalize_module_path(module_path),
2170 imported: imported.to_string(),
2171 exported: exported.to_string(),
2172 })
2173}
2174
2175pub fn rust_normalize_module_path(module_path: &str) -> Vec<String> {
2176 module_path
2177 .split("::")
2178 .filter_map(|segment| {
2179 let segment = segment.trim();
2180 if segment.is_empty() || matches!(segment, "self" | "crate") {
2181 None
2182 } else {
2183 Some(segment.to_string())
2184 }
2185 })
2186 .collect()
2187}
2188
2189pub fn export_source_module(source: &str, node: tree_sitter::Node) -> Option<String> {
2190 node.child_by_field_name("source")
2191 .or_else(|| find_child_by_kind(node, "string"))
2192 .and_then(|source_node| string_literal_content(source, source_node))
2193}
2194
2195pub fn find_child_by_kind<'tree>(
2200 node: tree_sitter::Node<'tree>,
2201 kind: &str,
2202) -> Option<tree_sitter::Node<'tree>> {
2203 let mut cursor = node.walk();
2204 if !cursor.goto_first_child() {
2205 return None;
2206 }
2207 loop {
2208 if cursor.node().kind() == kind {
2209 return Some(cursor.node());
2210 }
2211 if cursor.goto_first_child() {
2212 continue;
2213 }
2214 while !cursor.goto_next_sibling() {
2217 if !cursor.goto_parent() || cursor.node().id() == node.id() {
2218 return None;
2219 }
2220 }
2221 }
2222}
2223
2224pub fn string_literal_content(source: &str, node: tree_sitter::Node) -> Option<String> {
2225 let raw = node_text(source, node).trim();
2226 let quote = raw.chars().next()?;
2227 if quote != '\'' && quote != '"' {
2228 return None;
2229 }
2230 raw.strip_prefix(quote)
2231 .and_then(|value| value.strip_suffix(quote))
2232 .map(ToOwned::to_owned)
2233}
2234
2235pub fn node_text<'a>(source: &'a str, node: tree_sitter::Node) -> &'a str {
2236 &source[node.byte_range()]
2237}
2238
2239#[derive(Debug)]
2240pub struct ReexportSpecifier {
2241 pub imported: String,
2242 pub exported: String,
2243}
2244
2245#[derive(Debug)]
2246pub struct RustReexportSpecifier {
2247 pub module_path: Vec<String>,
2248 pub imported: String,
2249 pub exported: String,
2250}
2251
2252pub fn supports_type_refs(lang: LangId) -> bool {
2253 matches!(
2254 lang,
2255 LangId::TypeScript
2256 | LangId::Tsx
2257 | LangId::JavaScript
2258 | LangId::Python
2259 | LangId::Rust
2260 | LangId::Go
2261 )
2262}
2263
2264#[derive(Debug, Clone, Serialize, Deserialize)]
2265pub struct RawImportContribution {
2266 pub source: String,
2267 #[serde(default)]
2268 pub names: Vec<String>,
2269 #[serde(default)]
2270 pub default_import: Option<String>,
2271 #[serde(default)]
2272 pub namespace_import: Option<String>,
2273}
2274
2275#[derive(Debug, Clone, Serialize, Deserialize)]
2276pub struct RawReexportContribution {
2277 pub language: String,
2278 pub source: String,
2279 pub kind: String,
2280 #[serde(default)]
2281 pub imported: Option<String>,
2282 #[serde(default)]
2283 pub exported: Option<String>,
2284 pub line: u32,
2285}
2286
2287#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
2288pub struct MacroTokenRefContribution {
2289 pub caller_symbol: String,
2290 pub line: u32,
2291 pub name: String,
2292 #[serde(default, skip_serializing_if = "Option::is_none")]
2293 pub path: Option<Vec<String>>,
2294 pub shape: String,
2295}