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
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,8 @@ and project configuration; this is a static code graph rather than a full compil

### Framework and dynamic-dispatch rules

Route hooks are implemented for **Express, Flask, FastAPI, Django, Gin, Spring, Axum and Next.js**.
Route hooks are implemented for **Express, Flask, FastAPI, Django, Gin, Spring, Axum, Next.js,
NestJS, React Router and TanStack Router**.
Framework detection uses project manifests, so route coverage can differ when dependencies are
absent or when indexing a framework's own repository. The benchmark documents observed gaps.

Expand All @@ -241,6 +242,15 @@ event-emitter handlers, React re-render links and JSX parent/child links. These
heuristics with recorded provenance; they cover specific patterns rather than arbitrary
runtime behavior.

For NestJS, literal `RouterModule.register` paths and a literal `setGlobalPrefix` on a
recognizable `NestFactory.create` application are composed for HTTP-client matching, including
statically readable exclusions. Route node names remain controller-local. For React Router,
exported route-object arrays can be consumed across imports and re-exports, including literal
parent routes and `children` arrays. Candidate route nodes are retained for exported arrays;
only arrays reached from a recognized router call participate in navigation matching. Dynamic
route configuration remains outside this cross-file rule. Go interface dispatch includes unambiguous promoted methods;
method-set inference remains a bounded static approximation.

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
9 changes: 8 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,12 +209,19 @@ MCP 服务运行且启用监听时,会在防抖后自动同步源码变化。

### 框架与动态分派规则

已实现 **Express、Flask、FastAPI、Django、Gin、Spring、Axum、Next.js** 的路由提取 hook。
已实现 **Express、Flask、FastAPI、Django、Gin、Spring、Axum、Next.js、NestJS、React Router 和 TanStack Router** 的路由提取 hook。
框架检测依赖项目清单,因此缺失依赖声明或索引框架自身仓库时,路由覆盖可能不同;实测文档记录了已观察到的差异。

合成边规则覆盖接口与实现分派、Go 结构化接口、事件发射器处理函数、React 重新渲染、JSX 父子组件关系等模式。
这些规则带有来源信息和数量限制,属于针对特定模式的启发式分析,不覆盖任意运行时行为。

NestJS 中,可静态读取的 `RouterModule.register` 路径和由 `NestFactory.create` 创建的应用上的字面量
`setGlobalPrefix`(包括可读取的排除项)会参与 HTTP 客户端匹配;路由节点名称仍使用控制器内的路径。
React Router 支持通过导入和转导出使用其他文件中的导出路由数组,包括字面量父路由和 `children` 数组。
索引会保留导出数组的候选路由节点,但只有被已识别的路由器调用使用的数组才参与导航匹配。
动态路由配置不在此跨文件规则的覆盖范围内。
Go 接口分派包含无歧义的提升方法;方法集推断仍是有界的静态近似。

当前版本暂不支持 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 = 5;
pub const ENGINE_VERSION: u32 = 6;
/// 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
138 changes: 130 additions & 8 deletions crates/cg-resolve/src/frameworks/jsroutes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,10 @@ re!(capital_tag_re, r"<\s*([A-Z][\w.]*)");
re!(wrapper_re, r"^(?:Suspense|ErrorBoundary|\w*(?:Guard|Provider|Wrapper|Route)|(?:Protected|Private|Auth|Require\w*)\w*)$");
re!(router_element_re, r"^(?:Browser|Hash|Memory|Native|Static|History|unstable_History)?Router$");
re!(router_call_re, r"\b(?:createBrowserRouter|createHashRouter|createMemoryRouter|createRoutesFromElements|useRoutes)\b");
re!(route_array_re, r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)(?:\s*:\s*[^=;\n]+)?\s*=\s*\[");
re!(default_route_array_re, r"\bexport\s+default\s*\[");
re!(route_table_call_re, r"\b(?:createBrowserRouter|createHashRouter|createMemoryRouter|useRoutes)\s*\(");
re!(route_table_name_re, r"^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?$");

/// The component an `element` renders: the first tag that is no guard, provider or outlet.
fn element_component(value: &str) -> Option<String> {
Expand Down Expand Up @@ -411,7 +415,11 @@ impl<'a> RrScan<'a> {
while j > 0 && self.b[j - 1].is_ascii_whitespace() {
j -= 1;
}
&self.s[j.saturating_sub(12)..j]
let mut start = j.saturating_sub(12);
while !self.s.is_char_boundary(start) {
start += 1;
}
&self.s[start..j]
}

/// One syntactic unit starting at `at`: a string, a JSX element, a bracketed group or one
Expand All @@ -438,16 +446,22 @@ impl<'a> RrScan<'a> {
return at + 1;
}
b'{' | b'[' | b'(' => {}
_ => return at + 1,
_ => return at + self.s[at..].chars().next().map_or(1, char::len_utf8),
}
let close = match c {
b'{' => b'}',
b'[' => b']',
_ => b')',
};
let routers_call = c == b'(' && self.s[at.saturating_sub(48)..at].trim_end().ends_with(|ch: char| ch.is_alphanumeric()) && {
let before = self.s[at.saturating_sub(48)..at].trim_end();
before.ends_with("createRoutesFromElements") || before.ends_with("createRoutesFromChildren")
let mut before_start = at.saturating_sub(48);
while !self.s.is_char_boundary(before_start) {
before_start += 1;
}
let routers_call = c == b'(' && self.s[before_start..at].trim_end().ends_with(|ch: char| ch.is_alphanumeric()) && {
let before = self.s[before_start..at].trim_end();
["createRoutesFromElements", "createRoutesFromChildren", "createBrowserRouter", "createHashRouter", "createMemoryRouter", "useRoutes"]
.iter()
.any(|name| before.ends_with(name))
};
let mut fields: Vec<(&'a str, &'a str, usize)> = Vec::new();
let mut i = at + 1;
Expand Down Expand Up @@ -650,6 +664,10 @@ impl<'a> RrScan<'a> {
}
i += 1;
while i < self.b.len() {
if !self.s.is_char_boundary(i) {
i += 1;
continue;
}
if self.s[i..].starts_with("</") {
let end = self.s[i + 2..].find('>').map_or(self.b.len(), |e| i + 2 + e + 1);
return close(self, end);
Expand All @@ -670,6 +688,10 @@ impl<'a> RrScan<'a> {

/// The routes a file's own text declares (upstream `scanRoutes` for one file).
pub fn scan_react_router(rel: &str, src: &str) -> Vec<Route> {
scan_react_router_detailed(rel, src).into_iter().map(|(route, _)| route).collect()
}

fn scan_react_router_detailed(rel: &str, src: &str) -> Vec<(Route, bool)> {
let objects = router_call_re().is_match(src);
if !objects && !src.contains("<Route") {
return Vec::new();
Expand Down Expand Up @@ -723,10 +745,110 @@ pub fn scan_react_router(rel: &str, src: &str) -> Vec<Route> {
}
let line = line_at(src, s.at);
let handlers = s.component.iter().map(|c| Handler { name: c.clone(), line, col: 0 }).collect();
out.push(Route { method: String::new(), path, line, handlers, ref_kind: RefKind::Edge(EdgeKind::References), router: Some("react-router") });
let absolute = around(s.start, s.end).into_iter().chain(std::iter::once(*s)).any(|o| o.part.as_deref().is_some_and(|p| p.starts_with('/')));
out.push((
Route { method: String::new(), path, line, handlers, ref_kind: RefKind::Edge(EdgeKind::References), router: Some("react-router") },
absolute,
));
}
out.sort_by_key(|r| r.0.line);
out.dedup_by(|a, b| a.0.path == b.0.path && a.0.line == b.0.line);
out
}

/// Route-object arrays declared separately from the router that consumes them. The nodes are
/// candidates: navigation uses them only after an actual router call resolves to this binding.
fn route_arrays(src: &str) -> Vec<(String, usize, usize)> {
let mut arrays = Vec::new();
for cap in route_array_re().captures_iter(src) {
let open = cap.get(0).unwrap().end() - 1;
if let Some(close) = match_bracket(src, open) {
arrays.push((cap[1].to_owned(), open, close));
}
}
for hit in default_route_array_re().find_iter(src) {
let open = hit.end() - 1;
if let Some(close) = match_bracket(src, open) {
arrays.push(("#default".to_owned(), open, close));
}
}
arrays
}

pub fn scan_react_tables(rel: &str, src: &str) -> Vec<(String, Route, bool)> {
if !src.contains("export") {
return Vec::new();
}
let mut out = Vec::new();
for (name, open, close) in route_arrays(src) {
let wrapped = format!("createBrowserRouter({})", &src[open..=close]);
let line_offset = line_at(src, open) - 1;
for (mut route, absolute) in scan_react_router_detailed(rel, &wrapped) {
route.line += line_offset;
for handler in &mut route.handlers {
handler.line += line_offset;
}
route.router = Some("react-router-table");
out.push((name.clone(), route, absolute));
}
}
out
}

/// A reference to an array used as the router's input or a route object's children.
pub struct ReactTableUse {
pub owner: String,
pub name: String,
pub prefix: String,
pub absolute: bool,
}

fn react_refs(expr: &str, owner: &str, prefix: &str, absolute: bool, out: &mut Vec<ReactTableUse>, depth: u8) {
if depth > 16 {
return;
}
let expr = expr.trim();
let name = expr.strip_prefix("...").unwrap_or(expr).trim();
if route_table_name_re().is_match(name) {
out.push(ReactTableUse { owner: owner.to_owned(), name: name.to_owned(), prefix: prefix.to_owned(), absolute });
return;
}
if expr.starts_with('[') && match_bracket(expr, 0) == Some(expr.len() - 1) {
let body = &expr[1..expr.len() - 1];
let mut start = 0;
while start < body.len() {
let end = super::href::index_at_depth0(body, b',', start).unwrap_or(body.len());
react_refs(&body[start..end], owner, prefix, absolute, out, depth + 1);
start = end + 1;
}
} else if expr.starts_with('{') && match_bracket(expr, 0) == Some(expr.len() - 1) {
let part = match object_field(expr, "path") {
Some(p) => match literal(p) {
Some(p) => p,
None => return,
},
None => String::new(),
};
let is_absolute = absolute || part.starts_with('/');
let path = compose_route_path(&[prefix, &part]);
if let Some(children) = object_field(expr, "children") {
react_refs(children, owner, &path, is_absolute, out, depth + 1);
}
}
}

pub fn react_table_uses(src: &str) -> Vec<ReactTableUse> {
let mut out = Vec::new();
for m in route_table_call_re().find_iter(src) {
if let Some(first) = crate::synth::scan::call_args(src, m.end() - 1).and_then(|args| args.first().copied()) {
react_refs(first, "", "", false, &mut out, 0);
}
}
if src.contains("export") {
for (name, open, close) in route_arrays(src) {
react_refs(&src[open..=close], &name, "", false, &mut out, 0);
}
}
out.sort_by_key(|r| r.line);
out.dedup_by(|a, b| a.path == b.path && a.line == b.line);
out
}

Expand Down
25 changes: 25 additions & 0 deletions crates/cg-resolve/src/frameworks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
pub mod href;
pub mod jsroutes;
pub mod nav;
pub mod nest;
pub mod routes;

use crate::project::ProjectInfo;
Expand All @@ -29,6 +30,9 @@ pub fn hooks(project: &ProjectInfo) -> Vec<Arc<dyn FileHook>> {
if frameworks.iter().any(|f| f == "next") {
v.push(Arc::new(nav::ProxyScanner));
}
if frameworks.iter().any(|f| f == "nestjs") {
v.push(Arc::new(nest::NestScanner));
}
for name in frameworks {
let fw = match name.as_str() {
"express" => Framework::Express,
Expand All @@ -48,3 +52,24 @@ pub fn hooks(project: &ProjectInfo) -> Vec<Arc<dyn FileHook>> {
}
v
}

/// Resolve a JS binding using the project's import/export tables, including barrel exports.
pub(crate) fn js_symbol(e: &crate::engine::Engine<'_>, file: cg_core::FileId, name: &str) -> Option<cg_core::NodeIdx> {
use crate::engine::Bound;
let view = e.view;
let (head, tail) = name.split_once('.').map_or((name, None), |(h, t)| (h, Some(t)));
if head.is_empty() || !head.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$') {
return None;
}
if let Some(i) = view.imports_of(file).iter().position(|imp| view.text_str(imp.local) == head) {
return match (e.bind_import(file, i), tail) {
(Bound::Node(n), None) => Some(n),
(Bound::Module(f), Some(member)) if !member.contains('.') => match e.lookup_export(f, member, 0) {
Some(Bound::Node(n)) => Some(n),
_ => None,
},
_ => None,
};
}
tail.is_none().then(|| e.lookup_top_level(file, head)).flatten()
}
83 changes: 82 additions & 1 deletion crates/cg-resolve/src/frameworks/nav.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use super::href::{self, app_root_for, match_bracket, object_field, parse_href_ex
use super::jsroutes::next_route_of;
use crate::engine::Engine;
use crate::synth::scan::{call_args, enclosing_row, is_minified, local_initializer, mid_chain, LineIndex, FN_KINDS};
use crate::synth::sites::{PASS_NAV, PASS_PROXY};
use crate::synth::sites::{PASS_NAV, PASS_PROXY, PASS_REACT_TABLE};
use crate::synth::Out;
use cg_core::{EdgeKind, FileId, Lang, LangFamily, NodeIdx, NodeKind, NONE};
use cg_extract::{FileHook, HookCtx, HookOut, SiteFact};
Expand Down Expand Up @@ -162,6 +162,45 @@ struct Tables {
tanstack: RootedTables,
}

/// An anonymous `export default [...]` has no kernel symbol. Follow export aliases to its
/// persisted table sites instead of guessing a same-named declaration in another file.
fn exported_react_table(e: &Engine<'_>, f: FileId, name: &str, depth: u8) -> Option<(FileId, String)> {
use crate::engine::{Bound, ExportEntry};
if depth > 8 {
return None;
}
let view = e.view;
if let Some(Bound::Node(n)) = e.lookup_export(f, name, 0) {
let node = view.node(n);
return Some((node.file(), node.name().to_owned()));
}
if let Some(ExportEntry::Re(target, from)) = e.exports.get(f.idx())?.get(name) {
return exported_react_table(e, *target, view.text_str(*from), depth + 1);
}
if name == "default"
&& view.sites_of(f).iter().any(|s| {
s.pass == PASS_REACT_TABLE
&& ((s.role == 0 && view.text_str(cg_core::StrId(s.key_a)) == "#default")
|| (s.role == 1 && view.text_str(cg_core::StrId(s.key_b)) == "#default"))
})
{
return Some((f, "#default".to_owned()));
}
None
}

fn react_table_binding(e: &Engine<'_>, f: FileId, name: &str) -> Option<(FileId, String)> {
if let Some(n) = super::js_symbol(e, f, name) {
let node = e.view.node(n);
return Some((node.file(), node.name().to_owned()));
}
let (head, member) = name.split_once('.').map_or((name, None), |(a, b)| (a, Some(b)));
let (index, import) = e.view.imports_of(f).iter().enumerate().find(|(_, imp)| e.view.text_str(imp.local) == head)?;
let target = e.modules.target_file(*e.imp_targets.get(f.idx())?.get(index)?)?;
let imported = member.unwrap_or_else(|| e.view.text_str(import.imported));
exported_react_table(e, target, imported, 0)
}

fn route_tables(e: &Engine<'_>) -> Tables {
let view = e.view;
let mut t = Tables { next: RouteTable::default(), next_roots: Vec::new(), react: RootedTables::default(), tanstack: RootedTables::default() };
Expand Down Expand Up @@ -203,6 +242,48 @@ fn route_tables(e: &Engine<'_>) -> Tables {
}
}
}
// Resolve the table argument through imports and re-exports. Candidate arrays that are
// never passed to a router do not become navigation targets.
let mut queue = Vec::new();
for f in view.files() {
for site in view.sites_of(f).iter().filter(|s| s.pass == PASS_REACT_TABLE && s.role == 1 && view.text_str(cg_core::StrId(s.key_b)).is_empty()) {
let name = view.text_str(cg_core::StrId(site.key_a));
let payload = view.text_str(site.payload);
queue.push((f, name.to_owned(), app_root_for(view.file(f).path()).to_owned(), payload.get(1..).unwrap_or("").to_owned(), 0u8));
}
}
let mut activated = FxHashSet::default();
while let Some((f, name, root, prefix, depth)) = queue.pop() {
if depth > 16 {
continue;
}
let Some((decl_file, decl_name)) = react_table_binding(e, f, &name) else { continue };
if !activated.insert((decl_file, decl_name.clone(), root.clone(), prefix.clone())) {
continue;
}
for site in view.sites_of(decl_file).iter().filter(|s| s.pass == PASS_REACT_TABLE) {
let name = view.text_str(cg_core::StrId(site.key_a));
let payload = view.text_str(site.payload);
if site.role == 1 && view.text_str(cg_core::StrId(site.key_b)) == decl_name {
let sub = payload.get(1..).unwrap_or("");
let path = if payload.starts_with('a') { sub.to_owned() } else { href::compose_route_path(&[&prefix, sub.trim_start_matches('/')]) };
queue.push((decl_file, name.to_owned(), root.clone(), path, depth + 1));
} else if site.role == 0 && name == decl_name {
let node = view.node(site.node);
if node.kind() != NodeKind::Route || node.name().ends_with('*') {
continue;
}
let path = if payload == "a" { node.name().to_owned() } else { href::compose_route_path(&[&prefix, node.name().trim_start_matches('/')]) };
let p = if path.len() > 1 { path.trim_end_matches('/') } else { &path };
t.react.add(&root, p, site.node);
let mut segs: Vec<&str> = p.split('/').skip(1).collect();
while segs.len() > 1 && segs.last().is_some_and(|s| s.starts_with(':') && s.ends_with('?')) {
segs.pop();
optional.push((root.clone(), format!("/{}", segs.join("/")), site.node));
}
}
}
}
for (root, path, n) in optional {
if t.react.for_file(&root).is_some_and(|tb| !tb.exact.contains_key(&path)) {
t.react.add(&root, &path, n);
Expand Down
Loading
Loading