From 0d3abc28d46c05433241995b92b2c42c3e9f1bc6 Mon Sep 17 00:00:00 2001 From: sunerpy Date: Wed, 19 Aug 2026 23:48:12 +0800 Subject: [PATCH] fix(resolve): stop binding calls, imports and supertypes to coincidences MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A missing edge makes an agent look further; a false edge makes it confidently wrong. Three shapes produced false ones. Extraction discarded a member-shaped receiver, so `this.mailer.send(m)` reached resolution as the bare name `send`. With two same-named methods in one file the line-proximity term then scored the enclosing method +20.0 against the real target's +19.7, and a method resolved to ITSELF while the true callee went unreferenced. The receiver's last segment is now preserved, across TypeScript, Python, Go, Rust and Swift rather than TypeScript alone. Built-in receivers hijacked project methods. The inferred type is now required to be BOUND at the call site — declared in the same file, or carried by an import mapping — and the gate sits before typed resolution rather than after its failure, because the hijack arrives via a typed path that SUCCEEDS. No built-in name list is introduced; visibility is the discriminator. Inference additionally reads a class field's own declaration, which the enclosing-scope scan cannot reach, so a field receiver is typed instead of guessed. Import and supertype references bound to any local symbol sharing the name: an `imports` edge landed on a class property, and an out-of-repo supertype on an enum member. Both now require a target of a compatible kind AND locality, because kind filtering alone merely relocates the false edge onto a legally kinded type alias. Recursion is untouched: `self.run(n - 1)` is a genuine self-edge and the erlang golden's two remain. On this repo the change removes 111 `impl Drop for X` edges that had bound to a C++ enum member, leaving 21 that all target real in-repo traits, interfaces and modules, and upgrades 432 calls from a proximity guess to a receiver-typed binding. EXTRACTION_VERSION 5 -> 6: stored edges change, so an existing index is stale. --- .oxfmtignore | 5 +- crates/codegraph-extract/src/walker.rs | 207 +++- .../codegraph-resolve/src/import_resolver.rs | 437 ++++++++- crates/codegraph-resolve/src/name_matcher.rs | 905 +++++++++++++++++- crates/codegraph-resolve/src/resolver.rs | 162 +++- crates/codegraph-resolve/src/types.rs | 205 +++- .../tests/fixtures/tier2/bound/barrel.ts | 1 + .../tests/fixtures/tier2/bound/named.ts | 6 + .../tests/fixtures/tier2/bound/other.ts | 1 + .../tests/fixtures/tier2/bound/viaBarrel.ts | 6 + .../tests/fixtures/tier2/esm_import/run.ts | 5 + .../tests/fixtures/tier2/esm_import/types.ts | 4 + .../tests/fixtures/tier2/hijack/main.ts | 4 + .../tests/fixtures/tier2/hijack/other.ts | 1 + .../tests/fixtures/tier2/item4/mail.ts | 9 + .../tests/fixtures/tier2/item5/repro.ts | 28 + .../tests/fixtures/tier2/recur/rec.ts | 2 + .../tier2/rust_supertype/src/alias.rs | 1 + .../fixtures/tier2/rust_supertype/src/lib.rs | 22 + .../tier2/rust_supertype/src/ports.rs | 3 + .../tests/fixtures/tier2/sfc/Box.svelte | 9 + .../tests/fixtures/tier2/sfc/models.ts | 3 + .../tests/fixtures/tier2/sfc/package.json | 1 + .../tests/tier2_false_edges.rs | 454 +++++++++ crates/codegraph-store/src/index_state.rs | 2 +- crates/codegraph-store/tests/index_state.rs | 2 +- 26 files changed, 2445 insertions(+), 40 deletions(-) create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/bound/barrel.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/bound/named.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/bound/other.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/bound/viaBarrel.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/esm_import/run.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/esm_import/types.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/hijack/main.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/hijack/other.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/item4/mail.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/item5/repro.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/recur/rec.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/alias.rs create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/lib.rs create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/ports.rs create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/sfc/Box.svelte create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/sfc/models.ts create mode 100644 crates/codegraph-resolve/tests/fixtures/tier2/sfc/package.json create mode 100644 crates/codegraph-resolve/tests/tier2_false_edges.rs diff --git a/.oxfmtignore b/.oxfmtignore index 1aed11bb..2abf44c7 100644 --- a/.oxfmtignore +++ b/.oxfmtignore @@ -19,9 +19,12 @@ docs/upstream-sync/V1_5_COMMIT_MANIFEST.md reference/ # Test input fixtures are parsed by the extractors; reformatting changes the -# extraction output and breaks golden parity. +# extraction output and breaks golden parity. The tier2 fixtures additionally +# assert on exact LINE NUMBERS (a self-edge is only distinguishable from a +# correct edge by start_line), so reflowing them breaks those assertions. crates/codegraph-bench/fixtures/ crates/codegraph-extract/tests/fixtures/ +crates/codegraph-resolve/tests/fixtures/ # Embedded verbatim into the MCP tools/list response and byte-compared against # golden; reformatting breaks the MCP golden test. diff --git a/crates/codegraph-extract/src/walker.rs b/crates/codegraph-extract/src/walker.rs index e4f9ed92..0c4459bc 100644 --- a/crates/codegraph-extract/src/walker.rs +++ b/crates/codegraph-extract/src/walker.rs @@ -94,6 +94,57 @@ fn is_literal_receiver(node: SyntaxNode<'_>) -> bool { LITERAL_RECEIVER_KINDS.contains(&node.kind()) } +/// Call-node kinds whose `function` child names a member on a receiver — the +/// `obj.method` family across the grammars (`member_expression` for TS/JS/ArkTS, +/// `attribute` for Python, `field_expression` for Go/Rust/C/C++, +/// `navigation_expression` for Swift/Kotlin, plus C++ `qualified_identifier`). +const MEMBER_SHAPED_CALLEE_KINDS: [&str; 6] = [ + "member_expression", + "attribute", + "selector_expression", + "navigation_expression", + "field_expression", + "qualified_identifier", +]; + +fn is_member_shaped_callee(node: SyntaxNode<'_>) -> bool { + MEMBER_SHAPED_CALLEE_KINDS.contains(&node.kind()) +} + +/// The member segment of a member-shaped node: `property` (TS/JS), `field` +/// (Go/Rust/C/C++), else the second named child (Python `attribute`, Swift +/// `navigation_expression`, C++ `qualified_identifier`). +/// +/// Swift wraps the segment in a `navigation_suffix` whose text carries the +/// leading `.`, so its `simple_identifier` is unwrapped here (kotlin-ng exposes +/// identifiers directly, Swift does not — `tree-sitter.ts:2503-2506`). +fn member_name_of(node: SyntaxNode<'_>) -> Option> { + let segment = child_by_field(node, "property") + .or_else(|| child_by_field(node, "field")) + .or_else(|| node.named_child(1))?; + if segment.kind() == "navigation_suffix" { + return Some( + segment + .named_children(&mut segment.walk()) + .find(|c| c.kind() == "simple_identifier") + .unwrap_or(segment), + ); + } + Some(segment) +} + +/// A receiver segment usable as an `obj.method` receiver: a single bare +/// identifier that is not a self-reference. Anything else (an index expression, +/// a call, a whitespace-bearing span) keeps the bare method name, so no new +/// receiver grammar reaches the name matcher. +fn is_plain_receiver_segment(segment: &str) -> bool { + !segment.is_empty() + && !matches!(segment, "self" | "this" | "cls" | "super") + && segment + .chars() + .all(|c| c.is_alphanumeric() || c == '_' || c == '$') +} + pub struct TreeSitterWalker<'a, 'tree> { file_path: &'a str, source: &'a str, @@ -2972,32 +3023,8 @@ impl<'a, 'tree> TreeSitterWalker<'a, 'tree> { let mut callee_name = String::new(); let func = child_by_field(node, "function").or_else(|| node.named_child(0)); if let Some(func) = func { - if matches!( - func.kind(), - "member_expression" - | "attribute" - | "selector_expression" - | "navigation_expression" - | "field_expression" - | "qualified_identifier" - ) { - let property = child_by_field(func, "property") - .or_else(|| child_by_field(func, "field")) - .or_else(|| func.named_child(1)) - .map(|prop| { - // tree-sitter.ts:2503-2506 — Swift wraps the method - // name in navigation_suffix; unwrap its - // simple_identifier (kotlin-ng exposes identifiers - // directly, Swift does not). - if prop.kind() == "navigation_suffix" { - prop.named_children(&mut prop.walk()) - .find(|c| c.kind() == "simple_identifier") - .unwrap_or(prop) - } else { - prop - } - }); - if let Some(property) = property { + if is_member_shaped_callee(func) { + if let Some(property) = member_name_of(func) { let method_name = node_text(property, self.source); let receiver = child_by_field(func, "object") .or_else(|| child_by_field(func, "operand")) @@ -3058,6 +3085,26 @@ impl<'a, 'tree> TreeSitterWalker<'a, 'tree> { } else { method_name }; + } else if is_member_shaped_callee(receiver) { + // #1496 — a receiver that is itself member-shaped + // (`this.mailer`, `holder.values`, `a.b.c`) keeps its + // LAST segment, so the ref arrives as `obj.method`. + // Dropping it would leave resolution unable to + // separate `this.run()` (self-target correct) from + // `this.mailer.send()` (self-target wrong), and a bare + // `send` then binds to whichever same-named method is + // nearest the call line. One segment, not the full + // chain: that is the receiver grammar the name matcher + // already understands, and the same unwrap + // `extract_object_name_call` performs for + // Java/Kotlin/PHP (`tree-sitter.ts:2641-2651`). + let segment = member_name_of(receiver) + .map(|seg| node_text(seg, self.source)) + .filter(|seg| is_plain_receiver_segment(seg)); + callee_name = match segment { + Some(segment) => format!("{segment}.{method_name}"), + None => method_name, + }; } else { callee_name = method_name; } @@ -7328,6 +7375,114 @@ g() ->\n\ ); } + // ---- Member-expression receiver preservation (#1496) -------------------- + + #[test] + fn member_receiver_chain_keeps_last_segment() { + // `this.mailer.send(m)` must record `mailer.send`, not the bare `send`: + // the receiver's LAST segment is what lets resolution reach `Mailer::send` + // instead of proximity-picking the enclosing `Outbox::send`. + let ts = call_refs( + "src/mail.ts", + "export class Outbox { send(m: string): void { this.mailer.send(m); } }\n", + Language::TypeScript, + ); + assert!( + ts.iter().any(|c| c == "mailer.send"), + "TS `this.mailer.send(m)` must record `mailer.send`, got: {ts:?}" + ); + + // A deeper chain keeps only the last receiver segment (`obj.method` is the + // shape the name matcher implements; no new receiver grammar is added). + let deep = call_refs( + "src/deep.ts", + "export class C { go(): void { this.a.b.zzDeepMethod(); } }\n", + Language::TypeScript, + ); + assert!( + deep.iter().any(|c| c == "b.zzDeepMethod"), + "a deeper chain must record `b.zzDeepMethod`, got: {deep:?}" + ); + + // Python `attribute` receiver. + let py = call_refs( + "src/cache.py", + "class C:\n def get(self, k):\n return self.store.get(k)\n", + Language::Python, + ); + assert!( + py.iter().any(|c| c == "store.get"), + "Python `self.store.get(k)` must record `store.get`, got: {py:?}" + ); + + // Go `selector_expression` receiver. + let go = call_refs( + "src/a.go", + "package a\n\nfunc (c *C) Get() { c.inner.Fetch() }\n", + Language::Go, + ); + assert!( + go.iter().any(|c| c == "inner.Fetch"), + "Go `c.inner.Fetch()` must record `inner.Fetch`, got: {go:?}" + ); + + // Rust `field_expression` receiver. + let rs = call_refs( + "src/a.rs", + "impl C {\n fn get(&self) { self.inner.fetch(); }\n}\n", + Language::Rust, + ); + assert!( + rs.iter().any(|c| c == "inner.fetch"), + "Rust `self.inner.fetch()` must record `inner.fetch`, got: {rs:?}" + ); + + // Swift `navigation_expression` receiver. + let swift = call_refs( + "src/a.swift", + "class C {\n func get() { self.inner.fetch() }\n}\n", + Language::Swift, + ); + assert!( + swift.iter().any(|c| c == "inner.fetch"), + "Swift `self.inner.fetch()` must record `inner.fetch`, got: {swift:?}" + ); + } + + #[test] + fn bare_this_receiver_still_skips() { + // A `this`/`self` receiver that is the WHOLE receiver keeps the existing + // skip semantics — the recursion self-call must stay a bare name, which is + // what keeps a legitimate recursion self-edge resolvable. + let ts = call_refs( + "src/rec.ts", + "export class Walker { run(n: number): void { if (n > 0) { this.run(n - 1); } } }\n", + Language::TypeScript, + ); + assert!( + ts.iter().any(|c| c == "run"), + "TS `this.run(n)` must stay the bare `run`, got: {ts:?}" + ); + assert!( + !ts.iter().any(|c| c == "this.run"), + "TS `this.run(n)` must not keep the `this` receiver, got: {ts:?}" + ); + + let py = call_refs( + "src/rec.py", + "class C:\n def run(self):\n self.helper()\n", + Language::Python, + ); + assert!( + py.iter().any(|c| c == "helper"), + "Python `self.helper()` must stay the bare `helper`, got: {py:?}" + ); + assert!( + !py.iter().any(|c| c == "self.helper"), + "Python `self.helper()` must not keep the `self` receiver, got: {py:?}" + ); + } + #[test] fn identifier_receiver_calls_are_unaffected_by_the_literal_guard() { let py = call_refs( diff --git a/crates/codegraph-resolve/src/import_resolver.rs b/crates/codegraph-resolve/src/import_resolver.rs index 4e6fcc42..05627117 100644 --- a/crates/codegraph-resolve/src/import_resolver.rs +++ b/crates/codegraph-resolve/src/import_resolver.rs @@ -311,6 +311,37 @@ fn c_cpp_stdlib_headers() -> &'static BTreeSet<&'static str> { }) } +/// Languages using the JS module-specifier grammar, where a bare specifier names +/// an npm package rather than a project path. +/// +/// Wider than [`crate::types::ESM_LANGUAGES`] on purpose: that set is about +/// VISIBILITY (which needs an import-mapping channel), this one is about +/// SPECIFIER SHAPE, which Astro and ArkTS share even though they have no mapping +/// channel yet. +fn is_js_specifier_language(language: Language) -> bool { + matches!( + language, + Language::TypeScript + | Language::JavaScript + | Language::Tsx + | Language::Jsx + | Language::Svelte + | Language::Vue + | Language::Astro + | Language::ArkTs + ) +} + +/// Module-path roots that always name a crate OUTSIDE the repository for a Rust +/// `use` (#1536). +/// +/// Keyed on stdlib roots rather than on "the path does not resolve to a file", +/// because a workspace crate can re-export another crate's modules +/// (`pub use pupil_core::ports;`), so `crate::ports::X` has no local file and is +/// nonetheless entirely in-repo. Upstream measured the broader rule deleting 13 +/// real trait implementations. +const RUST_OUT_OF_REPO_ROOTS: [&str; 4] = ["std", "core", "alloc", "proc_macro"]; + /// Check if an import is external (`isExternalImport`, `import-resolver.ts:123-202`). fn is_external_import( import_path: &str, @@ -328,10 +359,14 @@ fn is_external_import( } } - if matches!( - language, - Language::TypeScript | Language::JavaScript | Language::Tsx | Language::Jsx - ) { + // The whole JS specifier family, not just the four bare-TS/JS languages + // (#1537/#1536). `extract_import_mappings` already routes Svelte and Vue + // through `extract_js_imports`, so an npm specifier in an SFC reached here and + // was answered "not external" — which let an out-of-repo supertype bind an + // in-repo class. Astro and ArkTS carry the same specifier grammar; they have + // no import-mapping channel yet, so for them only import PATH resolution + // changes, in the same correct direction. + if is_js_specifier_language(language) { const NODE_BUILTINS: [&str; 12] = [ "fs", "path", @@ -942,6 +977,193 @@ fn strip_js_comments(content: &str) -> String { out } +/// Bindings a Rust file's `use` declarations introduce, as `(local_name, path)`. +/// +/// `extract_import_mappings` has no Rust arm, so Rust has no import-mapping +/// channel at all; this is the narrow one the locality gate needs. Handles nested +/// groups (`use a::{b, c::d}`), `as` aliases, and `self`; a glob (`use a::*`) +/// binds no nameable symbol and is skipped rather than guessed at. +/// +/// Paths are returned verbatim so the caller decides locality — this function has +/// no notion of in-repo. +pub fn extract_rust_use_bindings(content: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + for raw in content.lines() { + let line = raw.trim(); + let Some(rest) = line + .strip_prefix("pub use ") + .or_else(|| line.strip_prefix("use ")) + else { + continue; + }; + let body = rest.trim().trim_end_matches(';').trim(); + if body.is_empty() { + continue; + } + expand_rust_use_tree("", body, &mut out); + } + out +} + +/// Expand one `use` tree body under `prefix`, appending each `(local_name, path)`. +fn expand_rust_use_tree(prefix: &str, body: &str, out: &mut Vec<(String, String)>) { + let body = body.trim(); + if body.is_empty() { + return; + } + // A brace group splits into its members, each re-expanded under the prefix + // that precedes the brace. + if let Some(open) = body.find('{') { + let head = body[..open].trim().trim_end_matches("::").trim(); + let Some(close) = body.rfind('}') else { + return; + }; + let inner = &body[open + 1..close]; + let nested_prefix = join_rust_path(prefix, head); + for member in split_top_level_commas(inner) { + expand_rust_use_tree(&nested_prefix, &member, out); + } + return; + } + if body.ends_with('*') { + return; + } + let (path_part, alias) = match body.split_once(" as ") { + Some((path, alias)) => (path.trim(), Some(alias.trim())), + None => (body, None), + }; + let full = join_rust_path(prefix, path_part); + let last = full.rsplit("::").next().unwrap_or(&full); + let local = match alias { + Some(alias) => alias.to_string(), + None if last == "self" => full + .trim_end_matches("::self") + .rsplit("::") + .next() + .unwrap_or("") + .to_string(), + None => last.to_string(), + }; + if local.is_empty() || local == "self" { + return; + } + out.push((local, full)); +} + +fn join_rust_path(prefix: &str, segment: &str) -> String { + match (prefix.is_empty(), segment.is_empty()) { + (true, _) => segment.to_string(), + (false, true) => prefix.to_string(), + (false, false) => format!("{prefix}::{segment}"), + } +} + +/// Split a `use` group's members on commas that are not inside a nested brace. +fn split_top_level_commas(inner: &str) -> Vec { + let mut parts = Vec::new(); + let mut depth = 0usize; + let mut current = String::new(); + for ch in inner.chars() { + match ch { + '{' => { + depth += 1; + current.push(ch); + } + '}' => { + depth = depth.saturating_sub(1); + current.push(ch); + } + ',' if depth == 0 => { + parts.push(std::mem::take(&mut current)); + } + _ => current.push(ch), + } + } + parts.push(current); + parts + .into_iter() + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty()) + .collect() +} + +/// Is `reference`'s name bound by an import whose module lives OUTSIDE the +/// repository? (#1537/#1536) +/// +/// Such a reference has no in-repo referent, so resolving it to a same-named +/// project symbol fabricates an edge — and a kind filter cannot catch it, because +/// the fabricated target is often a legal kind (a `function` for an `imports` +/// ref, a `type_alias` for a supertype). +/// +/// Two oracles only, each one its language cannot be wrong about: +/// - the JS specifier family, via the existing [`is_external_import`], which +/// already understands tsconfig path aliases and workspace packages; and +/// - Rust `use`, restricted to [`RUST_OUT_OF_REPO_ROOTS`], with the escape that a +/// path walking to a real file is local. +/// +/// Every other language returns `false` and resolves exactly as before: JVM and +/// Python use dedicated FQN/module matchers rather than `resolve_import_path`, so +/// there is no oracle here that could be trusted. +pub fn is_bound_to_out_of_repo_module( + reference: &RefView, + context: &dyn ResolutionContext, +) -> bool { + let head = reference + .reference_name + .split(['.', ':']) + .next() + .unwrap_or(&reference.reference_name); + if head.is_empty() { + return false; + } + + if is_js_specifier_language(reference.language) { + return context + .get_import_mappings(&reference.file_path, reference.language) + .into_iter() + .filter(|m| m.local_name == head) + .any(|m| is_external_import(&m.source, reference.language, context)); + } + + if reference.language == Language::Rust { + let Some(content) = context.read_file(&reference.file_path) else { + return false; + }; + return extract_rust_use_bindings(&content) + .into_iter() + .filter(|(local, _)| local == head) + .any(|(_, path)| rust_use_path_is_out_of_repo(&path, reference, context)); + } + + false +} + +/// Does a Rust `use` path name a crate outside the repository? +/// +/// True only for a [`RUST_OUT_OF_REPO_ROOTS`] root, and even then not when the +/// path walks to a real project file — a project module legitimately named `core` +/// must keep resolving. +fn rust_use_path_is_out_of_repo( + path: &str, + reference: &RefView, + context: &dyn ResolutionContext, +) -> bool { + let segments: Vec<&str> = path.split("::").filter(|s| !s.is_empty()).collect(); + let Some(root) = segments.first() else { + return false; + }; + if !RUST_OUT_OF_REPO_ROOTS.contains(root) { + return false; + } + if segments.len() >= 2 { + let module_segments = &segments[..segments.len() - 1]; + if resolve_rust_module_file(module_segments, &reference.file_path, context).is_some() { + return false; + } + } + true +} + /// Extract JS/TS cross-file re-exports and explicit local export aliases /// (`extractReExports`, `import-resolver.ts:989-1042`). pub fn extract_re_exports(content: &str, language: Language) -> Vec { @@ -2333,6 +2555,213 @@ mod tests { } } + // ---- Tier 2 item 6: import locality (#1537/#1536) ---------------------- + + #[test] + fn rust_use_bindings_cover_groups_aliases_and_globs() { + let bindings = extract_rust_use_bindings(concat!( + "use std::error::Error;\n", + "use crate::ports::Sha256Port;\n", + "use std::collections::{BTreeMap, HashMap};\n", + "use core::fmt::{self, Display as Disp};\n", + "pub use crate::api::Public;\n", + "use std::io::*;\n", + )); + let by_local = |local: &str| -> Option { + bindings + .iter() + .find(|(l, _)| l == local) + .map(|(_, path)| path.clone()) + }; + assert_eq!(by_local("Error").as_deref(), Some("std::error::Error")); + assert_eq!( + by_local("Sha256Port").as_deref(), + Some("crate::ports::Sha256Port") + ); + assert_eq!( + by_local("BTreeMap").as_deref(), + Some("std::collections::BTreeMap") + ); + assert_eq!( + by_local("HashMap").as_deref(), + Some("std::collections::HashMap") + ); + // `self` in a group binds the module name; `as` binds the alias. + assert_eq!(by_local("fmt").as_deref(), Some("core::fmt::self")); + assert_eq!(by_local("Disp").as_deref(), Some("core::fmt::Display")); + assert_eq!(by_local("Public").as_deref(), Some("crate::api::Public")); + // A glob binds no nameable symbol. + assert!( + !bindings.iter().any(|(l, _)| l == "*"), + "a glob must not produce a binding: {bindings:?}" + ); + } + + #[test] + fn stdlib_rooted_use_is_out_of_repo_but_crate_rooted_is_not() { + let mut ctx = TestContext { + project_root: "/proj".to_string(), + ..Default::default() + }; + ctx.file_contents.insert( + "src/lib.rs".to_string(), + "use std::error::Error;\nuse crate::ports::Sha256Port;\n".to_string(), + ); + ctx.existing_files.insert("src/ports.rs".to_string()); + + let out_of_repo = reference("Error", EdgeKind::Implements, "src/lib.rs", Language::Rust); + assert!( + is_bound_to_out_of_repo_module(&out_of_repo, &ctx), + "`use std::error::Error` is out-of-repo" + ); + + // The C3 falsifier: locality keys on the STDLIB ROOT, not on whether the + // module path resolves to a file. A workspace crate can re-export another + // crate's modules, so `crate::…` has no local file yet is entirely in-repo + // — the broader rule was measured deleting 13 real trait implementations. + let in_repo = reference( + "Sha256Port", + EdgeKind::Implements, + "src/lib.rs", + Language::Rust, + ); + assert!( + !is_bound_to_out_of_repo_module(&in_repo, &ctx), + "a crate-rooted `use` must stay local" + ); + } + + #[test] + fn reexported_sibling_crate_module_still_resolves() { + // The C3 rejection, stated as its own case: `pub use pupil_core::ports;` + // means `crate::ports::CacheStore` walks to NO local file, and it must + // still count as in-repo. + let mut ctx = TestContext { + project_root: "/proj".to_string(), + ..Default::default() + }; + ctx.file_contents.insert( + "src/cache.rs".to_string(), + "use crate::ports::CacheStore;\n".to_string(), + ); + let r = reference( + "CacheStore", + EdgeKind::Implements, + "src/cache.rs", + Language::Rust, + ); + assert!( + !is_bound_to_out_of_repo_module(&r, &ctx), + "an unresolvable but crate-rooted module path must not be judged out-of-repo" + ); + } + + #[test] + fn project_module_named_core_escapes_the_stdlib_root_rule() { + // The escape hatch: a stdlib-named project module that WALKS to a real + // file is local, so a repo with its own `core/` keeps resolving. + let mut ctx = TestContext { + project_root: "/proj".to_string(), + ..Default::default() + }; + ctx.file_contents.insert( + "src/lib.rs".to_string(), + "use core::engine::Engine;\n".to_string(), + ); + // A real module layout: `src/lib.rs` anchors the crate root, and `core` + // is a declared module directory, not a bare directory on disk. + ctx.existing_files.insert("src/lib.rs".to_string()); + ctx.existing_files.insert("src/core/mod.rs".to_string()); + ctx.existing_files.insert("src/core/engine.rs".to_string()); + let r = reference("Engine", EdgeKind::Implements, "src/lib.rs", Language::Rust); + assert!( + !is_bound_to_out_of_repo_module(&r, &ctx), + "a stdlib-named project module that resolves to a file is local" + ); + } + + #[test] + fn npm_specifier_binding_is_out_of_repo_in_every_sfc_language() { + for language in [ + Language::TypeScript, + Language::Svelte, + Language::Vue, + Language::Astro, + Language::ArkTs, + ] { + let mut ctx = TestContext { + project_root: "/proj".to_string(), + ..Default::default() + }; + ctx.import_mappings.insert( + "src/Box.svelte".to_string(), + vec![mapping("Serializable", "Serializable", "some-npm-pkg")], + ); + let r = reference( + "Serializable", + EdgeKind::Implements, + "src/Box.svelte", + language, + ); + assert!( + is_bound_to_out_of_repo_module(&r, &ctx), + "an npm specifier must read as out-of-repo in {language:?}" + ); + } + } + + #[test] + fn relative_specifier_binding_stays_local() { + let mut ctx = TestContext { + project_root: "/proj".to_string(), + ..Default::default() + }; + ctx.import_mappings.insert( + "src/box.ts".to_string(), + vec![mapping("Shape", "Shape", "./shape")], + ); + let r = reference( + "Shape", + EdgeKind::Implements, + "src/box.ts", + Language::TypeScript, + ); + assert!( + !is_bound_to_out_of_repo_module(&r, &ctx), + "a relative specifier is never out-of-repo" + ); + } + + #[test] + fn languages_without_an_oracle_abstain() { + // JVM and Python use dedicated FQN/module matchers rather than + // `resolve_import_path`, so the locality gate must not claim to know. + for language in [ + Language::Java, + Language::Kotlin, + Language::Python, + Language::Go, + ] { + let mut ctx = TestContext { + project_root: "/proj".to_string(), + ..Default::default() + }; + ctx.import_mappings.insert( + "src/A.java".to_string(), + vec![mapping( + "Serializable", + "Serializable", + "java.io.Serializable", + )], + ); + let r = reference("Serializable", EdgeKind::Implements, "src/A.java", language); + assert!( + !is_bound_to_out_of_repo_module(&r, &ctx), + "{language:?} has no trustworthy oracle and must abstain" + ); + } + } + #[test] fn extension_resolution_covers_all_language_arms() { assert!(extension_resolution(Language::TypeScript).contains(&".ts")); diff --git a/crates/codegraph-resolve/src/name_matcher.rs b/crates/codegraph-resolve/src/name_matcher.rs index d3adcf85..99130b50 100644 --- a/crates/codegraph-resolve/src/name_matcher.rs +++ b/crates/codegraph-resolve/src/name_matcher.rs @@ -5,7 +5,10 @@ //! cross-language family gate — mirror the upstream exactly. Every strategy cites its //! upstream source range. -use crate::types::{RefView, ResolutionContext, ResolvedBy, ResolvedRef}; +use crate::types::{ + RefView, ResolutionContext, ResolvedBy, ResolvedRef, declares_type_name, is_esm_language, + kind_is_eligible_target, +}; use codegraph_core::types::{EdgeKind, Language, Node, NodeKind}; use regex::Regex; use std::sync::OnceLock; @@ -255,7 +258,7 @@ pub fn match_by_exact_name( reference: &RefView, context: &dyn ResolutionContext, ) -> Option { - let candidates: Vec = apply_language_gate( + let reachable: Vec = apply_language_gate( context.get_nodes_by_name(&reference.reference_name), reference, ) @@ -264,11 +267,29 @@ pub fn match_by_exact_name( .filter(|n| is_lexically_reachable(n, reference, context)) .collect(); + // A same-named non-type is not a supertype, and a type member is not + // 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 + .iter() + .filter(|n| kind_is_eligible_target(reference.reference_kind, n.kind)) + .cloned() + .collect(); + if candidates.is_empty() { return None; } - if candidates.len() == 1 { + // Branch on the PRE-FILTER count. The single-candidate shortcut skips + // `find_best_match`, and with it the cross-language penalty that makes a + // genuinely ambiguous reference decline — so letting the kind filter collapse + // a multi-candidate set into that shortcut would CREATE an edge the scored + // path refused (a GDScript `extends Node` binding a Rust `struct Node` once + // its same-named enum-member rival was filtered out). These gates only ever + // remove an edge, so the ranking branch is chosen by how ambiguous the + // reference actually was, and only the CANDIDATES are narrowed. + if reachable.len() == 1 { let is_cross_language = candidates[0].language != reference.language; return Some(ResolvedRef { original: reference.clone(), @@ -976,6 +997,135 @@ fn infer_local_receiver_type( None } +/// Span end of `node`, falling back to its start when `end_line` was not +/// recorded — the same convention [`enclosing_scope_start_line`] applies. +fn span_end_line(node: &Node) -> i64 { + if node.end_line != 0 { + node.end_line + } else { + node.start_line + } +} + +/// Second chance for a receiver that is a CLASS FIELD rather than a local +/// (#1566, ESM only). +/// +/// [`enclosing_scope_start_line`] bounds the backward scan to the enclosing +/// FUNCTION or METHOD, so a field declared above a method is structurally +/// unreachable from a call inside it. This reads the field's OWN declaration +/// line instead: the tightest enclosing class-like node spanning the call, then +/// its `Property`/`Field` member of the receiver's name, then the existing +/// [`local_receiver_type_patterns`] applied to that single line. +/// +/// Deliberately a bounded NODE lookup, not a widened scan window. The window +/// scan takes the nearest match ABOVE the call, so a class-wide window would +/// prefer a sibling method's `const conn = new Wrong()` over the field — +/// precisely the cross-method leak [`enclosing_scope_start_line`] exists to +/// prevent. Reading one line that lies outside every method body cannot leak. +/// +/// Only ever turns inference `None` into `Some`: the caller reaches this after +/// the function-scope scan already declined, so no currently-succeeding +/// inference can change. The recovered type is still subject to +/// [`is_receiver_type_bound_at_call_site`], so an unbound one (a built-in +/// `Map`) is refused rather than resolved. +fn infer_class_field_receiver_type( + receiver_name: &str, + reference: &RefView, + context: &dyn ResolutionContext, +) -> Option { + if !is_esm_language(reference.language) { + return None; + } + let escaped = regex_escape(receiver_name); + let patterns = local_receiver_type_patterns_tagged(reference.language, &escaped); + if patterns.is_empty() { + return None; + } + + let in_file = context.get_nodes_in_file(&reference.file_path); + let enclosing = in_file + .iter() + .filter(|n| { + matches!( + n.kind, + NodeKind::Class | NodeKind::Struct | NodeKind::Interface + ) && n.language == reference.language + && n.start_line <= reference.line + && span_end_line(n) >= reference.line + }) + .max_by_key(|n| n.start_line)?; + + let want = format!("{}::{}", enclosing.qualified_name, receiver_name); + let field = in_file.iter().find(|n| { + matches!(n.kind, NodeKind::Property | NodeKind::Field) + && n.name == receiver_name + && n.qualified_name == want + && n.language == reference.language + })?; + + let source = context.read_file(&reference.file_path)?; + let line = source + .split('\n') + .nth((field.start_line - 1).max(0) as usize)? + .trim_end_matches('\r'); + if line.len() > 10_000 { + return None; + } + for (re, is_lua_annotation) in &patterns { + if let Some(caps) = re.captures(line) { + if let Some(m) = caps.get(1) { + if *is_lua_annotation && lua_annotation_is_method_call(line, m.end()) { + continue; + } + if let Some(ty) = normalize_inferred_type_name(m.as_str()) { + return Some(ty); + } + } + } + } + None +} + +/// Is the inferred receiver type `type_name` BOUND at the call site (#1566)? +/// +/// A built-in receiver (`new Map()`) normalizes to a bare type +/// name that some unrelated project file may also declare. Resolving a method on +/// it then fabricates an edge — and does so through a SUCCESSFUL typed path when +/// that file happens to declare a same-named method, so refusing only after +/// typed resolution FAILS would miss the worst case. +/// +/// Two indexed reads answer the question for the [`ESM_LANGUAGES`] family, where +/// cross-file visibility requires an explicit import: +/// 1. a same-file declaration that binds the name ([`declares_type_name`]), or +/// 2. an import mapping whose `local_name` is that name. +/// +/// Reading the IMPORTING file's `local_name` means a barrel `export *` chain +/// needs no specifier resolution. Existence is deliberately NOT the test: a +/// project `class Map` in an unimported file exists and must still not hijack. +/// +/// Known limit: a type made global by an ambient `.d.ts` declaration and used +/// without an import reads as unbound and is refused. That yields a MISSING +/// edge, not a false one. +/// +/// [`ESM_LANGUAGES`]: crate::types::ESM_LANGUAGES +fn is_receiver_type_bound_at_call_site( + type_name: &str, + reference: &RefView, + context: &dyn ResolutionContext, +) -> bool { + if context + .get_nodes_in_file(&reference.file_path) + .iter() + .any(|n| n.name == type_name && declares_type_name(n.kind)) + { + return true; + } + context + .get_import_mappings(&reference.file_path, reference.language) + .iter() + .any(|m| m.local_name == type_name) +} + /// True when a Lua/Luau `receiver:Capitalized` annotation match is really a /// method call (`lg:Log()`, `lg:Log"s"`, `lg:Log{t}`, or a longer `lg:Log.More` /// token the annotation regex stopped short of), which must NOT be read as a type @@ -1215,9 +1365,22 @@ pub fn match_method_call( let inferred = if reference.language == Language::Cpp { infer_cpp_receiver_type(&object_or_class, reference, context, 0) } else { + // The field lookup runs ONLY where the function-scope scan declined, + // so it can add an inference but never change one (#1566, ESM only). infer_local_receiver_type(&object_or_class, reference, context) + .or_else(|| infer_class_field_receiver_type(&object_or_class, reference, context)) }; if let Some(inferred) = inferred { + // #1566 — an inferred type the call site cannot SEE is not this + // project's type: a built-in `Map` must never resolve onto a + // same-named project class. Refuse before typed resolution runs, and + // before Strategies 1/2/3 below, because the hijack arrives via a + // typed-resolution SUCCESS as readily as via its failure. + if is_esm_language(reference.language) + && !is_receiver_type_bound_at_call_site(&inferred, reference, context) + { + return None; + } // Java/Kotlin: the file's import pins WHICH same-named class (#314); // other languages disambiguate by call-site file in resolve_method_on_type. let imported_fqn = if matches!(reference.language, Language::Java | Language::Kotlin) { @@ -2376,6 +2539,24 @@ mod tests { self.imports.insert(path.to_string(), mappings); self } + /// Declare `type_name` imported into `path`, ADDING to any mappings the + /// file already has. A real ESM file that names a type from another file + /// carries this import statement; the mock reports none unless a test + /// wires one, so a receiver-type fixture needs it to be BOUND at its call + /// site (#1566). + fn imports_type(mut self, path: &str, type_name: &str) -> Self { + self.imports + .entry(path.to_string()) + .or_default() + .push(ImportMapping { + local_name: type_name.to_string(), + exported_name: type_name.to_string(), + source: "./dep".to_string(), + is_default: false, + is_namespace: false, + }); + self + } } impl ResolutionContext for Ctx { @@ -4923,6 +5104,11 @@ mod tests { /// Build a ctx whose file `path` has `source`, plus an enclosing function /// spanning the whole file (so the scope bound includes the call line). + /// + /// `method`'s qualified name names the type the receiver is expected to infer + /// to (`Logger::log` → `Logger`), so that type is also declared imported into + /// `path` — the binding a real ESM call site carries and the mock otherwise + /// lacks (#1566). fn ctx_with_scope( path: &str, source: &str, @@ -4940,10 +5126,18 @@ mod tests { ); fn_node.start_line = 1; fn_node.end_line = source.split('\n').count() as i64 + 1; - Ctx::default() + let owner = method + .qualified_name + .rsplit_once("::") + .map(|(owner, _)| owner.to_string()); + let ctx = Ctx::default() .file(path, source) .nodes_in_file(path, vec![fn_node]) - .name(method_name, vec![method]) + .name(method_name, vec![method]); + match owner { + Some(owner) => ctx.imports_type(path, &owner), + None => ctx, + } } #[test] @@ -6419,4 +6613,705 @@ mod tests { "function:emit" ); } + + // ---- Tier 2 item 4: dotted receiver refs vs the file-path strategy ------ + + #[test] + fn dotted_receiver_ref_is_not_treated_as_a_file_path() { + // `has_short_extension("mailer.send")` is TRUE (a 4-char alphanumeric + // tail), so item 4's rewritten refs now reach `match_by_file_path` first. + // It must still decline: the lookup key is the WHOLE dotted name, which + // no file node carries — a decoy `send` file node must not be adopted. + let decoy = mk( + "file:send", + NodeKind::File, + "send", + "src/send.ts", + "src/send.ts", + Language::TypeScript, + ); + let ctx = Ctx::default() + .name("send", vec![decoy.clone()]) + .name("mailer.send", vec![]); + let r = refv( + "mailer.send", + EdgeKind::Calls, + "src/mail.ts", + Language::TypeScript, + 4, + ); + assert!( + match_by_file_path(&r, &ctx).is_none(), + "a dotted receiver ref must not resolve as a file path" + ); + + // End to end through `match_reference`: the same ref resolves by the + // method strategies, never with `ResolvedBy::FilePath`. + let mailer = mk( + "class:mailer", + NodeKind::Class, + "Mailer", + "Mailer", + "src/mail.ts", + Language::TypeScript, + ); + let send = mk( + "method:send", + NodeKind::Method, + "send", + "Mailer::send", + "src/mail.ts", + Language::TypeScript, + ); + let full = Ctx::default() + .name("send", vec![decoy, send.clone()]) + .name("Mailer", vec![mailer]) + .nodes_in_file("src/mail.ts", vec![send]); + let resolved = match_reference(&r, &full).expect("dotted receiver still resolves"); + assert_ne!( + resolved.resolved_by, + ResolvedBy::FilePath, + "a dotted receiver ref must not be resolved by the file-path strategy" + ); + assert_eq!(resolved.target_node_id, "method:send"); + } + + // ---- Tier 2 item 5: inferred-type visibility at the call site (#1566) --- + + /// A file declaring `class Map { }` plus a lone project method of + /// that name, and a local `const m = new Map(); m.()` in + /// `main.ts`. `bind_in_main` controls whether `Map` is visible at the call + /// site (same-file declaration), which is exactly what the gate reads. + fn builtin_hijack_ctx(method: &str, owner: &str, bind_in_main: bool) -> Ctx { + let map_class = mk( + "class:map", + NodeKind::Class, + "Map", + "Map", + "src/other.ts", + Language::TypeScript, + ); + let target = mk( + "method:target", + NodeKind::Method, + method, + &format!("{owner}::{method}"), + "src/other.ts", + Language::TypeScript, + ); + let mut caller = mk( + "function:useBuiltin", + NodeKind::Function, + "useBuiltin", + "useBuiltin", + "src/main.ts", + Language::TypeScript, + ); + caller.start_line = 1; + caller.end_line = 4; + let mut in_main = vec![caller]; + if bind_in_main { + let mut shadow = map_class.clone(); + shadow.id = "class:map-main".to_string(); + shadow.file_path = "src/main.ts".to_string(); + in_main.push(shadow); + } + Ctx::default() + .file( + "src/main.ts", + "function useBuiltin() {\n const m = new Map();\n m.MEMBER();\n}\n", + ) + .nodes_in_file("src/main.ts", in_main) + .name("Map", vec![map_class]) + .name(method, vec![target]) + } + + fn builtin_hijack_ref(method: &str) -> RefView { + refv( + &format!("m.{method}"), + EdgeKind::Calls, + "src/main.ts", + Language::TypeScript, + 3, + ) + } + + #[test] + fn unimported_project_class_does_not_hijack_builtin() { + // Given a built-in `Map` in main.ts and an UNIMPORTED project + // `class Map { get() }` in other.ts, + // When the call `m.get("a")` resolves, + // Then nothing binds — today the TYPED path SUCCEEDS at 0.9 on a flatly + // wrong edge, which is why the gate must sit before typed resolution. + let ctx = builtin_hijack_ctx("get", "Map", false); + let landed = match_method_call(&builtin_hijack_ref("get"), &ctx); + assert!( + landed.is_none(), + "an unbound inferred type must not resolve its method, got: {:?}", + landed.map(|r| (r.target_node_id, r.resolved_by, r.confidence)) + ); + } + + #[test] + fn unimported_project_class_without_the_method_does_not_fall_through() { + // The mirror: the unimported project `Map` has no `get`, so typed + // resolution FAILS and Strategy 3 would adopt a unique `Decoy::get` + // at 0.7. The gate refuses before either runs. + let ctx = builtin_hijack_ctx("get", "Decoy", false); + let landed = match_method_call(&builtin_hijack_ref("get"), &ctx); + assert!( + landed.is_none(), + "an unbound inferred type must not fall through to Strategy 3, got: {:?}", + landed.map(|r| (r.target_node_id, r.resolved_by, r.confidence)) + ); + } + + #[test] + fn same_file_project_map_still_resolves() { + // V5 — a project `class Map` declared in the CALLING file shadows the + // built-in, so the receiver type IS bound and the edge must be kept. + let ctx = builtin_hijack_ctx("get", "Map", true); + let res = + match_method_call(&builtin_hijack_ref("get"), &ctx).expect("same-file Map is bound"); + assert_eq!(res.target_node_id, "method:target"); + assert_eq!(res.resolved_by, ResolvedBy::InstanceMethod); + assert!((res.confidence - 0.9).abs() < 1e-9); + } + + #[test] + fn imported_project_map_still_resolves() { + // V1 — a named import binds `Map` at the call site. + let ctx = builtin_hijack_ctx("get", "Map", false).import( + "src/main.ts", + vec![ImportMapping { + local_name: "Map".to_string(), + exported_name: "Map".to_string(), + source: "./other".to_string(), + is_default: false, + is_namespace: false, + }], + ); + let res = + match_method_call(&builtin_hijack_ref("get"), &ctx).expect("imported Map is bound"); + assert_eq!(res.target_node_id, "method:target"); + assert!((res.confidence - 0.9).abs() < 1e-9); + } + + #[test] + fn barrel_imported_project_map_still_resolves() { + // V4 — a barrel re-export. The predicate reads the IMPORTING file's + // `local_name`, so it never has to resolve the specifier. + let ctx = builtin_hijack_ctx("get", "Map", false).import( + "src/main.ts", + vec![ImportMapping { + local_name: "Map".to_string(), + exported_name: "Map".to_string(), + source: "./barrel".to_string(), + is_default: false, + is_namespace: false, + }], + ); + let res = match_method_call(&builtin_hijack_ref("get"), &ctx).expect("barrel Map is bound"); + assert_eq!(res.target_node_id, "method:target"); + assert!((res.confidence - 0.9).abs() < 1e-9); + } + + /// C1/C2 — a receiver typed to a same-file PROJECT class `Real`. + /// `Real::poke` exists; `absentOnReal` does not, but a unique `Decoy` has it. + fn project_typed_receiver_ctx() -> Ctx { + let real = mk( + "class:real", + NodeKind::Class, + "Real", + "Real", + "src/main.ts", + Language::TypeScript, + ); + let poke = mk( + "method:poke", + NodeKind::Method, + "poke", + "Real::poke", + "src/main.ts", + Language::TypeScript, + ); + let absent = mk( + "method:absent", + NodeKind::Method, + "absentOnReal", + "Decoy::absentOnReal", + "src/decoy.ts", + Language::TypeScript, + ); + let mut caller = mk( + "function:use", + NodeKind::Function, + "use", + "use", + "src/main.ts", + Language::TypeScript, + ); + caller.start_line = 1; + caller.end_line = 4; + Ctx::default() + .file( + "src/main.ts", + "function use() {\n const r = new Real();\n r.poke();\n}\n", + ) + .nodes_in_file("src/main.ts", vec![real.clone(), poke.clone(), caller]) + .name("Real", vec![real]) + .name("poke", vec![poke]) + .name("absentOnReal", vec![absent]) + } + + #[test] + fn project_typed_receiver_still_resolves() { + // C1 — the inferred `Real` is declared in this file, so it is bound and + // typed resolution proceeds exactly as today. + let ctx = project_typed_receiver_ctx(); + let r = refv( + "r.poke", + EdgeKind::Calls, + "src/main.ts", + Language::TypeScript, + 3, + ); + let res = match_method_call(&r, &ctx).expect("project-typed receiver resolves"); + assert_eq!(res.target_node_id, "method:poke"); + assert!((res.confidence - 0.9).abs() < 1e-9); + } + + #[test] + fn absent_method_on_project_type_still_falls_through() { + // C2 — the type is BOUND but lacks the method, so Strategy 3's guess is + // reached unchanged. The gate keys on binding, not on method existence. + let ctx = project_typed_receiver_ctx(); + let r = refv( + "r.absentOnReal", + EdgeKind::Calls, + "src/main.ts", + Language::TypeScript, + 3, + ); + let res = match_method_call(&r, &ctx).expect("bound type still falls through"); + assert_eq!(res.target_node_id, "method:absent"); + assert!((res.confidence - 0.7).abs() < 1e-9); + } + + #[test] + fn go_same_package_receiver_still_resolves() { + // V3 — Go makes a same-package type in ANOTHER file visible with no + // import statement at all, so "bound = same-file or imported" + // under-approximates there. The ESM-only scope is what keeps this edge. + let thing = mk( + "struct:thing", + NodeKind::Struct, + "Thing", + "Thing", + "b.go", + Language::Go, + ); + let ping = mk( + "method:ping", + NodeKind::Method, + "Ping", + "Thing::Ping", + "b.go", + Language::Go, + ); + let mut caller = mk( + "function:run", + NodeKind::Function, + "run", + "run", + "a.go", + Language::Go, + ); + caller.start_line = 1; + caller.end_line = 4; + let ctx = Ctx::default() + .file("a.go", "func run() {\n\tvar t Thing\n\tt.Ping()\n}\n") + .nodes_in_file("a.go", vec![caller]) + .name("Thing", vec![thing]) + .name("Ping", vec![ping]); + let r = refv("t.Ping", EdgeKind::Calls, "a.go", Language::Go, 3); + let res = match_method_call(&r, &ctx).expect("go same-package receiver resolves"); + assert_eq!(res.target_node_id, "method:ping"); + assert!((res.confidence - 0.9).abs() < 1e-9); + } + + // ---- Tier 2 item 5: class-field receiver inference (§2.2b) -------------- + + /// A class whose FIELD is initialized to a project class, with the call in a + /// later method — the shape item 4's rewrite produces and that the + /// function-scope backward scan structurally cannot reach. `with_wrong` adds a + /// competing `Wrong::doThing`; without it the name is unique project-wide and + /// Strategy 3 takes its single-candidate shortcut instead of overlap scoring. + fn class_field_receiver_ctx( + source: &str, + field_line: i64, + sibling: Option, + with_wrong: bool, + ) -> Ctx { + let mut holder = mk( + "class:c", + NodeKind::Class, + "C", + "C", + "src/main.ts", + Language::TypeScript, + ); + holder.start_line = 1; + holder.end_line = source.split('\n').count() as i64; + let mut field = mk( + "property:conn", + NodeKind::Property, + "conn", + "C::conn", + "src/main.ts", + Language::TypeScript, + ); + field.start_line = field_line; + field.end_line = field_line; + let right = mk( + "class:right", + NodeKind::Class, + "Right", + "Right", + "src/dep.ts", + Language::TypeScript, + ); + let do_thing = mk( + "method:right-doThing", + NodeKind::Method, + "doThing", + "Right::doThing", + "src/dep.ts", + Language::TypeScript, + ); + let mut members = vec![holder, field]; + if let Some(sibling) = sibling { + members.push(sibling); + } + let wrong = mk( + "class:wrong", + NodeKind::Class, + "Wrong", + "Wrong", + "src/dep.ts", + Language::TypeScript, + ); + let mut do_thing_targets = vec![do_thing.clone()]; + if with_wrong { + do_thing_targets.push(mk( + "method:wrong-doThing", + NodeKind::Method, + "doThing", + "Wrong::doThing", + "src/dep.ts", + Language::TypeScript, + )); + } + // BOTH types are bound at the call site. Binding `Wrong` too is what makes + // the no-leak control meaningful: were inference to reach a sibling + // method's `new Wrong()`, the visibility gate would PERMIT it, so the + // assertion — not the gate — is what catches the leak. + Ctx::default() + .file("src/main.ts", source) + .nodes_in_file("src/main.ts", members) + .nodes_in_file("src/dep.ts", vec![do_thing, right.clone()]) + .name("Right", vec![right]) + .name("Wrong", vec![wrong]) + .name("doThing", do_thing_targets) + .imports_type("src/main.ts", "Right") + .imports_type("src/main.ts", "Wrong") + } + + #[test] + fn class_field_project_receiver_resolves_by_type() { + // Given `private conn = new Right()` as a class FIELD and + // `conn.doThing()` inside a method, + // When resolution runs, + // Then the edge comes from TYPED resolution at 0.9, not a Strategy 3 + // guess at 0.7 — asserting the confidence is what proves inference ran. + let source = concat!( + "export class C {\n", + " private conn = new Right();\n", + "\n", + " second(): void {\n", + " this.conn.doThing();\n", + " }\n", + "}\n", + ); + let mut second = mk( + "method:second", + NodeKind::Method, + "second", + "C::second", + "src/main.ts", + Language::TypeScript, + ); + second.start_line = 4; + second.end_line = 6; + let ctx = class_field_receiver_ctx(source, 2, Some(second), false); + let r = refv( + "conn.doThing", + EdgeKind::Calls, + "src/main.ts", + Language::TypeScript, + 5, + ); + let res = match_method_call(&r, &ctx).expect("class-field receiver resolves"); + assert_eq!(res.target_node_id, "method:right-doThing"); + assert_eq!(res.resolved_by, ResolvedBy::InstanceMethod); + assert!( + (res.confidence - 0.9).abs() < 1e-9, + "must be typed resolution (0.9), not a Strategy 3 guess: {}", + res.confidence + ); + } + + #[test] + fn class_field_inference_does_not_leak_sibling_method_local() { + // The falsifier for the rejected widened-window design: the backward + // scan takes the NEAREST match ABOVE the call, so a class-wide window + // scanned back from line 12 would hit the sibling method's + // `const conn = new Wrong()` at line 7 and infer `Wrong`. Reading only + // the field node's OWN line cannot leak, because it never looks at a + // line inside any method body. + let source = concat!( + "export class C {\n", + " private conn = new Right();\n", + "\n", + " first(): void {\n", + " const conn = new Wrong();\n", + " conn.doThing();\n", + " }\n", + "\n", + " second(): void {\n", + " this.conn.doThing();\n", + " }\n", + "}\n", + ); + let mut second = mk( + "method:second", + NodeKind::Method, + "second", + "C::second", + "src/main.ts", + Language::TypeScript, + ); + second.start_line = 9; + second.end_line = 11; + let ctx = class_field_receiver_ctx(source, 2, Some(second), true); + let r = refv( + "conn.doThing", + EdgeKind::Calls, + "src/main.ts", + Language::TypeScript, + 10, + ); + // Asserted as a pure NEGATIVE so it holds both before the fix (where the + // ref resolves to nothing) and after (where it reaches `Right::doThing`). + let landed = match_method_call(&r, &ctx).map(|res| res.target_node_id); + assert_ne!( + landed.as_deref(), + Some("method:wrong-doThing"), + "field inference must not read a sibling method's local declaration" + ); + } + + // ---- Tier 2 item 6: kind eligibility (#1537/#1536) --------------------- + + #[test] + fn import_does_not_bind_a_type_member() { + // `import * as path from 'node:path'` must not bind to some class's + // `path` PROPERTY — a type member is not importable on its own. + let prop = mk( + "property:path", + NodeKind::Property, + "path", + "Request::path", + "src/types.ts", + Language::TypeScript, + ); + let ctx = Ctx::default().name("path", vec![prop]); + let r = refv( + "path", + EdgeKind::Imports, + "src/run.ts", + Language::TypeScript, + 1, + ); + let landed = match_by_exact_name(&r, &ctx); + assert!( + landed.is_none(), + "an imports ref must not bind a property, got: {:?}", + landed.map(|res| res.target_node_id) + ); + } + + #[test] + fn import_does_not_bind_a_same_named_function() { + // 6f — a `function` IS an importable kind, so the kind gate permits it + // and only import LOCALITY can refuse: `node:path` lives outside the + // repository, so no in-repo `path` is its referent. Both halves are + // asserted here so neither gate alone satisfies the test. + let helper = mk( + "function:path", + NodeKind::Function, + "path", + "path", + "src/helpers.ts", + Language::TypeScript, + ); + assert!( + crate::types::is_importable_kind(NodeKind::Function), + "a function is importable — this case needs the locality gate, not the kind gate" + ); + let ctx = Ctx::default().name("path", vec![helper]); + let r = refv( + "path", + EdgeKind::Imports, + "src/run.ts", + Language::TypeScript, + 1, + ); + // Locality is decided in the resolver over the file's import mappings, so + // the end-to-end refusal is asserted by the `esm_import` fixture test. + // Here the kind gate must at least NOT be what refuses it. + assert!( + match_by_exact_name(&r, &ctx).is_some(), + "the kind gate must permit an importable kind; locality owns this refusal" + ); + } + + #[test] + fn out_of_repo_supertype_does_not_bind_enum_member() { + // 6b — `impl Error for MapperError` where `std::error::Error` is + // out-of-repo must not bind the enum's own `Error` VARIANT. + let member = mk( + "enum_member:Error", + NodeKind::EnumMember, + "Error", + "MapperError::Error", + "src/lib.rs", + Language::Rust, + ); + let ctx = Ctx::default().name("Error", vec![member]); + let r = refv( + "Error", + EdgeKind::Implements, + "src/lib.rs", + Language::Rust, + 8, + ); + let landed = match_by_exact_name(&r, &ctx); + assert!( + landed.is_none(), + "an implements ref must not bind an enum member, got: {:?}", + landed.map(|res| res.target_node_id) + ); + } + + #[test] + fn in_repo_trait_still_implements() { + // 6d control — a real in-repo trait target must keep its edge, and the + // pre-ranking filter is what lets it OUTRANK a same-named enum member + // rather than merely surviving. + let member = mk( + "enum_member:Error", + NodeKind::EnumMember, + "Error", + "MapperError::Error", + "src/lib.rs", + Language::Rust, + ); + let trait_node = mk( + "trait:Error", + NodeKind::Trait, + "Error", + "Error", + "src/ports.rs", + Language::Rust, + ); + let ctx = Ctx::default().name("Error", vec![member, trait_node]); + let r = refv( + "Error", + EdgeKind::Implements, + "src/lib.rs", + Language::Rust, + 8, + ); + let res = match_by_exact_name(&r, &ctx).expect("in-repo trait still resolves"); + assert_eq!( + res.target_node_id, "trait:Error", + "the legal supertype must outrank the same-named enum member" + ); + } + + #[test] + fn kind_filter_does_not_reach_the_single_candidate_shortcut() { + // Measured on this repo: a GDScript `extends Node` had two same-named + // rivals — an `enum_member Node` and a cross-language Rust `struct Node` — + // and `find_best_match` correctly declined both (the −80 cross-language + // penalty sinks every score below the −1.0 floor). Filtering the enum + // member out must NOT hand the survivor to the single-candidate shortcut, + // which skips that penalty and would fabricate the edge the scored path + // refused. These gates only ever remove an edge. + let member = mk( + "enum_member:Node", + NodeKind::EnumMember, + "Node", + "Command::Node", + "src/main.rs", + Language::Rust, + ); + let strukt = mk( + "struct:Node", + NodeKind::Struct, + "Node", + "Node", + "src/types.rs", + Language::Rust, + ); + let ctx = Ctx::default().name("Node", vec![member, strukt]); + let r = refv( + "Node", + EdgeKind::Extends, + "fixtures/godot/effect_manager.gd", + Language::Gdscript, + 1, + ); + let landed = match_by_exact_name(&r, &ctx); + assert!( + landed.is_none(), + "a cross-language ambiguous supertype must stay unresolved, got: {:?}", + landed.map(|res| (res.target_node_id, res.confidence)) + ); + } + + #[test] + fn class_implements_object_type_alias() { + // Gate 1's `TypeAlias` allowance is pinned as KEPT, not merely permitted: + // a TS class implementing an object type alias is a real edge. + let alias = mk( + "type_alias:Shape", + NodeKind::TypeAlias, + "Shape", + "Shape", + "src/shape.ts", + Language::TypeScript, + ); + let ctx = Ctx::default().name("Shape", vec![alias]); + let r = refv( + "Shape", + EdgeKind::Implements, + "src/box.ts", + Language::TypeScript, + 2, + ); + let res = match_by_exact_name(&r, &ctx).expect("type alias is a legal supertype"); + assert_eq!(res.target_node_id, "type_alias:Shape"); + } } diff --git a/crates/codegraph-resolve/src/resolver.rs b/crates/codegraph-resolve/src/resolver.rs index 39f0ab75..44c8e3e3 100644 --- a/crates/codegraph-resolve/src/resolver.rs +++ b/crates/codegraph-resolve/src/resolver.rs @@ -8,7 +8,9 @@ //! follow-ups — see `KNOWN_DIFFS.md`. Resolution is synchronous (rusqlite). use crate::framework::FrameworkResolver; -use crate::import_resolver::{is_php_include_path_ref, resolve_jvm_import, resolve_via_import}; +use crate::import_resolver::{ + is_bound_to_out_of_repo_module, is_php_include_path_ref, resolve_jvm_import, resolve_via_import, +}; use crate::name_matcher::{ crosses_known_family, is_php_property_receiver_shape, is_python_class_function_ref_target, match_dotted_call_chain, match_function_ref, match_method_call, match_reference, @@ -973,6 +975,82 @@ impl ReferenceResolver { &self, reference: &RefView, context: &dyn ResolutionContext, + ) -> (Option, Option) { + let (resolved, deferred) = self.resolve_one_pure_inner(reference, context); + let resolved = self.gate_target_kind(resolved, reference, context); + let resolved = self.gate_import_locality(resolved, reference, context); + (resolved, deferred) + } + + /// Drop a result whose reference name is bound by an import from OUTSIDE the + /// repository (#1537/#1536). + /// + /// Kind eligibility and locality are two independent gates and both are + /// needed: a kind filter alone RELOCATES the false edge onto a same-named node + /// of a legal kind (an out-of-repo supertype moving from an `enum_member` to a + /// sibling `type_alias`), and an out-of-repo `imports` ref binds a `function`, + /// which is importable. + /// + /// Scoped to the three reference kinds item 6 owns. A `calls` or `references` + /// ref through an external import is a wider claim with its own measurement, + /// not made here. + fn gate_import_locality( + &self, + result: Option, + reference: &RefView, + context: &dyn ResolutionContext, + ) -> Option { + let result = result?; + if !crate::types::is_inheritance_ref(reference.reference_kind) + && reference.reference_kind != EdgeKind::Imports + { + return Some(result); + } + if is_bound_to_out_of_repo_module(reference, context) { + return None; + } + Some(result) + } + + /// Drop a result whose target kind the reference kind forbids (#1537/#1536): + /// an `extends`/`implements` target that declares no type, or an `imports` + /// target that is a type member. + /// + /// Applied at the single seam every strategy returns through — framework, + /// import, name-match, fuzzy and chain alike — so no strategy can produce such + /// an edge by a route the candidate filter in `match_by_exact_name` does not + /// see. Judged on the reference kind as extracted, BEFORE `create_edges` + /// promotes `Extends` → `Implements`. + /// + /// One-way: it only ever removes an edge, and the dropped reference stays in + /// `unresolved_refs` as failed — the honest record for a supertype the + /// repository does not contain. + fn gate_target_kind( + &self, + result: Option, + reference: &RefView, + context: &dyn ResolutionContext, + ) -> Option { + let result = result?; + if !crate::types::is_inheritance_ref(reference.reference_kind) + && reference.reference_kind != EdgeKind::Imports + { + return Some(result); + } + let Some(target) = context.get_node_by_id(&result.target_node_id) else { + return Some(result); + }; + if crate::types::kind_is_eligible_target(reference.reference_kind, target.kind) { + Some(result) + } else { + None + } + } + + fn resolve_one_pure_inner( + &self, + reference: &RefView, + context: &dyn ResolutionContext, ) -> (Option, Option) { if self.is_built_in_or_external(reference) { return (None, None); @@ -2196,6 +2274,27 @@ mod tests { assert!(!is_supertype_bearing_or_module(NodeKind::Function)); } + #[test] + fn esm_chained_call_is_never_deferred_as_chain_ref() { + // The receiver-type visibility gate (#1566) installs at ONE site, + // `match_reference` → `match_method_call`. The #750 conformance pass + // reaches `match_method_call` on its PHP branch only, and a ref can only + // reach that pass by being deferred as a `ChainRef` — which requires + // `is_chain_language`. No ESM language is in it, so gating that pass would + // be dead code. Pinned here so adding a language cannot silently + // invalidate the premise. + for language in crate::types::ESM_LANGUAGES { + assert!( + !is_chain_language(language), + "{language:?} must not defer as a ChainRef, or item 5 needs a second gate site" + ); + } + // The languages that DO defer, so this is a discriminating assertion + // rather than a vacuous one. + assert!(is_chain_language(Language::Java)); + assert!(is_chain_language(Language::Rust)); + } + #[test] fn to_ref_view_and_back_roundtrip() { let stored = UnresolvedRef { @@ -2449,6 +2548,67 @@ mod tests { assert!(edges.iter().any(|e| e.kind == EdgeKind::Instantiates)); } + #[test] + fn extends_ref_judged_before_implements_promotion() { + // `create_edges` promotes `Extends` → `Implements` when the target is an + // interface, so the kind gate must judge the reference kind as EXTRACTED. + // Reading the post-promotion kind would test the wrong thing entirely. + let mut store = Store::open(&temp_db("promote-order")).expect("open"); + let iface = mk_node("interface:I", NodeKind::Interface, "I", "a.ts"); + let member = mk_node("enum_member:I", NodeKind::EnumMember, "I", "a.ts"); + let cls = mk_node("class:C", NodeKind::Class, "C", "a.ts"); + store + .upsert_nodes(&[iface.clone(), member.clone(), cls.clone()]) + .expect("upsert"); + let resolver = ReferenceResolver::new("/root"); + let context = crate::context::StoreResolutionContext::new(&store, "/root"); + + let extends_ref = RefView { + row_id: None, + from_node_id: cls.id.clone(), + reference_name: "I".to_string(), + reference_kind: EdgeKind::Extends, + line: 1, + column: 0, + file_path: "a.ts".to_string(), + language: Language::TypeScript, + is_function_ref: false, + reference_subkind: None, + }; + let to_member = ResolvedRef { + original: extends_ref.clone(), + target_node_id: member.id.clone(), + confidence: 0.9, + resolved_by: ResolvedBy::ExactMatch, + }; + let to_iface = ResolvedRef { + original: extends_ref, + target_node_id: iface.id.clone(), + confidence: 0.9, + resolved_by: ResolvedBy::ExactMatch, + }; + + assert!( + resolver + .gate_target_kind(Some(to_member.clone()), &to_member.original, &context) + .is_none(), + "an Extends ref must be judged against the supertype set, and an enum member fails it" + ); + assert!( + resolver + .gate_target_kind(Some(to_iface.clone()), &to_iface.original, &context) + .is_some(), + "an interface target passes the supertype set and only THEN promotes" + ); + let edges = resolver.create_edges(&[to_iface], &store); + assert_eq!(edges.len(), 1); + assert_eq!( + edges[0].kind, + EdgeKind::Implements, + "promotion still happens after the gate" + ); + } + #[test] fn resolve_all_reports_stats_and_skips_built_ins() { let mut store = Store::open(&temp_db("resolveall")).expect("open"); diff --git a/crates/codegraph-resolve/src/types.rs b/crates/codegraph-resolve/src/types.rs index 9cd7fa3c..d0ee6b73 100644 --- a/crates/codegraph-resolve/src/types.rs +++ b/crates/codegraph-resolve/src/types.rs @@ -6,7 +6,111 @@ //! [`codegraph_core::types::UnresolvedRef`] row read from the store. We model it //! here as [`RefView`] so the two never get confused. -use codegraph_core::types::{EdgeKind, Language, Node, ReferenceSubkind}; +use codegraph_core::types::{EdgeKind, Language, Node, NodeKind, ReferenceSubkind}; + +/// The ES-module family: the languages where a symbol declared in another file is +/// visible ONLY through an explicit `import`, and the set +/// [`crate::import_resolver::extract_import_mappings`] serves through +/// `extract_js_imports`. +/// +/// That equivalence is what makes "declared in this file, or imported into it" a +/// sound visibility oracle here and nowhere else: a package- or namespace-scoped +/// language (Go, Java, Kotlin, C#, Rust, Scala, Dart) makes a sibling-file type +/// visible with no import at all, so the same predicate would delete real edges +/// there. +pub const ESM_LANGUAGES: [Language; 6] = [ + Language::TypeScript, + Language::Tsx, + Language::JavaScript, + Language::Jsx, + Language::Svelte, + Language::Vue, +]; + +/// Is `language` in the [`ESM_LANGUAGES`] family? +pub fn is_esm_language(language: Language) -> bool { + ESM_LANGUAGES.contains(&language) +} + +/// Node kinds that DECLARE a name usable as a type. +/// +/// Two readings, deliberately one list: +/// - the only legal targets of an `extends`/`implements` reference — a +/// `property`, `enum_member` or `method` sharing a supertype's name is not a +/// supertype (#1537/#1536); and +/// - the same-file declarations that BIND a type name at a call site, which is +/// what the receiver-type visibility gate reads (#1566). A TS +/// `namespace Foo {}` binds `Foo` as much as a `class Foo` does, which is why +/// `Module`/`Namespace` belong here too. +/// +/// Upstream's set carries 11 kinds including `union`; we have no +/// `NodeKind::Union` yet, so this is the other 10 and `Union` must join it when +/// the kind exists. +pub const TYPE_DECLARING_KINDS: [NodeKind; 10] = [ + NodeKind::Class, + NodeKind::Struct, + NodeKind::Interface, + NodeKind::Trait, + NodeKind::Protocol, + NodeKind::Enum, + NodeKind::TypeAlias, + NodeKind::Component, + NodeKind::Module, + NodeKind::Namespace, +]; + +/// Does `kind` declare a name usable as a type ([`TYPE_DECLARING_KINDS`])? +pub fn declares_type_name(kind: NodeKind) -> bool { + TYPE_DECLARING_KINDS.contains(&kind) +} + +/// Node kinds an `imports` reference may NEVER target. +/// +/// A member of a type is not importable on its own, so an `imports` reference +/// landing on one is fabricated: `import * as path from 'node:path'` binding to +/// some class's `path` property (#1537). Stated as a DENY list rather than an +/// allow list because the importable set is open-ended — a file, class, function, +/// constant, variable, type alias and enum are all legitimately importable — while +/// the members that are not form a small, closed set. +pub const NON_IMPORTABLE_KINDS: [NodeKind; 5] = [ + NodeKind::Property, + NodeKind::Field, + NodeKind::Method, + NodeKind::EnumMember, + NodeKind::Parameter, +]; + +/// Is `kind` a legal target for an `imports` reference? +pub fn is_importable_kind(kind: NodeKind) -> bool { + !NON_IMPORTABLE_KINDS.contains(&kind) +} + +/// Is `kind` an inheritance reference, i.e. one whose target must be a type +/// ([`TYPE_DECLARING_KINDS`])? +/// +/// Judged on the reference kind as EXTRACTED. `create_edges` later promotes +/// `Extends` → `Implements` when the target is an interface/protocol, so an +/// `Extends` reference must be tested against the supertype set BEFORE that +/// promotion, not after. +pub fn is_inheritance_ref(kind: EdgeKind) -> bool { + matches!(kind, EdgeKind::Extends | EdgeKind::Implements) +} + +/// May a reference of kind `reference_kind` resolve to a node of kind +/// `target_kind`? (#1537/#1536) +/// +/// The two gates of item 6's kind eligibility, in one predicate so the candidate +/// filter and the resolution seam cannot drift apart. Every other reference kind +/// is unconstrained here and resolves exactly as before. +pub fn kind_is_eligible_target(reference_kind: EdgeKind, target_kind: NodeKind) -> bool { + if is_inheritance_ref(reference_kind) { + return declares_type_name(target_kind); + } + if reference_kind == EdgeKind::Imports { + return is_importable_kind(target_kind); + } + true +} /// An unresolved reference in resolution-ready form. /// @@ -283,6 +387,105 @@ mod tests { use super::*; use codegraph_core::types::{Language, Node, NodeKind}; + #[test] + fn all_node_kinds_classified_against_supertype_and_import_sets() { + // Every one of the 22 kinds is classified explicitly, so a kind added + // later cannot be silently omitted from either gate: the two expected + // lists below are exhaustive and the assertion compares whole sets. + let type_declaring: Vec = NodeKind::ALL + .into_iter() + .filter(|k| declares_type_name(*k)) + .collect(); + assert_eq!( + type_declaring, + vec![ + NodeKind::Module, + NodeKind::Class, + NodeKind::Struct, + NodeKind::Interface, + NodeKind::Trait, + NodeKind::Protocol, + NodeKind::Enum, + NodeKind::TypeAlias, + NodeKind::Namespace, + NodeKind::Component, + ], + "10 supertype-eligible kinds — no `Union` yet, which Tier 3 must add" + ); + + let non_importable: Vec = NodeKind::ALL + .into_iter() + .filter(|k| !is_importable_kind(*k)) + .collect(); + assert_eq!( + non_importable, + vec![ + NodeKind::Method, + NodeKind::Property, + NodeKind::Field, + NodeKind::EnumMember, + NodeKind::Parameter, + ] + ); + + assert_eq!( + NodeKind::ALL.len(), + 22, + "kind count changed — revisit both sets" + ); + } + + #[test] + fn kind_eligibility_gates_only_inheritance_and_imports() { + // Inheritance refs demand a type-declaring target. + for kind in [EdgeKind::Extends, EdgeKind::Implements] { + assert!(is_inheritance_ref(kind)); + assert!(kind_is_eligible_target(kind, NodeKind::Trait)); + assert!(kind_is_eligible_target(kind, NodeKind::TypeAlias)); + assert!(!kind_is_eligible_target(kind, NodeKind::EnumMember)); + assert!(!kind_is_eligible_target(kind, NodeKind::Function)); + } + // Imports refs deny type members. + assert!(kind_is_eligible_target( + EdgeKind::Imports, + NodeKind::Function + )); + assert!(kind_is_eligible_target(EdgeKind::Imports, NodeKind::Import)); + assert!(!kind_is_eligible_target( + EdgeKind::Imports, + NodeKind::Property + )); + // Every other reference kind is unconstrained. + assert!(!is_inheritance_ref(EdgeKind::Calls)); + for target in NodeKind::ALL { + assert!(kind_is_eligible_target(EdgeKind::Calls, target)); + assert!(kind_is_eligible_target(EdgeKind::References, target)); + } + } + + #[test] + fn esm_language_set_is_the_import_required_family() { + for language in ESM_LANGUAGES { + assert!(is_esm_language(language), "{language:?}"); + } + // Package/namespace-scoped languages must stay out: a sibling-file type + // is visible there with no import, so the visibility oracle would delete + // real edges. + for language in [ + Language::Go, + Language::Java, + Language::Kotlin, + Language::CSharp, + Language::Rust, + Language::Scala, + Language::Dart, + Language::Python, + Language::Cpp, + ] { + assert!(!is_esm_language(language), "{language:?}"); + } + } + #[test] fn resolved_by_as_str_all_variants() { assert_eq!(ResolvedBy::ExactMatch.as_str(), "exact-match"); diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/bound/barrel.ts b/crates/codegraph-resolve/tests/fixtures/tier2/bound/barrel.ts new file mode 100644 index 00000000..a756f847 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/bound/barrel.ts @@ -0,0 +1 @@ +export * from './other'; diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/bound/named.ts b/crates/codegraph-resolve/tests/fixtures/tier2/bound/named.ts new file mode 100644 index 00000000..9875fabf --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/bound/named.ts @@ -0,0 +1,6 @@ +import { Map } from './other'; + +export function useNamed(): string { + const m = new Map(); + return m.get('a'); +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/bound/other.ts b/crates/codegraph-resolve/tests/fixtures/tier2/bound/other.ts new file mode 100644 index 00000000..cb217154 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/bound/other.ts @@ -0,0 +1 @@ +export class Map { get(k: string): string { return k; } } diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/bound/viaBarrel.ts b/crates/codegraph-resolve/tests/fixtures/tier2/bound/viaBarrel.ts new file mode 100644 index 00000000..4748e6f8 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/bound/viaBarrel.ts @@ -0,0 +1,6 @@ +import { Map } from './barrel'; + +export function useBarrel(): string { + const m = new Map(); + return m.get('a'); +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/esm_import/run.ts b/crates/codegraph-resolve/tests/fixtures/tier2/esm_import/run.ts new file mode 100644 index 00000000..858d1a0a --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/esm_import/run.ts @@ -0,0 +1,5 @@ +import * as path from 'node:path'; + +export function run(): string { + return path.join('a', 'b'); +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/esm_import/types.ts b/crates/codegraph-resolve/tests/fixtures/tier2/esm_import/types.ts new file mode 100644 index 00000000..e9c8998e --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/esm_import/types.ts @@ -0,0 +1,4 @@ +export class Request { + path = ''; + url = ''; +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/hijack/main.ts b/crates/codegraph-resolve/tests/fixtures/tier2/hijack/main.ts new file mode 100644 index 00000000..682fd701 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/hijack/main.ts @@ -0,0 +1,4 @@ +export function useBuiltin(): void { + const m = new Map(); + m.get("a"); +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/hijack/other.ts b/crates/codegraph-resolve/tests/fixtures/tier2/hijack/other.ts new file mode 100644 index 00000000..25bdfa03 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/hijack/other.ts @@ -0,0 +1 @@ +export class Map { get(): string { return "hijacked"; } } diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/item4/mail.ts b/crates/codegraph-resolve/tests/fixtures/tier2/item4/mail.ts new file mode 100644 index 00000000..66906679 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/item4/mail.ts @@ -0,0 +1,9 @@ +export class Mailer { send(m: string): void { console.log(m); } } +export class Outbox { + private mailer = new Mailer(); + send(m: string): void { this.mailer.send(m); } +} +export class Relay { + private mailer = new Mailer(); + forward(m: string): void { this.mailer.send(m); } +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/item5/repro.ts b/crates/codegraph-resolve/tests/fixtures/tier2/item5/repro.ts new file mode 100644 index 00000000..3019f4f6 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/item5/repro.ts @@ -0,0 +1,28 @@ +export class LRUCache { + private store = new Map(); + + get(key: string): string | undefined { + return this.store.get(key); + } + + set(key: string, value: string): void { + this.store.set(key, value); + } + + has(key: string): boolean { + return this.store.has(key); + } +} + +export function useLocalMap(): boolean { + const values = new Map(); + values.set("answer", "42"); + values.get("answer"); + return values.has("answer"); +} + +export function useNestedMap( + holder: { values: Map }, +): string | undefined { + return holder.values.get("answer"); +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/recur/rec.ts b/crates/codegraph-resolve/tests/fixtures/tier2/recur/rec.ts new file mode 100644 index 00000000..d9958b1d --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/recur/rec.ts @@ -0,0 +1,2 @@ +export class Walker { run(n: number): void { if (n > 0) { this.run(n - 1); } } } +export class Other { run(n: number): void { void n; } } diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/alias.rs b/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/alias.rs new file mode 100644 index 00000000..05d7e9f5 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/alias.rs @@ -0,0 +1 @@ +pub type Error = String; diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/lib.rs b/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/lib.rs new file mode 100644 index 00000000..9f64040a --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/lib.rs @@ -0,0 +1,22 @@ +mod alias; +mod ports; + +use crate::ports::Sha256Port; +use std::error::Error; + +pub enum MapperError { + Error, + Missing, +} + +impl Error for MapperError {} + +pub struct Hasher { + salt: String, +} + +impl Sha256Port for Hasher { + fn hash(&self) -> String { + String::new() + } +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/ports.rs b/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/ports.rs new file mode 100644 index 00000000..04b246b4 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/rust_supertype/src/ports.rs @@ -0,0 +1,3 @@ +pub trait Sha256Port { + fn hash(&self) -> String; +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/sfc/Box.svelte b/crates/codegraph-resolve/tests/fixtures/tier2/sfc/Box.svelte new file mode 100644 index 00000000..a5b60ecc --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/sfc/Box.svelte @@ -0,0 +1,9 @@ + + +
hi
diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/sfc/models.ts b/crates/codegraph-resolve/tests/fixtures/tier2/sfc/models.ts new file mode 100644 index 00000000..54af3859 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/sfc/models.ts @@ -0,0 +1,3 @@ +export class Serializable { + a = 1; +} diff --git a/crates/codegraph-resolve/tests/fixtures/tier2/sfc/package.json b/crates/codegraph-resolve/tests/fixtures/tier2/sfc/package.json new file mode 100644 index 00000000..38911c74 --- /dev/null +++ b/crates/codegraph-resolve/tests/fixtures/tier2/sfc/package.json @@ -0,0 +1 @@ +{ "name": "sfc-fixture", "version": "1.0.0" } diff --git a/crates/codegraph-resolve/tests/tier2_false_edges.rs b/crates/codegraph-resolve/tests/tier2_false_edges.rs new file mode 100644 index 00000000..221cc1d7 --- /dev/null +++ b/crates/codegraph-resolve/tests/tier2_false_edges.rs @@ -0,0 +1,454 @@ +//! Tier 2 false-edge regression tests (upstream #1496 / #1566 / #1537 / #1536). +//! +//! A missing edge makes an agent look further; a FALSE edge makes it confidently +//! wrong. Each test here drives the FULL extract → resolve pipeline over a +//! committed fixture under `tests/fixtures/tier2/`, so it exercises real +//! tree-sitter extraction, real import-mapping extraction and real multi-file +//! resolution — behaviour a mock `ResolutionContext` structurally cannot reach. +//! +//! Fixtures are read in place and never written to; the store lives in a temp +//! file, so the worktree stays clean. + +use std::path::{Path, PathBuf}; + +use codegraph_core::types::{Edge, EdgeKind, FileRecord, Node, NodeKind}; +use codegraph_extract::{detect_language, extract_file}; +use codegraph_resolve::ReferenceResolver; +use codegraph_store::Store; + +fn fixture_root(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("fixtures") + .join("tier2") + .join(name) +} + +fn temp_db_path(test_name: &str) -> PathBuf { + let mut path = std::env::temp_dir(); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock after epoch") + .as_nanos(); + path.push(format!( + "codegraph-tier2-{test_name}-{}-{nanos}.db", + std::process::id() + )); + path +} + +/// Every indexable file under `root`, as project-relative `/`-separated paths, +/// sorted so indexing order is deterministic. +fn fixture_files(root: &Path) -> Vec { + let mut out = Vec::new(); + collect(root, root, &mut out); + out.sort(); + out +} + +fn collect(root: &Path, dir: &Path, out: &mut Vec) { + let entries = std::fs::read_dir(dir).expect("read fixture dir"); + for entry in entries { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + collect(root, &path, out); + } else if let Ok(relative) = path.strip_prefix(root) { + out.push(relative.to_string_lossy().replace('\\', "/")); + } + } +} + +/// A resolved graph over one Tier 2 fixture: the store plus every non-`Contains` +/// edge the pipeline produced. +struct Resolved { + store: Store, + edges: Vec, +} + +impl Resolved { + fn node(&self, id: &str) -> Node { + self.store + .node_by_id(id) + .expect("node lookup") + .expect("node exists") + } + + fn of_kind(&self, kind: EdgeKind) -> Vec<&Edge> { + self.edges.iter().filter(|e| e.kind == kind).collect() + } + + /// `(source, target, line, resolvedBy)` for every edge of `kind`, rendered as + /// `name@file:Lline` so a self-edge is distinguishable from a correct edge. + fn described(&self, kind: EdgeKind) -> Vec { + let mut rows: Vec = self + .of_kind(kind) + .into_iter() + .map(|e| { + let s = self.node(&e.source); + let t = self.node(&e.target); + let how = e + .metadata + .as_ref() + .and_then(|m| m.get("resolvedBy")) + .and_then(|v| v.as_str()) + .unwrap_or("?") + .to_string(); + let conf = e + .metadata + .as_ref() + .and_then(|m| m.get("confidence")) + .and_then(serde_json::Value::as_f64) + .unwrap_or(0.0); + format!( + "{:?}|{}@{}:L{} -> {:?}|{}@{}:L{} at {:?} [{how} {conf}]", + s.kind, + s.name, + s.file_path, + s.start_line, + t.kind, + t.name, + t.file_path, + t.start_line, + e.line, + ) + }) + .collect(); + rows.sort(); + rows + } + + fn self_edges(&self, kind: EdgeKind) -> Vec<&Edge> { + self.of_kind(kind) + .into_iter() + .filter(|e| e.source == e.target) + .collect() + } +} + +fn resolve_fixture(name: &str) -> Resolved { + let root = fixture_root(name); + assert!(root.is_dir(), "missing committed fixture {name}"); + let relative = fixture_files(&root); + assert!(!relative.is_empty(), "fixture {name} has no files"); + + let mut store = Store::open(&temp_db_path(name)).expect("open store"); + for path in &relative { + let language = detect_language(path); + let result = extract_file(&root, path).expect("extract file"); + store + .upsert_file(&FileRecord { + path: path.clone(), + content_hash: "fixture".to_string(), + language, + size: 0, + modified_at: 0, + indexed_at: 0, + node_count: result.nodes.len() as i64, + errors: Vec::new(), + }) + .expect("upsert file"); + store.upsert_nodes(&result.nodes).expect("upsert nodes"); + store + .insert_edges(&result.edges) + .expect("insert contains edges"); + store + .insert_unresolved_refs(&result.unresolved_references) + .expect("insert unresolved refs"); + } + + let root_str = root.to_string_lossy().to_string(); + let mut resolver = ReferenceResolver::new(root_str.clone()); + { + let context = codegraph_resolve::StoreResolutionContext::new(&store, &root_str); + resolver.initialize(&context); + } + resolver + .extract_and_persist_frameworks(&mut store, &relative) + .expect("framework extract"); + resolver + .resolve_and_persist(&mut store) + .expect("resolve and persist"); + resolver + .run_post_extract(&mut store) + .expect("run post extract"); + + let mut edges = Vec::new(); + for kind in NodeKind::ALL { + for node in store.nodes_by_kind(kind).expect("nodes by kind") { + for edge in store + .edges_by_source_kind(&node.id, None) + .expect("edges by source") + { + if edge.kind != EdgeKind::Contains { + edges.push(edge); + } + } + } + } + Resolved { store, edges } +} + +// ================= Item 4 — receiver preservation (#1496) ==================== + +#[test] +fn no_self_edge_for_member_receiver_call() { + // Given three classes where `Outbox.send` and `Relay.forward` both call + // `this.mailer.send(...)`, + // When the pipeline resolves, + // Then no `Calls` edge is a self-edge, and BOTH callers reach `Mailer::send` + // (start_line 1) rather than the proximity-nearest `Outbox::send` at line 4. + let g = resolve_fixture("item4"); + let described = g.described(EdgeKind::Calls); + + assert!( + g.self_edges(EdgeKind::Calls).is_empty(), + "a member-expression receiver must not resolve to the enclosing method: {described:?}" + ); + + let to_real_mailer = g + .of_kind(EdgeKind::Calls) + .into_iter() + .filter(|e| { + let t = g.node(&e.target); + t.name == "send" && t.start_line == 1 + }) + .count(); + assert_eq!( + to_real_mailer, 2, + "both `this.mailer.send(m)` calls must target Mailer::send@L1: {described:?}" + ); + + assert_eq!( + g.of_kind(EdgeKind::Calls).len(), + 2, + "exactly the two repaired edges, no spurious extras: {described:?}" + ); +} + +// ================= Item 5 — built-in receiver hijack (#1566) ================= + +/// `Calls` edges out of the symbol named `from`, described for assertion output. +fn calls_from(g: &Resolved, from: &str) -> Vec { + g.of_kind(EdgeKind::Calls) + .into_iter() + .filter(|e| g.node(&e.source).name == from) + .map(|e| { + let t = g.node(&e.target); + format!("{}@{}:L{}", t.name, t.file_path, t.start_line) + }) + .collect() +} + +#[test] +fn builtin_receiver_does_not_bind_project_method() { + // Given `useLocalMap`, whose receiver is a LOCAL built-in + // `new Map()`, + // When resolution runs, + // Then its three `set`/`get`/`has` calls bind to nothing — today each is + // adopted by the unique project method at `instance-method 0.7`. + let g = resolve_fixture("item5"); + let landed = calls_from(&g, "useLocalMap"); + assert!( + landed.is_empty(), + "a built-in Map receiver must not bind project methods, got: {landed:?}" + ); +} + +#[test] +fn nested_builtin_receiver_stays_unresolved() { + // `useNestedMap`'s receiver is `holder.values`, typed `Map` + // by the parameter annotation. Reachable only because item 4 now preserves + // the `values` segment; item 5's gate is what refuses it. + let g = resolve_fixture("item5"); + let landed = calls_from(&g, "useNestedMap"); + assert!( + landed.is_empty(), + "a nested built-in Map receiver must stay unresolved, got: {landed:?}" + ); +} + +#[test] +fn class_field_builtin_receiver_is_refused() { + // The WHOLE-fixture criterion. Every call in `item5` is a built-in `Map` + // method — three via a class FIELD receiver, three via a local, one nested — + // so the correct total is zero. A symbol-scoped assertion would pass while + // the three `LRUCache::get/set/has → itself` self-edges survived, which is + // exactly how that residue hid. + let g = resolve_fixture("item5"); + let described = g.described(EdgeKind::Calls); + assert!( + g.of_kind(EdgeKind::Calls).is_empty(), + "every call in item5 is a built-in Map method: {described:?}" + ); + assert!( + g.self_edges(EdgeKind::Calls).is_empty(), + "and none may be a self-edge: {described:?}" + ); +} + +#[test] +fn bound_project_map_resolves_through_both_import_routes() { + // Item 5's false-refusal fence, over REAL import extraction: a project + // `class Map` reached by a named import and by a barrel re-export must keep + // resolving. The named/barrel discrimination is what makes this a fixture + // rather than a mock — the predicate reads extracted import mappings. + let g = resolve_fixture("bound"); + let described = g.described(EdgeKind::Calls); + assert_eq!( + g.of_kind(EdgeKind::Calls).len(), + 2, + "both bound-Map calls must resolve: {described:?}" + ); + let to_project_get = g + .of_kind(EdgeKind::Calls) + .into_iter() + .filter(|e| { + let t = g.node(&e.target); + t.name == "get" && t.file_path == "other.ts" + }) + .count(); + assert_eq!( + to_project_get, 2, + "both must target the project `Map::get` in other.ts: {described:?}" + ); +} + +// ============ Item 6 — kind eligibility and import locality (#1537/#1536) ==== + +#[test] +fn phantom_import_binds_only_the_import_node() { + // Given `import * as path from 'node:path'` and an unrelated class carrying a + // `path` property, + // When resolution runs, + // Then the ONLY `imports` edge is the legitimate one to the `node:path` + // import node. The second assertion is what stops an implementation from + // passing by deleting all `imports` edges. + let g = resolve_fixture("esm_import"); + let described = g.described(EdgeKind::Imports); + let to_non_import = g + .of_kind(EdgeKind::Imports) + .into_iter() + .filter(|e| g.node(&e.target).kind != NodeKind::Import) + .count(); + assert_eq!( + to_non_import, 0, + "an out-of-repo import must not bind an in-repo symbol: {described:?}" + ); + assert_eq!( + g.of_kind(EdgeKind::Imports).len(), + 1, + "and the edge to the import node itself must survive: {described:?}" + ); +} + +#[test] +fn out_of_repo_supertype_does_not_bind_any_same_named_node() { + // 6b + 6c together. `impl Error for MapperError` names the out-of-repo + // `std::error::Error`; the fixture offers both an `enum_member Error` and a + // sibling `type_alias Error`. Asserting zero `implements` edges to ANY + // `Error`-named node is what fails a kind-filter-only implementation, which + // would still bind the legal-kind type alias. + let g = resolve_fixture("rust_supertype"); + let described = g.described(EdgeKind::Implements); + let to_error = g + .of_kind(EdgeKind::Implements) + .into_iter() + .filter(|e| g.node(&e.target).name == "Error") + .count(); + assert_eq!( + to_error, 0, + "an out-of-repo supertype must bind nothing: {described:?}" + ); +} + +#[test] +fn in_repo_rust_trait_implements_survives() { + // 6d control — the real in-repo trait edge must be the ONLY `implements` edge, + // and Gate 2 must not over-fire on the in-repo `use crate::ports::Sha256Port` + // that binds it. Without the imports assertions an over-firing locality rule + // would go unnoticed. + let g = resolve_fixture("rust_supertype"); + let implements = g.described(EdgeKind::Implements); + assert_eq!( + g.of_kind(EdgeKind::Implements).len(), + 1, + "exactly the in-repo trait edge: {implements:?}" + ); + assert_eq!( + g.node(&g.of_kind(EdgeKind::Implements)[0].target).name, + "Sha256Port" + ); + + let imports = g.described(EdgeKind::Imports); + assert_eq!( + g.of_kind(EdgeKind::Imports).len(), + 3, + "the in-repo `use` must keep resolving: {imports:?}" + ); + let to_trait = g + .of_kind(EdgeKind::Imports) + .into_iter() + .filter(|e| { + let t = g.node(&e.target); + t.kind == NodeKind::Trait && t.name == "Sha256Port" + }) + .count(); + assert_eq!( + to_trait, 1, + "`use crate::ports::Sha256Port` must still bind the real trait: {imports:?}" + ); +} + +#[test] +fn dropped_supertype_is_recorded_as_unresolved() { + // The gates only ever REMOVE an edge; the reference stays recorded as failed, + // which is the honest record for a supertype the repo does not contain. + let g = resolve_fixture("rust_supertype"); + let recorded = g + .store + .all_unresolved_refs() + .expect("unresolved refs") + .into_iter() + .filter(|r| r.reference_name.contains("Error")) + .count(); + assert!( + recorded >= 1, + "the dropped `Error` supertype must remain in unresolved_refs" + ); +} + +#[test] +fn npm_specifier_in_sfc_is_external() { + // 6e — a Svelte `