Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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。
Expand Down
2 changes: 1 addition & 1 deletion crates/cg-core/src/brand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
44 changes: 44 additions & 0 deletions crates/cg-extract/src/facts/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion crates/cg-extract/src/facts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
47 changes: 47 additions & 0 deletions crates/cg-extract/tests/facts_js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<A> { throw 0; }
function generic<A>(): A { throw 0; }
class Generic<A> { 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;
Expand Down
60 changes: 52 additions & 8 deletions crates/cg-resolve/src/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<NodeIdx>,
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<NodeIdx> {
// 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<NodeIdx> {
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()
}
}

Expand Down Expand Up @@ -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);
}
Expand All @@ -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<ValueType> {
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::<Vec<_>>(), 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<T> is not treated as T.
fn call_value(&self, wcx: &mut WorkerCx<'e, 'v>, callee: &str, scope: u32, line: u32, depth: u8) -> Option<ValueType> {
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading