diff --git a/README.md b/README.md index b58611e..1d902c9 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,14 @@ Extraction records source structure, symbols and references. Resolution uses ava import, receiver-type, module and package information. Coverage depends on language constructs and project configuration; this is a static code graph rather than a full compiler type checker. +TypeScript/TSX factory calls propagate explicit named return types from function declarations, +variable-initialized arrow/function expressions and methods, using the factory's enclosing +declarations and imports. Types declared inside the factory body do not shadow its return +annotation. Union/intersection types, generic substitution, arrays and async/generator wrappers +remain unresolved; an unsupported annotation does not justify guessing a same-named method. +Block-level type shadowing is not modeled. These return rules use engine version 10, so syncing +an older index refreshes its facts and call edges. + ### Framework and dynamic-dispatch rules Route hooks are implemented for **Express, Flask, FastAPI, Django, Gin, Spring, Axum, Next.js, diff --git a/README.zh-CN.md b/README.zh-CN.md index 8495b62..64ebb8e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -210,6 +210,11 @@ MCP 服务运行且启用监听时,会在防抖后自动同步源码变化。 提取阶段记录源码结构、符号和引用;引用解析阶段使用可获得的作用域、导入、接收者类型、模块及包信息。 覆盖度受语言构造和项目配置影响,当前实现是静态代码图谱,不能替代完整编译器的类型检查。 +TypeScript/TSX 工厂调用支持传播函数声明、变量初始化的箭头/函数表达式和方法的显式命名返回类型, +按工厂的外层声明及导入查找目标,函数体内部声明的类型不会遮蔽返回注解。 +联合/交叉类型、泛型替换、数组和 async/generator 包装仍保持未解析;不支持的注解不会作为猜测同名方法的依据。 +普通语句块中的类型遮蔽尚未建模。这些返回规则使用引擎版本 10,同步旧索引时会刷新 facts 和调用边。 + ### 框架与动态分派规则 已实现 **Express、Flask、FastAPI、Django、Gin、Spring、Axum、Next.js、NestJS、React Router 和 TanStack Router** 的路由提取 hook。 diff --git a/crates/cg-core/src/brand.rs b/crates/cg-core/src/brand.rs index 64f0c98..d6cfb16 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 = 9; +pub const ENGINE_VERSION: u32 = 10; /// 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 6eda32a..e4b7327 100644 --- a/crates/cg-extract/src/facts/js.rs +++ b/crates/cg-extract/src/facts/js.rs @@ -512,6 +512,49 @@ fn commonjs_value(cx: &mut Cx, name: &str, value: Node) { cx.facts.exports.push(ExportFact { name: name.to_owned(), node_row, from_spec, from_name, star: false }); } +/// Only nominal return annotations can currently identify a receiver. In +/// particular, do not reuse ts_type_name's union selection or generic erasure. +fn return_type_name(cx: &Cx, n: Node) -> String { + match n.kind() { + "type_annotation" | "parenthesized_type" => n.named_child(0).map(|c| return_type_name(cx, c)).unwrap_or_default(), + "type_identifier" | "nested_type_identifier" => cx.text(n).to_owned(), + _ => String::new(), + } +} + +fn return_annotation(cx: &mut Cx, n: Node, scope: u32) { + let (Some(annotation), Some(row)) = (n.child_by_field_name("return_type"), cx.row_at(cx.start(n))) else { return }; + let mut ty = return_type_name(cx, annotation); + // Calling an async/generator function produces a wrapper, regardless of a + // malformed annotation. Generic parameters must not resolve to a project + // class with the same name, including parameters on an enclosing class. + if kids(n).any(|c| matches!(c.kind(), "async" | "*")) { + ty.clear(); + } + let head = ty.split('.').next().unwrap_or(""); + let mut ancestor = Some(n); + while let Some(node) = ancestor { + if let Some(params) = node.child_by_field_name("type_parameters") { + if kids(params).filter_map(|p| p.child_by_field_name("name")).any(|name| cx.text(name) == head) { + ty.clear(); + break; + } + } + ancestor = node.parent(); + } + cx.facts.bindings.push(BindingFact { + scope, + name: cx.rows.node(row as usize).name().to_owned(), + kind: BindKind::ReturnType, + // Keep an empty fact for unsupported annotations: the resolver must + // distinguish explicit but unknown returns from absent evidence. + decl_type: ty, + init_ctor: String::new(), + line: cx.line(n), + node_row: row, + }); +} + /// `X.prototype` -> `X`. fn prototype_of<'a>(cx: &Cx<'a>, n: Node) -> Option<&'a str> { if n.kind() != "member_expression" || n.child_by_field_name("property").map(|p| cx.text(p)) != Some("prototype") { @@ -596,6 +639,7 @@ fn function(cx: &mut Cx, n: Node, scope: u32) { } } let sc = cx.push_scope(ScopeKind::Function, scope, n); + return_annotation(cx, n, sc); let line = cx.line(n); if let Some(p) = n.child_by_field_name("parameter") { bind_pattern(cx, p, sc, BindKind::Param, "", ""); // single-identifier arrow parameter diff --git a/crates/cg-extract/src/facts/mod.rs b/crates/cg-extract/src/facts/mod.rs index 80c5e11..1a62166 100644 --- a/crates/cg-extract/src/facts/mod.rs +++ b/crates/cg-extract/src/facts/mod.rs @@ -117,7 +117,8 @@ pub enum BindKind { /// This is declaration metadata and must not participate in lexical lookup. MemberFn = 5, /// Return annotation or a bounded inferred return expression, keyed by the - /// function's node. Metadata only; not a lexical binding. + /// function's node. An empty TS fact records an unsupported explicit + /// annotation. Metadata only; not a lexical binding. ReturnType = 6, /// `const local = other`: a name bound to nothing but another name (`init_ctor`). A call /// through it is a call of what the other name is. diff --git a/crates/cg-extract/tests/facts_js.rs b/crates/cg-extract/tests/facts_js.rs index 2db44f0..3e472ec 100644 --- a/crates/cg-extract/tests/facts_js.rs +++ b/crates/cg-extract/tests/facts_js.rs @@ -63,6 +63,53 @@ export class Widget extends Base { assert!(f.scopes.iter().filter(|s| s.kind == ScopeKind::Function).count() >= 3); } +#[test] +fn typescript_return_facts_preserve_unknowns_and_declaration_identity() { + let source = r#"class A {} +function named(): A { return new A(); } +const arrow = (): (A) => new A(); +const expression = function (): ns.A { throw 0; }; +class Factory { + make(): A { return new A(); } +} +function union(): A | Other { throw 0; } +function container(): Promise { throw 0; } +function generic(): A { throw 0; } +class Generic { genericMethod(): A { throw 0; } } +async function asyncFactory(): A { throw 0; } +function* generator(): A { throw 0; } +function unannotated() { return new A(); } +"#; + for (path, lang) in [("returns.ts", Lang::TypeScript), ("returns.tsx", Lang::Tsx)] { + let batch = run(path, source, lang); + assert_eq!(batch.flags & fileflags::PARSE_ERROR, 0); + let rows = batch.rows(); + let facts: Vec<_> = batch.facts.bindings.iter().filter(|b| b.kind == BindKind::ReturnType).collect(); + assert_eq!(facts.len(), 10, "{facts:#?}"); + for (name, expected) in [ + ("named", "A"), + ("arrow", "A"), + ("expression", "ns.A"), + ("make", "A"), + ("union", ""), + ("container", ""), + ("generic", ""), + ("genericMethod", ""), + ("asyncFactory", ""), + ("generator", ""), + ] { + let fact = facts.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("missing {name}: {facts:#?}")); + assert_eq!(fact.decl_type, expected, "{name}"); + assert!(fact.init_ctor.is_empty()); + let node = rows.node(fact.node_row as usize); + assert_eq!(node.name(), name); + assert_eq!(node.start_line(), fact.line); + } + } + let js = run("plain.js", "function make() { return new A(); }", Lang::JavaScript); + assert!(!js.facts.bindings.iter().any(|b| b.kind == BindKind::ReturnType)); +} + #[test] fn typescript_satisfies_preserves_initializer_evidence() { let src = r#"const direct = new Service() satisfies Runner; diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 27cf606..f2e2d60 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -132,29 +132,34 @@ fn lock_method(method: &str) -> bool { ) } -/// A known project type, possibly still inside a standard Rust container. +/// A project type, possibly still inside a standard Rust container, or an +/// explicit return annotation whose receiver we cannot model. /// Keep the container until an operation such as `unwrap` actually removes it. struct ValueType { - node: NodeIdx, + node: Option, wrappers: SmallVec<[StdWrapper; 2]>, } impl ValueType { fn plain(node: NodeIdx) -> Self { - Self { node, wrappers: SmallVec::new() } + Self { node: Some(node), wrappers: SmallVec::new() } + } + + fn unknown() -> Self { + Self { node: None, wrappers: SmallVec::new() } } fn receiver(self) -> Option { // The field cache stores one node, so it cannot preserve wrapper // methods such as Arc::clone. Only method_receiver may autoderef. - self.wrappers.is_empty().then_some(self.node) + self.wrappers.is_empty().then_some(self.node).flatten() } fn method_receiver(&self, method: &str) -> Option { if self.wrappers.contains(&StdWrapper::Pointer) && pointer_method(method) { return None; } - self.wrappers.iter().all(|w| matches!(w, StdWrapper::Pointer | StdWrapper::Guard)).then_some(self.node) + self.wrappers.iter().all(|w| matches!(w, StdWrapper::Pointer | StdWrapper::Guard)).then_some(self.node).flatten() } } @@ -991,6 +996,11 @@ impl<'e, 'v> FileCx<'e, 'v> { let cx = wcx.file_cx(self.e, node.file()); if let Some(b) = self.e.return_types.get(&n) { let rt = self.view.text_str(b.decl_type); + if cx.family == LangFamily::Js { + // TS facts also retain unsupported annotations. Failure to + // resolve one must not enable the unique-member fallback. + return Some(cx.ts_return_value(n, rt).unwrap_or_else(ValueType::unknown)); + } if !rt.is_empty() { return cx.type_value(wcx, rt, receiver, depth + 1); } @@ -999,6 +1009,40 @@ impl<'e, 'v> FileCx<'e, 'v> { cx.type_value(wcx, node.return_type()?, receiver, depth + 1) } + /// TS return facts contain only nominal names. Look in the declaration's + /// enclosing scopes and explicit imports, never another file's same-named + /// class or an unrelated nested declaration. + fn ts_return_value(&self, function: NodeIdx, name: &str) -> Option { + if name.is_empty() || name.len() > 4096 { + return None; + } + let (head, tail) = name.split_once('.').unwrap_or((name, "")); + // The annotation is outside the function body: declarations inside + // that body cannot shadow a type from an enclosing scope or import. + let mut owner = self.view.node(function).parent(); + let mut bound = None; + while let Some(scope) = owner { + let mut candidates = self.view.by_name(head).filter(|n| { + let node = self.view.node(*n); + node.file() == self.file && node.parent() == Some(scope) && Accept::Type.ok(node.kind()) + }); + if let Some(n) = candidates.next() { + if candidates.next().is_some() { + return None; + } + bound = Some(Bound::Node(n)); + break; + } + owner = self.view.node(scope).parent(); + } + let bound = bound.or_else(|| self.visible_import(head, 0).map(|i| self.e.bind_type_import(self.file, i as usize)))?; + let target = if tail.is_empty() { bound } else { self.walk_path_in_space(bound, &tail.split('.').collect::>(), true)? }; + match target { + Bound::Node(n) if self.view.node(n).kind().is_type() => Some(ValueType::plain(n)), + _ => None, + } + } + /// Follow declared return types through a bounded chain. Static methods do /// not implicitly return their owner, and Result is not treated as T. fn call_value(&self, wcx: &mut WorkerCx<'e, 'v>, callee: &str, scope: u32, line: u32, depth: u8) -> Option { @@ -1114,8 +1158,8 @@ impl<'e, 'v> FileCx<'e, 'v> { Some(StdWrapper::Guard) if matches!(method, "unwrap" | "expect" | "unwrap_or_else") => return Some(receiver), _ => {} } - receiver.method_receiver(method)?; - let (m, owner) = self.rust_member(wcx, receiver.node, method)?; + let node = receiver.method_receiver(method)?; + let (m, owner) = self.rust_member(wcx, node, method)?; self.returned_value(wcx, m, Some(owner), depth + 1) } @@ -1968,7 +2012,7 @@ impl<'e, 'v> FileCx<'e, 'v> { if b.kind != BindKind::LocalFn as u8 { return match self.binding_value(wcx, b, 0) { Some(t) if t.method_receiver(method).is_some() => { - let o = self.member_call(wcx, t.node, path, method, 90, call); + let o = self.member_call(wcx, t.method_receiver(method).unwrap(), path, method, 90, call); if o.status == status::RESOLVED { o } else { diff --git a/crates/cg-resolve/tests/typescript_returns.rs b/crates/cg-resolve/tests/typescript_returns.rs new file mode 100644 index 0000000..8c79618 --- /dev/null +++ b/crates/cg-resolve/tests/typescript_returns.rs @@ -0,0 +1,201 @@ +use cg_resolve::{build_seg, IndexOptions}; +use cg_store::{dump, View}; +use std::sync::Arc; + +fn edges(files: &[(&str, &str)]) -> Vec { + let dir = tempfile::tempdir().unwrap(); + for (name, text) in files { + let path = dir.path().join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + let built = build_seg(dir.path(), &IndexOptions { threads: Some(2), ..Default::default() }).unwrap(); + dump::dump_edges(&View::new(Arc::new(built.seg))) +} + +#[test] +fn typescript_factory_annotations_resolve_the_declared_receiver() { + for ext in ["ts", "tsx"] { + let graph = edges(&[ + ("types.ts", "export class A { run() {} }\nexport class B { run() {} }\n"), + ( + "factory.ts", + r#"import { A as Result } from './types'; +import * as types from './types'; +export function make(): Result { return new Result(); } +export const arrow = (): Result => new Result(); +export const expression = function (): types.A { return new Result(); }; +export class Factory { + make(): types.A { return new Result(); } + static build(): Result { return new Result(); } +} +"#, + ), + ("barrel.ts", "export { make as create, arrow, expression, Factory } from './factory';\n"), + ( + &format!("app.{ext}"), + r#"import { A } from './types'; +import { create, arrow, expression, Factory } from './barrel'; +export function direct() { const a = new A(); a.run(); } +export function named() { const a = create(); a.run(); } +export function chained() { create().run(); } +export function fromArrow() { const a = arrow(); a.run(); } +export function fromExpression() { const a = expression(); a.run(); } +export function fromMethod() { const factory = new Factory(); const a = factory.make(); a.run(); } +export function fromStatic() { const a = Factory.build(); a.run(); } +"#, + ), + ]); + for caller in ["direct", "named", "chained", "fromArrow", "fromExpression", "fromMethod", "fromStatic"] { + let prefix = format!("app.{ext}::{caller} -calls-> types.ts::"); + assert!(graph.contains(&format!("{prefix}A::run")), "{caller} missing A.run: {graph:#?}"); + assert!(!graph.contains(&format!("{prefix}B::run")), "{caller} must not reach B.run: {graph:#?}"); + } + } +} + +#[test] +fn nested_factories_keep_their_own_return_annotation() { + let graph = edges(&[( + "app.ts", + r#"class A { run() {} } +class B { run() {} } +export function first() { + function make(): A { return new A(); } + const value = make(); value.run(); +} +export function second() { + function make(): B { return new B(); } + const value = make(); value.run(); +} +export function firstArrow() { + const create = (): A => new A(); + const value = create(); value.run(); +} +export function secondArrow() { + const create = (): B => new B(); + const value = create(); value.run(); +} +"#, + )]); + for (caller, expected, wrong) in [("first", "A", "B"), ("second", "B", "A"), ("firstArrow", "A", "B"), ("secondArrow", "B", "A")] { + assert!(graph.contains(&format!("app.ts::{caller} -calls-> app.ts::{expected}::run")), "{graph:#?}"); + assert!(!graph.contains(&format!("app.ts::{caller} -calls-> app.ts::{wrong}::run")), "{graph:#?}"); + } +} + +#[test] +fn unsupported_factory_returns_do_not_guess_a_unique_member() { + // Only one `run` exists: ambiguity must not hide a global-name fallback. + for (declaration, invocation) in [ + ("function make(): A | Other { throw 0; }", "make()"), + ("function make(): A & Other { throw 0; }", "make()"), + ("function make(): A[] { return []; }", "make()"), + ("function make(): Promise { throw 0; }", "make()"), + ("async function make(): Promise { throw 0; }", "make()"), + ("function* make(): Generator { throw 0; }", "make()"), + ("function make(): External { throw 0; }", "make()"), + ("function make(): unknown { throw 0; }", "make()"), + ("function make(): any { throw 0; }", "make()"), + ("function make(): void {}", "make()"), + ("function make(): never { throw 0; }", "make()"), + ("function make(): A { throw 0; }", "make()"), + ("class Factory { make(): A { throw 0; } }\nconst factory = new Factory();", "factory.make()"), + ] { + let source = format!( + "import {{ External }} from 'external';\nclass A {{ run() {{}} }}\nclass Other {{}}\n{declaration}\nexport function use() {{ const a = {invocation}; a.run(); }}\n" + ); + let graph = edges(&[("app.ts", &source)]); + assert!(!graph.contains(&"app.ts::use -calls-> app.ts::A::run".to_owned()), "{declaration}: {graph:#?}"); + } +} + +#[test] +fn return_names_obey_the_factory_scope_and_imports() { + let graph = edges(&[ + ("unrelated.ts", "export class Missing { unique() {} }\n"), + ( + "app.ts", + r#"class A { run() {} } +export function outer() { + class A { run() {} } + function make(): A { return new A(); } + const a = make(); a.run(); +} +function missing(): Missing { throw 0; } +export function useMissing() { const a = missing(); a.unique(); } +"#, + ), + ]); + assert!(graph.contains(&"app.ts::outer -calls-> app.ts::outer::A::run".to_owned()), "{graph:#?}"); + assert!(!graph.contains(&"app.ts::outer -calls-> app.ts::A::run".to_owned()), "{graph:#?}"); + assert!(!graph.contains(&"app.ts::useMissing -calls-> unrelated.ts::Missing::unique".to_owned()), "{graph:#?}"); +} + +#[test] +fn imported_return_annotations_use_the_type_namespace() { + let graph = edges(&[ + ( + "types.ts", + "export interface Result { run(): void; }\nexport class Wrong { run() {} }\nexport function Result(): Wrong { return new Wrong(); }\n", + ), + ("barrel.ts", "export { Result as Renamed } from './types';\n"), + ( + "factory.ts", + "import { Renamed as ReturnType } from './barrel';\nimport * as types from './barrel';\nexport function named(): ReturnType { throw 0; }\nexport function qualified(): types.Renamed { throw 0; }\n", + ), + ( + "app.ts", + "import { named, qualified } from './factory';\nimport { Renamed } from './barrel';\nexport function fromNamed() { const value = named(); value.run(); }\nexport function fromQualified() { const value = qualified(); value.run(); }\nexport function fromValue() { const value = Renamed(); value.run(); }\n", + ), + ]); + for (caller, target) in [("fromNamed", "Result"), ("fromQualified", "Result"), ("fromValue", "Wrong")] { + let prefix = format!("app.ts::{caller} -calls-> "); + let targets: Vec<_> = graph.iter().filter(|edge| edge.starts_with(&prefix) && edge.ends_with("::run")).collect(); + let expected = format!("{prefix}types.ts::{target}::run"); + assert_eq!(targets, vec![&expected], "{caller}: {graph:#?}"); + } +} + +#[test] +fn function_body_types_do_not_shadow_return_annotations() { + for declaration in ["class Result { run() {} }", "interface Result { run(): void }", "type Result = { run(): void };"] { + // Each body declares the same name as its return annotation, but body + // declarations are not visible in the function's signature. + let factories = format!( + r#"function make(): Result {{ {declaration} throw 0; }} +const arrow = (): Result => {{ {declaration} throw 0; }}; +const expression = function (): Result {{ {declaration} throw 0; }}; +class Factory {{ make(): Result {{ {declaration} throw 0; }} }} +function fromNamed() {{ const value = make(); value.run(); }} +function fromArrow() {{ const value = arrow(); value.run(); }} +function fromExpression() {{ const value = expression(); value.run(); }} +function fromMethod() {{ const factory = new Factory(); const value = factory.make(); value.run(); }} +"# + ); + let nested_factories = factories.replace("Factory", "NestedFactory"); + let source = format!( + r#"import {{ A as Result }} from './types'; +{factories} +export function outer() {{ + class Result {{ run() {{}} }} + {nested_factories} +}} +"# + ); + let graph = edges(&[ + // Two project methods ensure a missing return type cannot pass + // through a unique-member fallback. + ("types.ts", "export class A { run() {} }\nexport class B { run() {} }\n"), + ("app.ts", &source), + ]); + for (scope, target) in [("", "types.ts::A::run"), ("outer::", "app.ts::outer::Result::run")] { + for caller in ["fromNamed", "fromArrow", "fromExpression", "fromMethod"] { + let prefix = format!("app.ts::{scope}{caller} -calls-> "); + let calls: Vec<_> = graph.iter().filter(|edge| edge.starts_with(&prefix) && edge.ends_with("::run")).collect(); + let expected = format!("{prefix}{target}"); + assert_eq!(calls, vec![&expected], "{declaration}, {scope}{caller}: {graph:#?}"); + } + } + } +} diff --git a/crates/cg-sync/tests/typescript_returns.rs b/crates/cg-sync/tests/typescript_returns.rs new file mode 100644 index 0000000..fc81052 --- /dev/null +++ b/crates/cg-sync/tests/typescript_returns.rs @@ -0,0 +1,126 @@ +use cg_resolve::{index_project, IndexOptions}; +use cg_store::{dump, Store}; +use cg_sync::{sync, SyncOptions}; +use std::path::Path; +use std::time::{Duration, SystemTime}; + +fn write(root: &Path, name: &str, source: &str, step: u64) { + let path = root.join(name); + std::fs::write(&path, source).unwrap(); + let stamp = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000 + step); + std::fs::OpenOptions::new().write(true).open(path).unwrap().set_modified(stamp).unwrap(); +} + +fn canonical(root: &Path) -> Vec { + let snap = Store::locate(root).unwrap().open_snapshot().unwrap(); + dump::canonical(&snap.view) +} + +fn assert_target(root: &Path, target: Option<&str>) { + let snap = Store::locate(root).unwrap().open_snapshot().unwrap(); + let edges = dump::dump_edges(&snap.view); + for name in ["A", "B"] { + let edge = format!("app.ts::use -calls-> types.ts::{name}::run"); + assert_eq!(edges.contains(&edge), target == Some(name), "{edge}: {edges:#?}"); + } +} + +#[test] +fn annotation_only_edits_invalidate_consumers_without_full_rebuild() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let opts = IndexOptions { threads: Some(2), ..Default::default() }; + // Keep enough unrelated files/references that a full rebuild cannot hide + // missing consumer invalidation. The factory body stays byte-identical. + for i in 0..40 { + write(root, &format!("filler{i}.ts"), &format!("function helper{i}() {{}}\nexport function other{i}() {{ helper{i}(); }}\n"), 1); + } + write(root, "types.ts", "export class A { run() {} }\nexport class B { run() {} }\n", 1); + write(root, "barrel.ts", "export { make as create } from './factory';\n", 1); + write(root, "app.ts", "import { create } from './barrel';\nexport function use() { const a = create(); a.run(); }\n", 1); + let factory = |annotation: &str| format!("import {{ A, B }} from './types';\nexport function make(){annotation} {{ throw 0; }}\n"); + write(root, "factory.ts", &factory(": A"), 1); + index_project(root, &opts).unwrap(); + assert_target(root, Some("A")); + for (i, (annotation, target)) in [ + (": B", Some("B")), + (": A | B", None), + (": A", Some("A")), + (": Promise", None), + (": A", Some("A")), + ("", None), + (": B", Some("B")), + (": A", Some("A")), + ] + .into_iter() + .enumerate() + { + write(root, "factory.ts", &factory(annotation), 100 + i as u64); + let report = sync(root, &SyncOptions { index: opts.clone(), ..Default::default() }).unwrap(); + assert!(report.full_rebuild.is_none(), "step {i}: {report:?}"); + assert_target(root, target); + let fresh = tempfile::tempdir().unwrap(); + for entry in std::fs::read_dir(root).unwrap() { + let entry = entry.unwrap(); + if entry.path().is_file() { + std::fs::copy(entry.path(), fresh.path().join(entry.file_name())).unwrap(); + } + } + index_project(fresh.path(), &opts).unwrap(); + assert_eq!(canonical(root), canonical(fresh.path()), "step {i}: {annotation}"); + } +} + +#[test] +fn factory_body_type_edits_preserve_the_imported_return_target() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let opts = IndexOptions { threads: Some(2), ..Default::default() }; + // A body declaration is outside the return annotation's scope. Adding, + // renaming or removing it must not redirect an unchanged consumer, even + // when the edit takes the delta path instead of rebuilding the project. + for i in 0..48 { + write(root, &format!("filler{i}.ts"), &format!("function helper{i}() {{}}\nexport function other{i}() {{ helper{i}(); }}\n"), 1); + } + write(root, "types.ts", "export class A { run() {} }\nexport class B { run() {} }\n", 1); + write(root, "app.ts", "import { make } from './factory';\nexport function use() { const a = make(); a.run(); }\n", 1); + let factory = |declaration: &str| format!("import {{ A, B }} from './types';\nexport function make(): A {{\n {declaration}\n throw 0;\n}}\n"); + let assert_imported_target = |root: &Path| { + let snap = Store::locate(root).unwrap().open_snapshot().unwrap(); + let edges = dump::dump_edges(&snap.view); + let targets: Vec<_> = edges.iter().filter(|edge| edge.starts_with("app.ts::use -calls-> ") && edge.ends_with("::run")).map(String::as_str).collect(); + assert_eq!(targets, ["app.ts::use -calls-> types.ts::A::run"], "{edges:#?}"); + }; + write(root, "factory.ts", &factory(""), 1); + index_project(root, &opts).unwrap(); + assert_imported_target(root); + for (i, declaration) in [ + "class A { run() {} }", + "class Local { run() {} }", + "", + "interface A { run(): void; }", + "interface Local { run(): void; }", + "", + "type A = B;", + "type Local = B;", + "", + ] + .into_iter() + .enumerate() + { + write(root, "factory.ts", &factory(declaration), 100 + i as u64); + let report = sync(root, &SyncOptions { index: opts.clone(), ..Default::default() }).unwrap(); + assert!(report.full_rebuild.is_none(), "step {i}: {declaration}: {report:?}"); + assert_imported_target(root); + let fresh = tempfile::tempdir().unwrap(); + for entry in std::fs::read_dir(root).unwrap() { + let entry = entry.unwrap(); + if entry.path().is_file() { + std::fs::copy(entry.path(), fresh.path().join(entry.file_name())).unwrap(); + } + } + index_project(fresh.path(), &opts).unwrap(); + assert_imported_target(fresh.path()); + assert_eq!(canonical(root), canonical(fresh.path()), "step {i}: {declaration}"); + } +}