From f78f346beca43b043a22ada2b5914c8f425e51e4 Mon Sep 17 00:00:00 2001 From: columbia11 Date: Tue, 3 Nov 2026 08:16:02 +0800 Subject: [PATCH 1/8] resolve: close graph gaps found against upstream CodeGraph - Multi-line imports: names on continuation lines resolve through the statement's first line (Python, TypeScript, Rust). - JVM calls take the single callable member over a same-named Kotlin property or Java field. - Rust generic type parameters are TypeParam bindings and never link to a same-named struct elsewhere. - Kotlin extension functions (`fun Lockable.awaitNanos()`) are members of their receiver type and its subtypes. - TypeScript `new X()` that resolves to an interface or type alias goes to the same-named value beside it. - Rust `let (tx, rx) = f()` / `f()?` types each element from the callee's returned tuple. - Rust `use` through a bare `crate`/`self`/`super` root no longer adds a file-level imports edge to the crate root or parent module. - Rust path members (`mio::Interest::AIO`) resolve by the path as written, so a dependency's type is not linked to a same-named local type. --- crates/cg-extract/src/facts/mod.rs | 3 + crates/cg-extract/src/facts/rust.rs | 41 ++++++ crates/cg-resolve/src/engine.rs | 21 +++- crates/cg-resolve/src/resolve.rs | 155 +++++++++++++++++++++-- crates/cg-resolve/tests/resolve_e2e.rs | 166 +++++++++++++++++++++++++ crates/cg-store/src/build.rs | 4 +- 6 files changed, 375 insertions(+), 15 deletions(-) diff --git a/crates/cg-extract/src/facts/mod.rs b/crates/cg-extract/src/facts/mod.rs index 621e7f0..6d24285 100644 --- a/crates/cg-extract/src/facts/mod.rs +++ b/crates/cg-extract/src/facts/mod.rs @@ -154,6 +154,9 @@ pub enum BindKind { /// C++ `#define BEGIN namespace fmt {`: `name` is a namespace opened only by a macro, which /// no node of the index stands for. Metadata only; not a lexical binding. MacroNamespace = 15, + /// A Rust type parameter of the fn, impl or trait whose scope holds it. Only a type + /// reference sees it: `T` in `fn new(value: T)` names no `struct T` elsewhere. + TypeParam = 16, } #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/cg-extract/src/facts/rust.rs b/crates/cg-extract/src/facts/rust.rs index abd3ed4..a0248d5 100644 --- a/crates/cg-extract/src/facts/rust.rs +++ b/crates/cg-extract/src/facts/rust.rs @@ -109,6 +109,7 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) { let generics = generics_of(cx, n); cx.generics.push(generics); let sc = cx.push_scope(ScopeKind::Class, scope, n); + bind_type_params(cx, sc); if n.kind() == "impl_item" { deref_impl(cx, n, scope); } @@ -176,6 +177,10 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) { } walk_children(cx, n, scope); } + "scoped_identifier" => { + scoped_receiver(cx, n); + walk_children(cx, n, scope); + } "for_expression" => { if let Some(p) = n.child_by_field_name("pattern") { bind_pattern(cx, p, scope, BindKind::Local); @@ -192,6 +197,20 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) { } } +/// `mio::Interest::AIO`: the kernel names the receiver of a path's member by its last segment +/// (`Interest`); the path as written keeps a dependency's type apart from a local one. +fn scoped_receiver(cx: &mut Cx, n: Node) { + let (Some(path), Some(member)) = (n.child_by_field_name("path"), n.child_by_field_name("name")) else { return }; + if path.kind() != "scoped_identifier" || !cx.text(member).starts_with(|c: char| c.is_ascii_uppercase()) { + return; + } + let Some(recv) = path.child_by_field_name("name") else { return }; + let pos = cx.start(recv); + let recv = cx.text(recv).to_owned(); + let name = cx.text(path).to_owned(); + cx.facts.call_names.push(CallNameFact { line: (pos >> 32) as u32, col: pos as u32, tail: recv.clone(), kernel_name: recv, name }); +} + /// Bounds that add nothing a call goes through. const MARKER_TRAITS: &[&str] = &["Clone", "Copy", "Send", "Sync", "Sized", "Debug", "Default", "Eq", "PartialEq", "Hash", "Ord", "PartialOrd", "Display", "Unpin", "Any"]; @@ -391,6 +410,19 @@ fn let_decl(cx: &mut Cx, n: Node, scope: u32) { if target.kind() == "identifier" { let nm = cx.text(target).to_owned(); cx.add_binding(scope, &nm, BindKind::Local, &ty, &init, line); + } else if target.kind() == "tuple_pattern" && init.ends_with([')', '?']) && !kids(target).any(|c| c.kind() == "remaining_field_pattern") { + // `let (tx, rx) = mpsc::channel()`: element i holds the call's `.i` + let elems: Vec = kids(target).filter(|c| (c.is_named() || c.kind() == "_") && !c.kind().ends_with("comment")).collect(); + for (i, e) in elems.into_iter().enumerate() { + // `mut rx`: `mutable_specifier` first, then the pattern + let id = if e.kind() == "mut_pattern" { e.named_child(1).unwrap_or(e) } else { e }; + if id.kind() == "identifier" { + let nm = cx.text(id).to_owned(); + cx.add_binding(scope, &nm, BindKind::Local, "", &format!("{init}.{i}"), line); + } else { + bind_pattern(cx, e, scope, BindKind::Local); + } + } } else { bind_pattern(cx, p, scope, BindKind::Local); } @@ -457,6 +489,7 @@ fn function_body(cx: &mut Cx, n: Node, scope: u32) { } } let sc = cx.push_scope(ScopeKind::Function, scope, n); + bind_type_params(cx, sc); if let Some(p) = n.child_by_field_name("parameters") { params(cx, p, sc); } @@ -465,6 +498,14 @@ fn function_body(cx: &mut Cx, n: Node, scope: u32) { } } +/// The type parameters of the item whose scope `sc` is (the innermost `cx.generics`). +fn bind_type_params(cx: &mut Cx, sc: u32) { + let names: Vec = cx.generics.last().map(|g| g.iter().map(|(n, _)| n.clone()).collect()).unwrap_or_default(); + for n in names { + cx.add_binding(sc, &n, BindKind::TypeParam, "", "", 0); + } +} + fn closure(cx: &mut Cx, n: Node, scope: u32) { let sc = cx.push_scope(ScopeKind::Function, scope, n); if let Some(p) = n.child_by_field_name("parameters") { diff --git a/crates/cg-resolve/src/engine.rs b/crates/cg-resolve/src/engine.rs index 0b5818a..5728029 100644 --- a/crates/cg-resolve/src/engine.rs +++ b/crates/cg-resolve/src/engine.rs @@ -694,8 +694,8 @@ impl<'v> Engine<'v> { cross.push(cand); } match self.view.file(tfile).lang().family() { - // Java/Kotlin nested types (pre-existing behaviour) - LangFamily::Jvm => best.filter(|_| tn.qname().contains("::")), + // Java/Kotlin nested types (pre-existing behaviour), then a Kotlin extension function + LangFamily::Jvm => best.filter(|_| tn.qname().contains("::")).or_else(|| self.kotlin_extension(t, name)), // Swift extensions (emitted as class nodes) add members in other files and other // modules (a test target extending the library's type). Pick deterministically: // posting order (base before delta) must never decide. @@ -716,6 +716,23 @@ impl<'v> Engine<'v> { } } + /// Kotlin `fun Lockable.awaitNanos()` outside any type body: the kernel names it + /// `Lockable::awaitNanos`, without the package. One in `t`'s package first, else the only one. + fn kotlin_extension(&self, t: NodeIdx, name: &str) -> Option { + let view = self.view; + let tn = view.node(t); + let mut cands: SmallVec<[NodeIdx; 4]> = view + .by_qname(&format!("{}::{}", tn.name(), name)) + .filter(|&c| view.file(view.hot(c).file).lang() == Lang::Kotlin && view.node(c).parent().is_none_or(|p| !view.node(p).kind().is_type())) + .collect(); + cands.sort_by_key(|&c| (view.file(view.hot(c).file).path(), view.node(c).start_line())); + let tpkg = self.modules.pkg_of(tn.file()); + match cands.as_slice() { + [only] => Some(*only), + _ => cands.iter().copied().find(|&c| self.modules.pkg_of(view.hot(c).file) == tpkg), + } + } + /// Whether a member with type `t`'s qualified name found in another file belongs to `t`: /// C# / Ruby when that file re-declares the type (partial class, reopened class or /// module); C/C++ when the member's file includes the type's file or vice versa. diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 21fe769..49a9975 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -183,6 +183,25 @@ fn pointer_method(method: &str) -> bool { ) } +/// `A, D` -> [`A`, `D`]: the items of a written type list, nested lists whole. +fn type_list(s: &str) -> Vec<&str> { + let (mut out, mut depth, mut start) = (Vec::new(), 0u32, 0); + for (i, c) in s.char_indices() { + match c { + '<' | '(' | '[' => depth += 1, + '>' | ')' | ']' => depth = depth.saturating_sub(1), + ',' if depth == 0 => { + out.push(s[start..i].trim()); + start = i + 1; + } + _ => {} + } + } + out.push(s[start..].trim()); + out.retain(|t| !t.is_empty()); + out +} + /// Paths here contain no source arguments except bounded constructor paths. /// Find the final complete call, allowing earlier calls in its receiver. fn split_call(value: &str) -> Option<(&str, &str)> { @@ -476,6 +495,7 @@ impl<'e, 'v> FileCx<'e, 'v> { || b.kind == BindKind::CommonJsObject as u8 || b.kind == BindKind::AssignedThisCall as u8 || b.kind == BindKind::MacroNamespace as u8 + || b.kind == BindKind::TypeParam as u8 { continue; } @@ -492,6 +512,18 @@ impl<'e, 'v> FileCx<'e, 'v> { } } + /// A type parameter `name` of an item enclosing `scope` (Rust `fn new(value: T)`). + fn type_param(&self, name: &str, scope: u32) -> bool { + let mut s = Some(scope); + while let Some(c) = s { + if self.bindings.get(&(c, name)).is_some_and(|l| l.iter().any(|b| b.kind == BindKind::TypeParam as u8)) { + return true; + } + s = self.scope_parent(c); + } + false + } + fn visible_import(&self, name: &str, scope: u32) -> Option { let list = self.import_by_local.get(name)?; list.iter().copied().find(|i| { @@ -899,6 +931,9 @@ impl<'e, 'v> FileCx<'e, 'v> { return Some(value); } if self.family == LangFamily::Rust { + if let Some((call, index)) = init.rsplit_once('.').and_then(|(c, i)| Some((c, i.parse::().ok()?))).filter(|(c, _)| c.ends_with([')', '?'])) { + return self.tuple_element(wcx, call, index, scope, line, depth + 1); + } if let Some((callee, args)) = split_call(init) { if let Some(owner) = callee.strip_suffix("::new") { if self.std_wrapper(wcx, owner) == Some(StdWrapper::Pointer) { @@ -921,6 +956,62 @@ impl<'e, 'v> FileCx<'e, 'v> { self.type_value(wcx, init, None, depth + 1) } + /// `let (tx, rx) = mpsc::channel()`: element `index` of the tuple a Rust function returns, + /// through the `Result` or `Option` a `?` opens. + fn tuple_element(&self, wcx: &mut WorkerCx<'e, 'v>, call: &str, index: usize, scope: u32, line: u32, depth: u8) -> Option { + if depth >= 16 { + return None; + } + let (call, tried) = match call.strip_suffix('?') { + Some(c) => (c, true), + None => (call, false), + }; + let (callee, _) = split_call(call)?; + let f = self.rust_callee(wcx, callee, scope, line)?; + let node = self.view.node(f); + let cx = wcx.file_cx(self.e, node.file()); + let mut ty = match self.e.return_types.get(&f) { + Some(b) => self.view.text_str(b.decl_type), + None => node.return_type()?, + } + .trim(); + if tried { + let open = ty.find('<')?; + if !matches!(cx.std_wrapper(wcx, ty[..open].trim()), Some(StdWrapper::Result | StdWrapper::Option)) { + return None; + } + ty = *type_list(ty[open + 1..].strip_suffix('>')?).first()?; + } + let elems = type_list(ty.strip_prefix('(')?.strip_suffix(')')?); + cx.type_value(wcx, elems.get(index)?, None, depth + 1) + } + + /// The function a Rust call path names: `helper`, `mpsc::channel`, `Pair::new`. + fn rust_callee(&self, wcx: &mut WorkerCx<'e, 'v>, callee: &str, scope: u32, line: u32) -> Option { + // a method's tuple (`stream.into_split()`) stays untyped: its receiver is not modelled here + if callee.contains('.') { + return None; + } + let Some((head, rest)) = callee.split_once("::") else { + return match self.resolve_name(wcx, callee, Accept::Callable, scope, line, None, true) { + NameRes::Found(n, ..) => Some(n), + _ => None, + }; + }; + if let Some(Bound::Node(n)) = self.rust_path_bound(callee) { + return Some(n); + } + let start = match self.resolve_name(wcx, head, Accept::Any, scope, line, None, false) { + NameRes::Found(n, ..) => Bound::Node(n), + NameRes::Module(m) => Bound::Module(m), + _ => return None, + }; + match self.walk_path(start, &rest.split("::").collect::>())? { + Bound::Node(n) if kind_of(self.view, n).is_callable() => Some(n), + _ => None, + } + } + /// A pytest fixture's value (upstream `pythonFixtureReturnType`): in a test file or a /// `conftest.py`, a parameter named after a fixture declared in the same file or in a /// `conftest.py` of its directory or above holds what the fixture returns. @@ -1544,6 +1635,11 @@ impl<'e, 'v> FileCx<'e, 'v> { return None; } let cands = self.e.member_overloads(t, name); + // Kotlin `val socketFactory` beside `fun socketFactory()`, a Java field beside its method: + // a call names the one method, whichever member is declared first + if cands.len() == 1 && self.family == LangFamily::Jvm { + return cands.first().copied(); + } self.pick_overload(wcx, &cands, args, r) } @@ -3176,6 +3272,8 @@ impl<'e, 'v> FileCx<'e, 'v> { } TypeRes::Unknown => NameRes::NotFound, } + } else if self.type_param(name, scope) { + NameRes::Local } else if let Some(n) = self.cpp_nested_type(r.from, name) { NameRes::Found(n, by::RECEIVER, 95) } else { @@ -3278,9 +3376,14 @@ impl<'e, 'v> FileCx<'e, 'v> { } fn resolve_import_ref(&self, name: &str, r: &RefRec) -> Outcome { - let Some(idxs) = self.imports_by_line.get(&r.line) else { return Outcome::st(status::NO_CANDIDATE) }; + let Some(idxs) = self.imports_by_line.get(&r.line) else { return self.continued_import_ref(name, r) }; let view = self.view; let tgt = |i: u32| self.e.imp_targets[self.file.idx()].get(i as usize).copied().unwrap_or(ImportTarget::External); + // Rust `crate`, `self`, `super` (alone in `use super::Addr`, or a path's root) name this + // crate's own modules, which the path's bound names already reach: no dependency + if self.family == LangFamily::Rust && matches!(name, "crate" | "self" | "super") { + return Outcome::st(status::BUILTIN); + } // 1. the module specifier itself (C facts keep `<..>` around angle includes and Ruby // facts prefix `require_relative` specs with `./`; the kernel's reference names carry // neither, and Ruby also emits the `.rb` path form) @@ -3309,16 +3412,8 @@ impl<'e, 'v> FileCx<'e, 'v> { } } // 2. a name bound by the import - for &i in idxs { - let imp = &self.imports[i as usize]; - let local = view.text_str(imp.local); - let spec = view.text_str(imp.spec); - let imported = view.text_str(imp.imported); - let full_rs = format!("{spec}::{imported}"); - let full_dot = format!("{spec}.{imported}"); - if (!local.is_empty() && local == name) || full_rs == name || full_dot == name { - return self.bound_outcome(self.e.bind_import(self.file, i as usize)); - } + if let Some(o) = self.import_bound_name(name, idxs) { + return o; } // 3. Rust: the root crate / module segment of a `use` path if self.family == LangFamily::Rust { @@ -3342,6 +3437,42 @@ impl<'e, 'v> FileCx<'e, 'v> { Outcome::st(status::NO_CANDIDATE) } + fn import_bound_name(&self, name: &str, idxs: &[u32]) -> Option { + let view = self.view; + idxs.iter().find_map(|&i| { + let imp = &self.imports[i as usize]; + let local = view.text_str(imp.local); + let spec = view.text_str(imp.spec); + let imported = view.text_str(imp.imported); + let bound = (!local.is_empty() && local == name) || format!("{spec}::{imported}") == name || format!("{spec}.{imported}") == name; + bound.then(|| self.bound_outcome(self.e.bind_import(self.file, i as usize))) + }) + } + + /// A name on a continuation line of a multi-line import (`from m import (\n a,\n)`, + /// `import {\n a,\n} from "m"`, `use m::{\n a,\n}`): the facts carry the statement's first + /// line, the nearest import line above the reference. + fn continued_import_ref(&self, name: &str, r: &RefRec) -> Outcome { + let start = self.imports.iter().map(|i| i.line).filter(|&l| l < r.line).max(); + start.and_then(|l| self.import_bound_name(name, &self.imports_by_line[&l])).unwrap_or_else(|| Outcome::st(status::NO_CANDIDATE)) + } + + /// TypeScript `interface ZodUnknown` beside `const ZodUnknown`: `new ZodUnknown()` makes the + /// value; the type only describes it. + fn js_value_twin(&self, o: Outcome) -> Outcome { + let (view, target) = (self.view, NodeIdx(o.target)); + if self.family != LangFamily::Js || o.status != status::RESOLVED || !matches!(kind_of(view, target), NodeKind::Interface | NodeKind::TypeAlias) { + return o; + } + let ty = view.node(target); + let twin = view.by_name(ty.name()).find(|&n| { + view.hot(n).file == ty.file() + && view.node(n).parent() == ty.parent() + && matches!(kind_of(view, n), NodeKind::Variable | NodeKind::Constant | NodeKind::Function | NodeKind::Class) + }); + twin.map_or(o, |n| Outcome::found(n, o.by, o.conf)) + } + /// Resolve one reference. `name` is the reference's text. pub fn resolve_ref(&self, wcx: &mut WorkerCx<'e, 'v>, r: &RefRec) -> Outcome { let name = self.view.text_str(r.name); @@ -3382,7 +3513,7 @@ impl<'e, 'v> FileCx<'e, 'v> { if o.status == status::NO_CANDIDATE { self.resolve_type_ref(wcx, r, name, Accept::Callable) } else { - o + self.js_value_twin(o) } } RefKind::Edge(EdgeKind::References) => { diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index 7b8e31c..9bf2267 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -378,6 +378,172 @@ fn synthesised_edges_for_dynamic_dispatch() { assert!(has("g/g.go::Greeter::Greet -calls-> g/g.go::En::Greet"), "go interface-impl: {edges:#?}"); } +#[test] +fn names_on_continuation_lines_of_multi_line_imports() { + let (_d, view) = project(&[ + ("pkg/core.py", "class Engine:\n pass\n\ndef make():\n pass\n"), + ("app.py", "from pkg.core import (\n Engine,\n make,\n)\n"), + ("lib.ts", "export function a() {}\nexport class B {}\n"), + ("main.ts", "import {\n a,\n B,\n} from \"./lib\";\n"), + ("Cargo.toml", "[package]\nname = \"demo\"\n"), + ("src/lib.rs", "pub mod util;\npub mod server;\n"), + ("src/util.rs", "pub fn helper() {}\npub struct Thing;\n"), + ("src/server.rs", "use crate::util::{\n helper,\n Thing,\n};\n"), + ]); + let edges = edges_of(&view); + for e in [ + "app.py -imports-> pkg/core.py::Engine", + "app.py -imports-> pkg/core.py::make", + "main.ts -imports-> lib.ts::a", + "main.ts -imports-> lib.ts::B", + "src/server.rs -imports-> src/util.rs::helper", + "src/server.rs -imports-> src/util.rs::Thing", + ] { + assert!(has(&edges, e), "{e}"); + } +} + +#[test] +fn kotlin_call_takes_the_method_beside_a_same_named_property() { + let (_d, view) = project(&[( + "src/com/x/Client.kt", + "package com.x\nclass Factory\nclass Client {\n val socketFactory: Factory = Factory()\n fun socketFactory(): Factory = socketFactory\n var method: String = \"GET\"\n fun method(m: String, body: String?): Client = this\n fun put(body: String): Client = method(\"PUT\", body)\n}\nclass User {\n fun run(c: Client) {\n c.socketFactory()\n }\n}\n", + )]); + let mut calls = Vec::new(); + for f in view.files() { + for n in view.nodes_in_file(f) { + let n = cg_core::NodeIdx(n); + for e in view.out_edges(n).filter(|e| e.kind == cg_core::EdgeKind::Calls) { + calls.push(format!("{} -> {}", view.node(n).name(), dump::node_key(&view, e.dst))); + } + } + } + assert!(calls.iter().any(|c| c.starts_with("run -> ") && c.contains("#method@com.x::Client::socketFactory")), "{calls:#?}"); + assert!(calls.iter().any(|c| c.starts_with("put -> ") && c.contains("#method@com.x::Client::method")), "{calls:#?}"); + assert!(!calls.iter().any(|c| c.contains("#field@") || c.contains("#property@")), "{calls:#?}"); +} + +#[test] +fn kotlin_extension_function_is_a_member_of_its_receiver_and_subtypes() { + let (_d, view) = project(&[ + ("src/com/x/Lockable.kt", "package com.x\ninterface Lockable\ninline fun Lockable.awaitNanos(nanos: Long) {}\n"), + ( + "src/com/x/TaskRunner.kt", + "package com.x\nclass TaskRunner : Lockable {\n fun direct(l: Lockable) {\n l.awaitNanos(6L)\n }\n fun subtype(r: TaskRunner) {\n r.awaitNanos(5L)\n }\n}\n", + ), + ]); + let edges = edges_of(&view); + for from in ["direct", "subtype"] { + assert!( + has(&edges, &format!("src/com/x/TaskRunner.kt::com.x::TaskRunner::{from} -calls-> src/com/x/Lockable.kt::Lockable::awaitNanos")), + "{from}: {edges:#?}" + ); + } +} + +#[test] +fn rust_use_through_crate_self_or_super_imports_no_module_file() { + let (_d, view) = project(&[ + ("Cargo.toml", "[package]\nname = \"demo\"\n"), + ("src/lib.rs", "pub mod util;\npub mod net;\n"), + ("src/util.rs", "pub struct Thing;\n"), + ("src/net/mod.rs", "pub mod tcp;\npub struct Addr;\n"), + ("src/net/tcp.rs", "use crate::util::Thing;\nuse super::Addr;\nuse self::inner::Deep;\nmod inner {\n pub struct Deep;\n}\n"), + ("tests/it.rs", "use demo::util::Thing;\n"), + ]); + let edges = edges_of(&view); + assert!(has(&edges, "src/net/tcp.rs -imports-> src/util.rs::Thing"), "{edges:#?}"); + assert!(has(&edges, "src/net/tcp.rs -imports-> src/net/mod.rs::Addr"), "{edges:#?}"); + // the bare `crate` / `super` / `self` root names no file the module depends on + assert!(!edges.iter().any(|e| e.starts_with("src/net/tcp.rs -imports-> ") && !e.contains("::")), "{edges:#?}"); + // a path through the crate's name, from another crate of the package, still does + assert!(has(&edges, "tests/it.rs -imports-> src/lib.rs"), "{edges:#?}"); +} + +#[test] +fn rust_path_member_receiver_is_the_type_the_path_names() { + let (_d, view) = project(&[ + ("Cargo.toml", "[package]\nname = \"demo\"\n"), + ("src/lib.rs", "pub mod other;\npub mod user;\npub enum Kind {\n A,\n}\n"), + ( + "src/user.rs", + "use crate::Kind;\npub fn local() {\n let _k = Kind::A;\n}\npub fn dependency() {\n let _k = mio::Kind::A;\n}\npub fn module() {\n let _k = crate::other::Kind::A;\n}\n", + ), + ("src/other.rs", "pub enum Kind {\n A,\n}\n"), + ]); + let edges = edges_of(&view); + assert!(has(&edges, "src/user.rs::local -references-> src/lib.rs::Kind"), "{edges:#?}"); + assert!(!edges.iter().any(|e| e.starts_with("src/user.rs::dependency -references-> ")), "{edges:#?}"); + assert!(has(&edges, "src/user.rs::module -references-> src/other.rs::Kind"), "{edges:#?}"); +} + +#[test] +fn typescript_new_makes_the_value_beside_a_same_named_interface() { + let (_d, view) = project(&[ + ( + "src/schemas.ts", + "function ctor(name: string): any {\n return null;\n}\nexport interface ZodUnknown {\n kind: string;\n}\nexport const ZodUnknown: any = ctor(\"ZodUnknown\");\nexport function local(): ZodUnknown {\n return new ZodUnknown();\n}\n", + ), + ("src/use.ts", "import { ZodUnknown } from \"./schemas\";\nexport function make(): ZodUnknown {\n return new ZodUnknown();\n}\n"), + ]); + // the interface and the const share a label: tell them apart by kind + let mut made = Vec::new(); + for f in view.files() { + for n in view.nodes_in_file(f) { + let n = cg_core::NodeIdx(n); + for e in view.out_edges(n).filter(|e| e.kind == cg_core::EdgeKind::Instantiates) { + made.push(format!("{} -> {}", view.node(n).name(), dump::node_key(&view, e.dst))); + } + } + } + for from in ["local", "make"] { + assert!(made.iter().any(|m| m.starts_with(&format!("{from} -> ")) && m.contains("@ZodUnknown:")), "{made:#?}"); + } + assert!(!made.iter().any(|m| m.contains("#interface@")), "{made:#?}"); +} + +#[test] +fn rust_tuple_destructuring_types_each_element() { + let (_d, view) = project(&[ + ("Cargo.toml", "[package]\nname = \"demo\"\n"), + ("src/lib.rs", "pub mod chan;\npub mod user;\n"), + ( + "src/chan.rs", + "pub struct Sender;\nimpl Sender {\n pub fn send(&self) {}\n}\npub struct Receiver;\nimpl Receiver {\n pub fn recv(&self) {}\n}\npub struct Other;\nimpl Other {\n pub fn send(&self) {}\n pub fn recv(&self) {}\n}\npub fn channel() -> (Sender, Receiver) {\n (Sender, Receiver)\n}\npub fn try_channel() -> Result<(Sender, Receiver), ()> {\n Ok((Sender, Receiver))\n}\n", + ), + ( + "src/user.rs", + "use crate::chan;\npub fn plain() {\n let (tx, rx) = chan::channel();\n tx.send();\n rx.recv();\n}\npub fn tried() -> Result<(), ()> {\n let (_, mut rx) = chan::try_channel()?;\n rx.recv();\n Ok(())\n}\n", + ), + ]); + let edges = edges_of(&view); + for e in [ + "src/user.rs::plain -calls-> src/chan.rs::Sender::send", + "src/user.rs::plain -calls-> src/chan.rs::Receiver::recv", + "src/user.rs::tried -calls-> src/chan.rs::Receiver::recv", + ] { + assert!(has(&edges, e), "{e}: {edges:#?}"); + } + assert!(!edges.iter().any(|e| e.contains("-calls-> src/chan.rs::Other::")), "{edges:#?}"); +} + +#[test] +fn rust_type_parameters_name_no_same_named_struct() { + let (_d, view) = project(&[ + ("Cargo.toml", "[package]\nname = \"demo\"\n"), + ("src/lib.rs", "pub mod cell;\nmod spot;\n"), + ( + "src/cell.rs", + "pub struct Real;\npub struct Cell {\n value: T,\n}\nimpl Cell {\n pub fn new(value: T) -> Option> {\n None\n }\n pub fn map(self, f: U, r: Real) -> U {\n f\n }\n}\npub fn free(t: T) {}\n", + ), + // Tokio's only `T` is local to a test fn in another file (`bucket_computation_spot_check::T`) + ("src/spot.rs", "#[cfg(test)]\nmod tests {\n #[test]\n fn spot_check() {\n struct T;\n struct U;\n }\n}\n"), + ]); + let edges = edges_of(&view); + assert!(has(&edges, "src/cell.rs::Cell::map -references-> src/cell.rs::Real"), "{edges:#?}"); + assert!(!edges.iter().any(|e| e.contains("-references->") && (e.ends_with("::T") || e.ends_with("::U"))), "{edges:#?}"); +} + fn edges_of(view: &View) -> Vec { let mut edges = dump::dump_edges(view); edges.dedup(); diff --git a/crates/cg-store/src/build.rs b/crates/cg-store/src/build.rs index 89ae9b5..d0d639b 100644 --- a/crates/cg-store/src/build.rs +++ b/crates/cg-store/src/build.rs @@ -465,7 +465,9 @@ pub fn build_draft_at(batches: &[FileBatch], delta: Option<(&[FileId], BuildBase let from_row = r.from_row().filter(|x| *x < kcount as u32).or_else(|| row_by_id(&mut id_to_row, &rows, r.from_id()?)); let from = nstart + from_row.unwrap_or(0); let is_call = r.kind() == RefKind::Edge(EdgeKind::Calls); - let name = if is_call { call_names.get(&(r.line(), r.col(), r.name())).copied().flatten().unwrap_or_else(|| r.name()) } else { r.name() }; + // Rust `mio::Interest::AIO` references `Interest` as the path writes it + let renamed = is_call || (b.lang == cg_core::Lang::Rust && r.kind() == RefKind::Edge(EdgeKind::References)); + let name = if renamed { call_names.get(&(r.line(), r.col(), r.name())).copied().flatten().unwrap_or_else(|| r.name()) } else { r.name() }; let args = if is_call && r.candidates().is_none() { call_args.get(&(r.line(), r.col(), tail_of(name))).copied().flatten().map(|call| { let mut joined = String::from(cg_extract::facts::args::ARGS_MARK); From dc97f828881269dea7d0ac3dfdb887e04cfaf914 Mon Sep 17 00:00:00 2001 From: columbia11 Date: Tue, 3 Nov 2026 08:47:37 +0800 Subject: [PATCH 2/8] resolve: JS re-export lists and require(m).member bind their names - `export { a as b } from "m"` records one import per specifier, without a local binding, so each re-exported name links to its definition (the barrel files of TypeScript projects such as Zod). - `var x = require("m").y` binds `x` to module m's export `y`, like `const { y } = require("m")`, and links the file to m. - Incremental parity fixture covers both, with edits on the defining and the consuming side. --- crates/cg-extract/src/facts/js.rs | 31 ++++++++++++++++++++++ crates/cg-resolve/src/resolve.rs | 4 ++- crates/cg-resolve/tests/resolve_e2e.rs | 29 ++++++++++++++++++++ crates/cg-sync/tests/incremental_parity.rs | 10 +++++++ 4 files changed, 73 insertions(+), 1 deletion(-) diff --git a/crates/cg-extract/src/facts/js.rs b/crates/cg-extract/src/facts/js.rs index e4b7327..a27da04 100644 --- a/crates/cg-extract/src/facts/js.rs +++ b/crates/cg-extract/src/facts/js.rs @@ -378,6 +378,7 @@ fn export_stmt(cx: &mut Cx, n: Node) { }); } let is_default = kids(n).any(|c| c.kind() == "default"); + let stmt_type_only = kids(n).any(|c| c.kind() == "type"); let mut had_clause = false; for ch in kids(n) { match ch.kind() { @@ -389,6 +390,20 @@ fn export_stmt(cx: &mut Cx, n: Node) { } let name = sp.child_by_field_name("name").map(|c| unquote(cx.text(c)).to_owned()).unwrap_or_default(); let alias = sp.child_by_field_name("alias").map(|c| unquote(cx.text(c)).to_owned()); + if let Some(spec) = &source { + // `export { a as b } from 'x'` imports `a` without binding it here (no local) + let line = cx.line(n); + let type_only = stmt_type_only || kids(sp).any(|c| c.kind() == "type"); + cx.add_import(ImportFact { + local: String::new(), + imported: name.clone(), + spec: spec.clone(), + kind: ImportKind::Named, + type_only, + scope: 0, + line, + }); + } cx.facts.exports.push(ExportFact { name: alias.unwrap_or_else(|| name.clone()), node_row: NONE, @@ -828,6 +843,16 @@ fn require_target(cx: &Cx, v: Node) -> Option { Some(unquote(cx.text(first)).to_owned()) } +/// `require('./utils').compileETag`: the module and the member it reads. +fn require_member(cx: &Cx, v: Node) -> Option<(String, String)> { + if v.kind() != "member_expression" { + return None; + } + let spec = require_target(cx, v.child_by_field_name("object")?)?; + let prop = v.child_by_field_name("property").filter(|p| p.kind() == "property_identifier")?; + Some((spec, cx.text(prop).to_owned())) +} + fn var_decl(cx: &mut Cx, n: Node, scope: u32) { for d in kids(n) { if d.kind() != "variable_declarator" { @@ -877,6 +902,12 @@ fn var_decl(cx: &mut Cx, n: Node, scope: u32) { } continue; } + // `var compileETag = require('./utils').compileETag`, like `const { compileETag } = require('./utils')` + if let Some((spec, imported)) = require_member(cx, v).filter(|_| name.kind() == "identifier") { + let local = cx.text(name).to_owned(); + cx.add_import(ImportFact { local, imported, spec, kind: ImportKind::Require, type_only: false, scope, line: cx.line(d) }); + continue; + } let is_fn = matches!(v.kind(), "arrow_function" | "function_expression" | "function" | "generator_function"); let constant = kids(n).next().is_some_and(|k| k.kind() == "const"); if is_fn && name.kind() == "identifier" { diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 49a9975..19765ef 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -3444,7 +3444,9 @@ impl<'e, 'v> FileCx<'e, 'v> { let local = view.text_str(imp.local); let spec = view.text_str(imp.spec); let imported = view.text_str(imp.imported); - let bound = (!local.is_empty() && local == name) || format!("{spec}::{imported}") == name || format!("{spec}.{imported}") == name; + // a JS re-export (`export { a as b } from 'm'`) binds no local: the reference names `a` + let reexport = local.is_empty() && self.family == LangFamily::Js && imported == name; + let bound = (!local.is_empty() && local == name) || reexport || format!("{spec}::{imported}") == name || format!("{spec}.{imported}") == name; bound.then(|| self.bound_outcome(self.e.bind_import(self.file, i as usize))) }) } diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index 9bf2267..b44710a 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -544,6 +544,35 @@ fn rust_type_parameters_name_no_same_named_struct() { assert!(!edges.iter().any(|e| e.contains("-references->") && (e.ends_with("::T") || e.ends_with("::U"))), "{edges:#?}"); } +#[test] +fn typescript_reexport_lists_import_each_name() { + let (_d, view) = project(&[ + ("core.ts", "export function _lt() {}\nexport function _gte() {}\nexport function _gt() {}\n"), + ("checks.ts", "export {\n _lt as lt,\n _gte as gte,\n _gte as minimum,\n} from \"./core\";\nexport { _gt } from \"./core\";\n"), + ]); + let edges = edges_of(&view); + for e in ["checks.ts -imports-> core.ts", "checks.ts -imports-> core.ts::_lt", "checks.ts -imports-> core.ts::_gte", "checks.ts -imports-> core.ts::_gt"] { + assert!(has(&edges, e), "{e}: {edges:#?}"); + } +} + +#[test] +fn commonjs_require_member_binds_the_export() { + let (_d, view) = project(&[ + ("lib/utils.js", "exports.compileETag = function(val) {\n return val;\n};\nexports.methods = ['get'];\n"), + ("lib/trust.js", "exports.compileTrust = function(val) {\n return val;\n};\n"), + ( + "lib/application.js", + "var compileETag = require('./utils').compileETag;\nvar { compileTrust } = require('./trust');\nfunction setup(val) {\n compileETag(val);\n compileTrust(val);\n}\nmodule.exports = setup;\n", + ), + ]); + let edges = edges_of(&view); + // the destructured form already binds the export; the member form must do the same + assert!(has(&edges, "lib/application.js::setup -calls-> lib/trust.js::compileTrust"), "{edges:#?}"); + assert!(has(&edges, "lib/application.js -imports-> lib/utils.js"), "{edges:#?}"); + assert!(has(&edges, "lib/application.js::setup -calls-> lib/utils.js::compileETag"), "{edges:#?}"); +} + fn edges_of(view: &View) -> Vec { let mut edges = dump::dump_edges(view); edges.dedup(); diff --git a/crates/cg-sync/tests/incremental_parity.rs b/crates/cg-sync/tests/incremental_parity.rs index d979bca..58ee59e 100644 --- a/crates/cg-sync/tests/incremental_parity.rs +++ b/crates/cg-sync/tests/incremental_parity.rs @@ -54,6 +54,10 @@ const FILES: &[(&str, &str)] = &[ ), ("py/tasks.py", "from celery import shared_task\n\n@shared_task\ndef send(to):\n pass\n"), ("py/views.py", "from .tasks import send\n\ndef signup():\n send.delay('a')\n"), + ("cjs/utils.js", "exports.compileETag = function(val) {\n return val;\n};\nexports.compileTrust = function(val) {\n return val;\n};\n"), + ("cjs/app.js", "var compileETag = require('./utils').compileETag;\nfunction setup(v) {\n compileETag(v);\n}\nmodule.exports = setup;\n"), + ("barrel/core.ts", "export function _lt() {}\nexport function _gte() {}\n"), + ("barrel/checks.ts", "export {\n _lt as lt,\n _gte as gte,\n} from './core';\n"), ]; /// One-sided edits of the links above: (file, from, to). @@ -80,6 +84,12 @@ const EDITS: &[(&str, &str, &str)] = &[ ("go/x/x.go", "func (p Prefix) Match(path string)", "func (p Prefix) Match(path []byte)"), ("py/tasks.py", "@shared_task\n", ""), ("app/about/page.tsx", "About", "AboutPage"), + ("cjs/utils.js", "exports.compileETag =", "exports.compileETagX ="), + ("cjs/utils.js", "exports.compileETagX =", "exports.compileETag ="), + ("cjs/app.js", ").compileETag;", ").compileTrust;"), + ("barrel/core.ts", "export function _lt()", "export function _ltX()"), + ("barrel/core.ts", "export function _ltX()", "export function _lt()"), + ("barrel/checks.ts", "_gte as gte,\n", ""), ]; struct Rng(u64); From 8492b908c84dcd5211078d47656dc8e7caee794b Mon Sep 17 00:00:00 2001 From: columbia11 Date: Tue, 3 Nov 2026 09:00:25 +0800 Subject: [PATCH 3/8] resolve: a JS call of a declared variable links that variable `const $ = django.jQuery; $(el)`, `Router = express.Router; new Router()` and `const compiledFn = compile(s); compiledFn(x)` call what the declaration's node holds. A call or `new` whose name is a var/let/const binding (not a parameter) now links to that declaration's variable or constant node; receivers of member calls are unchanged. --- crates/cg-resolve/src/resolve.rs | 18 ++++++++++++++++++ crates/cg-resolve/tests/resolve_e2e.rs | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 19765ef..466d11b 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -3475,11 +3475,29 @@ impl<'e, 'v> FileCx<'e, 'v> { twin.map_or(o, |n| Outcome::found(n, o.by, o.conf)) } + /// JS `const $ = django.jQuery; $(el)`, `Router = express.Router; new Router()`: a call of a + /// name a `var` / `let` / `const` declares runs what that declaration's node holds. + fn js_declared_value(&self, r: &RefRec, name: &str) -> Option { + if self.family != LangFamily::Js || !name.chars().all(|c| c == '$' || c == '_' || c.is_alphanumeric()) { + return None; + } + let b = self.lookup_binding(name, self.scope_at(r.line, r.col), r.line, false).filter(|b| b.kind == BindKind::Local as u8)?; + let view = self.view; + view.by_name(name).find(|&n| { + view.hot(n).file == self.file && view.node(n).start_line() == b.line && matches!(kind_of(view, n), NodeKind::Variable | NodeKind::Constant) + }) + } + /// Resolve one reference. `name` is the reference's text. pub fn resolve_ref(&self, wcx: &mut WorkerCx<'e, 'v>, r: &RefRec) -> Outcome { let name = self.view.text_str(r.name); let Some(kind) = RefKind::from_wire(r.kind) else { return Outcome::st(status::NO_CANDIDATE) }; let o = self.resolve_kind(wcx, r, name, kind); + if o.status == status::LOCAL_BINDING && matches!(kind, RefKind::Edge(EdgeKind::Calls | EdgeKind::Instantiates)) { + if let Some(n) = self.js_declared_value(r, name) { + return Outcome::found(n, by::LEXICAL, 90); + } + } // an extension no project declaration answers extends a dependency's type if o.status == status::RESOLVED && self.is_swift_extension(NodeIdx(o.target)) { return Outcome::st(status::EXTERNAL); diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index b44710a..a49446b 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -573,6 +573,25 @@ fn commonjs_require_member_binds_the_export() { assert!(has(&edges, "lib/application.js::setup -calls-> lib/utils.js::compileETag"), "{edges:#?}"); } +#[test] +fn javascript_calls_through_declared_variables_link_the_variable() { + let (_d, view) = project(&[ + ("admin.js", "\"use strict\";\n{\n const $ = django.jQuery;\n function init() {\n $(document);\n }\n}\n"), + ("express.js", "exports.Router = function Router() {};\n"), + ("router.js", "var express = require('./express')\n , Router = express.Router;\nfunction make() {\n return new Router();\n}\n"), + ( + "bench.ts", + "function compileFn(x: number) {\n return (v: number) => v === x;\n}\nconst compiledFn = compileFn(1);\nexport function run() {\n return compiledFn(2);\n}\nexport function apply(compiledFn: (v: number) => boolean) {\n return compiledFn(3);\n}\nexport function local() {\n const g = compileFn(4);\n return g(5);\n}\n", + ), + ]); + let edges = edges_of(&view); + for e in ["admin.js::init -calls-> admin.js::$", "router.js::make -instantiates-> router.js::Router", "bench.ts::run -calls-> bench.ts::compiledFn"] { + assert!(has(&edges, e), "{e}: {edges:#?}"); + } + // a parameter shadows the module's constant; a function-local variable has no node + assert!(!edges.iter().any(|e| e.starts_with("bench.ts::apply -calls-> ") || e.starts_with("bench.ts::local -calls-> bench.ts::g")), "{edges:#?}"); +} + fn edges_of(view: &View) -> Vec { let mut edges = dump::dump_edges(view); edges.dedup(); From 9ead71e811136d881a747ebdb5b4050a32cab8e5 Mon Sep 17 00:00:00 2001 From: columbia11 Date: Tue, 3 Nov 2026 09:18:52 +0800 Subject: [PATCH 4/8] resolve: TS `new` of a parameter and namespace-qualified type names - `new Class(..)` where `Class` is a parameter or a local resolves through the binding, never to a same-named class elsewhere (Zod's `_nonoptional(Class: ..)` linked util's abstract `Class`). - `core.output` keeps its namespace: the kernel names a `nested_type_identifier` by its last segment, so a call-name fact gives the written path and qualified lookup walks the namespace import and its star exports, instead of a same-named `output` beside the reference. A path no walk enters (members of a TS `namespace`, which the kernel flattens into the file) falls back to the last segment. --- crates/cg-extract/src/facts/js.rs | 14 +++++++++ crates/cg-resolve/src/resolve.rs | 18 ++++++++++- crates/cg-resolve/tests/resolve_e2e.rs | 41 ++++++++++++++++++++++++++ crates/cg-store/src/build.rs | 6 ++-- 4 files changed, 76 insertions(+), 3 deletions(-) diff --git a/crates/cg-extract/src/facts/js.rs b/crates/cg-extract/src/facts/js.rs index a27da04..24a5b76 100644 --- a/crates/cg-extract/src/facts/js.rs +++ b/crates/cg-extract/src/facts/js.rs @@ -112,6 +112,10 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) { } walk_children(cx, n, scope); } + "nested_type_identifier" => { + namespace_type(cx, n); + walk_children(cx, n, scope); + } _ => walk_children(cx, n, scope), } } @@ -843,6 +847,16 @@ fn require_target(cx: &Cx, v: Node) -> Option { Some(unquote(cx.text(first)).to_owned()) } +/// `core.output`: the kernel names the type by its last segment (`output`); the path as +/// written keeps the namespace's type apart from a same-named one beside the reference. +fn namespace_type(cx: &mut Cx, n: Node) { + let Some(name) = n.child_by_field_name("name") else { return }; + let pos = cx.start(name); + let tail = cx.text(name).to_owned(); + let path: String = cx.text(n).chars().filter(|c| !c.is_whitespace()).collect(); + cx.facts.call_names.push(CallNameFact { line: (pos >> 32) as u32, col: pos as u32, kernel_name: tail.clone(), tail, name: path }); +} + /// `require('./utils').compileETag`: the module and the member it reads. fn require_member(cx: &Cx, v: Node) -> Option<(String, String)> { if v.kind() != "member_expression" { diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 466d11b..17a547e 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -3528,6 +3528,16 @@ impl<'e, 'v> FileCx<'e, 'v> { } RefKind::Edge(EdgeKind::Extends | EdgeKind::Implements | EdgeKind::TypeOf | EdgeKind::Returns) => self.resolve_type_ref(wcx, r, name, Accept::Type), RefKind::Edge(EdgeKind::Instantiates) if self.swift_extended_builtin(name, r) => Outcome::st(status::BUILTIN), + // JS `new Class(..)` where `Class` is a parameter or a local: the value it holds, never a + // same-named class elsewhere (type lookup does not see lexical bindings) + RefKind::Edge(EdgeKind::Instantiates) + if self.family == LangFamily::Js + && self + .lookup_binding(name, self.scope_at(r.line, r.col), r.line, false) + .is_some_and(|b| b.kind == BindKind::Param as u8 || b.kind == BindKind::Local as u8) => + { + self.resolve_type_ref(wcx, r, name, Accept::Callable) + } RefKind::Edge(EdgeKind::Instantiates) => { let o = self.resolve_type_ref(wcx, r, name, Accept::Type); if o.status == status::NO_CANDIDATE { @@ -3538,7 +3548,7 @@ impl<'e, 'v> FileCx<'e, 'v> { } RefKind::Edge(EdgeKind::References) => { let o = self.resolve_type_ref(wcx, r, name, Accept::Type); - if matches!(o.status, status::NO_CANDIDATE) { + let o = if matches!(o.status, status::NO_CANDIDATE) { let any = self.resolve_type_ref(wcx, r, name, Accept::Any); if self.stray_csharp_member(any, r) { o @@ -3547,6 +3557,12 @@ impl<'e, 'v> FileCx<'e, 'v> { } } else { o + }; + // `errorUtil.ErrMessage`: the kernel flattens a TS `namespace`'s members into its file, + // where no path walk enters; the last segment, as the kernel names it + match name.rsplit_once('.') { + Some((_, tail)) if o.status == status::NO_CANDIDATE && self.family == LangFamily::Js => self.resolve_kind(wcx, r, tail, kind), + _ => o, } } RefKind::FunctionRef => self.resolve_call_name(wcx, r, name), diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index a49446b..de7a09a 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -592,6 +592,47 @@ fn javascript_calls_through_declared_variables_link_the_variable() { assert!(!edges.iter().any(|e| e.starts_with("bench.ts::apply -calls-> ") || e.starts_with("bench.ts::local -calls-> bench.ts::g")), "{edges:#?}"); } +#[test] +fn typescript_new_of_a_parameter_names_no_same_named_class() { + let (_d, view) = project(&[ + ("util.ts", "export abstract class Class {}\nexport class Widget {}\n"), + ( + "api.ts", + "import { Widget } from \"./util\";\nexport function make(Class: new (d: object) => object) {\n return new Class({});\n}\nexport function build() {\n return new Widget();\n}\n", + ), + ]); + let edges = edges_of(&view); + assert!(has(&edges, "api.ts::build -instantiates-> util.ts::Widget"), "{edges:#?}"); + // Zod's `_nonoptional(Class: util.SchemaClass<..>)`: the parameter holds the class + assert!(!edges.iter().any(|e| e.starts_with("api.ts::make -instantiates-> ")), "{edges:#?}"); +} + +#[test] +fn typescript_namespace_type_goes_through_the_star_exports() { + let (_d, view) = project(&[ + ("core/core.ts", "export type output = T;\nexport interface $ZodType {\n kind: string;\n}\n"), + ("core/index.ts", "export * from \"./core.js\";\n"), + ("helpers/errorUtil.ts", "export namespace errorUtil {\n export type ErrMessage = string | { message?: string };\n}\n"), + ("helpers/use.ts", "import { errorUtil } from \"./errorUtil.js\";\nexport function min(message?: errorUtil.ErrMessage): void {}\n"), + ("classic/in-out.ts", "import type * as core from \"../core/index.js\";\nexport type output = core.output;\n"), + ( + "classic/schemas.ts", + "import * as core from \"../core/index.js\";\nexport function parse(x: unknown): core.output {\n return x as core.output;\n}\nexport function kind(t: core.$ZodType): string {\n return t.kind;\n}\n", + ), + ]); + let edges = edges_of(&view); + // Zod's `core.output` beside classic's own `output` alias + for e in [ + "classic/schemas.ts::parse -references-> core/core.ts::output", + "classic/in-out.ts::output -references-> core/core.ts::output", + // a TS `namespace`'s members are flattened into its file: the path falls back to the last segment + "helpers/use.ts::min -references-> helpers/errorUtil.ts::ErrMessage", + ] { + assert!(has(&edges, e), "{e}: {edges:#?}"); + } + assert!(!edges.iter().any(|e| e.ends_with("-references-> classic/in-out.ts::output")), "{edges:#?}"); +} + fn edges_of(view: &View) -> Vec { let mut edges = dump::dump_edges(view); edges.dedup(); diff --git a/crates/cg-store/src/build.rs b/crates/cg-store/src/build.rs index d0d639b..006b29a 100644 --- a/crates/cg-store/src/build.rs +++ b/crates/cg-store/src/build.rs @@ -465,8 +465,10 @@ pub fn build_draft_at(batches: &[FileBatch], delta: Option<(&[FileId], BuildBase let from_row = r.from_row().filter(|x| *x < kcount as u32).or_else(|| row_by_id(&mut id_to_row, &rows, r.from_id()?)); let from = nstart + from_row.unwrap_or(0); let is_call = r.kind() == RefKind::Edge(EdgeKind::Calls); - // Rust `mio::Interest::AIO` references `Interest` as the path writes it - let renamed = is_call || (b.lang == cg_core::Lang::Rust && r.kind() == RefKind::Edge(EdgeKind::References)); + // Rust `mio::Interest::AIO` and TypeScript `core.output` reference the type as the + // path writes it + let renamed = + is_call || (matches!(b.lang.family(), cg_core::LangFamily::Rust | cg_core::LangFamily::Js) && r.kind() == RefKind::Edge(EdgeKind::References)); let name = if renamed { call_names.get(&(r.line(), r.col(), r.name())).copied().flatten().unwrap_or_else(|| r.name()) } else { r.name() }; let args = if is_call && r.candidates().is_none() { call_args.get(&(r.line(), r.col(), tail_of(name))).copied().flatten().map(|call| { From adb8c7ef6eed5d253397aea00bd2f2d1f1ce2bea Mon Sep 17 00:00:00 2001 From: columbia11 Date: Tue, 3 Nov 2026 09:39:59 +0800 Subject: [PATCH 5/8] resolve: TS variable and field annotations, and enum members in type positions A const's or class field's type annotation was never walked, so `const decode: (.., _ctx?: core.ParseContext<..>) => ..` kept the bare kernel name and fell to a same-named type elsewhere (v3's ParseContext, a test file's `declare module` augmentation of ZodType). Walk it like a parameter's. `typeName: ZodFirstPartyTypeKind.ZodLiteral` names the enum's member, not `class ZodLiteral`. --- crates/cg-extract/src/facts/js.rs | 9 +++++++-- crates/cg-resolve/src/resolve.rs | 8 +++++++- crates/cg-resolve/tests/resolve_e2e.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/cg-extract/src/facts/js.rs b/crates/cg-extract/src/facts/js.rs index 24a5b76..c75a8c1 100644 --- a/crates/cg-extract/src/facts/js.rs +++ b/crates/cg-extract/src/facts/js.rs @@ -802,8 +802,10 @@ fn class(cx: &mut Cx, n: Node, scope: u32) { let line = cx.line(m); cx.add_binding(sc, &nm, BindKind::Field, if ty.is_empty() { &vt } else { &ty }, &init, line); } - if let Some(v) = m.child_by_field_name("value") { - walk(cx, v, sc); + for c in ["type", "value"] { + if let Some(v) = m.child_by_field_name(c) { + walk(cx, v, sc); + } } } "method_definition" => { @@ -874,6 +876,9 @@ fn var_decl(cx: &mut Cx, n: Node, scope: u32) { } let Some(name) = d.child_by_field_name("name") else { continue }; let ty = d.child_by_field_name("type").map(|t| ts_type_name(cx, t)).unwrap_or_default(); + if let Some(t) = d.child_by_field_name("type") { + walk(cx, t, scope); // `core.ParseContext` inside the annotation + } let value = d.child_by_field_name("value"); if let Some(v) = value { // `var app = exports = module.exports = {}` ties subsequent diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 17a547e..804d929 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -3561,7 +3561,13 @@ impl<'e, 'v> FileCx<'e, 'v> { // `errorUtil.ErrMessage`: the kernel flattens a TS `namespace`'s members into its file, // where no path walk enters; the last segment, as the kernel names it match name.rsplit_once('.') { - Some((_, tail)) if o.status == status::NO_CANDIDATE && self.family == LangFamily::Js => self.resolve_kind(wcx, r, tail, kind), + Some((path, tail)) if o.status == status::NO_CANDIDATE && self.family == LangFamily::Js => match self.lookup_type(wcx, path) { + // `typeName: ZodFirstPartyTypeKind.ZodLiteral` names the enum's member, not `class ZodLiteral` + TypeRes::Node(e) if kind_of(self.view, e) == NodeKind::Enum => { + self.e.direct_member(e, tail).map_or(o, |m| Outcome::found(m, by::QUALIFIED, 90)) + } + _ => self.resolve_kind(wcx, r, tail, kind), + }, _ => o, } } diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index de7a09a..50a4b23 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -633,6 +633,32 @@ fn typescript_namespace_type_goes_through_the_star_exports() { assert!(!edges.iter().any(|e| e.ends_with("-references-> classic/in-out.ts::output")), "{edges:#?}"); } +#[test] +fn typescript_variable_and_field_annotations_and_enum_members_name_their_types() { + let (_d, view) = project(&[ + ("core/core.ts", "export type output = T;\n"), + ("core/index.ts", "export * from \"./core.js\";\n"), + ("classic/in-out.ts", "import type * as core from \"../core/index.js\";\nexport type output = core.output;\n"), + ( + "classic/parse.ts", + "import * as core from \"../core/index.js\";\nconst make = (): any => null;\nexport const parse: (x: unknown) => core.output = make();\nexport class Box {\n value?: core.output;\n}\n", + ), + ( + "v3/types.ts", + "export enum Kind {\n ZodLiteral = \"ZodLiteral\",\n}\nexport class ZodLiteral {}\nexport interface ZodLiteralDef {\n typeName: Kind.ZodLiteral;\n}\n", + ), + ]); + let edges = edges_of(&view); + // Zod's `export const decode: (.., _ctx?: core.ParseContext<..>) => ..` + assert!(has(&edges, "classic/parse.ts::parse -references-> core/core.ts::output"), "{edges:#?}"); + let field = edges.iter().any(|e| e.starts_with("classic/parse.ts::Box") && e.ends_with("-references-> core/core.ts::output")); + assert!(field, "{edges:#?}"); + assert!(!edges.iter().any(|e| e.ends_with("-references-> classic/in-out.ts::output")), "{edges:#?}"); + // v3's `typeName: ZodFirstPartyTypeKind.ZodLiteral` beside `class ZodLiteral` + assert!(has(&edges, "v3/types.ts::ZodLiteralDef::typeName -references-> v3/types.ts::Kind::ZodLiteral"), "{edges:#?}"); + assert!(!edges.iter().any(|e| e.ends_with("-references-> v3/types.ts::ZodLiteral")), "{edges:#?}"); +} + fn edges_of(view: &View) -> Vec { let mut edges = dump::dump_edges(view); edges.dedup(); From 1d8913fa23647ce44e0b751359829710ffc0f9dd Mon Sep 17 00:00:00 2001 From: columbia11 Date: Tue, 3 Nov 2026 11:07:39 +0800 Subject: [PATCH 6/8] resolve: JS/TS imports, window globals, type parameters, JSX render lines - An import of a name declared in its file as both a type and a value (`interface X` and `const X`) links the first declaration; `new X()` and calls still take the value. Sync re-resolves importers when the order of same-named declarations changes. - `import x from "./m"` links the module file for the bound name too; calls of `x` still reach the default export. - `X.m()` with no binding or import for `X` reaches the member of a `window.X = { m: .. }` global declared in another script. - TS class and function type parameters are bound, so `T` / `Output` inside name no same-named declaration elsewhere. - JSX render edges sit on the rendering component's first line, like the other synthesised edges. --- crates/cg-extract/src/facts/js.rs | 11 +++ crates/cg-resolve/src/resolve.rs | 38 ++++++++- crates/cg-resolve/src/synth/mod.rs | 4 +- crates/cg-resolve/tests/resolve_e2e.rs | 94 ++++++++++++++++++++++ crates/cg-sync/src/sync.rs | 25 +++++- crates/cg-sync/tests/incremental_parity.rs | 25 ++++++ 6 files changed, 194 insertions(+), 3 deletions(-) diff --git a/crates/cg-extract/src/facts/js.rs b/crates/cg-extract/src/facts/js.rs index c75a8c1..a4b4ec7 100644 --- a/crates/cg-extract/src/facts/js.rs +++ b/crates/cg-extract/src/facts/js.rs @@ -658,6 +658,7 @@ fn function(cx: &mut Cx, n: Node, scope: u32) { } } let sc = cx.push_scope(ScopeKind::Function, scope, n); + type_params(cx, n, sc); return_annotation(cx, n, sc); let line = cx.line(n); if let Some(p) = n.child_by_field_name("parameter") { @@ -692,6 +693,15 @@ fn function(cx: &mut Cx, n: Node, scope: u32) { } } +/// `class Schema`, `function f()`: `Output` and `T` inside name no declaration. +fn type_params(cx: &mut Cx, n: Node, sc: u32) { + let Some(params) = n.child_by_field_name("type_parameters") else { return }; + for name in kids(params).filter_map(|p| p.child_by_field_name("name")) { + let name = cx.text(name).to_owned(); + cx.add_binding(sc, &name, BindKind::TypeParam, "", "", 0); + } +} + /// Record the narrow `merge-descriptors` factory pattern used by Express: a local /// function/object is mixed with an imported module and then returned. We do not /// infer anything from an arbitrary function called `mixin` or from nested calls. @@ -787,6 +797,7 @@ fn factory_mixin(cx: &mut Cx, n: Node, scope: u32) { fn class(cx: &mut Cx, n: Node, scope: u32) { let sc = cx.push_scope(ScopeKind::Class, scope, n); + type_params(cx, n, sc); let Some(body) = n.child_by_field_name("body") else { walk_children(cx, n, scope); return; diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 804d929..1f0b289 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -2586,6 +2586,15 @@ impl<'e, 'v> FileCx<'e, 'v> { if is_builtin(self.family, root) { return Outcome::st(status::BUILTIN); } + // JS `window.SelectFilter = { init: .. }` in one script, `SelectFilter.init()` in another + if self.family == LangFamily::Js && path.is_empty() { + let mut globals = view.by_qname(&format!("window.{root}")); + if let (Some(g), None) = (globals.next(), globals.next()) { + if let Some(m) = self.e.direct_member(g, method) { + return Outcome::found(m, by::GLOBAL, 80); + } + } + } if matches!(self.family, LangFamily::C | LangFamily::CSharp | LangFamily::Php | LangFamily::Ruby) { if let Some(n) = self.qualified_callable(r.from, root, path, method, false) { return Outcome::found(self.cpp_function_overload(n, args), by::QUALIFIED, 90); @@ -3447,10 +3456,37 @@ impl<'e, 'v> FileCx<'e, 'v> { // a JS re-export (`export { a as b } from 'm'`) binds no local: the reference names `a` let reexport = local.is_empty() && self.family == LangFamily::Js && imported == name; let bound = (!local.is_empty() && local == name) || reexport || format!("{spec}::{imported}") == name || format!("{spec}.{imported}") == name; - bound.then(|| self.bound_outcome(self.e.bind_import(self.file, i as usize))) + if !bound { + return None; + } + // JS `import x from "./m"` names the module, as upstream does; calls of `x` still + // reach its default export + if self.family == LangFamily::Js && imp.kind == ImportKind::Default as u8 && imported == "default" { + if let Some(ImportTarget::File(tf)) = self.e.imp_targets[self.file.idx()].get(i as usize) { + return Some(Outcome::found(self.file_node(*tf), by::IMPORT, 95)); + } + } + Some(self.js_first_twin(self.bound_outcome(self.e.bind_import(self.file, i as usize)))) }) } + /// JS `interface X` and `const X` in one file: importing `X` names whichever comes first + /// (as upstream does); `new X()` and calls still take the value. + fn js_first_twin(&self, o: Outcome) -> Outcome { + if self.family != LangFamily::Js || o.status != status::RESOLVED { + return o; + } + let view = self.view; + let t = view.node(NodeIdx(o.target)); + let is_type = |n| matches!(kind_of(view, n), NodeKind::Interface | NodeKind::TypeAlias | NodeKind::Class | NodeKind::Enum); + let is_value = |n| matches!(kind_of(view, n), NodeKind::Variable | NodeKind::Constant | NodeKind::Function); + let twins: Vec<_> = view.by_name(t.name()).filter(|&n| view.hot(n).file == t.file() && view.node(n).parent() == t.parent()).collect(); + if !(twins.iter().any(|&n| is_type(n)) && twins.iter().any(|&n| is_value(n))) { + return o; + } + twins.into_iter().min_by_key(|&n| (view.node(n).start_line(), view.node(n).start_col())).map_or(o, |n| Outcome::found(n, o.by, o.conf)) + } + /// A name on a continuation line of a multi-line import (`from m import (\n a,\n)`, /// `import {\n a,\n} from "m"`, `use m::{\n a,\n}`): the facts carry the statement's first /// line, the nearest import line above the reference. diff --git a/crates/cg-resolve/src/synth/mod.rs b/crates/cg-resolve/src/synth/mod.rs index a25783c..40975ae 100644 --- a/crates/cg-resolve/src/synth/mod.rs +++ b/crates/cg-resolve/src/synth/mod.rs @@ -447,7 +447,9 @@ fn jsx_render<'e, 'v>(e: &'e Engine<'v>, out: &mut Out, wcx: &mut WorkerCx<'e, ' if let NameRes::Found(t, ..) = cx.resolve_name(wcx, tag, Accept::Callable, 0, u32::MAX, None, false) { let k = view.node(t).kind(); if matches!(k, NodeKind::Function | NodeKind::Class | NodeKind::Component | NodeKind::Variable | NodeKind::Constant) && t != s.node { - out.push(EdgeKind::Calls, s.node, t, 0, "jsx-render", Some(path_line(view, f, s.line)), Some(("via", tag)), order_of("jsx-render")); + // like the other synthesised edges, on the rendering component's first line + let line = view.node(s.node).start_line(); + out.push(EdgeKind::Calls, s.node, t, line, "jsx-render", Some(path_line(view, f, s.line)), Some(("via", tag)), order_of("jsx-render")); } } } diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index 50a4b23..4e0b236 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -370,6 +370,15 @@ fn synthesised_edges_for_dynamic_dispatch() { let has = |needle: &str| edges.iter().any(|e| e == needle); assert!(has("ui/App.tsx::App -calls-> ui/Child.tsx::Child"), "jsx-render: {edges:#?}"); assert!(synth_meta(&v, "ui/App.tsx::App", "ui/Child.tsx::Child").unwrap().contains("jsx-render")); + // like the other synthesised edges, a render sits on the rendering component's first line + let render_lines: Vec<_> = v + .files() + .flat_map(|f| v.nodes_in_file(f)) + .flat_map(|n| v.out_edges(cg_core::NodeIdx(n))) + .filter(|e| e.kind == cg_core::EdgeKind::Calls && cg_store::dump::node_label(&v, e.dst) == "ui/Child.tsx::Child") + .map(|e| e.line) + .collect(); + assert_eq!(render_lines, [Some(2)]); assert!(has("ui/Comp.jsx::Comp::handle -calls-> ui/Comp.jsx::Comp::render"), "react-render: {edges:#?}"); assert!(has("bus/bus.ts::fire -calls-> bus/bus.ts::onTick"), "event-emitter: {edges:#?}"); assert!(synth_meta(&v, "bus/bus.ts::fire", "bus/bus.ts::onTick").unwrap().contains("\"event\":\"tick\"")); @@ -502,6 +511,91 @@ fn typescript_new_makes_the_value_beside_a_same_named_interface() { assert!(!made.iter().any(|m| m.contains("#interface@")), "{made:#?}"); } +#[test] +fn typescript_import_of_a_type_and_value_twin_names_its_first_declaration() { + let (_d, view) = project(&[ + ( + "src/schemas.ts", + "function ctor(): any {\n return null;\n}\nexport interface TypeFirst {\n kind: string;\n}\nexport const TypeFirst: any = ctor();\nexport const ValueFirst: any = ctor();\nexport type ValueFirst = { kind: string };\n", + ), + ("src/index.ts", "export { TypeFirst, ValueFirst } from \"./schemas\";\n"), + ("src/use.ts", "import { TypeFirst, ValueFirst } from \"./schemas\";\nexport function make() {\n return [new TypeFirst(), new ValueFirst()];\n}\n"), + ]); + let mut edges = Vec::new(); + for f in view.files() { + for n in view.nodes_in_file(f) { + let n = cg_core::NodeIdx(n); + for e in view.out_edges(n).filter(|e| matches!(e.kind, cg_core::EdgeKind::Imports | cg_core::EdgeKind::Instantiates)) { + edges.push(format!("{} -{:?}-> {}", dump::node_label(&view, n), e.kind, dump::node_key(&view, e.dst))); + } + } + } + let to = |from: &str, kind: &str, name: &str| { + edges.iter().filter(|e| e.starts_with(&format!("{from} -{kind}-> ")) && e.contains(&format!("@{name}:"))).collect::>() + }; + // `import` and `export .. from` name the declaration that comes first, as upstream does + for from in ["src/use.ts", "src/index.ts"] { + let (t, v) = (to(from, "Imports", "TypeFirst"), to(from, "Imports", "ValueFirst")); + assert!(t.len() == 1 && t[0].contains("#interface@"), "{edges:#?}"); + assert!(v.len() == 1 && v[0].contains("#constant@"), "{edges:#?}"); + } + // `new` still makes the value + for name in ["TypeFirst", "ValueFirst"] { + let made = to("src/use.ts::make", "Instantiates", name); + assert!(made.len() == 1 && made[0].contains("#constant@"), "{edges:#?}"); + } +} + +#[test] +fn typescript_type_parameters_name_no_declaration() { + let (_d, view) = project(&[ + ("src/output.ts", "export class Output {\n run() {}\n}\nexport interface T {\n kind: string;\n}\n"), + ( + "src/schema.ts", + "export class Schema {\n parse(data: unknown): Output {\n return data as Output;\n }\n}\nexport function make(value: T): T {\n return value;\n}\n", + ), + ]); + let edges = edges_of(&view); + assert!(!edges.iter().any(|e| e.starts_with("src/schema.ts") && e.contains("-> src/output.ts")), "{edges:#?}"); +} + +#[test] +fn javascript_window_global_members_answer_unbound_receivers() { + let (_d, view) = project(&[ + ( + "static/filter.js", + "'use strict';\n{\n window.SelectFilter = {\n init: function (id) {\n SelectFilter.refresh(id);\n },\n refresh: function (id) {}\n };\n}\n", + ), + ("static/inlines.js", "function update(row) {\n SelectFilter.init(row);\n}\nfunction shadowed(SelectFilter) {\n SelectFilter.init(1);\n}\n"), + ]); + let edges = edges_of(&view); + assert!(has(&edges, "static/inlines.js::update -calls-> static/filter.js::window.SelectFilter::init"), "{edges:#?}"); + assert!(has(&edges, "static/filter.js::window.SelectFilter::init -calls-> static/filter.js::window.SelectFilter::refresh"), "{edges:#?}"); + // a parameter of that name is not the global + assert!(!edges.iter().any(|e| e.starts_with("static/inlines.js::shadowed -calls-> ")), "{edges:#?}"); +} + +#[test] +fn javascript_default_import_names_the_module_file() { + let (_d, view) = project(&[ + ("src/anon.ts", "export default function () {\n return 1;\n}\n"), + ("src/named.ts", "export default function named() {\n return 2;\n}\n"), + ("src/use.ts", "import anon from \"./anon\";\nimport named from \"./named\";\nexport function run() {\n return anon() + named();\n}\n"), + ]); + let edges = edges_of(&view); + // the statement and the bound name both link the file, as upstream does + let user = view.files().find(|&f| view.file(f).path() == "src/use.ts").unwrap(); + let mut sites: Vec<_> = view + .out_edges(view.file(user).rec.node_start) + .filter(|e| e.kind == cg_core::EdgeKind::Imports) + .map(|e| format!("{:?}:{:?} {}", e.line, e.col, dump::node_label(&view, e.dst))) + .collect(); + sites.sort(); + assert_eq!(sites, ["Some(1):Some(0) src/anon.ts", "Some(1):Some(7) src/anon.ts", "Some(2):Some(0) src/named.ts", "Some(2):Some(7) src/named.ts"]); + // calls still reach the function + assert!(has(&edges, "src/use.ts::run -calls-> src/named.ts::named"), "{edges:#?}"); +} + #[test] fn rust_tuple_destructuring_types_each_element() { let (_d, view) = project(&[ diff --git a/crates/cg-sync/src/sync.rs b/crates/cg-sync/src/sync.rs index 335a1bd..09d651a 100644 --- a/crates/cg-sync/src/sync.rs +++ b/crates/cg-sync/src/sync.rs @@ -272,6 +272,26 @@ fn js_value_fact_sig(view: &View, f: FileId) -> JsValueFactSig { .collect() } +/// JS `interface X` beside `const X`: importing `X` names whichever comes first, so swapping +/// same-named declarations changes what importers link. +fn js_twin_order_sig(view: &View, f: FileId) -> Vec<(String, u8)> { + if view.file(f).lang().family() != LangFamily::Js { + return Vec::new(); + } + let mut count: FxHashMap<&str, u32> = FxHashMap::default(); + for n in view.nodes_in_file(f) { + *count.entry(view.node(NodeIdx(n)).qname()).or_default() += 1; + } + let mut twins: Vec<_> = view + .nodes_in_file(f) + .map(|n| view.node(NodeIdx(n))) + .filter(|n| count[n.qname()] > 1) + .map(|n| (n.start_line(), n.start_col(), n.qname().to_owned(), n.kind() as u8)) + .collect(); + twins.sort(); + twins.into_iter().map(|(_, _, q, k)| (q, k)).collect() +} + /// These facts change resolution even when the kernel's declaration identity /// stays the same (e.g. `obj.old = function internal` -> `obj.new = ...`, or the target of a /// Rust `impl Deref`, which has no node of its own). @@ -609,7 +629,10 @@ pub fn sync_locked(store: &Store, guard: &WriteGuard, root: &Path, opts: &SyncOp } if states[i] == DeltaState::Replaced { pair_nodes(&base_view, &view1, *f, &mut remap); - if export_sig(&base_view, *f) != export_sig(&view1, *f) || reexported_import_sig(&base_view, *f) != reexported_import_sig(&view1, *f) { + if export_sig(&base_view, *f) != export_sig(&view1, *f) + || reexported_import_sig(&base_view, *f) != reexported_import_sig(&view1, *f) + || js_twin_order_sig(&base_view, *f) != js_twin_order_sig(&view1, *f) + { export_changed.push(*f); } } diff --git a/crates/cg-sync/tests/incremental_parity.rs b/crates/cg-sync/tests/incremental_parity.rs index 58ee59e..64b7874 100644 --- a/crates/cg-sync/tests/incremental_parity.rs +++ b/crates/cg-sync/tests/incremental_parity.rs @@ -58,6 +58,12 @@ const FILES: &[(&str, &str)] = &[ ("cjs/app.js", "var compileETag = require('./utils').compileETag;\nfunction setup(v) {\n compileETag(v);\n}\nmodule.exports = setup;\n"), ("barrel/core.ts", "export function _lt() {}\nexport function _gte() {}\n"), ("barrel/checks.ts", "export {\n _lt as lt,\n _gte as gte,\n} from './core';\n"), + ("twin/schema.ts", "export interface Shape {\n kind: string;\n}\nexport const Shape: any = null;\n"), + ("twin/use.ts", "import { Shape } from './schema';\nexport function make() {\n return new Shape();\n}\n"), + ("win/filter.js", "window.Filter = {\n init: function () {}\n};\n"), + ("win/use.js", "function setup() {\n Filter.init();\n}\n"), + ("esm/anon.ts", "export default function () {\n return 1;\n}\n"), + ("esm/use.ts", "import anon from './anon';\nexport function run() {\n return anon();\n}\n"), ]; /// One-sided edits of the links above: (file, from, to). @@ -90,6 +96,25 @@ const EDITS: &[(&str, &str, &str)] = &[ ("barrel/core.ts", "export function _lt()", "export function _ltX()"), ("barrel/core.ts", "export function _ltX()", "export function _lt()"), ("barrel/checks.ts", "_gte as gte,\n", ""), + // `import { Shape }` names whichever of the twins comes first + ( + "twin/schema.ts", + "export interface Shape {\n kind: string;\n}\nexport const Shape: any = null;\n", + "export const Shape: any = null;\nexport interface Shape {\n kind: string;\n}\n", + ), + ( + "twin/schema.ts", + "export const Shape: any = null;\nexport interface Shape {\n kind: string;\n}\n", + "export interface Shape {\n kind: string;\n}\nexport const Shape: any = null;\n", + ), + // `Filter.init()` reaches the `window.Filter` global of another script + ("win/filter.js", "window.Filter =", "window.Filtr ="), + ("win/filter.js", "window.Filtr =", "window.Filter ="), + ("win/filter.js", " init: function", " start: function"), + ("win/filter.js", " start: function", " init: function"), + // `import anon` names the file whatever its default export is called + ("esm/anon.ts", "export default function ()", "export default function named()"), + ("esm/anon.ts", "export default function named()", "export default function ()"), ]; struct Rng(u64); From c270e8083473056057816570f7f43d26cfd28be9 Mon Sep 17 00:00:00 2001 From: columbia11 Date: Tue, 3 Nov 2026 12:11:43 +0800 Subject: [PATCH 7/8] resolve: TS overloads through receivers, `new` of a bare interface, CommonJS forwarded exports - A TS call through a typed receiver (`doc.write(..)`) links the method's first declaration, which stands for its overload signatures as upstream links it; `this.f(..)` keeps the overload its arguments fit. - `new File([], name)` that only finds an interface or type alias, with no value beside it, links nothing: the value is a global's (the DOM's). - `var express = require('..'); express.Router()` reaches the variable the module forwards (`var Router = require('router'); exports.Router = Router`), also through a package root's `module.exports = require(..)`. --- crates/cg-resolve/src/resolve.rs | 72 ++++++++++++++++++++-- crates/cg-resolve/tests/resolve_e2e.rs | 61 ++++++++++++++++++ crates/cg-sync/tests/incremental_parity.rs | 11 ++++ 3 files changed, 140 insertions(+), 4 deletions(-) diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 1f0b289..05b8c72 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -3238,7 +3238,13 @@ impl<'e, 'v> FileCx<'e, 'v> { match parse_shape(name) { Shape::Bare(n) if self.swift_extended_builtin(n, r) => Outcome::st(status::BUILTIN), Shape::Bare(n) => self.call_bare(wcx, r, n, Accept::Callable, args), - Shape::Member { root, path, method } => self.call_member(wcx, r, root, &path, method, args), + Shape::Member { root, path, method } => { + let o = self.js_first_overload(self.call_member(wcx, r, root, &path, method, args)); + if o.status == status::RESOLVED || !path.is_empty() { + return o; + } + self.js_required_export(r, root, method).map_or(o, |n| Outcome::found(n, by::IMPORT, 90)) + } Shape::This { kw, fields, method } if self.family == LangFamily::Js && kw != "this" => self.call_member(wcx, r, kw, &fields, method, args), Shape::This { kw, fields, method } => self.call_this(wcx, r, kw, &fields, method, args), Shape::Super { method } => self.call_super(wcx, r, method, args), @@ -3250,11 +3256,11 @@ impl<'e, 'v> FileCx<'e, 'v> { None => Outcome::st(status::NO_CANDIDATE), }, }, - Shape::CallResult { inner, method } => self.call_result(wcx, r, inner, method, args), + Shape::CallResult { inner, method } => self.js_first_overload(self.call_result(wcx, r, inner, method, args)), Shape::ValueResult { inner, method } => { let value = self.expression_value(wcx, inner, self.scope_at(r.line, r.col), r.line, 0); match value.and_then(|v| v.method_receiver(method)) { - Some(t) => self.member_call(wcx, t, &[], method, 85, args.map(|a| (a, r))), + Some(t) => self.js_first_overload(self.member_call(wcx, t, &[], method, 85, args.map(|a| (a, r)))), None => Outcome::st(status::NO_CANDIDATE), } } @@ -3470,6 +3476,56 @@ impl<'e, 'v> FileCx<'e, 'v> { }) } + /// TS `doc.write(..)` on a typed receiver: the method's first declaration stands for its + /// overload signatures, as upstream links it (`this.write(..)` keeps the overload that fits). + fn js_first_overload(&self, o: Outcome) -> Outcome { + if self.family != LangFamily::Js || o.status != status::RESOLVED || kind_of(self.view, NodeIdx(o.target)) != NodeKind::Method { + return o; + } + let view = self.view; + let m = view.node(NodeIdx(o.target)); + view.by_name(m.name()) + .filter(|&n| view.node(n).parent() == m.parent() && kind_of(view, n) == NodeKind::Method) + .min_by_key(|&n| (view.node(n).start_line(), view.node(n).start_col())) + .map_or(o, |n| Outcome::found(n, o.by, o.conf)) + } + + /// CommonJS `var express = require('./express'); express.Router()`: the variable the module + /// exports under that name (`exports.Router = Router`). + fn js_required_export(&self, r: &RefRec, root: &str, method: &str) -> Option { + if self.family != LangFamily::Js { + return None; + } + let i = self.visible_import(root, self.scope_at(r.line, r.col))?; + if self.imports[i as usize].kind != ImportKind::Require as u8 { + return None; + } + let Some(ImportTarget::File(tf)) = self.e.imp_targets[self.file.idx()].get(i as usize).copied() else { return None }; + let view = self.view; + let variable = |n: NodeIdx| matches!(kind_of(view, n), NodeKind::Variable | NodeKind::Constant); + if let Some(Bound::Node(n)) = self.e.lookup_export(tf, method, 0) { + return variable(n).then_some(n); + } + // `var Router = require('router'); exports.Router = Router` forwards a dependency: the + // variable holding it is what the project can link. The file may sit behind a package + // root's `module.exports = require('./lib/express')`. + let mut files = vec![tf]; + let mut i = 0; + while i < files.len() && files.len() < 8 { + for &s in &self.e.stars[files[i].idx()] { + if !files.contains(&s) { + files.push(s); + } + } + i += 1; + } + files.into_iter().find_map(|f| { + let spec_of = |name: &str| view.imports_of(f).iter().find(|i| view.text_str(i.local) == name).map(|i| view.text_str(i.spec)); + let forwarded = view.exports_of(f).iter().any(|e| view.text_str(e.name) == method && spec_of(method) == Some(view.text_str(e.from_spec))); + self.e.lookup_top_level(f, method).filter(|&n| forwarded && variable(n)) + }) + } + /// JS `interface X` and `const X` in one file: importing `X` names whichever comes first /// (as upstream does); `new X()` and calls still take the value. fn js_first_twin(&self, o: Outcome) -> Outcome { @@ -3579,7 +3635,15 @@ impl<'e, 'v> FileCx<'e, 'v> { if o.status == status::NO_CANDIDATE { self.resolve_type_ref(wcx, r, name, Accept::Callable) } else { - self.js_value_twin(o) + let o = self.js_value_twin(o); + // `new File([], name)` with only `interface File` in reach: a global's value (the + // DOM's), since an interface makes none + let bare_type = o.status == status::RESOLVED && matches!(kind_of(self.view, NodeIdx(o.target)), NodeKind::Interface | NodeKind::TypeAlias); + if self.family == LangFamily::Js && bare_type { + Outcome::st(status::NO_CANDIDATE) + } else { + o + } } } RefKind::Edge(EdgeKind::References) => { diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index 4e0b236..09caddc 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -559,6 +559,67 @@ fn typescript_type_parameters_name_no_declaration() { assert!(!edges.iter().any(|e| e.starts_with("src/schema.ts") && e.contains("-> src/output.ts")), "{edges:#?}"); } +/// `from -kind-> path:line#kind@qname` for every edge of the given kinds out of `from`. +fn keyed_edges(view: &View, kinds: &[cg_core::EdgeKind]) -> Vec { + let mut out = Vec::new(); + for f in view.files() { + for n in view.nodes_in_file(f) { + let n = cg_core::NodeIdx(n); + for e in view.out_edges(n).filter(|e| kinds.contains(&e.kind)) { + out.push(format!("{} -{:?}-> {}", dump::node_label(view, n), e.kind, dump::node_key(view, e.dst))); + } + } + } + out +} + +#[test] +fn typescript_receiver_calls_name_the_first_overload() { + let (_d, view) = project(&[( + "src/doc.ts", + "type ModeWriter = (doc: Doc) => void;\nexport class Doc {\n write(fn: ModeWriter): void;\n write(line: string): void;\n write(arg: any) {}\n f(s: string): void;\n f(n: number, m?: number): void;\n f(a: any, b?: any): void {}\n run(n: number) {\n this.f('x');\n this.f(n, 2);\n }\n}\nexport function emit(doc: Doc) {\n doc.write(`a`);\n doc.write('b');\n}\n", + )]); + let edges = keyed_edges(&view, &[cg_core::EdgeKind::Calls]); + // through a typed receiver, the method's first declaration stands for its overloads, as upstream links it + let writes: Vec<_> = edges.iter().filter(|e| e.starts_with("src/doc.ts::emit -Calls-> ")).collect(); + assert!(writes.len() == 2 && writes.iter().all(|w| w.contains("src/doc.ts:3:")), "{edges:#?}"); + // `this.f(..)` keeps the overload its arguments fit + for line in [6, 7] { + assert!(edges.iter().any(|e| e.starts_with("src/doc.ts::Doc::run -Calls-> ") && e.contains(&format!("src/doc.ts:{line}:"))), "{edges:#?}"); + } +} + +#[test] +fn typescript_new_of_a_bare_interface_links_nothing() { + let (_d, view) = project(&[ + ("src/types.ts", "export interface File {\n name: string;\n}\nexport type Blob = { size: number };\n"), + ("src/use.test.ts", "export function make() {\n return [new File([], \"a.txt\"), new Blob()];\n}\n"), + ]); + let edges = keyed_edges(&view, &[cg_core::EdgeKind::Instantiates, cg_core::EdgeKind::Calls]); + // the DOM's `File`, not the project's interface: an interface makes no value + assert!(!edges.iter().any(|e| e.starts_with("src/use.test.ts::make ")), "{edges:#?}"); +} + +#[test] +fn commonjs_member_call_reaches_the_variable_a_module_exports() { + let (_d, view) = project(&[ + ( + "lib/express.js", + "var bodyParser = require('body-parser');\nvar Router = require('router');\nexports = module.exports = createApplication;\nfunction createApplication() {\n return {};\n}\nexports.Router = Router;\nexports.json = bodyParser.json;\n", + ), + ("test/app.js", "var express = require('../lib/express');\nfunction make() {\n var app = express();\n express.json();\n return express.Router();\n}\n"), + // the package root forwards the whole module + ("index.js", "module.exports = require('./lib/express');\n"), + ("test/root.js", "var express = require('..');\nfunction viaRoot() {\n return express.Router();\n}\n"), + ]); + let edges = edges_of(&view); + assert!(has(&edges, "test/app.js::make -calls-> lib/express.js::createApplication"), "{edges:#?}"); + assert!(has(&edges, "test/app.js::make -calls-> lib/express.js::Router"), "{edges:#?}"); + assert!(has(&edges, "test/root.js::viaRoot -calls-> lib/express.js::Router"), "{edges:#?}"); + // `exports.json = bodyParser.json` is a dependency's function, not the `bodyParser` variable + assert!(!has(&edges, "test/app.js::make -calls-> lib/express.js::bodyParser"), "{edges:#?}"); +} + #[test] fn javascript_window_global_members_answer_unbound_receivers() { let (_d, view) = project(&[ diff --git a/crates/cg-sync/tests/incremental_parity.rs b/crates/cg-sync/tests/incremental_parity.rs index 64b7874..054b333 100644 --- a/crates/cg-sync/tests/incremental_parity.rs +++ b/crates/cg-sync/tests/incremental_parity.rs @@ -64,6 +64,9 @@ const FILES: &[(&str, &str)] = &[ ("win/use.js", "function setup() {\n Filter.init();\n}\n"), ("esm/anon.ts", "export default function () {\n return 1;\n}\n"), ("esm/use.ts", "import anon from './anon';\nexport function run() {\n return anon();\n}\n"), + ("ov/doc.ts", "export class Doc {\n write(fn: () => void): void;\n write(line: string): void;\n write(arg: any) {}\n}\nexport function emit(doc: Doc) {\n doc.write('a');\n}\n"), + ("fwd/express.js", "var Router = require('router');\nexports = module.exports = createApplication;\nfunction createApplication() {}\nexports.Router = Router;\n"), + ("fwd/use.js", "var express = require('./express');\nfunction make() {\n return express.Router();\n}\n"), ]; /// One-sided edits of the links above: (file, from, to). @@ -115,6 +118,14 @@ const EDITS: &[(&str, &str, &str)] = &[ // `import anon` names the file whatever its default export is called ("esm/anon.ts", "export default function ()", "export default function named()"), ("esm/anon.ts", "export default function named()", "export default function ()"), + // `doc.write(..)` names the first overload + ("ov/doc.ts", " write(fn: () => void): void;\n write(line: string): void;\n", " write(line: string): void;\n write(fn: () => void): void;\n"), + ("ov/doc.ts", " write(line: string): void;\n write(fn: () => void): void;\n", " write(fn: () => void): void;\n write(line: string): void;\n"), + // `express.Router()` reaches the variable `exports.Router` forwards + ("fwd/express.js", "var Router = require('router');", "var Rtr = require('router');"), + ("fwd/express.js", "var Rtr = require('router');", "var Router = require('router');"), + ("fwd/express.js", "exports.Router = Router;", "exports.Router = createApplication;"), + ("fwd/express.js", "exports.Router = createApplication;", "exports.Router = Router;"), ]; struct Rng(u64); From 12d6fd0f2db76d465de4bd418bf08e3d5a89819e Mon Sep 17 00:00:00 2001 From: columbia11 Date: Tue, 3 Nov 2026 12:18:13 +0800 Subject: [PATCH 8/8] resolve: first-overload rule for TS only Overload signatures exist only in TypeScript; a method defined twice in plain JS is a redefinition, where the last definition wins. --- crates/cg-resolve/src/resolve.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 05b8c72..53ba48e 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -3479,7 +3479,8 @@ impl<'e, 'v> FileCx<'e, 'v> { /// TS `doc.write(..)` on a typed receiver: the method's first declaration stands for its /// overload signatures, as upstream links it (`this.write(..)` keeps the overload that fits). fn js_first_overload(&self, o: Outcome) -> Outcome { - if self.family != LangFamily::Js || o.status != status::RESOLVED || kind_of(self.view, NodeIdx(o.target)) != NodeKind::Method { + // overload signatures are TS; plain JS's repeated method is a redefinition, the last wins + if !matches!(self.lang, Lang::TypeScript | Lang::Tsx) || o.status != status::RESOLVED || kind_of(self.view, NodeIdx(o.target)) != NodeKind::Method { return o; } let view = self.view;