diff --git a/crates/cg-core/src/brand.rs b/crates/cg-core/src/brand.rs index a568c5e..64f0c98 100644 --- a/crates/cg-core/src/brand.rs +++ b/crates/cg-core/src/brand.rs @@ -17,7 +17,7 @@ pub const UPSTREAM_CONFIG_FILE: &str = "codegraph.json"; pub const CONFIG_FILE: &str = "cgr.json"; /// Version of the resolution rules: changing resolver behaviour bumps this, which /// marks older indexes as "built by an older engine" (design doc 5.8). -pub const ENGINE_VERSION: u32 = 8; +pub const ENGINE_VERSION: u32 = 9; /// Version of the on-disk segment format; a mismatch forces a full rebuild. pub const FORMAT_VERSION: u32 = 2; /// The upstream commit whose kernel is vendored (see crates/cg-kernel/UPSTREAM_COMMIT). diff --git a/crates/cg-extract/src/facts/js.rs b/crates/cg-extract/src/facts/js.rs index 491ad92..6eda32a 100644 --- a/crates/cg-extract/src/facts/js.rs +++ b/crates/cg-extract/src/facts/js.rs @@ -11,6 +11,27 @@ pub const AMBIENT_MODULE: &str = "\0ambient"; pub fn extract(cx: &mut Cx, root: Node) { walk(cx, root, 0); + // Mutations are relevant only to initializer / factory evidence. Keep the + // subset needed by resolution, avoiding a permanent fact for every write. + let mutations: std::collections::HashSet = cx.facts.bindings.iter().filter(|b| b.kind == BindKind::Mutation).map(|b| b.name.clone()).collect(); + let relevant: std::collections::HashSet = cx + .facts + .bindings + .iter() + .filter(|b| b.init_ctor.ends_with("()") || b.kind == BindKind::CommonJsObject) + .map(|b| b.name.clone()) + .chain(cx.facts.bindings.iter().filter(|b| b.kind == BindKind::MemberFn && !b.init_ctor.is_empty()).map(|b| b.init_ctor.clone())) + .chain(cx.facts.imports.iter().map(|i| i.local.clone())) + .collect(); + cx.facts.bindings.retain(|b| { + if b.kind == BindKind::Mutation { + relevant.contains(&b.name) || b.name == "module.exports" || b.name.split_once('.').is_some_and(|(root, _)| relevant.contains(root)) + } else if b.kind == BindKind::FactoryMixin { + !b.init_ctor.split(',').any(|name| mutations.contains(name)) + } else { + true + } + }); let script = !kids(root).any(|c| matches!(c.kind(), "import_statement" | "export_statement" | "import_alias")); for decl in kids(root).filter(|c| c.kind() == "ambient_declaration") { let Some(module) = kids(decl).find(|c| c.kind() == "module") else { continue }; @@ -49,6 +70,15 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) { if scope == 0 { commonjs_export(cx, n); } + if let Some(left) = n.child_by_field_name("left") { + record_mutations(cx, left, scope); + } + walk_children(cx, n, scope); + } + "augmented_assignment_expression" | "update_expression" => { + if let Some(left) = n.child_by_field_name("left").or_else(|| n.child_by_field_name("argument")) { + record_mutations(cx, left, scope); + } walk_children(cx, n, scope); } "function_declaration" | "generator_function_declaration" => { @@ -67,6 +97,7 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) { "lexical_declaration" | "variable_declaration" => var_decl(cx, n, scope), "call_expression" => { super::args::js_call(cx, n); + assigned_this_call(cx, n, scope); walk_children(cx, n, scope); } "for_in_statement" => { @@ -107,6 +138,64 @@ fn names_in_pattern(cx: &Cx, n: Node, out: &mut Vec) { } } +fn record_mutations(cx: &mut Cx, target: Node, scope: u32) { + let mut names = Vec::new(); + names_in_pattern(cx, target, &mut names); + if target.kind() == "member_expression" { + if let (Some(object), Some(property)) = (target.child_by_field_name("object"), target.child_by_field_name("property")) { + if object.kind() == "identifier" { + names.push(format!("{}.{}", cx.text(object), cx.text(property))); + } + } + } + for name in names { + cx.add_binding(scope, &name, BindKind::Mutation, "", "", cx.line(target)); + } +} + +fn assigned_this_call(cx: &mut Cx, call: Node, scope: u32) { + let Some(callee) = call.child_by_field_name("function").filter(|f| f.kind() == "member_expression") else { return }; + let (Some(receiver), Some(method)) = (callee.child_by_field_name("object"), callee.child_by_field_name("property")) else { return }; + if receiver.kind() != "this" { + return; + } + // Only the nearest function supplies the receiver. In particular, a + // nested ordinary callback must not inherit its outer method's `this`. + let mut ancestor = call.parent(); + let function = loop { + let Some(n) = ancestor else { return }; + if matches!(n.kind(), "function_declaration" | "function_expression" | "function" | "arrow_function" | "method_definition") { + break n; + } + ancestor = n.parent(); + }; + if !matches!(function.kind(), "function_expression" | "function") { + return; + } + let Some(assignment) = function.parent().filter(|p| p.kind() == "assignment_expression" && p.child_by_field_name("right") == Some(function)) else { + return; + }; + let Some(object) = assignment + .child_by_field_name("left") + .filter(|l| l.kind() == "member_expression") + .and_then(|l| l.child_by_field_name("object")) + .filter(|o| o.kind() == "identifier") + else { + return; + }; + let Some(row) = cx.row_at(cx.start(function)) else { return }; + let (line, col) = cg_core::text::unpack_pos(cx.start(call)); + cx.facts.bindings.push(BindingFact { + scope, + name: cx.text(method).to_owned(), + kind: BindKind::AssignedThisCall, + decl_type: cx.text(object).to_owned(), + init_ctor: col.to_string(), + line, + node_row: row, + }); +} + fn bind_pattern(cx: &mut Cx, pat: Node, scope: u32, kind: BindKind, decl_type: &str, init: &str) { let mut names = Vec::new(); names_in_pattern(cx, pat, &mut names); @@ -156,6 +245,9 @@ fn value_info(cx: &Cx, v: Node) -> (String, String) { fn value_info_inner(cx: &Cx, v: Node, in_satisfies: bool) -> (String, String) { match v.kind() { + // Assignment expressions evaluate to their right-hand value, including + // `const app = module.exports = express()`. + "assignment_expression" => v.child_by_field_name("right").map(|c| value_info_inner(cx, c, in_satisfies)).unwrap_or_default(), "new_expression" => { let c = v.child_by_field_name("constructor").map(|c| cx.text(c).to_owned()).unwrap_or_default(); (String::new(), c) @@ -460,14 +552,17 @@ fn enclosing_constructor<'a>(cx: &Cx<'a>, n: Node) -> Option<&'a str> { } fn function(cx: &mut Cx, n: Node, scope: u32) { + if scope == 0 && n.kind() == "function_declaration" { + factory_mixin(cx, n, scope); + } // The kernel labels `obj.method = function method() {}` as a Function. Keep // evidence of the member assignment so an unknown receiver cannot match an // unrelated, plain function with the same name. A member given to an ES5 // constructor's prototype (`X.prototype.m = ...`, `this.m = ...` in `function X`) // records the constructor's name. if let Some(parent) = n.parent() { - let (member, owner) = match parent.kind() { - "object" if n.kind() == "method_definition" => (n.child_by_field_name("name"), prototype_object_owner(cx, parent)), + let (member, owner, object_name) = match parent.kind() { + "object" if n.kind() == "method_definition" => (n.child_by_field_name("name"), prototype_object_owner(cx, parent), None), "assignment_expression" if parent.child_by_field_name("right") == Some(n) => { let left = parent.child_by_field_name("left").filter(|left| matches!(left.kind(), "member_expression" | "subscript_expression")); let member = left.and_then(|left| { @@ -479,12 +574,12 @@ fn function(cx: &mut Cx, n: Node, scope: u32) { Some(o) => prototype_of(cx, o), None => None, }; - (member, owner) + (member, owner, object.filter(|o| o.kind() == "identifier").map(|o| cx.text(o))) } "pair" if parent.child_by_field_name("value") == Some(n) => { - (parent.child_by_field_name("key"), parent.parent().and_then(|o| prototype_object_owner(cx, o))) + (parent.child_by_field_name("key"), parent.parent().and_then(|o| prototype_object_owner(cx, o)), None) } - _ => (None, None), + _ => (None, None, None), }; if let Some(member) = member { if let Some(row) = cx.row_at(cx.start(n)) { @@ -493,7 +588,7 @@ fn function(cx: &mut Cx, n: Node, scope: u32) { name: cx.text(member).trim_matches(['\'', '"']).to_owned(), kind: BindKind::MemberFn, decl_type: owner.unwrap_or_default().to_owned(), - init_ctor: String::new(), + init_ctor: object_name.unwrap_or_default().to_owned(), line: cx.line(n), node_row: row, }); @@ -534,6 +629,99 @@ fn function(cx: &mut Cx, n: Node, scope: u32) { } } +/// 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. +fn factory_mixin(cx: &mut Cx, n: Node, scope: u32) { + let (Some(name), Some(body)) = (n.child_by_field_name("name"), n.child_by_field_name("body")) else { return }; + if n.child_by_field_name("parameters").is_some_and(|p| kids(p).any(|c| c.is_named())) { + return; + } + let statements: Vec<_> = kids(body).filter(|s| s.is_named()).collect(); + // An early exit or loop makes a direct mixin conditional on control flow. + if statements.iter().any(|s| { + matches!( + s.kind(), + "if_statement" + | "switch_statement" + | "try_statement" + | "for_statement" + | "for_in_statement" + | "while_statement" + | "do_statement" + | "throw_statement" + ) + }) { + return; + } + let returns: Vec<_> = statements.iter().filter(|s| s.kind() == "return_statement").collect(); + if returns.len() != 1 { + return; + } + let Some(value) = kids(*returns[0]).find(|c| c.kind() == "identifier") else { return }; + let returned = cx.text(value); + let mut locals = Vec::new(); + let mut declared_object = None; + for s in &statements { + if matches!(s.kind(), "lexical_declaration" | "variable_declaration") { + for d in kids(*s).filter(|d| d.kind() == "variable_declarator") { + if let Some(id) = d.child_by_field_name("name").filter(|x| x.kind() == "identifier") { + let local = cx.text(id); + locals.push(local); + if local == returned + && d.child_by_field_name("value").is_some_and(|v| matches!(v.kind(), "function_expression" | "function" | "arrow_function" | "object")) + { + declared_object = Some(d.start_byte()); + } + } + } + } + } + let Some(declared_at) = declared_object else { return }; + for s in &statements { + if s.kind() != "expression_statement" || s.start_byte() <= declared_at || s.start_byte() >= returns[0].start_byte() { + continue; + } + let Some(call) = kids(*s).find(|c| c.kind() == "call_expression") else { continue }; + let (Some(func), Some(args)) = (call.child_by_field_name("function"), call.child_by_field_name("arguments")) else { continue }; + if func.kind() != "identifier" { + continue; + } + let callee = cx.text(func); + if locals.contains(&callee) || !cx.facts.imports.iter().any(|i| i.scope == 0 && i.local == callee && i.spec == "merge-descriptors") { + continue; + } + let args: Vec<_> = kids(args).filter(|c| c.is_named()).collect(); + if args.len() < 2 || args[0].kind() != "identifier" || cx.text(args[0]) != returned || args[1].kind() != "identifier" { + continue; + } + let source = cx.text(args[1]); + if locals.contains(&source) { + continue; + } + let reassigned = statements.iter().filter(|s| s.kind() == "expression_statement").any(|s| { + kids(*s).any(|c| { + c.kind() == "assignment_expression" + && c.child_by_field_name("left").is_some_and(|left| left.kind() == "identifier" && [returned, callee, source].contains(&cx.text(left))) + }) + }); + if reassigned { + continue; + } + let Some(spec) = cx.facts.imports.iter().find(|i| i.scope == 0 && i.local == source).map(|i| i.spec.clone()) else { continue }; + let Some(row) = cx.row_at(cx.start(n)) else { continue }; + cx.facts.bindings.push(BindingFact { + scope, + name: cx.text(name).to_owned(), + kind: BindKind::FactoryMixin, + decl_type: spec, + init_ctor: format!("{callee},{source},{returned}"), + line: cx.line(n), + node_row: row, + }); + } +} + fn class(cx: &mut Cx, n: Node, scope: u32) { let sc = cx.push_scope(ScopeKind::Class, scope, n); let Some(body) = n.child_by_field_name("body") else { @@ -605,6 +793,21 @@ fn var_decl(cx: &mut Cx, n: Node, scope: u32) { let ty = d.child_by_field_name("type").map(|t| ts_type_name(cx, t)).unwrap_or_default(); let value = d.child_by_field_name("value"); if let Some(v) = value { + // `var app = exports = module.exports = {}` ties subsequent + // `app.method = ...` assignments to the module's exported object. + if scope == 0 && name.kind() == "identifier" && cx.lookup_binding(0, "module").is_none() { + let mut cur = v; + let mut module_export = false; + while cur.kind() == "assignment_expression" { + module_export |= cur.child_by_field_name("left").is_some_and(|left| cx.text(left) == "module.exports"); + let Some(right) = cur.child_by_field_name("right") else { break }; + cur = right; + } + if module_export && cur.kind() == "object" { + let local = cx.text(name).to_owned(); + cx.add_binding(scope, &local, BindKind::CommonJsObject, "", "", cx.line(d)); + } + } if let Some(spec) = require_target(cx, v) { let line = cx.line(d); match name.kind() { @@ -636,6 +839,8 @@ fn var_decl(cx: &mut Cx, n: Node, scope: u32) { let nm = cx.text(name).to_owned(); let line = cx.line(d); cx.add_binding(scope, &nm, BindKind::LocalFn, "", "", line); + let row = cx.row_at(cx.start(v)); + cx.facts.bindings.last_mut().unwrap().node_row = row.unwrap_or(NONE); } else if constant && name.kind() == "identifier" && v.kind() == "identifier" && ty.is_empty() && cx.text(v) != cx.text(name) { // `const local = other`: the name is the other name let (nm, other) = (cx.text(name).to_owned(), cx.text(v).to_owned()); diff --git a/crates/cg-extract/src/facts/mod.rs b/crates/cg-extract/src/facts/mod.rs index d401d43..80c5e11 100644 --- a/crates/cg-extract/src/facts/mod.rs +++ b/crates/cg-extract/src/facts/mod.rs @@ -131,6 +131,17 @@ pub enum BindKind { /// Rust `type X = Y;` outside an impl, keyed by the alias's node: `decl_type` is `Y`. /// Metadata only; not a lexical binding. TypeAlias = 10, + /// A JS factory returns an object it mixed with an imported module's members. + /// Metadata only; `decl_type` is the source module specifier. + FactoryMixin = 11, + /// A JavaScript name is assigned after declaration. Metadata only. + Mutation = 12, + /// A top-level JavaScript object is assigned to `module.exports` in its initializer. + /// Metadata only; `name` is the local object name. + CommonJsObject = 13, + /// A `this.member()` inside a function assigned to a named object property. + /// Metadata only; `decl_type` identifies that object and `init_ctor` the call column. + AssignedThisCall = 14, } #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/cg-extract/src/facts/util.rs b/crates/cg-extract/src/facts/util.rs index 941ed1d..eebd0b6 100644 --- a/crates/cg-extract/src/facts/util.rs +++ b/crates/cg-extract/src/facts/util.rs @@ -120,7 +120,18 @@ impl<'a> Cx<'a> { if let Some(b) = self.facts.bindings.iter().rev().find(|b| { b.scope == scope && b.name == name - && !matches!(b.kind, BindKind::MemberFn | BindKind::ReturnType | BindKind::Deref | BindKind::Fixture | BindKind::TypeAlias) + && !matches!( + b.kind, + BindKind::MemberFn + | BindKind::ReturnType + | BindKind::Deref + | BindKind::Fixture + | BindKind::TypeAlias + | BindKind::FactoryMixin + | BindKind::Mutation + | BindKind::CommonJsObject + | BindKind::AssignedThisCall + ) }) { return Some((b.decl_type.clone(), b.init_ctor.clone())); } diff --git a/crates/cg-kernel/patches/P5-js-ts-graph.patch b/crates/cg-kernel/patches/P5-js-ts-graph.patch new file mode 100644 index 0000000..2c0ccc8 --- /dev/null +++ b/crates/cg-kernel/patches/P5-js-ts-graph.patch @@ -0,0 +1,156 @@ +diff -r -N -U 0 a/src/hooks.rs b/src/hooks.rs +--- a/src/hooks.rs 2026-11-02 01:04:51 ++++ b/src/hooks.rs 2026-11-02 01:04:57 +@@ -75,0 +76,36 @@ ++/// Retry a completed error tree with an equal-byte-length lexical rewrite. The walker and facts ++/// still read the original source. Accept the retry only when it removes every parse error and ++/// preserve the original result if the bounded optional retry fails. ++pub(crate) fn parse_with_rewrite( ++ parser: &mut Parser, ++ source: &str, ++ rewrite: impl FnOnce(&Tree, &str) -> Option, ++) -> Option { ++ let start = Instant::now(); ++ let original = parse(parser, source)?; ++ if !original.root_node().has_error() { ++ return Some(original); ++ } ++ let Some(masked) = rewrite(&original, source) else { return Some(original) }; ++ if masked.len() != source.len() { ++ return Some(original); ++ } ++ let limit = TIMEOUT.with(|c| c.get()); ++ let remaining = match limit { ++ Some(limit) => match limit.checked_sub(start.elapsed()) { ++ Some(left) if !left.is_zero() => Some(left), ++ _ => return Some(original), ++ }, ++ None => None, ++ }; ++ TIMEOUT.with(|c| c.set(remaining)); ++ let retry = parse(parser, &masked); ++ TIMEOUT.with(|c| c.set(limit)); ++ if let Some(tree) = retry.filter(|t| !t.root_node().has_error()) { ++ return Some(tree); ++ } ++ TIMED_OUT.with(|c| c.set(false)); ++ STASH.with(|s| *s.borrow_mut() = Some(original.clone())); ++ Some(original) ++} ++ +diff -r -N -U 0 a/src/tsjs/extractors.rs b/src/tsjs/extractors.rs +--- a/src/tsjs/extractors.rs 2026-11-02 01:19:35 ++++ b/src/tsjs/extractors.rs 2026-11-02 01:19:35 +@@ -1673 +1673,5 @@ +- if let Some(r) = recv_ident { ++ if let Some(r) = receiver.filter(|r| matches!(r.kind(), "this" | "super")) { ++ // Preserve the receiver: an unrelated bare function of the ++ // same name cannot stand in for `this.m()` or `super.m()`. ++ callee_name = format!("{}.{method_name}", self.text(r)); ++ } else if let Some(r) = recv_ident { +@@ -1675,5 +1679 @@ +- if !matches!(receiver_name, "self" | "this" | "cls" | "super") { +- callee_name = format!("{receiver_name}.{method_name}"); +- } else { +- callee_name = method_name.to_string(); +- } ++ callee_name = format!("{receiver_name}.{method_name}"); +@@ -1718,2 +1718 @@ +- // class keeps the bare method name, as a call on +- // `this` does. ++ // class keeps the enclosing receiver. +@@ -1721 +1720 @@ +- method_name.to_string() ++ format!("this.{method_name}") +diff -r -N -U 0 a/src/tsjs/mod.rs b/src/tsjs/mod.rs +--- a/src/tsjs/mod.rs 2026-11-02 01:04:51 ++++ b/src/tsjs/mod.rs 2026-11-02 01:05:16 +@@ -13,0 +14 @@ ++mod variance; +@@ -235 +236,5 @@ +- let tree = crate::hooks::parse(&mut parser, source) ++ let tree = if matches!(language, "typescript" | "tsx") { ++ crate::hooks::parse_with_rewrite(&mut parser, source, variance::mask) ++ } else { ++ crate::hooks::parse(&mut parser, source) ++ } +diff -r -N -U 0 a/src/tsjs/variance.rs b/src/tsjs/variance.rs +--- a/src/tsjs/variance.rs 1969-12-31 18:00:00 ++++ b/src/tsjs/variance.rs 2026-11-02 01:05:13 +@@ -0,0 +1,76 @@ ++//! A narrow recovery for variance annotations unsupported by the pinned TS grammar. ++//! Only a failed type-parameter list on a type declaration is considered; the parser ++//! retry must be error-free. The equal-length mask leaves all source locations unchanged. ++ ++use tree_sitter::{Node, Tree}; ++ ++fn skip_trivia(bytes: &[u8], mut i: usize, end: usize) -> usize { ++ while i < end { ++ if bytes[i].is_ascii_whitespace() { ++ i += 1; ++ } else if bytes[i..end].starts_with(b"/*") { ++ let Some(close) = bytes[i + 2..end].windows(2).position(|w| w == b"*/") else { return end }; ++ i += close + 4; ++ } else if bytes[i..end].starts_with(b"//") { ++ i += 2; ++ while i < end && bytes[i] != b'\n' { i += 1; } ++ } else { ++ break; ++ } ++ } ++ i ++} ++ ++fn ident_end(bytes: &[u8], start: usize, end: usize) -> usize { ++ if start >= end || !(bytes[start].is_ascii_alphabetic() || matches!(bytes[start], b'_' | b'$')) { ++ return start; ++ } ++ let mut i = start + 1; ++ while i < end && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'_' | b'$')) { i += 1; } ++ i ++} ++ ++fn parameter_prefix(bytes: &[u8], start: usize, end: usize, spans: &mut Vec<(usize, usize)>) { ++ let first = skip_trivia(bytes, start, end); ++ let first_end = ident_end(bytes, first, end); ++ if first == first_end || !matches!(&bytes[first..first_end], b"in" | b"out") { return; } ++ let next = skip_trivia(bytes, first_end, end); ++ if next == first_end { return; } ++ let next_end = ident_end(bytes, next, end); ++ if next == next_end || &bytes[next..next_end] == b"extends" { return; } ++ if &bytes[first..first_end] == b"in" && &bytes[next..next_end] == b"out" { ++ let name = skip_trivia(bytes, next_end, end); ++ let name_end = ident_end(bytes, name, end); ++ if name == next_end || name == name_end || &bytes[name..name_end] == b"extends" { return; } ++ spans.push((next, next_end)); ++ } ++ spans.push((first, first_end)); ++} ++ ++fn find_spans(node: Node<'_>, source: &[u8], spans: &mut Vec<(usize, usize)>) { ++ let mut pending = vec![node]; ++ while let Some(n) = pending.pop() { ++ if !n.has_error() { continue; } ++ if n.kind() == "type_parameters" ++ && n.parent().is_some_and(|p| matches!(p.kind(), "interface_declaration" | "class_declaration" | "abstract_class_declaration" | "type_alias_declaration")) ++ { ++ let mut cursor = n.walk(); ++ for child in n.children(&mut cursor) { ++ if matches!(child.kind(), "<" | ",") { ++ parameter_prefix(source, child.end_byte(), n.end_byte(), spans); ++ } ++ } ++ } ++ let mut cursor = n.walk(); ++ pending.extend(n.named_children(&mut cursor).filter(|c| c.has_error())); ++ } ++} ++ ++pub(super) fn mask(tree: &Tree, source: &str) -> Option { ++ let mut spans = Vec::new(); ++ find_spans(tree.root_node(), source.as_bytes(), &mut spans); ++ if spans.is_empty() { return None; } ++ let mut bytes = source.as_bytes().to_vec(); ++ for (start, end) in spans { bytes[start..end].fill(b' '); } ++ String::from_utf8(bytes).ok() ++} diff --git a/crates/cg-kernel/src/hooks.rs b/crates/cg-kernel/src/hooks.rs index 481a01e..935b055 100644 --- a/crates/cg-kernel/src/hooks.rs +++ b/crates/cg-kernel/src/hooks.rs @@ -73,6 +73,42 @@ pub(crate) fn parse(parser: &mut Parser, source: &str) -> Option { tree } +/// Retry a completed error tree with an equal-byte-length lexical rewrite. The walker and facts +/// still read the original source. Accept the retry only when it removes every parse error and +/// preserve the original result if the bounded optional retry fails. +pub(crate) fn parse_with_rewrite( + parser: &mut Parser, + source: &str, + rewrite: impl FnOnce(&Tree, &str) -> Option, +) -> Option { + let start = Instant::now(); + let original = parse(parser, source)?; + if !original.root_node().has_error() { + return Some(original); + } + let Some(masked) = rewrite(&original, source) else { return Some(original) }; + if masked.len() != source.len() { + return Some(original); + } + let limit = TIMEOUT.with(|c| c.get()); + let remaining = match limit { + Some(limit) => match limit.checked_sub(start.elapsed()) { + Some(left) if !left.is_zero() => Some(left), + _ => return Some(original), + }, + None => None, + }; + TIMEOUT.with(|c| c.set(remaining)); + let retry = parse(parser, &masked); + TIMEOUT.with(|c| c.set(limit)); + if let Some(tree) = retry.filter(|t| !t.root_node().has_error()) { + return Some(tree); + } + TIMED_OUT.with(|c| c.set(false)); + STASH.with(|s| *s.borrow_mut() = Some(original.clone())); + Some(original) +} + /// The tree-sitter grammar the kernel uses for `lang` (tests and dev tools; the facts /// extractor never needs it because it reuses the kernel's tree). pub fn language(lang: &str) -> Option { diff --git a/crates/cg-kernel/src/tsjs/extractors.rs b/crates/cg-kernel/src/tsjs/extractors.rs index 6ebdb88..4d137ec 100644 --- a/crates/cg-kernel/src/tsjs/extractors.rs +++ b/crates/cg-kernel/src/tsjs/extractors.rs @@ -1670,13 +1670,13 @@ impl<'t> Walker<'t> { let recv_ident = receiver.filter(|r| { matches!(r.kind(), "identifier" | "simple_identifier" | "field_identifier") }); - if let Some(r) = recv_ident { + if let Some(r) = receiver.filter(|r| matches!(r.kind(), "this" | "super")) { + // Preserve the receiver: an unrelated bare function of the + // same name cannot stand in for `this.m()` or `super.m()`. + callee_name = format!("{}.{method_name}", self.text(r)); + } else if let Some(r) = recv_ident { let receiver_name = self.text(r); - if !matches!(receiver_name, "self" | "this" | "cls" | "super") { - callee_name = format!("{receiver_name}.{method_name}"); - } else { - callee_name = method_name.to_string(); - } + callee_name = format!("{receiver_name}.{method_name}"); } else if receiver.is_some_and(|r| self.is_unresolved_member_chain(r)) { // Retain the call site for effects without guessing a // project method. Mirrors the TS extraction path. @@ -1715,10 +1715,9 @@ impl<'t> Walker<'t> { }; // `new this.constructor().copy(this)`, a static // `new this().init()`: an instance of the enclosing - // class keeps the bare method name, as a call on - // `this` does. + // class keeps the enclosing receiver. callee_name = if ctor == "this" || ctor == "this.constructor" { - method_name.to_string() + format!("this.{method_name}") } else { format!("new {ctor}().{method_name}") }; diff --git a/crates/cg-kernel/src/tsjs/mod.rs b/crates/cg-kernel/src/tsjs/mod.rs index 7707a47..8632871 100644 --- a/crates/cg-kernel/src/tsjs/mod.rs +++ b/crates/cg-kernel/src/tsjs/mod.rs @@ -11,6 +11,7 @@ mod extractors; mod fnref; +mod variance; use crate::textutil as util; use crate::buffers::{ @@ -232,7 +233,11 @@ pub fn extract(file_path: &str, source: &str, language: &str) -> Result usize { + while i < end { + if bytes[i].is_ascii_whitespace() { + i += 1; + } else if bytes[i..end].starts_with(b"/*") { + let Some(close) = bytes[i + 2..end].windows(2).position(|w| w == b"*/") else { return end }; + i += close + 4; + } else if bytes[i..end].starts_with(b"//") { + i += 2; + while i < end && bytes[i] != b'\n' { i += 1; } + } else { + break; + } + } + i +} + +fn ident_end(bytes: &[u8], start: usize, end: usize) -> usize { + if start >= end || !(bytes[start].is_ascii_alphabetic() || matches!(bytes[start], b'_' | b'$')) { + return start; + } + let mut i = start + 1; + while i < end && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'_' | b'$')) { i += 1; } + i +} + +fn parameter_prefix(bytes: &[u8], start: usize, end: usize, spans: &mut Vec<(usize, usize)>) { + let first = skip_trivia(bytes, start, end); + let first_end = ident_end(bytes, first, end); + if first == first_end || !matches!(&bytes[first..first_end], b"in" | b"out") { return; } + let next = skip_trivia(bytes, first_end, end); + if next == first_end { return; } + let next_end = ident_end(bytes, next, end); + if next == next_end || &bytes[next..next_end] == b"extends" { return; } + if &bytes[first..first_end] == b"in" && &bytes[next..next_end] == b"out" { + let name = skip_trivia(bytes, next_end, end); + let name_end = ident_end(bytes, name, end); + if name == next_end || name == name_end || &bytes[name..name_end] == b"extends" { return; } + spans.push((next, next_end)); + } + spans.push((first, first_end)); +} + +fn find_spans(node: Node<'_>, source: &[u8], spans: &mut Vec<(usize, usize)>) { + let mut pending = vec![node]; + while let Some(n) = pending.pop() { + if !n.has_error() { continue; } + if n.kind() == "type_parameters" + && n.parent().is_some_and(|p| matches!(p.kind(), "interface_declaration" | "class_declaration" | "abstract_class_declaration" | "type_alias_declaration")) + { + let mut cursor = n.walk(); + for child in n.children(&mut cursor) { + if matches!(child.kind(), "<" | ",") { + parameter_prefix(source, child.end_byte(), n.end_byte(), spans); + } + } + } + let mut cursor = n.walk(); + pending.extend(n.named_children(&mut cursor).filter(|c| c.has_error())); + } +} + +pub(super) fn mask(tree: &Tree, source: &str) -> Option { + let mut spans = Vec::new(); + find_spans(tree.root_node(), source.as_bytes(), &mut spans); + if spans.is_empty() { return None; } + let mut bytes = source.as_bytes().to_vec(); + for (start, end) in spans { bytes[start..end].fill(b' '); } + String::from_utf8(bytes).ok() +} diff --git a/crates/cg-resolve/src/engine.rs b/crates/cg-resolve/src/engine.rs index 9649577..719bbab 100644 --- a/crates/cg-resolve/src/engine.rs +++ b/crates/cg-resolve/src/engine.rs @@ -21,6 +21,9 @@ pub enum ExportEntry { Module(FileId), } +type ExportMap<'v> = FxHashMap<&'v str, ExportEntry>; +type FileExports<'v> = (usize, ExportMap<'v>, ExportMap<'v>, Vec); + /// Result of binding a local name through an import. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Bound { @@ -39,6 +42,8 @@ pub struct Engine<'v> { /// Per file (indexed by `FileId`): targets aligned with `view.imports_of(file)`. pub imp_targets: Vec>, pub exports: Vec>, + /// JS/TS type declarations sharing an exported name with a runtime value. + pub type_exports: Vec>, pub stars: Vec>, /// Per package: top-level definitions by name. pub pkg_defs: Vec>>, @@ -115,6 +120,7 @@ impl<'v> Engine<'v> { modules, imp_targets, exports: vec![FxHashMap::default(); n_files], + type_exports: vec![FxHashMap::default(); n_files], stars: vec![Vec::new(); n_files], pkg_defs: Vec::new(), supers: FxHashMap::default(), @@ -182,11 +188,12 @@ impl<'v> Engine<'v> { fn build_exports(&mut self, files: &[FileId]) { let view = self.view; - let results: Vec<(usize, FxHashMap<&'v str, ExportEntry>, Vec)> = files + let results: Vec> = files .par_iter() .map(|&f| { let lang = view.file(f).lang(); let mut map: FxHashMap<&'v str, ExportEntry> = FxHashMap::default(); + let mut types: FxHashMap<&'v str, ExportEntry> = FxHashMap::default(); let mut stars = Vec::new(); let family = lang.family(); // Local definitions @@ -198,9 +205,26 @@ impl<'v> Engine<'v> { }; if exported { let name = node.name(); + if family == LangFamily::Js && node.kind().is_type() { + match types.get(name) { + Some(ExportEntry::Node(prev)) if node.kind() == NodeKind::Class && view.node(*prev).kind() != NodeKind::Class => { + types.insert(name, ExportEntry::Node(n)); + } + Some(_) => {} + None => { + types.insert(name, ExportEntry::Node(n)); + } + } + } match map.get(name) { // class beats interface/type alias for merged declarations - Some(ExportEntry::Node(prev)) if view.node(*prev).kind().is_type() && !node.kind().is_type() => {} + Some(ExportEntry::Node(prev)) + if family == LangFamily::Js + && matches!(view.node(*prev).kind(), NodeKind::Interface | NodeKind::TypeAlias) + && !node.kind().is_type() => + { + map.insert(name, ExportEntry::Node(n)); + } Some(ExportEntry::Node(prev)) if !(node.kind() == NodeKind::Class && view.node(*prev).kind() != NodeKind::Class) => {} _ => { map.insert(name, ExportEntry::Node(n)); @@ -238,7 +262,34 @@ impl<'v> Engine<'v> { } else { // `export { a as b }` / `export default a`: alias of a local definition let local = view.text_str(ex.from_name); - if let Some(n) = self.top_level_nodes(f).find(|n| view.node(*n).name() == local) { + if family == LangFamily::Js { + if let Some(n) = self.top_level_nodes(f).find(|n| view.node(*n).name() == local && view.node(*n).kind().is_type()) { + types.insert(name, ExportEntry::Node(n)); + } + } + let imported = (family == LangFamily::Js) + .then(|| { + view.imports_of(f).iter().enumerate().find(|(_, imp)| view.text_str(imp.local) == local && imp.scope.0 == view.scope_base(f)) + }) + .flatten(); + if let Some((i, imp)) = imported { + if let Some(ImportTarget::File(tf)) = self.imp_targets[f.idx()].get(i).copied() { + let from = view.text_str(imp.imported); + let entry = if imp.kind == ImportKind::Namespace as u8 || from == "*" { + ExportEntry::Module(tf) + } else { + ExportEntry::Re(tf, imp.imported) + }; + map.insert(name, entry); + } + } else if let Some(n) = (family == LangFamily::Js) + .then(|| { + self.top_level_nodes(f) + .find(|n| view.node(*n).name() == local && !matches!(view.node(*n).kind(), NodeKind::Interface | NodeKind::TypeAlias)) + }) + .flatten() + .or_else(|| self.top_level_nodes(f).find(|n| view.node(*n).name() == local)) + { map.insert(name, ExportEntry::Node(n)); } } @@ -263,11 +314,12 @@ impl<'v> Engine<'v> { } } } - (f.idx(), map, stars) + (f.idx(), map, types, stars) }) .collect(); - for (i, m, s) in results { + for (i, m, t, s) in results { self.exports[i] = m; + self.type_exports[i] = t; self.stars[i] = s; } // Rust child modules (`mod x;` -> x.rs) are exports of their parent module @@ -389,15 +441,28 @@ impl<'v> Engine<'v> { // ---------------------------------------------------------------- lookups pub fn lookup_export(&self, f: FileId, name: &str, depth: u8) -> Option { + self.lookup_export_in_space(f, name, depth, false) + } + + pub fn lookup_type_export(&self, f: FileId, name: &str, depth: u8) -> Option { + self.lookup_export_in_space(f, name, depth, true) + } + + fn lookup_export_in_space(&self, f: FileId, name: &str, depth: u8, type_space: bool) -> Option { if depth > 8 || f.idx() >= self.exports.len() { return None; } + if type_space { + if let Some(ExportEntry::Node(n)) = self.type_exports[f.idx()].get(name) { + return Some(Bound::Node(*n)); + } + } if let Some(e) = self.exports[f.idx()].get(name) { match *e { ExportEntry::Node(n) => return Some(Bound::Node(n)), ExportEntry::Module(m) => return Some(Bound::Module(m)), ExportEntry::Re(tf, from) => { - if let Some(b) = self.lookup_export(tf, self.view.text_str(from), depth + 1) { + if let Some(b) = self.lookup_export_in_space(tf, self.view.text_str(from), depth + 1, type_space) { return Some(b); } } @@ -405,7 +470,7 @@ impl<'v> Engine<'v> { } if name != "default" { for &tf in &self.stars[f.idx()] { - if let Some(b) = self.lookup_export(tf, name, depth + 1) { + if let Some(b) = self.lookup_export_in_space(tf, name, depth + 1, type_space) { return Some(b); } } @@ -441,6 +506,14 @@ impl<'v> Engine<'v> { /// Bind the name introduced by an import record. pub fn bind_import(&self, f: FileId, idx: usize) -> Bound { + self.bind_import_in_space(f, idx, false) + } + + pub fn bind_type_import(&self, f: FileId, idx: usize) -> Bound { + self.bind_import_in_space(f, idx, true) + } + + fn bind_import_in_space(&self, f: FileId, idx: usize, type_space: bool) -> Bound { let imp = &self.view.imports_of(f)[idx]; let tgt = self.imp_targets[f.idx()].get(idx).copied().unwrap_or(ImportTarget::External); let imported = self.view.text_str(imp.imported); @@ -463,7 +536,7 @@ impl<'v> Engine<'v> { } return Bound::Unknown; } - if let Some(b) = self.lookup_export(tf, imported, 0) { + if let Some(b) = self.lookup_export_in_space(tf, imported, 0, type_space) { return b; } if let Some(sm) = self.submodule(tf, imported) { diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index cd5dc1b..27cf606 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -466,6 +466,10 @@ impl<'e, 'v> FileCx<'e, 'v> { || b.kind == BindKind::Deref as u8 || b.kind == BindKind::Fixture as u8 || b.kind == BindKind::TypeAlias as u8 + || b.kind == BindKind::FactoryMixin as u8 + || b.kind == BindKind::Mutation as u8 + || b.kind == BindKind::CommonJsObject as u8 + || b.kind == BindKind::AssignedThisCall as u8 { continue; } @@ -569,16 +573,22 @@ impl<'e, 'v> FileCx<'e, 'v> { /// Follow `segs` from a module / type: exports, top-level definitions, submodules, members. fn walk_path(&self, start: Bound, segs: &[&str]) -> Option { + self.walk_path_in_space(start, segs, false) + } + + fn walk_path_in_space(&self, start: Bound, segs: &[&str], type_space: bool) -> Option { let mut cur = start; - for seg in segs { + for (i, seg) in segs.iter().enumerate() { cur = match cur { - Bound::Module(m) => match self.e.lookup_export(m, seg, 0) { - Some(b) => b, - None => match (self.view.file(m).lang().family() != LangFamily::Js).then(|| self.e.lookup_top_level(m, seg)).flatten() { - Some(n) => Bound::Node(n), - None => Bound::Module(self.e.submodule(m, seg)?), - }, - }, + Bound::Module(m) => { + match if type_space && i + 1 == segs.len() { self.e.lookup_type_export(m, seg, 0) } else { self.e.lookup_export(m, seg, 0) } { + Some(b) => b, + None => match (self.view.file(m).lang().family() != LangFamily::Js).then(|| self.e.lookup_top_level(m, seg)).flatten() { + Some(n) => Bound::Node(n), + None => Bound::Module(self.e.submodule(m, seg)?), + }, + } + } Bound::Node(n) => Bound::Node(self.e.direct_member(n, seg).or_else(|| self.e.find_member(n, seg))?), Bound::Pkg(p) => { let n = self.e.pkg_defs.get(p.0 as usize).and_then(|m| m.get(*seg)).and_then(|l| l.iter().find(|n| self.visible(**n, seg)))?; @@ -618,11 +628,11 @@ impl<'e, 'v> FileCx<'e, 'v> { } let segs: Vec<&str> = rest.split(['.', ':']).filter(|s| !s.is_empty()).collect(); match self.resolve_name(wcx, head, Accept::Any, 0, u32::MAX, None, false) { - NameRes::Module(tf) => match self.walk_path(Bound::Module(tf), &segs) { + NameRes::Module(tf) => match self.walk_path_in_space(Bound::Module(tf), &segs, true) { Some(Bound::Node(n)) => TypeRes::Node(n), _ => TypeRes::Unknown, }, - NameRes::Pkg(p) => match self.walk_path(Bound::Pkg(p), &segs) { + NameRes::Pkg(p) => match self.walk_path_in_space(Bound::Pkg(p), &segs, true) { Some(Bound::Node(n)) => TypeRes::Node(n), _ => TypeRes::Unknown, }, @@ -1620,6 +1630,11 @@ impl<'e, 'v> FileCx<'e, 'v> { return NameRes::Found(b.node, by::LEXICAL, 98); } if b.kind == BindKind::LocalFn as u8 { + if self.family == LangFamily::Js { + // Without the declaration's exact node, a same-named function in + // another closure is not evidence for this binding. + return NameRes::Local; + } // a local function declared in this scope: its node is the same-named nested definition let hit = view.by_name(name).find(|n| view.hot(*n).file == self.file && matches!(kind_of(view, *n), NodeKind::Function | NodeKind::Method)); if let Some(n) = hit { @@ -1637,7 +1652,7 @@ impl<'e, 'v> FileCx<'e, 'v> { } // 3. import binding if let Some(i) = self.visible_import(name, scope) { - match e.bind_import(self.file, i as usize) { + match if accept == Accept::Type { e.bind_type_import(self.file, i as usize) } else { e.bind_import(self.file, i as usize) } { Bound::Node(n) => { if accept.ok(kind_of(view, n)) || accept == Accept::Any { return NameRes::Found(n, by::IMPORT, 95); @@ -1665,12 +1680,6 @@ impl<'e, 'v> FileCx<'e, 'v> { Bound::Unknown => {} } } - // JS / TS: `this.method()` is emitted as a bare `method`; an explicit import wins over it - if accept != Accept::Type && self.family == LangFamily::Js { - if let Some(m) = self.enclosing_member(wcx, from, name, args) { - return NameRes::Found(m, by::RECEIVER, 88); - } - } // 4. same file let bare_callable = accept == Accept::Callable; let mut same: SmallVec<[NodeIdx; 4]> = SmallVec::new(); @@ -1782,6 +1791,11 @@ impl<'e, 'v> FileCx<'e, 'v> { /// Method of an untyped receiver: only when the name is unique in the language family. fn fallback_method(&self, method: &str) -> Outcome { + // A unique property name does not identify an arbitrary JavaScript receiver. + // `router.use()` and `app.use()` can denote completely unrelated objects. + if self.family == LangFamily::Js { + return Outcome::st(status::NO_CANDIDATE); + } if is_common_method(self.family, method) || is_builtin(self.family, method) { return Outcome::st(status::NO_CANDIDATE); } @@ -1813,6 +1827,77 @@ impl<'e, 'v> FileCx<'e, 'v> { } } + /// Express' own factory returns an application with `lib/application.js` mixed in. + /// Resolve only a direct call to that repository's actual exported factory, never + /// an untyped variable or a router merely sharing a method name. + fn express_application_member(&self, b: &BindingRec, method: &str) -> Option { + if self.family != LangFamily::Js { + return None; + } + let init = self.view.text_str(b.init_ctor); + let head = init.strip_suffix("()")?; + if head.is_empty() || head.contains(['.', ':', '(', ')']) { + return None; + } + let scope = b.scope.0.wrapping_sub(self.scope_base); + if self.lookup_binding(head, scope, b.line, false).is_some() { + return None; + } + let i = self.visible_import(head, scope)?; + let factory = match self.e.bind_import(self.file, i as usize) { + Bound::Node(n) => n, + Bound::Module(f) => match self.e.lookup_export(f, COMMONJS_MODULE, 0)? { + Bound::Node(n) => n, + _ => return None, + }, + _ => return None, + }; + let node = self.view.node(factory); + if node.kind() != NodeKind::Function || node.name() != "createApplication" { + return None; + } + let factory_path = self.view.file(node.file()).path(); + let package = self.e.project.packages.iter().find(|p| { + p.name.as_deref() == Some("express") + && factory_path == if p.dir.is_empty() { "lib/express.js".to_owned() } else { format!("{}/lib/express.js", p.dir) } + })?; + let local = self.view.text_str(b.name); + let overridden_member = format!("{local}.{method}"); + if self + .view + .bindings_of(self.file) + .iter() + .any(|fact| fact.kind == BindKind::Mutation as u8 && [local, head, overridden_member.as_str()].contains(&self.view.text_str(fact.name))) + { + return None; + } + let application = if package.dir.is_empty() { "lib/application.js".to_owned() } else { format!("{}/lib/application.js", package.dir) }; + let mixin = self.view.bindings_of(node.file()).iter().find_map(|fact| { + if fact.kind != BindKind::FactoryMixin as u8 || fact.node != factory { + return None; + } + match self.e.modules.resolve_import(self.view.file(node.file()).lang(), self.view.text_str(fact.decl_type), node.file()) { + ImportTarget::File(f) if self.view.file(f).path() == application => Some(f), + _ => None, + } + })?; + let facts = self.view.bindings_of(mixin); + // Only members actually assigned to the exported object qualify. A + // same-named method of another object in the module is not evidence. + let mut candidates = facts.iter().filter(|fact| { + if fact.kind != BindKind::MemberFn as u8 || fact.node.is_none() || self.view.text_str(fact.name) != method { + return false; + } + let object = self.view.text_str(fact.init_ctor); + !object.is_empty() + && facts.iter().any(|b| b.kind == BindKind::CommonJsObject as u8 && self.view.text_str(b.name) == object && b.line <= fact.line) + && !facts.iter().any(|b| b.kind == BindKind::Mutation as u8 && self.view.text_str(b.name) == object) + && facts.iter().filter(|b| b.kind == BindKind::Mutation as u8 && self.view.text_str(b.name) == "module.exports").count() == 1 + }); + let candidate = candidates.next()?.node; + candidates.next().is_none().then_some(candidate) + } + fn in_module(&self, wcx: &mut WorkerCx<'e, 'v>, tf: FileId, path: &[&str], method: &str) -> Outcome { // walk module / type segments; the last segment may be a member of a type reached on the way let mut segs: Vec<&str> = path.to_vec(); @@ -1895,10 +1980,21 @@ impl<'e, 'v> FileCx<'e, 'v> { if !self.view.text_str(b.decl_type).is_empty() { return Outcome::st(status::NO_CANDIDATE); } + if path.is_empty() { + if let Some(member) = self.express_application_member(b, method) { + return Outcome::found(member, by::FRAMEWORK, 90); + } + } // `const api = { run: impl }` at the top of this file: `api.run()` runs `impl` - if self.family == LangFamily::Js && path.is_empty() && b.scope.0 == self.scope_base && Self::is_call(r) { - if let Some(m) = self.e.lookup_top_level(self.file, root).and_then(|n| self.forward_alias_node(wcx, n, Some(method))) { - return Outcome::found(m, by::LEXICAL, 90); + if self.family == LangFamily::Js && path.is_empty() && b.scope.0 == self.scope_base { + if let Some(n) = self.e.lookup_top_level(self.file, root) { + if let Some(m) = self + .e + .direct_member(n, method) + .or_else(|| Self::is_call(r).then(|| self.forward_alias_node(wcx, n, Some(method))).flatten()) + { + return Outcome::found(m, by::LEXICAL, 90); + } } } let init = self.view.text_str(b.init_ctor); @@ -2062,6 +2158,11 @@ impl<'e, 'v> FileCx<'e, 'v> { // in a function given to an ES5 constructor's prototype, `this` is the constructor's object let t = self.enclosing_type(r.from).or_else(|| self.e.proto_owner.get(&r.from).copied().filter(|_| self.family == LangFamily::Js)); let Some(t) = t else { + if self.family == LangFamily::Js && fields.is_empty() { + if let Some(n) = self.assigned_this_member(r, method) { + return Outcome::found(n, by::RECEIVER, 90); + } + } return if fields.is_empty() { self.fallback_method(method) } else { Outcome::st(status::NO_CANDIDATE) }; }; let _ = kw; @@ -2089,6 +2190,35 @@ impl<'e, 'v> FileCx<'e, 'v> { Outcome::st(status::NO_CANDIDATE) } + fn assigned_this_member(&self, r: &RefRec, method: &str) -> Option { + let facts = self.view.bindings_of(self.file); + let call = facts.iter().find(|b| { + b.kind == BindKind::AssignedThisCall as u8 + && b.node == r.from + && b.line == r.line + && self.view.text_str(b.name) == method + && self.view.text_str(b.init_ctor).parse::().ok() == Some(r.col) + })?; + let object = self.view.text_str(call.decl_type); + let from = facts.iter().find(|b| b.kind == BindKind::MemberFn as u8 && b.node == r.from && self.view.text_str(b.init_ctor) == object)?; + if facts.iter().any(|b| b.kind == BindKind::Mutation as u8 && self.view.text_str(b.name) == object) { + return None; + } + let property = format!("{object}.{method}"); + if facts.iter().filter(|b| b.kind == BindKind::Mutation as u8 && self.view.text_str(b.name) == property).count() > 1 { + return None; + } + let mut targets = facts.iter().filter(|b| { + b.kind == BindKind::MemberFn as u8 + && b.node.is_some() + && b.scope == from.scope + && self.view.text_str(b.name) == method + && self.view.text_str(b.init_ctor) == object + }); + let node = targets.next()?.node; + targets.next().is_none().then_some(node) + } + fn call_super(&self, wcx: &mut WorkerCx<'e, 'v>, r: &RefRec, method: &str, args: Option<&CallArgs<'v>>) -> Outcome { let Some(t) = self.enclosing_type(r.from) else { return Outcome::st(status::NO_CANDIDATE) }; for a in self.e.ancestors(t) { @@ -2122,16 +2252,25 @@ impl<'e, 'v> FileCx<'e, 'v> { pub fn resolve_call_name(&self, wcx: &mut WorkerCx<'e, 'v>, r: &RefRec, name: &str) -> Outcome { let args = CallArgs::of(self.view, r); - if self.family != LangFamily::Rust || !name.contains("self") { - return self.call_name_with(wcx, r, name, args.as_ref()); - } - // `self.state.lock()`: `self` is the type the calling method belongs to - let previous = wcx.self_ty.replace(self.enclosing_type(r.from).unwrap_or(NodeIdx(NONE))); - if wcx.self_ty == Some(NodeIdx(NONE)) { - wcx.self_ty = None; + let o = if self.family != LangFamily::Rust || !name.contains("self") { + self.call_name_with(wcx, r, name, args.as_ref()) + } else { + // `self.state.lock()`: `self` is the type the calling method belongs to + let previous = wcx.self_ty.replace(self.enclosing_type(r.from).unwrap_or(NodeIdx(NONE))); + if wcx.self_ty == Some(NodeIdx(NONE)) { + wcx.self_ty = None; + } + let result = self.call_name_with(wcx, r, name, args.as_ref()); + wcx.self_ty = previous; + result + }; + if self.family == LangFamily::Js + && Self::is_call(r) + && o.status == status::RESOLVED + && matches!(kind_of(self.view, NodeIdx(o.target)), NodeKind::Interface | NodeKind::TypeAlias) + { + return Outcome::st(status::NO_CANDIDATE); } - let o = self.call_name_with(wcx, r, name, args.as_ref()); - wcx.self_ty = previous; o } @@ -2139,6 +2278,7 @@ impl<'e, 'v> FileCx<'e, 'v> { match parse_shape(name) { 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::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), Shape::New { class, method } => match self.lookup_type(wcx, class) { diff --git a/crates/cg-scan/src/walk.rs b/crates/cg-scan/src/walk.rs index bee537a..696d596 100644 --- a/crates/cg-scan/src/walk.rs +++ b/crates/cg-scan/src/walk.rs @@ -232,6 +232,7 @@ pub fn find_config_files(root: &Path, config: &ProjectConfig, max_depth: usize) || (name.starts_with("requirements") && name.ends_with(".txt")) }; let mut out = Vec::new(); + let mut ignored_candidates = FxHashSet::default(); let walker = WalkBuilder::new(root).standard_filters(false).follow_links(false).max_depth(Some(max_depth)).build(); for e in walker.flatten() { let Some(rel) = rel_string(root, e.path()) else { continue }; @@ -239,14 +240,31 @@ pub fn find_config_files(root: &Path, config: &ProjectConfig, max_depth: usize) continue; } let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false); - if rules.is_ignored(&rel, is_dir) { - continue; + if !is_dir && !e.file_type().is_some_and(|t| t.is_symlink()) && is_config(e.file_name().to_str().unwrap_or("")) { + if !rules.is_ignored(&rel, false) { + out.push(rel); + } else if !rules.builtin_ignored(&rel, false) { + ignored_candidates.insert(rel); + } } - if !is_dir && is_config(e.file_name().to_str().unwrap_or("")) { - out.push(rel); + } + // A checked-in manifest can be covered by a broad .gitignore intended for + // generated files (for example, `**/package.json`). Source scanning already + // revives tracked-but-ignored files; apply the same policy to configuration. + // Built-in exclusions and explicit cgr excludes still win. Avoid a Git + // subprocess when there are no ignored candidate manifests. + if !ignored_candidates.is_empty() { + for rel in git_tracked_ignored(root) { + if !ignored_candidates.contains(&rel) { + continue; + } + if std::fs::symlink_metadata(root.join(&rel)).is_ok_and(|meta| meta.is_file() && !meta.file_type().is_symlink()) { + out.push(rel); + } } } out.sort(); + out.dedup(); out } diff --git a/crates/cg-sync/src/sync.rs b/crates/cg-sync/src/sync.rs index 1d174fb..ed71a29 100644 --- a/crates/cg-sync/src/sync.rs +++ b/crates/cg-sync/src/sync.rs @@ -282,9 +282,12 @@ fn resolver_fact_sig(view: &View, f: FileId) -> ResolverFactSig { ((b.kind == BindKind::MemberFn as u8 || b.kind == BindKind::ReturnType as u8 || b.kind == BindKind::Fixture as u8 - || b.kind == BindKind::TypeAlias as u8) + || b.kind == BindKind::TypeAlias as u8 + || b.kind == BindKind::FactoryMixin as u8) && b.node.is_some()) || b.kind == BindKind::Deref as u8 + || b.kind == BindKind::Mutation as u8 + || b.kind == BindKind::CommonJsObject as u8 }) .map(|b| { ( @@ -310,6 +313,18 @@ fn export_sig(view: &View, f: FileId) -> ExportSig { v } +/// A local export can forward an imported binding (`import * as z ...; export { z }`). +/// Changing that import changes the exported module even when the export syntax is unchanged. +fn reexported_import_sig(view: &View, f: FileId) -> BTreeSet<(String, String, String, u8, u8)> { + let locals: FxHashSet<&str> = + view.exports_of(f).iter().filter(|e| view.text_str(e.from_spec).is_empty() && e.node.is_none()).map(|e| view.text_str(e.from_name)).collect(); + view.imports_of(f) + .iter() + .filter(|i| i.scope.0 == view.scope_base(f) && locals.contains(view.text_str(i.local))) + .map(|i| (view.text_str(i.local).to_owned(), view.text_str(i.spec).to_owned(), view.text_str(i.imported).to_owned(), i.kind, i.type_only)) + .collect() +} + /// Pair the nodes of a replaced file before and after the edit by identity (kind + qualified /// name + occurrence). A pair whose definition details are unchanged keeps its meaning, so /// references that resolved to the old node can simply point at the new one. @@ -593,7 +608,7 @@ 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) { + if export_sig(&base_view, *f) != export_sig(&view1, *f) || reexported_import_sig(&base_view, *f) != reexported_import_sig(&view1, *f) { export_changed.push(*f); } }