From 7e18405daf33d3a2c9869d5c6304ed13cd2fedf7 Mon Sep 17 00:00:00 2001 From: sunerpy Date: Thu, 27 Aug 2026 18:10:44 +0800 Subject: [PATCH] fix(resolve): avoid cloning snapshot nodes during resolution --- crates/codegraph-resolve/src/context.rs | 82 +++++++++--- .../codegraph-resolve/src/frameworks/godot.rs | 29 +++-- .../src/frameworks/nestjs.rs | 18 +-- .../codegraph-resolve/src/frameworks/react.rs | 8 +- .../codegraph-resolve/src/frameworks/tauri.rs | 6 +- .../codegraph-resolve/src/frameworks/vue.rs | 6 +- .../codegraph-resolve/src/import_resolver.rs | 119 +++++++++--------- crates/codegraph-resolve/src/name_matcher.rs | 93 +++++++------- crates/codegraph-resolve/src/resolver.rs | 14 ++- .../codegraph-resolve/src/snapshot_context.rs | 118 ++++++++++++----- crates/codegraph-resolve/src/types.rs | 44 +++++++ 11 files changed, 356 insertions(+), 181 deletions(-) diff --git a/crates/codegraph-resolve/src/context.rs b/crates/codegraph-resolve/src/context.rs index 7d6de5b4..52ed30a8 100644 --- a/crates/codegraph-resolve/src/context.rs +++ b/crates/codegraph-resolve/src/context.rs @@ -13,9 +13,11 @@ use crate::workspace_packages::{WorkspacePackages, load_workspace_packages}; use crate::{import_resolver, pathutil}; use codegraph_core::types::{EdgeKind, Language, Node, NodeKind}; use codegraph_store::Store; +use std::borrow::Borrow; use std::cell::RefCell; use std::collections::BTreeSet; use std::path::Path; +use std::sync::Arc; /// `DEFAULT_CACHE_LIMIT` (`index.ts:54`). Override via env in the upstream; the /// Rust port keeps the fixed default for one resolution run. @@ -33,13 +35,13 @@ pub struct StoreResolutionContext<'a> { } struct Caches { - node_cache: LruCache>, + node_cache: LruCache>>, file_cache: LruCache>, import_mapping_cache: LruCache>, re_export_cache: LruCache>, - name_cache: LruCache>, - lower_name_cache: LruCache>, - qualified_name_cache: LruCache>, + name_cache: LruCache>>, + lower_name_cache: LruCache>>, + qualified_name_cache: LruCache>>, project_aliases: Option>, go_module: Option>, go_modules: Option>, @@ -93,27 +95,55 @@ impl<'a> StoreResolutionContext<'a> { impl ResolutionContext for StoreResolutionContext<'_> { fn get_nodes_in_file(&self, file_path: &str) -> Vec { + self.get_nodes_in_file_shared(file_path) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_in_file_shared(&self, file_path: &str) -> Vec> { let mut c = self.caches.borrow_mut(); if let Some(cached) = c.node_cache.get(&file_path.to_string()) { return cached; } - let result = self.store.nodes_by_file_path(file_path).unwrap_or_default(); + let result: Vec> = self + .store + .nodes_by_file_path(file_path) + .unwrap_or_default() + .into_iter() + .map(Arc::new) + .collect(); c.node_cache.set(file_path.to_string(), result.clone()); result } fn get_nodes_by_name(&self, name: &str) -> Vec { + self.get_nodes_by_name_shared(name) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_by_name_shared(&self, name: &str) -> Vec> { let mut c = self.caches.borrow_mut(); if let Some(cached) = c.name_cache.get(&name.to_string()) { return cached; } let mut result = self.store.nodes_by_name(name).unwrap_or_default(); order_candidates(&mut result); + let result: Vec> = result.into_iter().map(Arc::new).collect(); c.name_cache.set(name.to_string(), result.clone()); result } fn get_nodes_by_qualified_name(&self, qualified_name: &str) -> Vec { + self.get_nodes_by_qualified_name_shared(qualified_name) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_by_qualified_name_shared(&self, qualified_name: &str) -> Vec> { let mut c = self.caches.borrow_mut(); if let Some(cached) = c.qualified_name_cache.get(&qualified_name.to_string()) { return cached; @@ -123,6 +153,7 @@ impl ResolutionContext for StoreResolutionContext<'_> { .nodes_by_qualified_name(qualified_name) .unwrap_or_default(); order_candidates(&mut result); + let result: Vec> = result.into_iter().map(Arc::new).collect(); c.qualified_name_cache .set(qualified_name.to_string(), result.clone()); result @@ -132,6 +163,15 @@ impl ResolutionContext for StoreResolutionContext<'_> { self.store.nodes_by_kind(kind).unwrap_or_default() } + fn get_nodes_by_kind_shared(&self, kind: NodeKind) -> Vec> { + self.store + .nodes_by_kind(kind) + .unwrap_or_default() + .into_iter() + .map(Arc::new) + .collect() + } + fn known_node_names(&self) -> Vec { self.store.all_node_names().unwrap_or_default() } @@ -180,6 +220,13 @@ impl ResolutionContext for StoreResolutionContext<'_> { } fn get_nodes_by_lower_name(&self, lower_name: &str) -> Vec { + self.get_nodes_by_lower_name_shared(lower_name) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_by_lower_name_shared(&self, lower_name: &str) -> Vec> { let mut c = self.caches.borrow_mut(); if let Some(cached) = c.lower_name_cache.get(&lower_name.to_string()) { return cached; @@ -189,6 +236,7 @@ impl ResolutionContext for StoreResolutionContext<'_> { .nodes_by_lower_name(lower_name) .unwrap_or_default(); order_candidates(&mut result); + let result: Vec> = result.into_iter().map(Arc::new).collect(); c.lower_name_cache .set(lower_name.to_string(), result.clone()); result @@ -210,11 +258,11 @@ impl ResolutionContext for StoreResolutionContext<'_> { NodeKind::Protocol, NodeKind::Enum, ]; - let type_nodes: Vec = self - .get_nodes_by_name(type_name) + let type_nodes = self + .get_nodes_by_name_shared(type_name) .into_iter() .filter(|n| SUPERTYPE_BEARING.contains(&n.kind) && n.language == language) - .collect(); + .collect::>(); if type_nodes.is_empty() { return Vec::new(); } @@ -318,12 +366,6 @@ impl ResolutionContext for StoreResolutionContext<'_> { } } -/// Shares the byte-equivalence-critical [`order_candidates`] tie-break with the -/// [`SnapshotResolutionContext`](crate::snapshot_context::SnapshotResolutionContext). -pub(crate) fn order_candidates_pub(nodes: &mut [Node]) { - order_candidates(nodes); -} - /// Shares [`is_js_family_path`] with the snapshot context. pub(crate) fn is_js_family_path_pub(file_path: &str) -> bool { is_js_family_path(file_path) @@ -350,8 +392,10 @@ pub(crate) fn load_go_modules_pub(project_root: &str, files: &[String]) -> Vec>(nodes: &mut [T]) { nodes.sort_by(|a, b| { + let a = a.borrow(); + let b = b.borrow(); a.file_path .cmp(&b.file_path) .then(a.start_line.cmp(&b.start_line)) @@ -652,6 +696,12 @@ mod tests { assert_eq!(ctx.get_nodes_by_lower_name("foo").len(), 1); assert!(ctx.get_node_by_id("f1").is_some()); assert!(ctx.get_node_by_id("missing").is_none()); + let by_name = ctx.get_nodes_by_name_shared("foo"); + let by_name_cached = ctx.get_nodes_by_name_shared("foo"); + assert!(Arc::ptr_eq(&by_name[0], &by_name_cached[0])); + let by_file = ctx.get_nodes_in_file_shared("a.ts"); + let by_file_cached = ctx.get_nodes_in_file_shared("a.ts"); + assert!(Arc::ptr_eq(&by_file[0], &by_file_cached[0])); assert!(ctx.known_node_names().contains(&"foo".to_string())); assert_eq!(ctx.get_project_root(), root.to_str().unwrap()); std::fs::remove_dir_all(&root).ok(); @@ -798,7 +848,7 @@ mod tests { node("b", "n", NodeKind::Function, "b.ts", 1, 0), node("a", "n", NodeKind::Function, "a.ts", 1, 0), ]; - order_candidates_pub(&mut nodes); + order_candidates(&mut nodes); assert_eq!(nodes[0].id, "a"); assert!(is_js_family_path_pub("x.ts")); assert!(!is_js_family_path_pub("x.py")); diff --git a/crates/codegraph-resolve/src/frameworks/godot.rs b/crates/codegraph-resolve/src/frameworks/godot.rs index 0831584f..41b751b8 100644 --- a/crates/codegraph-resolve/src/frameworks/godot.rs +++ b/crates/codegraph-resolve/src/frameworks/godot.rs @@ -336,11 +336,12 @@ impl FrameworkResolver for GodotResolver { /// `[autoload]` entries that have a backing script path. fn autoload_singletons(context: &dyn ResolutionContext) -> Vec { context - .get_nodes_by_kind(NodeKind::Constant) + .get_nodes_by_kind_shared(NodeKind::Constant) .into_iter() .filter(|n| { n.language == Language::GodotProject && godot_project::is_project_godot(&n.file_path) }) + .map(|node| node.as_ref().clone()) .collect() } @@ -360,10 +361,10 @@ fn resolve_class_member( member: &str, ) -> Option { let mut class_files: Vec = context - .get_nodes_by_name(receiver) + .get_nodes_by_name_shared(receiver) .into_iter() .filter(|n| n.kind == NodeKind::Class && n.language == Language::Gdscript) - .map(|n| n.file_path) + .map(|n| n.file_path.clone()) .collect(); if class_files.is_empty() { return None; @@ -373,7 +374,7 @@ fn resolve_class_member( let class_file = &class_files[0]; let mut matches = context - .get_nodes_in_file(class_file) + .get_nodes_in_file_shared(class_file) .into_iter() .filter(|n| { n.kind == NodeKind::Function && n.language == Language::Gdscript && n.name == member @@ -382,7 +383,7 @@ fn resolve_class_member( if matches.next().is_some() { return None; } - Some(first) + Some(first.as_ref().clone()) } /// Resolve an autoload method call `access` (`Receiver.member`) to the UNIQUE @@ -410,7 +411,7 @@ fn resolve_autoload_func(context: &dyn ResolutionContext, access: &str) -> Optio let script_path = bindings.get(receiver)?; let mut matches = context - .get_nodes_in_file(script_path) + .get_nodes_in_file_shared(script_path) .into_iter() .filter(|n| { n.kind == NodeKind::Function && n.language == Language::Gdscript && n.name == member @@ -419,7 +420,7 @@ fn resolve_autoload_func(context: &dyn ResolutionContext, access: &str) -> Optio if matches.next().is_some() { return None; } - Some(first) + Some(first.as_ref().clone()) } /// Find the autoload singleton node whose name EXACTLY equals `name`. @@ -428,11 +429,15 @@ fn resolve_autoload_func(context: &dyn ResolutionContext, access: &str) -> Optio /// resolves when it names a real `[autoload]` singleton. Scans the `Constant` /// nodes restricted to `project.godot` so it cannot match an unrelated constant. fn find_autoload_singleton(context: &dyn ResolutionContext, name: &str) -> Option { - context.get_nodes_by_name(name).into_iter().find(|n| { - n.kind == NodeKind::Constant - && n.language == Language::GodotProject - && godot_project::is_project_godot(&n.file_path) - }) + context + .get_nodes_by_name_shared(name) + .into_iter() + .find(|n| { + n.kind == NodeKind::Constant + && n.language == Language::GodotProject + && godot_project::is_project_godot(&n.file_path) + }) + .map(|node| node.as_ref().clone()) } /// Map of `autoload name -> repo-relative script path`, recovered by RE-READING diff --git a/crates/codegraph-resolve/src/frameworks/nestjs.rs b/crates/codegraph-resolve/src/frameworks/nestjs.rs index ce9220a7..5a667d9e 100644 --- a/crates/codegraph-resolve/src/frameworks/nestjs.rs +++ b/crates/codegraph-resolve/src/frameworks/nestjs.rs @@ -75,11 +75,11 @@ impl FrameworkResolver for NestjsResolver { if !suffix.is_match(&reference.reference_name) { continue; } - let candidates: Vec = context - .get_nodes_by_name(&reference.reference_name) + let candidates = context + .get_nodes_by_name_shared(&reference.reference_name) .into_iter() .filter(|n| n.kind == NodeKind::Class) - .collect(); + .collect::>(); if candidates.is_empty() { return None; } @@ -270,17 +270,17 @@ impl FrameworkResolver for NestjsResolver { let mut updates: Vec = Vec::new(); for (controller_name, prefix) in &controller_to_prefix { - let classes: Vec = context - .get_nodes_by_name(controller_name) + let classes = context + .get_nodes_by_name_shared(controller_name) .into_iter() .filter(|n| n.kind == NodeKind::Class) - .collect(); + .collect::>(); for cls in classes { - let routes: Vec = context - .get_nodes_in_file(&cls.file_path) + let routes = context + .get_nodes_in_file_shared(&cls.file_path) .into_iter() .filter(|n| n.kind == NodeKind::Route) - .collect(); + .collect::>(); for route in routes { if route.start_line < cls.start_line || route.start_line > cls.end_line { continue; diff --git a/crates/codegraph-resolve/src/frameworks/react.rs b/crates/codegraph-resolve/src/frameworks/react.rs index cfef9dcc..dcb7d547 100644 --- a/crates/codegraph-resolve/src/frameworks/react.rs +++ b/crates/codegraph-resolve/src/frameworks/react.rs @@ -346,7 +346,7 @@ fn resolve_component( from_file: &str, context: &dyn ResolutionContext, ) -> Option { - let candidates = context.get_nodes_by_name(name); + let candidates = context.get_nodes_by_name_shared(name); if candidates.is_empty() { return None; } @@ -392,7 +392,7 @@ fn resolve_component( /// `resolveHook` (react.ts:328-343). fn resolve_hook(name: &str, context: &dyn ResolutionContext) -> Option { - let candidates = context.get_nodes_by_name(name); + let candidates = context.get_nodes_by_name_shared(name); if candidates.is_empty() { return None; } @@ -415,12 +415,12 @@ fn resolve_hook(name: &str, context: &dyn ResolutionContext) -> Option { /// `resolveContext` (react.ts:348-368). fn resolve_context(name: &str, context: &dyn ResolutionContext) -> Option { - let candidates = context.get_nodes_by_name(name); + let candidates = context.get_nodes_by_name_shared(name); if candidates.is_empty() { // Strip Context/Provider suffix fallback (react.ts:351-357). let base_name = strip_context_suffix(name); if base_name != name { - let base_candidates = context.get_nodes_by_name(base_name); + let base_candidates = context.get_nodes_by_name_shared(base_name); if !base_candidates.is_empty() { return Some(base_candidates[0].id.clone()); } diff --git a/crates/codegraph-resolve/src/frameworks/tauri.rs b/crates/codegraph-resolve/src/frameworks/tauri.rs index 6c3d3b6b..5517abaf 100644 --- a/crates/codegraph-resolve/src/frameworks/tauri.rs +++ b/crates/codegraph-resolve/src/frameworks/tauri.rs @@ -256,11 +256,11 @@ fn build_roster(context: &dyn ResolutionContext) -> Roster { /// cannot say which function the attribute belongs to, so the key is poisoned /// rather than guessed. fn admit_command(roster: &mut Roster, context: &dyn ResolutionContext, file: &str, name: &str) { - let mut candidates: Vec = context - .get_nodes_in_file(file) + let mut candidates = context + .get_nodes_in_file_shared(file) .into_iter() .filter(|n| n.name == name && matches!(n.kind, NodeKind::Function | NodeKind::Method)) - .collect(); + .collect::>(); let camel = snake_to_camel(name); match candidates.len() { 1 => { diff --git a/crates/codegraph-resolve/src/frameworks/vue.rs b/crates/codegraph-resolve/src/frameworks/vue.rs index 1c3417a7..dace768e 100644 --- a/crates/codegraph-resolve/src/frameworks/vue.rs +++ b/crates/codegraph-resolve/src/frameworks/vue.rs @@ -261,7 +261,7 @@ fn resolve_alias(alias_path: &str, context: &dyn ResolutionContext) -> Option Option { context - .get_nodes_in_file(file) + .get_nodes_in_file_shared(file) .into_iter() .find(|n| n.kind == NodeKind::Component && n.name == name) - .map(|n| n.id) + .map(|n| n.id.clone()) }; let from_dir = dir_of(from_file); diff --git a/crates/codegraph-resolve/src/import_resolver.rs b/crates/codegraph-resolve/src/import_resolver.rs index 0558c3ca..952e6d82 100644 --- a/crates/codegraph-resolve/src/import_resolver.rs +++ b/crates/codegraph-resolve/src/import_resolver.rs @@ -19,7 +19,7 @@ use crate::workspace_packages::resolve_workspace_import; use codegraph_core::types::{Language, Node, NodeKind}; use regex::Regex; use std::collections::BTreeSet; -use std::sync::OnceLock; +use std::sync::{Arc, OnceLock}; /// Extension resolution order by language (`EXTENSION_RESOLUTION`, /// `import-resolver.ts:17-37`). @@ -1295,13 +1295,13 @@ pub fn resolve_jvm_import( return None; } - let candidates = context.get_nodes_by_qualified_name(&format!("{pkg}::{sym}")); + let candidates = context.get_nodes_by_qualified_name_shared(&format!("{pkg}::{sym}")); if candidates.is_empty() { return None; } let best = if candidates.len() == 1 { - candidates[0].clone() + candidates[0].as_ref().clone() } else { pick_closest_jvm_candidate(&candidates, &reference.file_path) }; @@ -1314,7 +1314,7 @@ pub fn resolve_jvm_import( } /// `pickClosestJvmCandidate` (`import-resolver.ts:1096-1119`). -fn pick_closest_jvm_candidate(candidates: &[Node], from_path: &str) -> Node { +fn pick_closest_jvm_candidate(candidates: &[Arc], from_path: &str) -> Node { let from_dirs: Vec<&str> = drop_last_segment(from_path); let shared_prefix = |p: &str| -> usize { let d = drop_last_segment(p); @@ -1330,16 +1330,16 @@ fn pick_closest_jvm_candidate(candidates: &[Node], from_path: &str) -> Node { }; let is_expect = |n: &Node| -> bool { n.decorators.iter().any(|d| d == "expect") }; - let mut best = candidates[0].clone(); + let mut best = Arc::clone(&candidates[0]); let mut best_prox = shared_prefix(&best.file_path); for c in &candidates[1..] { let prox = shared_prefix(&c.file_path); if prox > best_prox || (prox == best_prox && is_expect(c) && !is_expect(&best)) { - best = c.clone(); + best = Arc::clone(c); best_prox = prox; } } - best + best.as_ref().clone() } fn drop_last_segment(path: &str) -> Vec<&str> { @@ -1376,13 +1376,13 @@ pub fn resolve_via_import( }); let sibling_base = pathutil::basename(&sibling_path); if let Some(sibling) = context - .get_nodes_by_name(sibling_base) + .get_nodes_by_name_shared(sibling_base) .into_iter() .find(|n| n.kind == NodeKind::File && n.file_path == sibling_path) { return Some(ResolvedRef { original: reference.clone(), - target_node_id: sibling.id, + target_node_id: sibling.id.clone(), confidence: 0.92, resolved_by: ResolvedBy::Import, }); @@ -1395,13 +1395,13 @@ pub fn resolve_via_import( )?; let basename = pathutil::basename(&resolved_path); if let Some(file_node) = context - .get_nodes_by_name(basename) + .get_nodes_by_name_shared(basename) .into_iter() .find(|n| n.kind == NodeKind::File && n.file_path == resolved_path) { return Some(ResolvedRef { original: reference.clone(), - target_node_id: file_node.id, + target_node_id: file_node.id.clone(), confidence: 0.9, resolved_by: ResolvedBy::Import, }); @@ -1416,13 +1416,13 @@ pub fn resolve_via_import( { let basename = pathutil::basename(&resolved_path); if let Some(file_node) = context - .get_nodes_by_name(basename) + .get_nodes_by_name_shared(basename) .into_iter() .find(|n| n.kind == NodeKind::File && n.file_path == resolved_path) { return Some(ResolvedRef { original: reference.clone(), - target_node_id: file_node.id, + target_node_id: file_node.id.clone(), confidence: 0.9, resolved_by: ResolvedBy::Import, }); @@ -1622,13 +1622,13 @@ fn resolve_module_import_to_file( ) { if resolved_path != reference.file_path { if let Some(file_node) = context - .get_nodes_in_file(&resolved_path) + .get_nodes_in_file_shared(&resolved_path) .into_iter() .find(|n| n.kind == NodeKind::File) { return Some(ResolvedRef { original: reference.clone(), - target_node_id: file_node.id, + target_node_id: file_node.id.clone(), confidence: 0.9, resolved_by: ResolvedBy::Import, }); @@ -1644,13 +1644,13 @@ fn resolve_module_import_to_file( find_python_module_file(&module_path, context, &reference.file_path) { if let Some(file_node) = context - .get_nodes_in_file(&mod_file) + .get_nodes_in_file_shared(&mod_file) .into_iter() .find(|n| n.kind == NodeKind::File) { return Some(ResolvedRef { original: reference.clone(), - target_node_id: file_node.id, + target_node_id: file_node.id.clone(), confidence: 0.9, resolved_by: ResolvedBy::Import, }); @@ -1693,7 +1693,7 @@ fn resolve_java_imported_reference( reference.reference_name[imp.local_name.len() + 1..].to_string() }; - let candidates = context.get_nodes_by_name(&member_name); + let candidates = context.get_nodes_by_name_shared(&member_name); for node in &candidates { if node.language != reference.language { continue; @@ -1764,7 +1764,7 @@ fn find_exported_symbol( } visited.insert(file_path.to_string()); - let nodes_in_file = context.get_nodes_in_file(file_path); + let nodes_in_file = context.get_nodes_in_file_shared(file_path); let re_exports = context.get_re_exports(file_path, language); let requested_name = if want.is_default { @@ -1786,7 +1786,7 @@ fn find_exported_symbol( .iter() .find(|node| node.name == *original_name && node.kind == NodeKind::Function) { - return Some(target.clone()); + return Some(target.as_ref().clone()); } } } @@ -1804,7 +1804,7 @@ fn find_exported_symbol( }) }) { - return Some(direct.clone()); + return Some(direct.as_ref().clone()); } } else if want.is_namespace { if let Some(member) = &want.member_name { @@ -1812,14 +1812,14 @@ fn find_exported_symbol( .iter() .find(|n| &n.name == member && n.is_exported) { - return Some(direct.clone()); + return Some(direct.as_ref().clone()); } } } else if let Some(direct) = nodes_in_file .iter() .find(|n| n.name == want.exported_name && n.is_exported) { - return Some(direct.clone()); + return Some(direct.as_ref().clone()); } // Cross-file re-export hits (import-resolver.ts:1855-1893). @@ -1981,8 +1981,8 @@ fn resolve_static_member( let member = remainder.split('.').next().filter(|s| !s.is_empty())?; let qualified = format!("{}::{}", container.qualified_name, member); - let mut candidates: Vec = context - .get_nodes_by_qualified_name(&qualified) + let mut candidates: Vec> = context + .get_nodes_by_qualified_name_shared(&qualified) .into_iter() .filter(|n| n.file_path == container.file_path) .collect(); @@ -1995,10 +1995,10 @@ fn resolve_static_member( .iter() .find(|n| matches!(n.kind, NodeKind::Method | NodeKind::Function)) { - return Some(callable.clone()); + return Some(callable.as_ref().clone()); } } - Some(candidates.swap_remove(0)) + Some(candidates.swap_remove(0).as_ref().clone()) } /// The module whose `module_path` covers `import_path`, longest match first. @@ -2059,7 +2059,7 @@ fn resolve_go_cross_package_reference( }; let pkg_dir = go_package_dir(&imp.source, module); - for node in context.get_nodes_by_name(member) { + for node in context.get_nodes_by_name_shared(member) { if node.language != Language::Go || !node.is_exported { continue; } @@ -2071,7 +2071,7 @@ fn resolve_go_cross_package_reference( if file_dir == pkg_dir { return Some(ResolvedRef { original: reference.clone(), - target_node_id: node.id, + target_node_id: node.id.clone(), confidence: 0.9, resolved_by: ResolvedBy::Import, }); @@ -2126,7 +2126,7 @@ fn resolve_python_module_member( } if let Some(target) = context - .get_nodes_in_file(&resolved_path) + .get_nodes_in_file_shared(&resolved_path) .into_iter() .find(|n| { n.name == member @@ -2141,7 +2141,7 @@ fn resolve_python_module_member( { return Some(ResolvedRef { original: reference.clone(), - target_node_id: target.id, + target_node_id: target.id.clone(), confidence: 0.85, resolved_by: ResolvedBy::Import, }); @@ -2217,7 +2217,7 @@ fn resolve_python_from_import_member( // `get_nodes_in_file` is ordered by `start_line`, so a file declaring the // name twice resolves deterministically to the first declaration. if let Some(target) = context - .get_nodes_in_file(&module_file) + .get_nodes_in_file_shared(&module_file) .into_iter() .find(|n| { n.name == imp.exported_name @@ -2232,7 +2232,7 @@ fn resolve_python_from_import_member( { return Some(ResolvedRef { original: reference.clone(), - target_node_id: target.id, + target_node_id: target.id.clone(), confidence: 0.9, resolved_by: ResolvedBy::Import, }); @@ -2257,10 +2257,10 @@ fn resolve_python_absolute_module( let hit_id = find_python_module_file(&reference.reference_name, context, &reference.file_path) .and_then(|path| { context - .get_nodes_in_file(&path) + .get_nodes_in_file_shared(&path) .into_iter() .find(|n| n.kind == NodeKind::File) - .map(|n| n.id) + .map(|n| n.id.clone()) })?; Some(ResolvedRef { original: reference.clone(), @@ -2285,7 +2285,7 @@ fn find_python_module_file( let ends_with = |p: &str, want: &str| p == want || p.ends_with(&format!("/{want}")); let module_file = context - .get_nodes_by_name(&format!("{last_seg}.py")) + .get_nodes_by_name_shared(&format!("{last_seg}.py")) .into_iter() .find(|n| { n.kind == NodeKind::File @@ -2293,17 +2293,17 @@ fn find_python_module_file( && ends_with(&n.file_path, &format!("{rel}.py")) }); if let Some(n) = module_file { - return Some(n.file_path); + return Some(n.file_path.clone()); } context - .get_nodes_by_name("__init__.py") + .get_nodes_by_name_shared("__init__.py") .into_iter() .find(|n| { n.kind == NodeKind::File && n.file_path != exclude_file_path && ends_with(&n.file_path, &format!("{rel}/__init__.py")) }) - .map(|n| n.file_path) + .map(|n| n.file_path.clone()) } /// Rust qualified path `A::B::C` → leaf `C` in the file the module prefix @@ -2327,25 +2327,28 @@ fn resolve_rust_path_reference( if file == reference.file_path { return None; } - let target = context.get_nodes_in_file(&file).into_iter().find(|n| { - n.name == leaf - && matches!( - n.kind, - NodeKind::Function - | NodeKind::Struct - | NodeKind::Union - | NodeKind::Enum - | NodeKind::Trait - | NodeKind::TypeAlias - | NodeKind::Constant - | NodeKind::Method - | NodeKind::Class - | NodeKind::Interface - ) - })?; + let target = context + .get_nodes_in_file_shared(&file) + .into_iter() + .find(|n| { + n.name == leaf + && matches!( + n.kind, + NodeKind::Function + | NodeKind::Struct + | NodeKind::Union + | NodeKind::Enum + | NodeKind::Trait + | NodeKind::TypeAlias + | NodeKind::Constant + | NodeKind::Method + | NodeKind::Class + | NodeKind::Interface + ) + })?; Some(ResolvedRef { original: reference.clone(), - target_node_id: target.id, + target_node_id: target.id.clone(), confidence: 0.9, resolved_by: ResolvedBy::Import, }) @@ -2495,13 +2498,13 @@ fn resolve_lua_require( continue; } if let Some(file_node) = context - .get_nodes_in_file(best) + .get_nodes_in_file_shared(best) .into_iter() .find(|n| n.kind == NodeKind::File) { return Some(ResolvedRef { original: reference.clone(), - target_node_id: file_node.id, + target_node_id: file_node.id.clone(), confidence: 0.9, resolved_by: ResolvedBy::Import, }); diff --git a/crates/codegraph-resolve/src/name_matcher.rs b/crates/codegraph-resolve/src/name_matcher.rs index a5c69117..903c9659 100644 --- a/crates/codegraph-resolve/src/name_matcher.rs +++ b/crates/codegraph-resolve/src/name_matcher.rs @@ -11,7 +11,8 @@ use crate::types::{ }; use codegraph_core::types::{EdgeKind, Language, Node, NodeKind}; use regex::Regex; -use std::sync::OnceLock; +use std::borrow::Borrow; +use std::sync::{Arc, OnceLock}; /// Ceiling on same-name candidates a proximity-SCORED strategy will rank /// (`AMBIGUOUS_NAME_CEILING`, upstream name-matcher; override @@ -50,8 +51,8 @@ pub fn match_by_file_path( return None; } - let candidates = context.get_nodes_by_name(file_name); - let file_nodes: Vec = candidates + let candidates = context.get_nodes_by_name_shared(file_name); + let file_nodes: Vec> = candidates .into_iter() .filter(|n| n.kind == NodeKind::File) .collect(); @@ -74,6 +75,7 @@ pub fn match_by_file_path( // Suffix match, picking the closest file node (name-matcher.ts:54-64). let suffix_matches: Vec<&Node> = file_nodes .iter() + .map(Arc::as_ref) .filter(|n| { n.qualified_name.ends_with(&reference.reference_name) || n.file_path.ends_with(&reference.reference_name) @@ -192,15 +194,15 @@ pub fn crosses_known_family(a: Language, b: Language) -> bool { /// Drop cross-language candidates from a name lookup (`applyLanguageGate`, /// `name-matcher.ts:160-168`). -fn apply_language_gate(candidates: Vec, reference: &RefView) -> Vec { +fn apply_language_gate>(candidates: Vec, reference: &RefView) -> Vec { match reference.reference_kind { EdgeKind::References => candidates .into_iter() - .filter(|c| same_language_family(c.language, reference.language)) + .filter(|c| same_language_family(c.borrow().language, reference.language)) .collect(), EdgeKind::Imports => candidates .into_iter() - .filter(|c| !crosses_known_family(c.language, reference.language)) + .filter(|c| !crosses_known_family(c.borrow().language, reference.language)) .collect(), _ => candidates, } @@ -233,8 +235,8 @@ fn is_lexically_reachable( if parent_qualified.is_empty() { return true; } - let containers: Vec = context - .get_nodes_by_qualified_name(parent_qualified) + let containers: Vec> = context + .get_nodes_by_qualified_name_shared(parent_qualified) .into_iter() .filter(|p| { p.file_path == candidate.file_path @@ -258,8 +260,8 @@ pub fn match_by_exact_name( reference: &RefView, context: &dyn ResolutionContext, ) -> Option { - let reachable: Vec = apply_language_gate( - context.get_nodes_by_name(&reference.reference_name), + let reachable: Vec> = apply_language_gate( + context.get_nodes_by_name_shared(&reference.reference_name), reference, ) .into_iter() @@ -271,7 +273,7 @@ pub fn match_by_exact_name( // importable (#1537/#1536). Filtering BEFORE ranking — not just refusing the // winner afterwards — is what lets a legitimate supertype OUTRANK a // same-named enum member instead of the whole reference being dropped. - let candidates: Vec = reachable + let candidates: Vec> = reachable .iter() .filter(|n| kind_is_eligible_target(reference.reference_kind, n.kind)) .cloned() @@ -328,7 +330,7 @@ pub fn match_by_qualified_name( return None; } - let candidates = context.get_nodes_by_qualified_name(&reference.reference_name); + let candidates = context.get_nodes_by_qualified_name_shared(&reference.reference_name); if candidates.len() == 1 { return Some(ResolvedRef { original: reference.clone(), @@ -358,8 +360,8 @@ pub fn match_by_qualified_name( // with the reference (#1079). let parts: Vec<&str> = reference.reference_name.split([':', '.']).collect(); if let Some(last_name) = parts.last().filter(|s| !s.is_empty()) { - let partial: Vec = context - .get_nodes_by_name(last_name) + let partial: Vec> = context + .get_nodes_by_name_shared(last_name) .into_iter() .filter(|c| c.qualified_name.ends_with(&reference.reference_name)) .collect(); @@ -385,14 +387,14 @@ pub fn match_by_qualified_name( /// `a/svc`. No-op when there are <2 candidates or none share the call site's /// file. The partition is STABLE (preserves within-group order), so edge output /// stays deterministic. -fn prefer_call_site_file(nodes: Vec, call_site_file: &str) -> Vec { +fn prefer_call_site_file>(nodes: Vec, call_site_file: &str) -> Vec { if nodes.len() < 2 { return nodes; } - let mut same: Vec = Vec::new(); - let mut other: Vec = Vec::new(); + let mut same: Vec = Vec::new(); + let mut other: Vec = Vec::new(); for n in nodes { - if n.file_path == call_site_file { + if n.borrow().file_path == call_site_file { same.push(n); } else { other.push(n); @@ -419,9 +421,9 @@ pub(crate) fn resolve_method_on_type( preferred_fqn: Option<&str>, depth: u32, ) -> Option { - let method_candidates = context.get_nodes_by_name(method_name); + let method_candidates = context.get_nodes_by_name_shared(method_name); let want = format!("{type_name}::{method_name}"); - let matches: Vec = method_candidates + let matches: Vec> = method_candidates .into_iter() .filter(|m| { m.kind == NodeKind::Method @@ -499,7 +501,7 @@ fn cpp_last_segment(name: &str) -> &str { /// (`cppClassExists`, `name-matcher.ts:621-626`). fn cpp_class_exists(name: &str, reference: &RefView, context: &dyn ResolutionContext) -> bool { let last = cpp_last_segment(name); - context.get_nodes_by_name(last).iter().any(|n| { + context.get_nodes_by_name_shared(last).iter().any(|n| { matches!(n.kind, NodeKind::Class | NodeKind::Struct | NodeKind::Union) && n.language == reference.language }) @@ -726,7 +728,7 @@ fn infer_java_field_receiver_type( reference: &RefView, context: &dyn ResolutionContext, ) -> Option { - let in_file = context.get_nodes_in_file(&reference.file_path); + let in_file = context.get_nodes_in_file_shared(&reference.file_path); if in_file.is_empty() { return None; } @@ -930,7 +932,7 @@ fn local_receiver_type_patterns_tagged(language: Language, r: &str) -> Vec<(Rege /// so a same-named variable in another function can't leak in. fn enclosing_scope_start_line(reference: &RefView, context: &dyn ResolutionContext) -> i64 { let mut start = 1i64; - for n in context.get_nodes_in_file(&reference.file_path) { + for n in context.get_nodes_in_file_shared(&reference.file_path) { if !matches!(n.kind, NodeKind::Function | NodeKind::Method) || n.language != reference.language { @@ -1043,7 +1045,7 @@ fn infer_class_field_receiver_type( return None; } - let in_file = context.get_nodes_in_file(&reference.file_path); + let in_file = context.get_nodes_in_file_shared(&reference.file_path); let enclosing = in_file .iter() .filter(|n| { @@ -1115,7 +1117,7 @@ fn is_receiver_type_bound_at_call_site( context: &dyn ResolutionContext, ) -> bool { if context - .get_nodes_in_file(&reference.file_path) + .get_nodes_in_file_shared(&reference.file_path) .iter() .any(|n| n.name == type_name && declares_type_name(n.kind)) { @@ -1432,7 +1434,7 @@ pub fn match_method_call( // receiver names a class in several files, try the call site's own file // first (#1079). for class_node in prefer_call_site_file( - context.get_nodes_by_name(&object_or_class), + context.get_nodes_by_name_shared(&object_or_class), &reference.file_path, ) { if matches!( @@ -1458,7 +1460,7 @@ pub fn match_method_call( let capitalized = capitalize(&object_or_class); if capitalized != object_or_class { for class_node in prefer_call_site_file( - context.get_nodes_by_name(&capitalized), + context.get_nodes_by_name_shared(&capitalized), &reference.file_path, ) { if matches!( @@ -1483,17 +1485,17 @@ pub fn match_method_call( // Strategy 3: methods-by-name, receiver-overlap scoring // (name-matcher.ts:882-933). - let method_candidates = context.get_nodes_by_name(&method_name); + let method_candidates = context.get_nodes_by_name_shared(&method_name); // Ubiquitous-method ceiling (#999): bail before the O(K) scoring work when a // method name is re-declared across a vendored theme/SDK. if method_candidates.len() > ambiguous_name_ceiling() { return None; } - let methods: Vec = method_candidates + let methods: Vec> = method_candidates .into_iter() .filter(|n| n.kind == NodeKind::Method && n.name == method_name) .collect(); - let same_language: Vec = methods + let same_language: Vec> = methods .iter() .filter(|m| m.language == reference.language) .cloned() @@ -1767,13 +1769,14 @@ fn find_method_in_class( context: &dyn ResolutionContext, ) -> Option { context - .get_nodes_in_file(&class_node.file_path) + .get_nodes_in_file_shared(&class_node.file_path) .into_iter() .find(|n| { n.kind == NodeKind::Method && n.name == method_name && n.qualified_name.contains(&class_node.name) }) + .map(|node| node.as_ref().clone()) } fn capitalize(s: &str) -> String { @@ -1874,11 +1877,15 @@ fn drop_last(path: &str) -> Vec<&str> { /// Find the best matching node among multiple candidates (`findBestMatch`, /// `name-matcher.ts:973-1055`). -fn find_best_match<'a>(reference: &RefView, candidates: &'a [Node]) -> Option<&'a Node> { +fn find_best_match<'a, T: Borrow>( + reference: &RefView, + candidates: &'a [T], +) -> Option<&'a Node> { let mut best_score = -1.0f64; let mut best_node: Option<&Node> = None; for candidate in candidates { + let candidate = candidate.borrow(); let mut score = 0.0f64; if candidate.file_path == reference.file_path { @@ -1938,7 +1945,7 @@ fn find_best_match<'a>(reference: &RefView, candidates: &'a [Node]) -> Option<&' /// `name-matcher.ts:1060-1088`). pub fn match_fuzzy(reference: &RefView, context: &dyn ResolutionContext) -> Option { let lower_name = reference.reference_name.to_lowercase(); - let candidates = context.get_nodes_by_lower_name(&lower_name); + let candidates = context.get_nodes_by_lower_name_shared(&lower_name); if candidates.len() > ambiguous_name_ceiling() { return None; } @@ -1952,7 +1959,7 @@ pub fn match_fuzzy(reference: &RefView, context: &dyn ResolutionContext) -> Opti reference, ); - let same_language: Vec = callable_candidates + let same_language: Vec> = callable_candidates .iter() .filter(|n| n.language == reference.language) .cloned() @@ -2135,8 +2142,8 @@ fn lookup_callee_return_type( method = parts.last().copied().unwrap_or(callee).to_string(); cls = Some(parts[..parts.len() - 1].join("::")); } - let candidates: Vec = context - .get_nodes_by_name(&method) + let candidates: Vec> = context + .get_nodes_by_name_shared(&method) .into_iter() .filter(|n| { matches!(n.kind, NodeKind::Method | NodeKind::Function) @@ -2251,8 +2258,8 @@ pub fn match_function_ref( // that scope, unique-or-drop. Exempt from bare_fn_only. if let Some(sep) = reference.reference_name.rfind("::") { let member_name = &reference.reference_name[sep + 2..]; - let scoped: Vec = context - .get_nodes_by_name(member_name) + let scoped: Vec> = context + .get_nodes_by_name_shared(member_name) .into_iter() .filter(|n| { matches!(n.kind, NodeKind::Function | NodeKind::Method) @@ -2268,13 +2275,14 @@ pub fn match_function_ref( } let same_file: Vec<&Node> = scoped .iter() + .map(Arc::as_ref) .filter(|n| n.file_path == reference.file_path) .collect(); if same_file.is_empty() && scoped.len() > 1 { return None; } let pool: Vec<&Node> = if same_file.is_empty() { - scoped.iter().collect() + scoped.iter().map(Arc::as_ref).collect() } else { same_file }; @@ -2290,8 +2298,8 @@ pub fn match_function_ref( }); } - let mut candidates: Vec = context - .get_nodes_by_name(&reference.reference_name) + let mut candidates: Vec> = context + .get_nodes_by_name_shared(&reference.reference_name) .into_iter() .filter(|n| { (n.kind == NodeKind::Function @@ -2312,7 +2320,7 @@ pub fn match_function_ref( && candidates.iter().any(|n| n.kind == NodeKind::Method) { let class_prefix = context - .get_node_by_id(&reference.from_node_id) + .get_node_by_id_shared(&reference.from_node_id) .and_then(|f| { let sep = f.qualified_name.rfind("::")?; if sep > 0 { @@ -2346,6 +2354,7 @@ pub fn match_function_ref( let same_file: Vec<&Node> = candidates .iter() + .map(Arc::as_ref) .filter(|n| n.file_path == reference.file_path) .collect(); if !same_file.is_empty() { diff --git a/crates/codegraph-resolve/src/resolver.rs b/crates/codegraph-resolve/src/resolver.rs index 7220bac9..2e103a89 100644 --- a/crates/codegraph-resolve/src/resolver.rs +++ b/crates/codegraph-resolve/src/resolver.rs @@ -1037,7 +1037,7 @@ impl ReferenceResolver { { return Some(result); } - let Some(target) = context.get_node_by_id(&result.target_node_id) else { + let Some(target) = context.get_node_by_id_shared(&result.target_node_id) else { return Some(result); }; if crate::types::kind_is_eligible_target(reference.reference_kind, target.kind) { @@ -1079,7 +1079,7 @@ impl ReferenceResolver { if let Some(via_import) = self.gate_language(resolve_via_import(reference, context), reference, context) { - if let Some(target) = context.get_node_by_id(&via_import.target_node_id) { + if let Some(target) = context.get_node_by_id_shared(&via_import.target_node_id) { if matches!(target.kind, NodeKind::Function | NodeKind::Method) || is_python_class_function_ref_target(reference.language, target.kind) { @@ -1179,7 +1179,7 @@ impl ReferenceResolver { if member.is_empty() { return (None, None); } - let Some(from_node) = context.get_node_by_id(&reference.from_node_id) else { + let Some(from_node) = context.get_node_by_id_shared(&reference.from_node_id) else { return (None, None); }; let class_prefix = if matches!( @@ -1205,7 +1205,7 @@ impl ReferenceResolver { }; let qualified = format!("{class_prefix}::{member}"); let target = context - .get_nodes_by_qualified_name(&qualified) + .get_nodes_by_qualified_name_shared(&qualified) .into_iter() .filter(|n| { matches!(n.kind, NodeKind::Function | NodeKind::Method) @@ -1217,7 +1217,7 @@ impl ReferenceResolver { Some(target) => ( Some(ResolvedRef { original: reference.clone(), - target_node_id: target.id, + target_node_id: target.id.clone(), confidence: 0.95, resolved_by: ResolvedBy::FunctionRef, }), @@ -1982,7 +1982,9 @@ impl ReferenceResolver { target_node_id: &str, context: &dyn ResolutionContext, ) -> Option { - context.get_node_by_id(target_node_id).map(|n| n.language) + context + .get_node_by_id_shared(target_node_id) + .map(|n| n.language) } } diff --git a/crates/codegraph-resolve/src/snapshot_context.rs b/crates/codegraph-resolve/src/snapshot_context.rs index d8ce2204..b6c0ad9e 100644 --- a/crates/codegraph-resolve/src/snapshot_context.rs +++ b/crates/codegraph-resolve/src/snapshot_context.rs @@ -23,10 +23,11 @@ //! //! Each node-lookup `Vec` is built by copying the store's own query output //! verbatim (`nodes_by_file_path`, `nodes_by_kind`, `all_node_names`) or by -//! applying the identical [`order_candidates`](crate::context) tie-break, so the +//! applying the identical [`order_candidates`](crate::context::order_candidates) +//! tie-break, so the //! candidate order matches the store context exactly. -use crate::context::{DEFAULT_CACHE_LIMIT, order_candidates_pub}; +use crate::context::{DEFAULT_CACHE_LIMIT, order_candidates}; use crate::import_resolver; use crate::path_aliases::{AliasMap, load_project_aliases}; use crate::types::{GoModule, ImportMapping, ReExport, ResolutionContext}; @@ -193,12 +194,12 @@ impl SnapshotCaches { /// safe to share across `rayon` threads. struct NodeSnapshot { project_root: String, - by_name: HashMap>, - by_lower_name: HashMap>, - by_qualified_name: HashMap>, - by_kind: HashMap>, - by_file_path: HashMap>, - by_id: HashMap, + by_name: HashMap>>, + by_lower_name: HashMap>>, + by_qualified_name: HashMap>>, + by_kind: HashMap>>, + by_file_path: HashMap>>, + by_id: HashMap>, known_node_names: Vec, known_file_paths: HashSet, all_file_paths: Vec, @@ -238,50 +239,64 @@ impl SnapshotResolutionContext { let project_root = project_root.into(); let nodes = store.all_nodes()?; - let mut by_name: HashMap> = HashMap::new(); - let mut by_lower_name: HashMap> = HashMap::new(); - let mut by_qualified_name: HashMap> = HashMap::new(); - let mut by_id: HashMap = HashMap::with_capacity(nodes.len()); + let mut by_name: HashMap>> = HashMap::new(); + let mut by_lower_name: HashMap>> = HashMap::new(); + let mut by_qualified_name: HashMap>> = HashMap::new(); + let mut by_id: HashMap> = HashMap::with_capacity(nodes.len()); - for node in &nodes { + for node in nodes { + let node = Arc::new(node); by_name .entry(node.name.clone()) .or_default() - .push(node.clone()); + .push(Arc::clone(&node)); by_lower_name .entry(node.name.to_lowercase()) .or_default() - .push(node.clone()); + .push(Arc::clone(&node)); by_qualified_name .entry(node.qualified_name.clone()) .or_default() - .push(node.clone()); - by_id.insert(node.id.clone(), node.clone()); + .push(Arc::clone(&node)); + by_id.insert(node.id.clone(), node); } for list in by_name.values_mut() { - order_candidates_pub(list); + order_candidates(list); } for list in by_lower_name.values_mut() { - order_candidates_pub(list); + order_candidates(list); } for list in by_qualified_name.values_mut() { - order_candidates_pub(list); + order_candidates(list); } // Per-file and per-kind lists copy the store's own query output verbatim // so the candidate order matches `nodes_by_file_path` (ORDER BY // start_line) and `nodes_by_kind` (SQLite scan order) exactly. - let mut file_paths: Vec = nodes.iter().map(|n| n.file_path.clone()).collect(); + let mut file_paths: Vec = by_id.values().map(|n| n.file_path.clone()).collect(); file_paths.sort_unstable(); file_paths.dedup(); - let mut by_file_path: HashMap> = HashMap::with_capacity(file_paths.len()); + let mut by_file_path: HashMap>> = + HashMap::with_capacity(file_paths.len()); for fp in &file_paths { - by_file_path.insert(fp.clone(), store.nodes_by_file_path(fp).unwrap_or_default()); + let entries = store + .nodes_by_file_path(fp) + .unwrap_or_default() + .into_iter() + .filter_map(|node| by_id.get(&node.id).cloned()) + .collect(); + by_file_path.insert(fp.clone(), entries); } - let mut by_kind: HashMap> = HashMap::new(); + let mut by_kind: HashMap>> = HashMap::new(); for kind in NodeKind::ALL { - by_kind.insert(kind, store.nodes_by_kind(kind).unwrap_or_default()); + let entries = store + .nodes_by_kind(kind) + .unwrap_or_default() + .into_iter() + .filter_map(|node| by_id.get(&node.id).cloned()) + .collect(); + by_kind.insert(kind, entries); } let known_node_names = store.all_node_names().unwrap_or_default(); @@ -366,6 +381,13 @@ impl SnapshotResolutionContext { impl ResolutionContext for SnapshotResolutionContext { fn get_nodes_in_file(&self, file_path: &str) -> Vec { + self.get_nodes_in_file_shared(file_path) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_in_file_shared(&self, file_path: &str) -> Vec> { self.snapshot .by_file_path .get(file_path) @@ -374,10 +396,24 @@ impl ResolutionContext for SnapshotResolutionContext { } fn get_nodes_by_name(&self, name: &str) -> Vec { + self.get_nodes_by_name_shared(name) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_by_name_shared(&self, name: &str) -> Vec> { self.snapshot.by_name.get(name).cloned().unwrap_or_default() } fn get_nodes_by_qualified_name(&self, qualified_name: &str) -> Vec { + self.get_nodes_by_qualified_name_shared(qualified_name) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_by_qualified_name_shared(&self, qualified_name: &str) -> Vec> { self.snapshot .by_qualified_name .get(qualified_name) @@ -386,6 +422,13 @@ impl ResolutionContext for SnapshotResolutionContext { } fn get_nodes_by_kind(&self, kind: NodeKind) -> Vec { + self.get_nodes_by_kind_shared(kind) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_by_kind_shared(&self, kind: NodeKind) -> Vec> { self.snapshot .by_kind .get(&kind) @@ -431,6 +474,13 @@ impl ResolutionContext for SnapshotResolutionContext { } fn get_nodes_by_lower_name(&self, lower_name: &str) -> Vec { + self.get_nodes_by_lower_name_shared(lower_name) + .into_iter() + .map(|node| node.as_ref().clone()) + .collect() + } + + fn get_nodes_by_lower_name_shared(&self, lower_name: &str) -> Vec> { self.snapshot .by_lower_name .get(lower_name) @@ -439,6 +489,11 @@ impl ResolutionContext for SnapshotResolutionContext { } fn get_node_by_id(&self, id: &str) -> Option { + self.get_node_by_id_shared(id) + .map(|node| node.as_ref().clone()) + } + + fn get_node_by_id_shared(&self, id: &str) -> Option> { self.snapshot.by_id.get(id).cloned() } @@ -455,11 +510,11 @@ impl ResolutionContext for SnapshotResolutionContext { NodeKind::Protocol, NodeKind::Enum, ]; - let type_nodes: Vec = self - .get_nodes_by_name(type_name) + let type_nodes = self + .get_nodes_by_name_shared(type_name) .into_iter() .filter(|n| SUPERTYPE_BEARING.contains(&n.kind) && n.language == language) - .collect(); + .collect::>(); if type_nodes.is_empty() { return Vec::new(); } @@ -659,6 +714,13 @@ mod tests { assert_eq!(ctx.get_nodes_by_lower_name("child").len(), 1); assert!(ctx.get_node_by_id("child").is_some()); assert!(ctx.get_node_by_id("missing").is_none()); + let by_name = ctx.get_nodes_by_name_shared("Child"); + let by_file = ctx.get_nodes_in_file_shared("a.ts"); + let by_kind = ctx.get_nodes_by_kind_shared(NodeKind::Class); + let by_id = ctx.get_node_by_id_shared("child").expect("shared id"); + assert!(Arc::ptr_eq(&by_name[0], &by_file[0])); + assert!(Arc::ptr_eq(&by_name[0], &by_kind[0])); + assert!(Arc::ptr_eq(&by_name[0], &by_id)); assert!(ctx.known_node_names().contains(&"Child".to_string())); assert_eq!(ctx.get_project_root(), root.to_str().unwrap()); assert!(ctx.get_nodes_in_file("nope.ts").is_empty()); diff --git a/crates/codegraph-resolve/src/types.rs b/crates/codegraph-resolve/src/types.rs index 20d2dd24..fe65b4ee 100644 --- a/crates/codegraph-resolve/src/types.rs +++ b/crates/codegraph-resolve/src/types.rs @@ -7,6 +7,7 @@ //! here as [`RefView`] so the two never get confused. use codegraph_core::types::{EdgeKind, Language, Node, NodeKind, ReferenceSubkind}; +use std::sync::Arc; /// The ES-module family: the languages where a symbol declared in another file is /// visible ONLY through an explicit `import`, and the set @@ -295,12 +296,44 @@ pub struct FrameworkResolverExtractionResult { pub trait ResolutionContext { /// Get all nodes in a file (`getNodesInFile`, ordered by `start_line`). fn get_nodes_in_file(&self, file_path: &str) -> Vec; + /// Shared-node variant for hot resolution paths. + /// + /// The default preserves compatibility for lightweight/test contexts. + /// Production contexts override it so repeated lookups clone only `Arc` + /// handles instead of every `Node` string/vector field. + fn get_nodes_in_file_shared(&self, file_path: &str) -> Vec> { + self.get_nodes_in_file(file_path) + .into_iter() + .map(Arc::new) + .collect() + } /// Get all nodes by name (`getNodesByName`). fn get_nodes_by_name(&self, name: &str) -> Vec; + /// Shared-node variant of [`Self::get_nodes_by_name`]. + fn get_nodes_by_name_shared(&self, name: &str) -> Vec> { + self.get_nodes_by_name(name) + .into_iter() + .map(Arc::new) + .collect() + } /// Get all nodes by exact qualified name (`getNodesByQualifiedName`). fn get_nodes_by_qualified_name(&self, qualified_name: &str) -> Vec; + /// Shared-node variant of [`Self::get_nodes_by_qualified_name`]. + fn get_nodes_by_qualified_name_shared(&self, qualified_name: &str) -> Vec> { + self.get_nodes_by_qualified_name(qualified_name) + .into_iter() + .map(Arc::new) + .collect() + } /// Get all nodes of a kind (`getNodesByKind`). fn get_nodes_by_kind(&self, kind: codegraph_core::types::NodeKind) -> Vec; + /// Shared-node variant of [`Self::get_nodes_by_kind`]. + fn get_nodes_by_kind_shared(&self, kind: codegraph_core::types::NodeKind) -> Vec> { + self.get_nodes_by_kind(kind) + .into_iter() + .map(Arc::new) + .collect() + } /// All node names for the `warmCaches` known-name set (`index.ts:298-308`). /// Default loops every kind (old behavior); store contexts override to pull @@ -332,11 +365,22 @@ pub trait ResolutionContext { fn get_all_files(&self) -> Vec; /// Get nodes by lowercase name (`getNodesByLowerName`, O(1) via index). fn get_nodes_by_lower_name(&self, lower_name: &str) -> Vec; + /// Shared-node variant of [`Self::get_nodes_by_lower_name`]. + fn get_nodes_by_lower_name_shared(&self, lower_name: &str) -> Vec> { + self.get_nodes_by_lower_name(lower_name) + .into_iter() + .map(Arc::new) + .collect() + } /// Resolve a node by id (`queries.getNodeById`). The upstream context reaches /// `queries` directly for this (`index.ts:1087,1094`); the Rust port exposes /// it on the trait so the orchestrator's language gates stay pure. fn get_node_by_id(&self, id: &str) -> Option; + /// Shared-node variant of [`Self::get_node_by_id`]. + fn get_node_by_id_shared(&self, id: &str) -> Option> { + self.get_node_by_id(id).map(Arc::new) + } /// Direct supertypes of `type_name` in `language` (`getSupertypes?`). ///