From 249dd48142fdbe20027c21937e237cc89b695f28 Mon Sep 17 00:00:00 2001 From: hongtaihu <13541229370@qq.com> Date: Mon, 2 Nov 2026 01:00:50 +0800 Subject: [PATCH] fix: propagate TypeScript factory return annotations Implemented and validated by OpenAI Codex. --- README.md | 5 + README.zh-CN.md | 4 + crates/cg-core/src/brand.rs | 2 +- crates/cg-extract/src/facts/js.rs | 46 ++++++ crates/cg-extract/src/facts/mod.rs | 3 +- crates/cg-extract/tests/facts_js.rs | 47 +++++++ crates/cg-resolve/src/resolve.rs | 60 ++++++-- crates/cg-resolve/tests/typescript_returns.rs | 133 ++++++++++++++++++ crates/cg-sync/tests/typescript_returns.rs | 72 ++++++++++ 9 files changed, 361 insertions(+), 11 deletions(-) create mode 100644 crates/cg-resolve/tests/typescript_returns.rs create mode 100644 crates/cg-sync/tests/typescript_returns.rs diff --git a/README.md b/README.md index 1d83d22..b046e3b 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,11 @@ 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 lexical scope +and imports. Union/intersection types, generic substitution, arrays and async/generator wrappers +remain unresolved; an unsupported annotation does not justify guessing a same-named method. + ### 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 c6c9c90..35ee792 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -207,6 +207,10 @@ MCP 服务运行且启用监听时,会在防抖后自动同步源码变化。 提取阶段记录源码结构、符号和引用;引用解析阶段使用可获得的作用域、导入、接收者类型、模块及包信息。 覆盖度受语言构造和项目配置影响,当前实现是静态代码图谱,不能替代完整编译器的类型检查。 +TypeScript/TSX 工厂调用支持传播函数声明、变量初始化的箭头/函数表达式和方法的显式命名返回类型, +按工厂声明的词法作用域及导入查找目标。联合/交叉类型、泛型替换、数组和 async/generator 包装仍保持 +未解析;不支持的注解不会作为猜测同名方法的依据。 + ### 框架与动态分派规则 已实现 **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 ea99859..e6690aa 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 = 6; +pub const ENGINE_VERSION: u32 = 7; /// 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 b84f524..835bf79 100644 --- a/crates/cg-extract/src/facts/js.rs +++ b/crates/cg-extract/src/facts/js.rs @@ -370,6 +370,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, + }); +} + fn function(cx: &mut Cx, n: Node, scope: u32) { // The kernel labels `obj.method = function method() {}` as a Function. Keep // evidence of the member assignment so an unknown receiver cannot match an @@ -399,6 +442,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 @@ -533,6 +577,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 { let (vt, init) = value_info(cx, v); let dt = if ty.is_empty() { vt } else { ty }; diff --git a/crates/cg-extract/src/facts/mod.rs b/crates/cg-extract/src/facts/mod.rs index f8f974b..3f0bb5b 100644 --- a/crates/cg-extract/src/facts/mod.rs +++ b/crates/cg-extract/src/facts/mod.rs @@ -110,7 +110,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, } diff --git a/crates/cg-extract/tests/facts_js.rs b/crates/cg-extract/tests/facts_js.rs index 950637c..672cfa0 100644 --- a/crates/cg-extract/tests/facts_js.rs +++ b/crates/cg-extract/tests/facts_js.rs @@ -62,3 +62,50 @@ 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_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)); +} diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index a26c563..8397d36 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -109,29 +109,34 @@ enum StdWrapper { Pointer, } -/// 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| *w == StdWrapper::Pointer).then_some(self.node) + self.wrappers.iter().all(|w| *w == StdWrapper::Pointer).then_some(self.node).flatten() } } @@ -739,6 +744,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); } @@ -747,6 +757,38 @@ 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, "")); + let mut owner = Some(function); + 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_import(self.file, i as usize)))?; + let target = if tail.is_empty() { bound } else { self.walk_path(bound, &tail.split('.').collect::>())? }; + 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 { @@ -809,9 +851,9 @@ impl<'e, 'v> FileCx<'e, 'v> { _ => {} } } - receiver.method_receiver(method)?; - let m = self.e.find_member(receiver.node, method)?; - self.returned_value(wcx, m, Some(receiver.node), depth + 1) + let node = receiver.method_receiver(method)?; + let m = self.e.find_member(node, method)?; + self.returned_value(wcx, m, Some(node), depth + 1) } /// Declared type of field `name` of type `t` (through the hierarchy). @@ -1430,7 +1472,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..eabb749 --- /dev/null +++ b/crates/cg-resolve/tests/typescript_returns.rs @@ -0,0 +1,133 @@ +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:#?}"); +} diff --git a/crates/cg-sync/tests/typescript_returns.rs b/crates/cg-sync/tests/typescript_returns.rs new file mode 100644 index 0000000..0fed92a --- /dev/null +++ b/crates/cg-sync/tests/typescript_returns.rs @@ -0,0 +1,72 @@ +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}"); + } +}