diff --git a/crates/cg-core/src/brand.rs b/crates/cg-core/src/brand.rs index e6690aa..a568c5e 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 = 7; +pub const ENGINE_VERSION: u32 = 8; /// 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/args.rs b/crates/cg-extract/src/facts/args.rs index d28a8dd..9e7dade 100644 --- a/crates/cg-extract/src/facts/args.rs +++ b/crates/cg-extract/src/facts/args.rs @@ -5,6 +5,7 @@ //! * `T:` - a literal, `new T(..)` or a cast: the static type as written //! * `V:` - a local, parameter or field, typed at resolution from its binding //! * `F:` - `this.`: a field of the enclosing type +//! * `C:` - a call inside `satisfies`, typed from an unambiguous return annotation //! * `#this` - `this` //! * `N` - `null` / `undefined` //! * `L` - a lambda / function literal taking `k` parameters; `L` alone: a method @@ -259,10 +260,14 @@ fn js_type(cx: &Cx, t: Node) -> String { } fn js_shape(cx: &Cx, a: Node) -> String { + js_shape_inner(cx, a, false) +} + +fn js_shape_inner(cx: &Cx, a: Node, in_satisfies: bool) -> String { let typed = |t: &str| format!("T:{t}"); match a.kind() { "string" | "template_string" => typed("string"), - "number" => typed("number"), + "number" => typed(if cx.text(a).ends_with('n') { "bigint" } else { "number" }), "true" | "false" => typed("boolean"), "null" | "undefined" => "N".into(), "this" => "#this".into(), @@ -284,13 +289,20 @@ fn js_shape(cx: &Cx, a: Node) -> String { }; lambda(n) } - "parenthesized_expression" | "non_null_expression" => a.named_child(0).map(|c| js_shape(cx, c)).unwrap_or_else(|| "?".into()), - "as_expression" | "satisfies_expression" => match a.named_child(1).map(|t| js_type(cx, t)) { + "parenthesized_expression" | "non_null_expression" => a.named_child(0).map(|c| js_shape_inner(cx, c, in_satisfies)).unwrap_or_else(|| "?".into()), + "satisfies_expression" => a.named_child(0).map(|c| js_shape_inner(cx, c, true)).unwrap_or_else(|| "?".into()), + "call_expression" if in_satisfies => match a.child_by_field_name("function") { + Some(f) if f.kind() == "identifier" => format!("C:{}", cx.text(f)), + _ => "?".into(), + }, + "as_expression" => match a.named_child(1).map(|t| js_type(cx, t)) { Some(t) if !t.is_empty() => typed(&t), _ => "?".into(), }, "unary_expression" => match a.child_by_field_name("argument") { - Some(o) if o.kind() == "number" && matches!(cx.text(a).as_bytes().first(), Some(b'-' | b'+')) => typed("number"), + Some(o) if o.kind() == "number" && matches!(cx.text(a).as_bytes().first(), Some(b'-' | b'+')) => { + typed(if cx.text(o).ends_with('n') { "bigint" } else { "number" }) + } _ => "?".into(), }, _ => "?".into(), diff --git a/crates/cg-extract/src/facts/js.rs b/crates/cg-extract/src/facts/js.rs index f020b33..491ad92 100644 --- a/crates/cg-extract/src/facts/js.rs +++ b/crates/cg-extract/src/facts/js.rs @@ -151,13 +151,39 @@ fn ts_type_name(cx: &Cx, n: Node) -> String { /// (declared type, initialiser) of a value expression: `new Foo()` -> ("", "Foo"), /// `foo()` -> ("", "foo()"), `x as Foo` -> ("Foo", ""). fn value_info(cx: &Cx, v: Node) -> (String, String) { + value_info_inner(cx, v, false) +} + +fn value_info_inner(cx: &Cx, v: Node, in_satisfies: bool) -> (String, String) { match v.kind() { "new_expression" => { let c = v.child_by_field_name("constructor").map(|c| cx.text(c).to_owned()).unwrap_or_default(); (String::new(), c) } - "await_expression" | "parenthesized_expression" | "non_null_expression" => v.named_child(0).map(|c| value_info(cx, c)).unwrap_or_default(), - "as_expression" | "satisfies_expression" => { + "await_expression" | "parenthesized_expression" | "non_null_expression" => { + v.named_child(0).map(|c| value_info_inner(cx, c, in_satisfies)).unwrap_or_default() + } + // Preserve the operand's evidence, but mark it so an unknown receiver + // cannot be guessed from an unrelated global method. + "satisfies_expression" => { + let (ty, init) = v.named_child(0).map(|c| value_info_inner(cx, c, true)).unwrap_or_default(); + if ty.is_empty() && !init.starts_with(JS_SATISFIES_VALUE) { + (ty, format!("{JS_SATISFIES_VALUE}{init}")) + } else { + (ty, init) + } + } + "identifier" if in_satisfies => (String::new(), format!("{JS_BINDING_ALIAS}{}", cx.text(v))), + "string" | "template_string" if in_satisfies => ("string".into(), String::new()), + "number" if in_satisfies => (if cx.text(v).ends_with('n') { "bigint" } else { "number" }.into(), String::new()), + "true" | "false" if in_satisfies => ("boolean".into(), String::new()), + "unary_expression" if in_satisfies => match v.child_by_field_name("argument") { + Some(n) if n.kind() == "number" && matches!(cx.text(v).as_bytes().first(), Some(b'-' | b'+')) => { + (if cx.text(n).ends_with('n') { "bigint" } else { "number" }.into(), String::new()) + } + _ => Default::default(), + }, + "as_expression" => { let t = v.named_child(1).map(|c| ts_type_name(cx, c)).unwrap_or_default(); (t, String::new()) } diff --git a/crates/cg-extract/src/facts/mod.rs b/crates/cg-extract/src/facts/mod.rs index 8d6707c..d401d43 100644 --- a/crates/cg-extract/src/facts/mod.rs +++ b/crates/cg-extract/src/facts/mod.rs @@ -20,6 +20,13 @@ pub use util::Cx; /// `default` export. The leading NUL keeps it out of ordinary source identifiers. pub const COMMONJS_MODULE: &str = "\0cjs:module.exports"; +/// Marks initializer evidence collected through a TypeScript `satisfies` expression. +pub const JS_SATISFIES_VALUE: &str = "\0js:satisfies:"; + +/// Initializer evidence that names a JavaScript/TypeScript lexical binding. +/// The NUL prefix distinguishes it from a constructor or call path. +pub const JS_BINDING_ALIAS: &str = "\0js:binding:"; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(u8)] pub enum ImportKind { @@ -134,7 +141,7 @@ pub struct BindingFact { /// Declared type, usually reduced to its head (`Foo` -> `Foo`). Rust /// retains generic arguments to distinguish containers and pointer targets. pub decl_type: String, - /// Constructor or bounded initializer call path (`Foo::new().build()`), or empty. + /// Constructor, bounded initializer call path, tagged lexical alias, or empty. pub init_ctor: String, /// 1-based declaration line; the binding is visible from here on (hoisted functions /// are visible throughout their scope and use line 0). diff --git a/crates/cg-extract/tests/facts_js.rs b/crates/cg-extract/tests/facts_js.rs index 950637c..2db44f0 100644 --- a/crates/cg-extract/tests/facts_js.rs +++ b/crates/cg-extract/tests/facts_js.rs @@ -62,3 +62,33 @@ export class Widget extends Base { assert!(f.scopes.iter().any(|s| s.kind == ScopeKind::Class)); assert!(f.scopes.iter().filter(|s| s.kind == ScopeKind::Function).count() >= 3); } + +#[test] +fn typescript_satisfies_preserves_initializer_evidence() { + let src = r#"const direct = new Service() satisfies Runner; +const factory = makeService() satisfies Runner; +const grouped = (new Service() satisfies Runner) satisfies object; +const asserted = (new Service() as Runner) satisfies object; +const cast = new Service() as Runner; +const unknown = externalValue satisfies Runner; +const annotated: Runner = new Service() satisfies object; +class Holder { service = new Service() satisfies Runner; } +"#; + for lang in [Lang::TypeScript, Lang::Tsx] { + let b = run("satisfies.ts", src, lang); + assert_eq!(b.flags & (fileflags::PARSE_ERROR | fileflags::PANICKED), 0, "{:?}", b.errors); + for (name, decl_type, init_ctor) in [ + ("direct", "", "\0js:satisfies:Service"), + ("factory", "", "\0js:satisfies:makeService()"), + ("grouped", "", "\0js:satisfies:Service"), + ("asserted", "Runner", ""), + ("cast", "Runner", ""), + ("unknown", "", "\0js:satisfies:\0js:binding:externalValue"), + ("annotated", "Runner", "\0js:satisfies:Service"), + ("service", "", "\0js:satisfies:Service"), + ] { + let binding = b.facts.bindings.iter().find(|binding| binding.name == name).unwrap(); + assert_eq!((binding.decl_type.as_str(), binding.init_ctor.as_str()), (decl_type, init_ctor), "{lang:?} {name}"); + } + } +} diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 1b5e712..cd5dc1b 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -9,7 +9,7 @@ use crate::modules::{ImportTarget, PkgId}; use crate::overload::{self, ArgTy, CallArgs}; use crate::shape::{parse_shape, split_head, Shape}; use cg_core::{text::pack_pos, EdgeKind, FileId, Lang, LangFamily, NodeIdx, NodeKind, RefKind, Visibility, NONE}; -use cg_extract::facts::COMMONJS_MODULE; +use cg_extract::facts::{COMMONJS_MODULE, JS_BINDING_ALIAS, JS_SATISFIES_VALUE}; use cg_extract::{BindKind, ImportKind, ScopeKind}; use cg_store::{status, BindingRec, ImportRec, RefRec, ScopeRec, View}; use rustc_hash::{FxHashMap, FxHashSet}; @@ -562,7 +562,9 @@ impl<'e, 'v> FileCx<'e, 'v> { /// Binding of a file-level variable called `name` (module singletons such as `app = Flask()`). pub fn file_binding(&self, name: &str) -> Option<&'v BindingRec> { - self.bindings.get(&(0, name)).and_then(|l| l.iter().copied().find(|b| b.kind == BindKind::Local as u8 || b.kind == BindKind::Field as u8)) + self.bindings + .get(&(0, name)) + .and_then(|l| l.iter().copied().find(|b| b.kind == BindKind::Local as u8 || b.kind == BindKind::Field as u8 || b.kind == BindKind::Alias as u8)) } /// Follow `segs` from a module / type: exports, top-level definitions, submodules, members. @@ -695,17 +697,72 @@ impl<'e, 'v> FileCx<'e, 'v> { if let Some(other) = self.lookup_binding(init, scope, b.line, false).filter(|o| !std::ptr::eq(*o, b)) { return self.binding_value(wcx, other, depth + 1); } + if self.visible_import(init, scope).is_some() { + return self.imported_binding_value(wcx, init, scope, depth + 1); + } } // The new variable is not in scope in its own initializer (`let rt = rt()`). - let shadows = init.split(['.', ':', '(']).next() == Some(self.view.text_str(b.name)); + let root = init.strip_prefix(JS_SATISFIES_VALUE).unwrap_or(init); + let root = root.strip_prefix(JS_BINDING_ALIAS).unwrap_or(root); + let shadows = root.split(['.', ':', '(']).next() == Some(self.view.text_str(b.name)); let line = if shadows { b.line.saturating_sub(1) } else { b.line }; self.expression_value(wcx, init, scope, line, depth + 1) } + fn imported_binding_value(&self, wcx: &mut WorkerCx<'e, 'v>, name: &str, scope: u32, depth: u8) -> Option { + if depth >= 16 { + return None; + } + let import = self.visible_import(name, scope)?; + let Bound::Node(node) = self.e.bind_import(self.file, import as usize) else { return None }; + if self.view.node(node).kind().is_type() { + return Some(ValueType::plain(node)); + } + let owner = self.view.hot(node).file; + let cx = wcx.file_cx(self.e, owner); + let binding = cx.file_binding(self.view.node(node).name())?; + cx.binding_value(wcx, binding, depth + 1) + } + + /// Do not guess a member of an unresolved value when an alias leads back + /// to an explicit type or a `satisfies` operand. + fn blocks_member_fallback(&self, wcx: &mut WorkerCx<'e, 'v>, binding: &BindingRec, depth: u8) -> bool { + if depth >= 16 { + return true; + } + let init = self.view.text_str(binding.init_ctor); + if !self.view.text_str(binding.decl_type).is_empty() || init.starts_with(JS_SATISFIES_VALUE) || init.starts_with(JS_BINDING_ALIAS) { + return true; + } + if binding.kind != BindKind::Alias as u8 { + return false; + } + let scope = binding.scope.0.wrapping_sub(self.scope_base); + if let Some(other) = self.lookup_binding(init, scope, binding.line, false) { + return std::ptr::eq(other, binding) || self.blocks_member_fallback(wcx, other, depth + 1); + } + let Some(import) = self.visible_import(init, scope) else { return false }; + let Bound::Node(node) = self.e.bind_import(self.file, import as usize) else { return true }; + let cx = wcx.file_cx(self.e, self.view.hot(node).file); + match cx.file_binding(self.view.node(node).name()) { + Some(other) => cx.blocks_member_fallback(wcx, other, depth + 1), + None => true, + } + } + fn expression_value(&self, wcx: &mut WorkerCx<'e, 'v>, init: &str, scope: u32, line: u32, depth: u8) -> Option { if depth >= 16 { return None; } + if let Some(inner) = init.strip_prefix(JS_SATISFIES_VALUE) { + return self.expression_value(wcx, inner, scope, line, depth + 1); + } + if let Some(name) = init.strip_prefix(JS_BINDING_ALIAS) { + if let Some(binding) = self.lookup_binding(name, scope, line, false) { + return self.binding_value(wcx, binding, depth + 1); + } + return self.imported_binding_value(wcx, name, scope, depth + 1); + } // `A()|B()`: a factory returning different classes in different branches is typed by // the nearest class they all derive from, or not at all if self.family == LangFamily::Python && init.contains('|') { @@ -1153,6 +1210,54 @@ impl<'e, 'v> FileCx<'e, 'v> { ArgTy::Named(self.view.node(t).name().to_owned(), Some(t)) } + /// Recover a primitive return annotation only from a single unambiguous JS callee. + fn primitive_call_arg(&self, wcx: &mut WorkerCx<'e, 'v>, callee: &str, scope: u32, line: u32) -> Option { + if self.family != LangFamily::Js || callee.is_empty() || !callee.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$') { + return None; + } + let NameRes::Found(node, ..) = self.resolve_name(wcx, callee, Accept::Callable, scope, line, None, false) else { return None }; + if self.sibling_overloads(node).len() != 1 { + return None; + } + let (_, ret) = self.view.node(node).signature()?.rsplit_once(':')?; + let ret = ret.trim().trim_end_matches(';').trim(); + matches!(ret, "string" | "number" | "boolean" | "bigint" | "symbol").then(|| self.named_arg(wcx, ret)) + } + + fn binding_arg_type(&self, wcx: &mut WorkerCx<'e, 'v>, b: &BindingRec, depth: u8) -> ArgTy { + if depth >= 16 { + return ArgTy::Unknown; + } + let declared = self.view.text_str(b.decl_type); + if !declared.is_empty() { + return self.named_arg(wcx, declared); + } + let init = self.view.text_str(b.init_ctor); + let satisfied = init.strip_prefix(JS_SATISFIES_VALUE); + let value = satisfied.unwrap_or(init); + let alias = value.strip_prefix(JS_BINDING_ALIAS).or_else(|| (b.kind == BindKind::Alias as u8).then_some(value)); + let scope = b.scope.0.wrapping_sub(self.scope_base); + if let Some(name) = alias { + if let Some(other) = self.lookup_binding(name, scope, b.line, false).filter(|other| !std::ptr::eq(*other, b)) { + return self.binding_arg_type(wcx, other, depth + 1); + } + if let Some(import) = self.visible_import(name, scope) { + if let Bound::Node(node) = self.e.bind_import(self.file, import as usize) { + let cx = wcx.file_cx(self.e, self.view.hot(node).file); + if let Some(other) = cx.file_binding(self.view.node(node).name()) { + return cx.binding_arg_type(wcx, other, depth + 1); + } + } + } + } + if let Some(callee) = satisfied.and_then(|s| s.strip_suffix("()")) { + if let Some(arg) = self.primitive_call_arg(wcx, callee, scope, b.line) { + return arg; + } + } + self.binding_type(wcx, b).map_or(ArgTy::Unknown, |t| self.node_arg(t)) + } + fn arg_type(&self, wcx: &mut WorkerCx<'e, 'v>, shape: &str, scope: u32, r: &RefRec) -> ArgTy { match shape { "?" => ArgTy::Unknown, @@ -1163,16 +1268,15 @@ impl<'e, 'v> FileCx<'e, 'v> { if let Some(t) = shape.strip_prefix("T:") { return self.named_arg(wcx, t); } + if let Some(callee) = shape.strip_prefix("C:") { + return self.primitive_call_arg(wcx, callee, scope, r.line).unwrap_or(ArgTy::Unknown); + } if let Some(v) = shape.strip_prefix("V:") { if let Some(b) = self.lookup_binding(v, scope, r.line, false) { if b.kind == BindKind::LocalFn as u8 { return ArgTy::Lambda(None); } - let dt = self.view.text_str(b.decl_type); - if !dt.is_empty() { - return self.named_arg(wcx, dt); - } - return self.binding_type(wcx, b).map_or(ArgTy::Unknown, |t| self.node_arg(t)); + return self.binding_arg_type(wcx, b, 0); } // a bare field: Java / Kotlin only (JS reads fields through `this.`) return if self.family == LangFamily::Jvm { self.field_arg(wcx, r, v) } else { ArgTy::Unknown }; @@ -1797,9 +1901,13 @@ impl<'e, 'v> FileCx<'e, 'v> { return Outcome::found(m, by::LEXICAL, 90); } } - // An initializer rooted in an explicit external import - // does not justify guessing an unrelated project member. let init = self.view.text_str(b.init_ctor); + // Unknown satisfies operands and their aliases do not + // justify guessing an unrelated project member. + if self.blocks_member_fallback(wcx, b, 0) { + return Outcome::st(status::LOCAL_BINDING); + } + // Neither does an initializer rooted in an external import. let head = init.split(['.', ':', '(']).next().unwrap_or(""); if let Some(i) = self.visible_import(head, scope).filter(|_| self.lookup_binding(head, scope, r.line, false).is_none()) { if self.e.bind_import(self.file, i as usize) == Bound::External { diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index d33b3ab..6b5cf9c 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -77,6 +77,54 @@ export class Widget extends Base { assert!(has(&edges, "src/index.ts -imports-> src/service.ts")); } +#[test] +fn typescript_satisfies_keeps_concrete_call_targets() { + let (_d, view) = project(&[ + ("service.ts", "export interface Runner { run(): void }\nexport class Service { run() {} extra() {} }\nexport function makeService(): Service { return new Service(); }\n"), + ( + "app.ts", + r#"import { Runner, Service, makeService } from './service'; +export function direct() { + const service = new Service() satisfies Runner; + service.run(); + service.extra(); +} +export function factory() { + const service = makeService() satisfies Runner; + service.run(); + service.extra(); +} +export function plainFactory() { + const service = makeService(); + service.run(); + service.extra(); +} +export class Holder { + service = new Service() satisfies Runner; + use() { this.service.run(); this.service.extra(); } +} +export function asserted() { + const service = (new Service() as Runner) satisfies object; + service.run(); +} +"#, + ), + ]); + let edges = dump::dump_edges(&view); + for caller in ["app.ts::direct", "app.ts::Holder::use"] { + for method in ["run", "extra"] { + assert!( + has(&edges, &format!("{caller} -calls-> service.ts::Service::{method}")), + "{caller} must retain the initializer's concrete receiver: {edges:#?}" + ); + } + assert!(!has(&edges, &format!("{caller} -calls-> service.ts::Runner::run")), "satisfies must not replace the receiver with its constraint"); + } + assert!(has(&edges, "app.ts::factory -calls-> service.ts::makeService"), "the factory call itself must be preserved"); + assert!(!has(&edges, "app.ts::factory -calls-> service.ts::Runner::run"), "satisfies must not replace an unknown receiver with its constraint"); + assert!(has(&edges, "app.ts::asserted -calls-> service.ts::Runner::run"), "an inner as assertion still supplies its explicit type"); +} + #[test] fn python_modules_and_self() { let (_d, view) = project(&[ diff --git a/crates/cg-sync/src/sync.rs b/crates/cg-sync/src/sync.rs index 9cb006c..1d174fb 100644 --- a/crates/cg-sync/src/sync.rs +++ b/crates/cg-sync/src/sync.rs @@ -15,7 +15,7 @@ use crate::detect::{diff_view, Diff}; use cg_core::budget::MemBudget; use cg_core::config::ProjectConfig; -use cg_core::{brand, CgError, EdgeKind, FileId, NodeIdx, RefKind, Result, StrId, NONE}; +use cg_core::{brand, CgError, EdgeKind, FileId, LangFamily, NodeIdx, NodeKind, RefKind, Result, StrId, NONE}; use cg_extract::{fileflags, try_extract_stream, BindKind, ExtractConfig, FileBatch}; use cg_resolve::driver::{make_edge, round_of, update_of, FNREF_META}; use cg_resolve::{hooks_for, index_with_guard, resolve_refs, Engine, IndexOptions, Outcome, ProjectInfo, Round_}; @@ -257,6 +257,20 @@ fn defs_of(view: &View, f: FileId) -> BTreeMap> { type ExportSig = Vec<(String, String, String, u8)>; type ResolverFactSig = BTreeSet<(u8, String, String, String, String)>; +type JsValueFactSig = Vec<(u8, String, String, String)>; + +/// Module-level value evidence can be followed through imported aliases. +fn js_value_fact_sig(view: &View, f: FileId) -> JsValueFactSig { + if view.file(f).lang().family() != LangFamily::Js { + return Vec::new(); + } + let scope = view.scope_base(f); + view.bindings_of(f) + .iter() + .filter(|b| b.scope.0 == scope && (b.kind == BindKind::Local as u8 || b.kind == BindKind::Alias as u8)) + .map(|b| (b.kind, view.text_str(b.name).to_owned(), view.text_str(b.decl_type).to_owned(), view.text_str(b.init_ctor).to_owned())) + .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 @@ -545,8 +559,20 @@ pub fn sync_locked(store: &Store, guard: &WriteGuard, root: &Path, opts: &SyncOp let old = if states[i] == DeltaState::Replaced { defs_of(&base_view, *f) } else { BTreeMap::new() }; let new = defs_of(&view1, *f); definitions_changed |= old != new; + if view1.file(*f).lang().family() == LangFamily::Js + && old.keys().chain(new.keys()).any(|key| { + matches!(NodeKind::from_u8(key.kind), Some(NodeKind::Function | NodeKind::Method | NodeKind::Component)) && old.get(key) != new.get(key) + }) + { + // An exported value may depend on a function's return annotation. + export_changed.push(*f); + } let old_facts = if states[i] == DeltaState::Replaced { resolver_fact_sig(&base_view, *f) } else { BTreeSet::new() }; let new_facts = resolver_fact_sig(&view1, *f); + let old_values = if states[i] == DeltaState::Replaced { js_value_fact_sig(&base_view, *f) } else { Vec::new() }; + if old_values != js_value_fact_sig(&view1, *f) { + export_changed.push(*f); + } if old_facts != new_facts { definitions_changed = true; d_names.extend(old_facts.iter().chain(&new_facts).map(|fact| fact.1.clone())); @@ -594,7 +620,27 @@ pub fn sync_locked(store: &Store, guard: &WriteGuard, root: &Path, opts: &SyncOp if !export_changed.is_empty() { let live: Vec = view1.files().collect(); let mut importers: FxHashMap> = FxHashMap::default(); + let mut value_forwarders: FxHashSet = FxHashSet::default(); for g in &live { + if view1.file(*g).lang().family() == LangFamily::Js { + let scope = view1.scope_base(*g); + let values: FxHashSet<&str> = view1 + .bindings_of(*g) + .iter() + .filter(|b| { + b.scope.0 == scope + && (b.kind == BindKind::Local as u8 || b.kind == BindKind::Alias as u8) + && (!view1.text_str(b.decl_type).is_empty() || !view1.text_str(b.init_ctor).is_empty()) + }) + .map(|b| view1.text_str(b.name)) + .collect(); + if engine.exports[g.idx()].values().any(|e| match e { + cg_resolve::ExportEntry::Node(n) if view1.hot(*n).file == *g => values.contains(view1.node(*n).name()), + _ => false, + }) { + value_forwarders.insert(g.0); + } + } let mut srcs: FxHashSet = FxHashSet::default(); for t in &engine.imp_targets[g.idx()] { match t { @@ -646,7 +692,7 @@ pub fn sync_locked(store: &Store, guard: &WriteGuard, root: &Path, opts: &SyncOp .values() .any(|e| matches!(e, cg_resolve::ExportEntry::Re(y, _) | cg_resolve::ExportEntry::Module(y) if y.0 == x)) || base_reexports(*g, x); - if reexports && seen.insert(*g) { + if (reexports || value_forwarders.contains(g)) && seen.insert(*g) { frontier.push(*g); } } diff --git a/crates/cg-sync/tests/incremental.rs b/crates/cg-sync/tests/incremental.rs index abe7593..78570f8 100644 --- a/crates/cg-sync/tests/incremental.rs +++ b/crates/cg-sync/tests/incremental.rs @@ -532,6 +532,46 @@ fn up_to_date_tree_writes_nothing() { assert_eq!(Store::at(root).read_manifest().unwrap().unwrap().generation, m2.generation); } +#[test] +fn typescript_satisfies_receiver_edits_match_full_rebuild() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "service.ts", "export interface Runner { run(): void }\nexport class First { run() {} }\nexport class Second { run() {} }\n", 0); + // Enough independent files and references to exercise a delta rather than + // the small-project or affected-reference full-rebuild fallback. + for i in 0..40 { + write(root, &format!("filler{i}.ts"), &format!("export function filler{i}() {{ helper{i}(); }}\nfunction helper{i}() {{}}\n"), 0); + } + for (step, (expression, target)) in [ + ("new First() satisfies Runner", "First"), + ("new Second() satisfies Runner", "Second"), + ("(new First() as Runner) satisfies object", "Runner"), + ("new First() satisfies Runner", "First"), + ] + .iter() + .enumerate() + { + write( + root, + "app.ts", + &format!( + "import {{ Runner, First, Second }} from './service';\nexport function main() {{\n const service = {expression};\n service.run();\n}}\n" + ), + step as u64 + 1, + ); + if step == 0 { + index_project(root, &opts()).unwrap(); + } else { + let report = sync(root, &SyncOptions { index: opts(), ..Default::default() }).unwrap(); + assert!(report.full_rebuild.is_none(), "must exercise incremental resolution: {report:?}"); + } + let snap = Store::at(root).open_snapshot().unwrap(); + let calls: Vec<_> = dump::dump_edges(&snap.view).into_iter().filter(|edge| edge.starts_with("app.ts::main -calls-> ")).collect(); + assert_eq!(calls, vec![format!("app.ts::main -calls-> service.ts::{target}::run")]); + assert_eq!(canonical_of(root), full_canonical(root), "{expression}"); + } +} + #[test] fn compaction_preserves_live_graph_and_future_sync_without_source_access() { let dir = tempfile::tempdir().unwrap();