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
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,35 @@ only arrays reached from a recognized router call participate in navigation matc
route configuration remains outside this cross-file rule. Go interface dispatch includes unambiguous promoted methods;
method-set inference remains a bounded static approximation.

Engine rule version 7 adds these resolution rules and synthesis passes, all bounded static rules
that link nothing when a name is ambiguous:

- **Go**: embedded standard-library types take part in interface satisfaction (the `io.Reader`,
`*os.File`, `error`, ... method table is ported from upstream) and other outside embeds are
opaque; a project embedding the kernel writes without its package binds through the written
qualifier; func-field dispatch (`d.refreshf()` reaches the functions put in the field, through one
field-to-field copy); protoc `Unimplemented*Server` stubs reach hand-written servers; Gin's
`Context.Next` reaches registered middleware.
- **TS/JS**: calls through `const local = other` and `export const alias = realImpl` reach the
real function, as do object-literal members (`api.run()`); conditional / `??` / `||` arms of
module-level values (`const-alias`); ES5 constructors with `prototype` methods and
`util.inherits` / `Object.create` inheritance; ambient modules declared with `declare module 'x'`
in `.d.ts` files; Redux thunk `dispatch` chains and RTK Query generated hooks.
- **Rust**: generic parameters resolve through their trait bounds (an unbounded parameter no longer
matches a project type of the same name); `impl Deref` targets, `type X = Y` aliases and
`Mutex` / `RwLock` lock guards are looked through; `self.field` call chains are evaluated.
- **Python**: factories returning different classes in different branches are typed by the nearest
common base; `self.x = self.make()` types a field across methods; pytest fixture parameters (same
file or a `conftest.py` above) take the fixture's return type.
- **Cross-language / JVM**: Spring test requests (MockMvc, WebTestClient, TestRestTemplate,
RestAssured) reach routes; Kotlin Multiplatform `expect` reaches each platform's `actual`; a Tauri
frontend's `invoke('cmd')` reaches the registered `#[tauri::command]`; React Native
`NativeModules.X.m()` reaches the Java / Kotlin module's `@ReactMethod`.

Not covered: MyBatis XML, Angular templates, Vue / Svelte ecosystem stores and routers, React Native
events and the Fabric / Expo native side, Tauri events, GoFrame, and Python parameter-type flow
(upstream implements it for Ruby only).

C/C++, C#, PHP, Ruby, Swift and the other upstream language families are outside this version's
supported extraction set. Vue/Svelte-specific extraction is also outside the current scope.

Expand Down
21 changes: 21 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,27 @@ React Router 支持通过导入和转导出使用其他文件中的导出路由
动态路由配置不在此跨文件规则的覆盖范围内。
Go 接口分派包含无歧义的提升方法;方法集推断仍是有界的静态近似。

引擎规则版本 7 补充了以下解析规则与合成边(均为有界的静态规则,歧义时不连):

- **Go**:嵌入的标准库类型参与接口判定(`io.Reader`、`*os.File`、`error` 等方法表移植自上游),
其他外部嵌入类型按"不透明"处理;按书写的包限定绑定内核丢掉限定的项目内嵌入;
func 字段分派(`d.refreshf()` 连到写入该字段的函数,含一层字段间复制);
protoc 生成的 `Unimplemented*Server` 连到手写实现;Gin `Context.Next` 连到注册的中间件。
- **TS/JS**:`const local = other` 与 `export const alias = realImpl` 的调用转发到真实函数,
对象字面量成员(`api.run()`)同样转发;模块级常量的条件 / `??` / `||` 各分支(`const-alias`);
ES5 构造函数及其 `prototype` 方法、`util.inherits` / `Object.create` 继承;
`.d.ts` 中 `declare module 'x'` 声明的环境模块;Redux thunk 的 `dispatch` 链与 RTK Query 生成的 hook。
- **Rust**:泛型参数按 trait 约束解析(无约束的类型参数不再误连同名项目类型);
`impl Deref` 目标类型、`type X = Y` 别名、`Mutex` / `RwLock` 的锁 guard 自动解引用;`self.字段` 调用链求值。
- **Python**:分支返回不同类的工厂函数按最近公共基类类型化;`self.x = self.make()` 跨方法字段流;
pytest fixture 参数(同文件或上级目录 `conftest.py`)取 fixture 的返回类型。
- **跨语言 / JVM**:Spring 测试请求(MockMvc、WebTestClient、TestRestTemplate、RestAssured)连到路由;
Kotlin Multiplatform `expect` 连到各平台 `actual`;Tauri 前端 `invoke('cmd')` 连到已注册的 `#[tauri::command]`;
React Native `NativeModules.X.m()` 连到 Java / Kotlin 模块的 `@ReactMethod`。

尚未覆盖:MyBatis XML、Angular 模板、Vue / Svelte 生态的 store 与路由、React Native 事件与 Fabric/Expo 原生侧、
Tauri 事件、GoFrame,以及 Python 参数类型流(上游仅对 Ruby 实现)。

当前版本暂不支持 C/C++、C#、PHP、Ruby、Swift 等上游语言,也不包含 Vue/Svelte 专用提取逻辑。

## 命令行参考
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 = 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).
Expand Down
166 changes: 157 additions & 9 deletions crates/cg-extract/src/facts/go.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,17 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
// `type A = B` names another type; a defined `type A B` is a type of its own
if let Some(name) = n.child_by_field_name("name") {
let name = cx.text(name).to_owned();
cx.facts.go_types.push(GoTypeFact { name, alias: true, type_params: Vec::new() });
cx.facts.go_types.push(GoTypeFact { name, alias: true, type_params: Vec::new(), func_type: false });
}
}
"composite_literal" => {
field_literal(cx, n);
walk_children(cx, n, scope);
}
"assignment_statement" => {
field_assignment(cx, n);
walk_children(cx, n, scope);
}
"short_var_declaration" => {
let (l, r) = (n.child_by_field_name("left"), n.child_by_field_name("right"));
if let (Some(l), Some(r)) = (l, r) {
Expand Down Expand Up @@ -193,15 +201,35 @@ fn function(cx: &mut Cx, n: Node, scope: u32) {
}

fn type_spec(cx: &mut Cx, n: Node, scope: u32) {
if let (Some(name), Some(tp)) = (n.child_by_field_name("name"), n.child_by_field_name("type_parameters")) {
let params: Vec<String> = kids(tp)
.filter(|d| d.kind() == "type_parameter_declaration")
.flat_map(|d| kids(d).filter(|c| c.kind() == "identifier").map(|c| cx.text(c).to_owned()).collect::<Vec<_>>())
.collect();
let name = cx.text(name).to_owned();
cx.facts.go_types.push(GoTypeFact { name, alias: false, type_params: params });
let ty = n.child_by_field_name("type");
let func_type = ty.is_some_and(|t| t.kind() == "function_type");
if let Some(name) = n.child_by_field_name("name") {
let params: Vec<String> = n
.child_by_field_name("type_parameters")
.map(|tp| {
kids(tp)
.filter(|d| d.kind() == "type_parameter_declaration")
.flat_map(|d| kids(d).filter(|c| c.kind() == "identifier").map(|c| cx.text(c).to_owned()).collect::<Vec<_>>())
.collect()
})
.unwrap_or_default();
if !params.is_empty() || func_type {
let name = cx.text(name).to_owned();
cx.facts.go_types.push(GoTypeFact { name, alias: false, type_params: params, func_type });
}
}
let Some(ty) = ty else { return };
let row = cx.row_at(cx.start(n));
if ty.kind() == "interface_type" {
// embedded interfaces (`io.Reader`, `error`); a union or `~T` constrains, it embeds nothing
for elem in kids(ty).filter(|c| c.kind() == "type_elem") {
let types: Vec<Node> = kids(elem).filter(|c| c.is_named()).collect();
if let ([t], Some(row)) = (types.as_slice(), row) {
embed(cx, row, *t);
}
}
return;
}
let Some(ty) = n.child_by_field_name("type") else { return };
if ty.kind() != "struct_type" {
return;
}
Expand All @@ -219,11 +247,131 @@ fn type_spec(cx: &mut Cx, n: Node, scope: u32) {
// embedded field: promoted fields / methods; named after its type
let simple = tname.rsplit('.').next().unwrap_or("").to_owned();
cx.add_binding(sc, &simple, BindKind::Field, &tname, "embedded", line);
if let (Some(t), Some(row)) = (ftype, row) {
embed(cx, row, t);
}
} else {
let func = ftype.is_some_and(|t| t.kind() == "function_type");
for nm in names {
let t = cx.text(nm).to_owned();
cx.add_binding(sc, &t, BindKind::Field, &tname, "", line);
if let (true, Some(row)) = (func, row) {
cx.facts.go_fields.push(GoFieldFact::FuncField { row, field: t });
}
}
}
}
}

/// Record an embedded type: `io.Reader`, `*os.File`, `Base`, `error`.
fn embed(cx: &mut Cx, row: u32, t: Node) {
let t = match t.kind() {
"pointer_type" | "parenthesized_type" => match t.named_child(0) {
Some(inner) => inner,
None => return,
},
"generic_type" => match t.child_by_field_name("type") {
Some(inner) => inner,
None => return,
},
_ => t,
};
let (qualifier, name) = match t.kind() {
"type_identifier" => (String::new(), cx.text(t).to_owned()),
"qualified_type" => match (t.child_by_field_name("package"), t.child_by_field_name("name")) {
(Some(p), Some(nm)) => (cx.text(p).to_owned(), cx.text(nm).to_owned()),
_ => return,
},
_ => return,
};
cx.facts.go_embeds.push(GoEmbedFact { row, qualifier, name });
}

/// A value a struct field can be given: a name (`h`, `d.refresh`, `pkg.Handle`, `o.opts.F`) or
/// a conversion of one (`HandlerFunc(h.serve)`, kept as written for the linker to check).
fn field_value(cx: &Cx, v: Node) -> Option<String> {
let v = if v.kind() == "literal_element" { v.named_child(0)? } else { v };
match v.kind() {
"identifier" => Some(cx.text(v).to_owned()),
"selector_expression" => {
let text = cx.text(v);
let plain = text.split('.').all(|s| {
let s = s.trim();
s.chars().next().is_some_and(|c| c.is_alphabetic() || c == '_') && s.chars().all(|c| c.is_alphanumeric() || c == '_')
});
(plain && text.split('.').count() <= 3).then(|| text.split_whitespace().collect())
}
"parenthesized_expression" => field_value(cx, v.named_child(0)?),
"call_expression" => {
let callee = v.child_by_field_name("function")?;
let args: Vec<Node> = kids(v.child_by_field_name("arguments")?).filter(|a| a.is_named()).collect();
if !matches!(callee.kind(), "identifier" | "selector_expression") || args.len() != 1 {
return None;
}
let inner = field_value(cx, args[0])?;
Some(format!("{}({inner})", cx.text(callee)))
}
_ => None,
}
}

/// `T{F: v}` / `&T{a, v}`: the values a composite literal puts in the fields of `T`.
fn field_literal(cx: &mut Cx, n: Node) {
let Some(ty) = n.child_by_field_name("type") else { return };
let ty_text = match ty.kind() {
"type_identifier" | "qualified_type" => cx.text(ty).to_owned(),
"generic_type" => match ty.child_by_field_name("type") {
Some(t) => cx.text(t).to_owned(),
None => return,
},
_ => return,
};
let Some(body) = n.child_by_field_name("body") else { return };
for (i, el) in kids(body).filter(|c| c.is_named() && c.kind() != "comment").enumerate() {
let (field, value) = match el.kind() {
"keyed_element" => {
let key = el.child_by_field_name("key").and_then(|k| k.named_child(0));
let Some(key) = key.filter(|k| matches!(k.kind(), "identifier" | "field_identifier")) else { continue };
let Some(value) = el.child_by_field_name("value") else { continue };
(cx.text(key).to_owned(), value)
}
"literal_element" => (format!("#{i}"), el),
_ => continue,
};
let pos = cx.start(value);
if let Some(value) = field_value(cx, value) {
cx.facts.go_fields.push(GoFieldFact::Literal { ty: ty_text.clone(), field, value, line: (pos >> 32) as u32, col: pos as u32 });
}
}
}

/// `x.F = v` / `x.y.F = v`: a value put in field `F` of what `x` (or `x.y`) holds.
fn field_assignment(cx: &mut Cx, n: Node) {
if n.child_by_field_name("operator").map(|o| cx.text(o)) != Some("=") {
return;
}
let (Some(left), Some(right)) = (n.child_by_field_name("left"), n.child_by_field_name("right")) else { return };
let lefts: Vec<Node> = kids(left).filter(|c| c.is_named()).collect();
let rights: Vec<Node> = kids(right).filter(|c| c.is_named()).collect();
if lefts.len() != rights.len() {
return;
}
for (l, r) in lefts.into_iter().zip(rights) {
if l.kind() != "selector_expression" {
continue;
}
let (Some(operand), Some(field)) = (l.child_by_field_name("operand"), l.child_by_field_name("field")) else { continue };
let receiver = match operand.kind() {
"identifier" => cx.text(operand).to_owned(),
"selector_expression" => match (operand.child_by_field_name("operand"), operand.child_by_field_name("field")) {
(Some(o), Some(f)) if o.kind() == "identifier" => format!("{}.{}", cx.text(o), cx.text(f)),
_ => continue,
},
_ => continue,
};
if let Some(value) = field_value(cx, r) {
let pos = cx.start(r);
cx.facts.go_fields.push(GoFieldFact::Assign { receiver, field: cx.text(field).to_owned(), value, line: (pos >> 32) as u32, col: pos as u32 });
}
}
}
Loading
Loading