From 3aa21ac958bc3ec507ad6b5594287301b98a6339 Mon Sep 17 00:00:00 2001
From: NianJiuZst <3235467914@qq.com>
Date: Sun, 1 Nov 2026 09:11:35 -0600
Subject: [PATCH 1/2] feat: port upstream overload, framework and
dynamic-dispatch resolution
Close the gaps against upstream CodeGraph in three areas.
Types and overloads:
- Calls record their argument shapes (Java, Kotlin, TS/JS) and pick the
overload whose arity and argument types fit, instead of the first declared.
- Java/Kotlin calls on a field receiver (`repo.find()`, `this.repo.find()`)
are typed by the field; same-package Java types resolve through the
package node, so `Token.Tag` names the nested type.
- Go structural interfaces match by method key, parameter/result counts and
types; interface dispatch follows upstream's per-type override pass.
Frameworks:
- Next.js routes named by path with upstream segments; router.push,
redirect and navigation; middleware/proxy matcher coverage.
- React Router and TanStack Router route tables, links and navigation.
- NestJS HTTP, GraphQL, microservice and WebSocket routes.
- Express chained router.route() and cross-file mount prefixes.
- A decorator route's bare handler name falls back to the method it sits on.
Dynamic and cross-boundary calls:
- Callback collections, object registries, HTTP client -> route,
queue job -> consumer, event bus and sockets, Celery tasks, Spring events.
- Synthesized edges merge by (source, target) in upstream pass order.
Engine rule version 5; segment format unchanged. Incremental sync recomputes
the cross-file passes and re-resolves names whose signatures changed.
Minified files are skipped by the new site scanners, and facts compute
columns incrementally so a one-line bundle no longer costs quadratic time.
Co-Authored-By: Claude Opus 5.5
---
crates/cg-core/src/brand.rs | 2 +-
crates/cg-core/src/text.rs | 6 +
crates/cg-extract/src/facts/args.rs | 298 ++++
crates/cg-extract/src/facts/go.rs | 15 +
crates/cg-extract/src/facts/java.rs | 8 +-
crates/cg-extract/src/facts/js.rs | 8 +-
crates/cg-extract/src/facts/kotlin.rs | 4 +
crates/cg-extract/src/facts/mod.rs | 25 +
crates/cg-extract/src/facts/util.rs | 23 +-
crates/cg-resolve/src/engine.rs | 32 +
crates/cg-resolve/src/frameworks/href.rs | 527 ++++++
crates/cg-resolve/src/frameworks/jsroutes.rs | 994 ++++++++++++
crates/cg-resolve/src/frameworks/mod.rs | 26 +-
crates/cg-resolve/src/frameworks/nav.rs | 822 ++++++++++
crates/cg-resolve/src/frameworks/routes.rs | 249 +--
crates/cg-resolve/src/lib.rs | 1 +
crates/cg-resolve/src/overload.rs | 684 ++++++++
crates/cg-resolve/src/project.rs | 6 +
crates/cg-resolve/src/resolve.rs | 367 ++++-
crates/cg-resolve/src/synth/dynamic.rs | 1531 ++++++++++++++++++
crates/cg-resolve/src/synth/go.rs | 321 ++++
crates/cg-resolve/src/synth/mod.rs | 375 +++--
crates/cg-resolve/src/synth/scan.rs | 183 +++
crates/cg-resolve/src/synth/sites.rs | 48 +
crates/cg-resolve/tests/upstream_parity.rs | 393 +++++
crates/cg-store/src/build.rs | 30 +-
crates/cg-sync/src/sync.rs | 4 +-
crates/cg-sync/tests/incremental_parity.rs | 274 ++++
28 files changed, 6960 insertions(+), 296 deletions(-)
create mode 100644 crates/cg-extract/src/facts/args.rs
create mode 100644 crates/cg-resolve/src/frameworks/href.rs
create mode 100644 crates/cg-resolve/src/frameworks/jsroutes.rs
create mode 100644 crates/cg-resolve/src/frameworks/nav.rs
create mode 100644 crates/cg-resolve/src/overload.rs
create mode 100644 crates/cg-resolve/src/synth/dynamic.rs
create mode 100644 crates/cg-resolve/src/synth/go.rs
create mode 100644 crates/cg-resolve/src/synth/scan.rs
create mode 100644 crates/cg-resolve/tests/upstream_parity.rs
create mode 100644 crates/cg-sync/tests/incremental_parity.rs
diff --git a/crates/cg-core/src/brand.rs b/crates/cg-core/src/brand.rs
index 8d42f0e..8740215 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 = 4;
+pub const ENGINE_VERSION: u32 = 5;
/// 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-core/src/text.rs b/crates/cg-core/src/text.rs
index 323124c..574dd89 100644
--- a/crates/cg-core/src/text.rs
+++ b/crates/cg-core/src/text.rs
@@ -63,3 +63,9 @@ pub fn truncate16(s: &str, max_units: usize) -> &str {
pub const fn pack_pos(line: u32, col16: u32) -> u64 {
((line as u64) << 32) | col16 as u64
}
+
+/// Inverse of [`pack_pos`]: (line, utf16 column).
+#[inline]
+pub const fn unpack_pos(pos: u64) -> (u32, u32) {
+ ((pos >> 32) as u32, pos as u32)
+}
diff --git a/crates/cg-extract/src/facts/args.rs b/crates/cg-extract/src/facts/args.rs
new file mode 100644
index 0000000..d28a8dd
--- /dev/null
+++ b/crates/cg-extract/src/facts/args.rs
@@ -0,0 +1,298 @@
+//! Argument shapes of call sites, for overload selection (upstream `javaOverloadsFitting`):
+//! a call's arguments decide which of several same-named methods it reaches. Each argument
+//! is read from syntax alone and stored as one short string:
+//!
+//! * `T:` - a literal, `new T(..)` or a cast: the static type as written
+//! * `V:` - a local, parameter or field, typed at resolution from its binding
+//! * `F:` - `this.`: a field of the enclosing type
+//! * `#this` - `this`
+//! * `N` - `null` / `undefined`
+//! * `L` - a lambda / function literal taking `k` parameters; `L` alone: a method
+//! reference, whose parameter count the text does not say
+//! * `?` - anything else (a call, an operator, ...): fits every parameter
+//!
+//! A spread argument (`...xs`) or a named one (Kotlin `f(n = 1)`) makes the positional
+//! reading unreliable, and such a call records nothing.
+
+use super::util::{kids, Cx};
+use super::CallArgsFact;
+use cg_core::text::unpack_pos;
+use tree_sitter::Node;
+
+/// First item of a reference's candidate list that carries argument shapes.
+pub const ARGS_MARK: &str = "#args";
+
+/// More arguments than this are not worth a list (and no overload set differs that late).
+const MAX_ARGS: usize = 24;
+
+fn push(cx: &mut Cx, at: Node, tail: &str, args: Vec) {
+ if tail.is_empty() || args.len() > MAX_ARGS {
+ return;
+ }
+ let (line, col) = unpack_pos(cx.start(at));
+ cx.facts.call_args.push(CallArgsFact { line, col, tail: tail.to_owned(), args });
+}
+
+fn lambda(params: usize) -> String {
+ format!("L{params}")
+}
+
+// ------------------------------------------------------------------- Java
+
+/// `foo(a, "x")`, `obj.foo(1)`, `this.foo()`, `super.foo()`: the kernel's reference sits at
+/// the start of the `method_invocation`.
+pub fn java_call(cx: &mut Cx, call: Node) {
+ let Some(name) = call.child_by_field_name("name") else { return };
+ let Some(list) = call.child_by_field_name("arguments") else { return };
+ let tail = cx.text(name).to_owned();
+ let mut args = Vec::new();
+ for a in kids(list) {
+ if !a.is_named() || a.kind().ends_with("comment") {
+ continue;
+ }
+ args.push(java_shape(cx, a));
+ }
+ push(cx, call, &tail, args);
+}
+
+fn java_type(cx: &Cx, t: Node) -> String {
+ match t.kind() {
+ "generic_type" => t.named_child(0).map(|c| java_type(cx, c)).unwrap_or_default(),
+ "annotated_type" => kids(t).find(|c| !matches!(c.kind(), "annotation" | "marker_annotation")).map(|c| java_type(cx, c)).unwrap_or_default(),
+ "array_type" => {
+ let el = t.child_by_field_name("element").map(|c| java_type(cx, c)).unwrap_or_default();
+ if el.is_empty() {
+ String::new()
+ } else {
+ format!("{el}[]")
+ }
+ }
+ "type_identifier" if cx.text(t) == "var" => String::new(),
+ "type_identifier" | "scoped_type_identifier" | "integral_type" | "floating_point_type" | "boolean_type" => cx.text(t).to_owned(),
+ _ => String::new(),
+ }
+}
+
+fn java_shape(cx: &Cx, a: Node) -> String {
+ let text = cx.text(a);
+ let typed = |t: &str| format!("T:{t}");
+ match a.kind() {
+ "string_literal" | "text_block" => typed("String"),
+ "character_literal" => typed("char"),
+ "decimal_integer_literal" | "hex_integer_literal" | "octal_integer_literal" | "binary_integer_literal" => {
+ typed(if text.ends_with(['l', 'L']) { "long" } else { "int" })
+ }
+ "decimal_floating_point_literal" | "hex_floating_point_literal" => typed(if text.ends_with(['f', 'F']) { "float" } else { "double" }),
+ "true" | "false" => typed("boolean"),
+ "null_literal" => "N".into(),
+ "this" => "#this".into(),
+ "identifier" => format!("V:{text}"),
+ "object_creation_expression" => match a.child_by_field_name("type").map(|t| java_type(cx, t)) {
+ Some(t) if !t.is_empty() => typed(&t),
+ _ => "?".into(),
+ },
+ "array_creation_expression" => match a.child_by_field_name("type").map(|t| java_type(cx, t)) {
+ Some(t) if !t.is_empty() => typed(&format!("{t}[]")),
+ _ => "?".into(),
+ },
+ "cast_expression" => match a.child_by_field_name("type").map(|t| java_type(cx, t)) {
+ Some(t) if !t.is_empty() => typed(&t),
+ _ => "?".into(),
+ },
+ "field_access" => match (a.child_by_field_name("object"), a.child_by_field_name("field")) {
+ (Some(o), Some(f)) if o.kind() == "this" => format!("F:{}", cx.text(f)),
+ _ => "?".into(),
+ },
+ "lambda_expression" => {
+ let n = match a.child_by_field_name("parameters") {
+ Some(p) if p.kind() == "identifier" => 1,
+ Some(p) => kids(p).filter(|c| c.is_named() && !c.kind().ends_with("comment")).count(),
+ None => 0,
+ };
+ lambda(n)
+ }
+ "method_reference" => "L".into(),
+ "parenthesized_expression" => a.named_child(0).map(|c| java_shape(cx, c)).unwrap_or_else(|| "?".into()),
+ "unary_expression" => match a.child_by_field_name("operand") {
+ // `-1`, `-2.5`: the operand's numeric type
+ Some(o) if text.starts_with(['-', '+']) && o.kind().contains("literal") => java_shape(cx, o),
+ _ => "?".into(),
+ },
+ _ => "?".into(),
+ }
+}
+
+// ------------------------------------------------------------------- Kotlin
+
+/// `f(a, b)`, `obj.f(1)`, `f(1) { .. }`: the kernel's reference sits at the start of the
+/// `call_expression` (the inner one, for a trailing lambda).
+pub fn kotlin_call(cx: &mut Cx, call: Node) {
+ let mut c = call.walk();
+ let parts: Vec = call.named_children(&mut c).collect();
+ let (Some(callee), Some(suffix)) = (parts.first().copied(), parts.get(1).copied()) else { return };
+ if suffix.kind() != "call_suffix" {
+ return;
+ }
+ let tail = match callee.kind() {
+ "simple_identifier" => cx.text(callee).to_owned(),
+ "navigation_expression" => match kids(callee).filter(|k| k.kind() == "navigation_suffix").last() {
+ Some(s) => kids(s).find(|k| k.kind() == "simple_identifier").map(|k| cx.text(k).to_owned()).unwrap_or_default(),
+ None => String::new(),
+ },
+ _ => String::new(),
+ };
+ let mut args = Vec::new();
+ for part in kids(suffix) {
+ match part.kind() {
+ "value_arguments" => {
+ for va in kids(part).filter(|k| k.kind() == "value_argument") {
+ let mut vc = va.walk();
+ let inner: Vec = va.named_children(&mut vc).collect();
+ // `name = value` and `*spread` are not positional
+ if inner.len() != 1 || kids(va).any(|k| !k.is_named() && matches!(cx.text(k), "*" | "=")) {
+ return;
+ }
+ args.push(kotlin_shape(cx, inner[0]));
+ }
+ }
+ "annotated_lambda" => args.push(kotlin_lambda(cx, part)),
+ _ => {}
+ }
+ }
+ // `f(1) { .. }` parses as a call of the call `f(1)` with the lambda: it is one more
+ // argument of the inner call.
+ if let Some(parent) = call.parent() {
+ if parent.kind() == "call_expression" && parent.named_child(0) == Some(call) {
+ if let Some(outer) = parent.named_child(1).filter(|s| s.kind() == "call_suffix") {
+ if kids(outer).all(|k| !k.is_named() || k.kind() == "annotated_lambda") {
+ for l in kids(outer).filter(|k| k.kind() == "annotated_lambda") {
+ args.push(kotlin_lambda(cx, l));
+ }
+ }
+ }
+ }
+ }
+ push(cx, call, &tail, args);
+}
+
+fn kotlin_lambda(cx: &Cx, n: Node) -> String {
+ let lit = if n.kind() == "lambda_literal" { Some(n) } else { kids(n).find(|k| k.kind() == "lambda_literal") };
+ let Some(lit) = lit else { return "?".into() };
+ let params = kids(lit).find(|k| k.kind() == "lambda_parameters").map_or(0, |p| kids(p).filter(|k| k.is_named()).count());
+ let _ = cx;
+ // `{ it }` takes one implicit parameter or none: the count is unknown
+ if params == 0 {
+ "L".into()
+ } else {
+ lambda(params)
+ }
+}
+
+fn kotlin_shape(cx: &Cx, a: Node) -> String {
+ let text = cx.text(a);
+ let typed = |t: &str| format!("T:{t}");
+ match a.kind() {
+ "string_literal" | "line_string_literal" | "multi_line_string_literal" => typed("String"),
+ "character_literal" => typed("Char"),
+ "integer_literal" | "hex_literal" | "bin_literal" => typed("Int"),
+ "long_literal" => typed("Long"),
+ "real_literal" => typed(if text.ends_with(['f', 'F']) { "Float" } else { "Double" }),
+ "boolean_literal" => typed("Boolean"),
+ "null_literal" => "N".into(),
+ "this_expression" => "#this".into(),
+ "simple_identifier" if text == "null" => "N".into(),
+ "simple_identifier" => format!("V:{text}"),
+ "lambda_literal" | "annotated_lambda" => kotlin_lambda(cx, a),
+ "anonymous_function" => "L".into(),
+ "callable_reference" => "L".into(),
+ "parenthesized_expression" => a.named_child(0).map(|c| kotlin_shape(cx, c)).unwrap_or_else(|| "?".into()),
+ "as_expression" => match a.named_child(1) {
+ Some(t) => typed(cx.text(t).trim_end_matches('?')),
+ None => "?".into(),
+ },
+ "prefix_expression" if text.starts_with(['-', '+']) => match a.named_child(a.named_child_count().saturating_sub(1)) {
+ Some(o) if o.kind().ends_with("literal") => kotlin_shape(cx, o),
+ _ => "?".into(),
+ },
+ _ => "?".into(),
+ }
+}
+
+// ------------------------------------------------------------------- TypeScript / JavaScript
+
+/// `f(a)`, `obj.f(1)`, `this.f()`: the kernel's reference sits at the call, or at its callee
+/// when an `await` sits inside the callee; both positions are recorded.
+pub fn js_call(cx: &mut Cx, call: Node) {
+ let Some(func) = call.child_by_field_name("function") else { return };
+ let Some(list) = call.child_by_field_name("arguments") else { return };
+ if list.kind() != "arguments" {
+ return; // a tagged template
+ }
+ let tail = match func.kind() {
+ "identifier" => cx.text(func).to_owned(),
+ "member_expression" => func.child_by_field_name("property").map(|p| cx.text(p).to_owned()).unwrap_or_default(),
+ _ => return,
+ };
+ let mut args = Vec::new();
+ for a in kids(list) {
+ if !a.is_named() || a.kind() == "comment" {
+ continue;
+ }
+ if a.kind() == "spread_element" {
+ return;
+ }
+ args.push(js_shape(cx, a));
+ }
+ if cx.start(func) != cx.start(call) {
+ push(cx, func, &tail, args.clone());
+ }
+ push(cx, call, &tail, args);
+}
+
+fn js_type(cx: &Cx, t: Node) -> String {
+ match t.kind() {
+ "type_annotation" | "parenthesized_type" => t.named_child(0).map(|c| js_type(cx, c)).unwrap_or_default(),
+ "predefined_type" | "type_identifier" | "nested_type_identifier" => cx.text(t).to_owned(),
+ "generic_type" => t.child_by_field_name("name").map(|c| cx.text(c).to_owned()).unwrap_or_default(),
+ _ => String::new(),
+ }
+}
+
+fn js_shape(cx: &Cx, a: Node) -> String {
+ let typed = |t: &str| format!("T:{t}");
+ match a.kind() {
+ "string" | "template_string" => typed("string"),
+ "number" => typed("number"),
+ "true" | "false" => typed("boolean"),
+ "null" | "undefined" => "N".into(),
+ "this" => "#this".into(),
+ "identifier" if cx.text(a) == "undefined" => "N".into(),
+ "identifier" => format!("V:{}", cx.text(a)),
+ "member_expression" => match (a.child_by_field_name("object"), a.child_by_field_name("property")) {
+ (Some(o), Some(p)) if o.kind() == "this" && p.kind() == "property_identifier" => format!("F:{}", cx.text(p)),
+ _ => "?".into(),
+ },
+ "new_expression" => match a.child_by_field_name("constructor") {
+ Some(c) if matches!(c.kind(), "identifier" | "member_expression") => typed(cx.text(c)),
+ _ => "?".into(),
+ },
+ "arrow_function" | "function_expression" | "function" => {
+ let n = if a.child_by_field_name("parameter").is_some() {
+ 1
+ } else {
+ a.child_by_field_name("parameters").map_or(0, |p| kids(p).filter(|c| c.is_named() && c.kind() != "comment").count())
+ };
+ lambda(n)
+ }
+ "parenthesized_expression" | "non_null_expression" => a.named_child(0).map(|c| js_shape(cx, c)).unwrap_or_else(|| "?".into()),
+ "as_expression" | "satisfies_expression" => match a.named_child(1).map(|t| js_type(cx, t)) {
+ Some(t) if !t.is_empty() => typed(&t),
+ _ => "?".into(),
+ },
+ "unary_expression" => match a.child_by_field_name("argument") {
+ Some(o) if o.kind() == "number" && matches!(cx.text(a).as_bytes().first(), Some(b'-' | b'+')) => typed("number"),
+ _ => "?".into(),
+ },
+ _ => "?".into(),
+ }
+}
diff --git a/crates/cg-extract/src/facts/go.rs b/crates/cg-extract/src/facts/go.rs
index 132ed2c..853fd9a 100644
--- a/crates/cg-extract/src/facts/go.rs
+++ b/crates/cg-extract/src/facts/go.rs
@@ -44,6 +44,13 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
"function_declaration" | "method_declaration" => function(cx, n, scope),
"func_literal" => function(cx, n, scope),
"type_spec" => type_spec(cx, n, scope),
+ "type_alias" => {
+ // `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() });
+ }
+ }
"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) {
@@ -186,6 +193,14 @@ 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 = 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::>())
+ .collect();
+ let name = cx.text(name).to_owned();
+ cx.facts.go_types.push(GoTypeFact { name, alias: false, type_params: params });
+ }
let Some(ty) = n.child_by_field_name("type") else { return };
if ty.kind() != "struct_type" {
return;
diff --git a/crates/cg-extract/src/facts/java.rs b/crates/cg-extract/src/facts/java.rs
index ed974ff..4b3279c 100644
--- a/crates/cg-extract/src/facts/java.rs
+++ b/crates/cg-extract/src/facts/java.rs
@@ -26,6 +26,10 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
"class_declaration" | "interface_declaration" | "enum_declaration" | "record_declaration" | "annotation_type_declaration" => class(cx, n, scope),
"method_declaration" | "constructor_declaration" | "compact_constructor_declaration" => function(cx, n, scope),
"lambda_expression" => lambda(cx, n, scope),
+ "method_invocation" => {
+ super::args::java_call(cx, n);
+ walk_children(cx, n, scope);
+ }
"local_variable_declaration" => {
declare(cx, n, scope, BindKind::Local);
walk_children(cx, n, scope);
@@ -69,9 +73,11 @@ fn java_type_name(cx: &Cx, n: Node) -> String {
match n.kind() {
"type_identifier" if cx.text(n) == "var" => String::new(),
"type_identifier" | "scoped_type_identifier" => cx.text(n).to_owned(),
+ // primitives type their arguments for overload selection (`args`); they name no member
+ "integral_type" | "floating_point_type" | "boolean_type" => cx.text(n).to_owned(),
"generic_type" => n.named_child(0).map(|c| java_type_name(cx, c)).unwrap_or_default(),
"annotated_type" => kids(n).find(|c| !matches!(c.kind(), "annotation" | "marker_annotation")).map(|c| java_type_name(cx, c)).unwrap_or_default(),
- _ => String::new(), // primitives, arrays, `var`, void
+ _ => String::new(), // arrays, `var`, void
}
}
diff --git a/crates/cg-extract/src/facts/js.rs b/crates/cg-extract/src/facts/js.rs
index 86d259e..b84f524 100644
--- a/crates/cg-extract/src/facts/js.rs
+++ b/crates/cg-extract/src/facts/js.rs
@@ -41,6 +41,10 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
"function_expression" | "function" | "generator_function" | "arrow_function" | "method_definition" => function(cx, n, scope),
"class_declaration" | "abstract_class_declaration" | "class" => class(cx, n, scope),
"lexical_declaration" | "variable_declaration" => var_decl(cx, n, scope),
+ "call_expression" => {
+ super::args::js_call(cx, n);
+ walk_children(cx, n, scope);
+ }
"for_in_statement" => {
if let Some(l) = n.child_by_field_name("left") {
bind_pattern(cx, l, scope, BindKind::Local, "", "");
@@ -99,6 +103,8 @@ fn ts_type_name(cx: &Cx, n: Node) -> String {
match n.kind() {
"type_annotation" => n.named_child(0).map(|c| ts_type_name(cx, c)).unwrap_or_default(),
"type_identifier" | "identifier" => cx.text(n).to_owned(),
+ // primitives type arguments for overload selection (`args`); `any` / `unknown` say nothing
+ "predefined_type" if matches!(cx.text(n), "string" | "number" | "boolean" | "bigint" | "symbol") => cx.text(n).to_owned(),
"nested_type_identifier" | "member_expression" => cx.text(n).to_owned(),
"generic_type" => n.child_by_field_name("name").map(|c| ts_type_name(cx, c)).unwrap_or_default(),
"parenthesized_type" | "readonly_type" | "required_parameter" => n.named_child(0).map(|c| ts_type_name(cx, c)).unwrap_or_default(),
@@ -108,7 +114,7 @@ fn ts_type_name(cx: &Cx, n: Node) -> String {
continue;
}
let t = ts_type_name(cx, ch);
- if !t.is_empty() && t != "null" && t != "undefined" {
+ if !t.is_empty() && !matches!(t.as_str(), "null" | "undefined" | "string" | "number" | "boolean" | "bigint" | "symbol") {
return t;
}
}
diff --git a/crates/cg-extract/src/facts/kotlin.rs b/crates/cg-extract/src/facts/kotlin.rs
index 06ba49c..c749160 100644
--- a/crates/cg-extract/src/facts/kotlin.rs
+++ b/crates/cg-extract/src/facts/kotlin.rs
@@ -35,6 +35,10 @@ fn walk(cx: &mut Cx, n: Node, scope: u32) {
"class_declaration" | "object_declaration" | "companion_object" => class(cx, n, scope),
"function_declaration" | "secondary_constructor" | "anonymous_function" => function(cx, n, scope),
"lambda_literal" => lambda(cx, n, scope),
+ "call_expression" => {
+ super::args::kotlin_call(cx, n);
+ walk_children(cx, n, scope);
+ }
"property_declaration" => {
property(cx, n, scope);
walk_children(cx, n, scope);
diff --git a/crates/cg-extract/src/facts/mod.rs b/crates/cg-extract/src/facts/mod.rs
index 939f25b..f8f974b 100644
--- a/crates/cg-extract/src/facts/mod.rs
+++ b/crates/cg-extract/src/facts/mod.rs
@@ -6,6 +6,7 @@ use crate::rows::FileRows;
use cg_core::{text, Lang, NONE};
use tree_sitter::{Node, Tree};
+pub mod args;
mod go;
mod java;
mod js;
@@ -140,6 +141,11 @@ pub struct Facts {
/// Precise call paths lost by the compatibility kernel. Applied to matching
/// call references before storage; node identities and sites stay unchanged.
pub call_names: Vec,
+ /// Argument shapes of call sites, for overload selection (see `args`).
+ pub call_args: Vec,
+ /// Go type declarations whose names stand for other types: true aliases and the type
+ /// parameters of generic types (structural interface matching leaves them open).
+ pub go_types: Vec,
/// A supplementary parse exhausted its deadline. The pipeline exposes this
/// as an incomplete file rather than silently advertising complete facts.
pub timed_out: bool,
@@ -154,6 +160,25 @@ pub struct CallNameFact {
pub name: String,
}
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct GoTypeFact {
+ pub name: String,
+ /// `type A = B`
+ pub alias: bool,
+ pub type_params: Vec,
+}
+
+/// The arguments of one call, keyed like the kernel's call reference: its position and the
+/// called name's last segment. Stored with the reference (`args::ARGS_MARK` list).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CallArgsFact {
+ pub line: u32,
+ pub col: u32,
+ pub tail: String,
+ /// One shape per argument, in order (see `args`).
+ pub args: Vec,
+}
+
impl Facts {
pub fn new(file_end: u64) -> Facts {
Facts { scopes: vec![ScopeFact { kind: ScopeKind::File, parent: NONE, start: 0, end: file_end }], ..Default::default() }
diff --git a/crates/cg-extract/src/facts/util.rs b/crates/cg-extract/src/facts/util.rs
index 074777d..839acc1 100644
--- a/crates/cg-extract/src/facts/util.rs
+++ b/crates/cg-extract/src/facts/util.rs
@@ -11,6 +11,9 @@ pub struct Cx<'a> {
pub parse_timeout: std::time::Duration,
line_starts: Vec,
row_by_start: Option>,
+ /// Last (row, byte, UTF-16 column) computed: positions are asked in source order, and on
+ /// a minified one-line file counting each column from the line start is quadratic.
+ last_pos: std::cell::Cell<(usize, usize, u32)>,
}
impl<'a> Cx<'a> {
@@ -18,7 +21,15 @@ impl<'a> Cx<'a> {
let line_starts = text::line_starts(src);
let end_line = line_starts.len() as u32;
let facts = Facts::new(pack_pos(end_line + 1, 0));
- Cx { src, rows, facts, parse_timeout: std::time::Duration::from_secs(5), line_starts, row_by_start: None }
+ Cx {
+ src,
+ rows,
+ facts,
+ parse_timeout: std::time::Duration::from_secs(5),
+ line_starts,
+ row_by_start: None,
+ last_pos: std::cell::Cell::new((usize::MAX, 0, 0)),
+ }
}
/// Kernel node row whose span starts exactly at `pos` (packed line / UTF-16 column), skipping
@@ -51,9 +62,17 @@ impl<'a> Cx<'a> {
/// Packed (1-based line, UTF-16 column) of a byte offset.
pub fn pos_at(&self, byte: usize, row: usize) -> u64 {
let ls = self.line_starts[row.min(self.line_starts.len() - 1)] as usize;
+ let (last_row, last_byte, last_col) = self.last_pos.get();
+ if last_row == row && last_byte <= byte && byte - last_byte < byte - ls && self.src.is_char_boundary(last_byte) && self.src.is_char_boundary(byte) {
+ let col = last_col + self.src[last_byte..byte].chars().map(|c| c.len_utf16() as u32).sum::();
+ self.last_pos.set((row, byte, col));
+ return pack_pos(row as u32 + 1, col);
+ }
let le = self.line_starts.get(row + 1).map(|v| *v as usize).unwrap_or(self.src.len());
let line = &self.src[ls..le];
- pack_pos(row as u32 + 1, col16(line, byte - ls))
+ let col = col16(line, byte - ls);
+ self.last_pos.set((row, byte, col));
+ pack_pos(row as u32 + 1, col)
}
pub fn start(&self, n: Node) -> u64 {
diff --git a/crates/cg-resolve/src/engine.rs b/crates/cg-resolve/src/engine.rs
index 677e51c..b214a03 100644
--- a/crates/cg-resolve/src/engine.rs
+++ b/crates/cg-resolve/src/engine.rs
@@ -275,12 +275,23 @@ impl<'v> Engine<'v> {
if p.is_none() {
continue;
}
+ let jvm = view.file(f).lang().family() == LangFamily::Jvm;
for n in self.top_level_nodes(f) {
let node = view.node(n);
// Go methods are not package-level names; Java/Kotlin nest members under classes
if node.kind() == NodeKind::Method {
continue;
}
+ // a Java / Kotlin file's declarations sit inside its `package` namespace node
+ if jvm && node.kind() == NodeKind::Namespace {
+ for e in view.out_edges(n).filter(|e| e.kind == EdgeKind::Contains) {
+ let child = view.node(e.dst);
+ if child.kind().is_definition() && child.kind() != NodeKind::Method {
+ defs[p.0 as usize].entry(child.name()).or_default().push(e.dst);
+ }
+ }
+ continue;
+ }
defs[p.0 as usize].entry(node.name()).or_default().push(n);
}
}
@@ -504,6 +515,27 @@ impl<'v> Engine<'v> {
None
}
+ /// Every callable member called `name` declared in the body of `t` or of one of its
+ /// ancestors, nearest type first and in declaration order: the overload set a call picks
+ /// from. Members declared outside a body (Go receivers, Rust impls) have no overloads.
+ pub fn member_overloads(&self, t: NodeIdx, name: &str) -> SmallVec<[NodeIdx; 4]> {
+ let mut out = SmallVec::new();
+ for ty in std::iter::once(t).chain(self.ancestors(t)) {
+ for e in self.view.out_edges(ty) {
+ if e.kind == EdgeKind::Contains {
+ let c = self.view.node(e.dst);
+ if c.name() == name && c.kind().is_callable() && !out.contains(&e.dst) {
+ out.push(e.dst);
+ }
+ }
+ }
+ if out.len() > 32 {
+ break;
+ }
+ }
+ out
+ }
+
/// Go: promoted members through embedded structs are covered by `ancestors`
/// (embedding is recorded as `extends`).
pub fn node_is_type(&self, n: NodeIdx) -> bool {
diff --git a/crates/cg-resolve/src/frameworks/href.rs b/crates/cg-resolve/src/frameworks/href.rs
new file mode 100644
index 0000000..f2b7580
--- /dev/null
+++ b/crates/cg-resolve/src/frameworks/href.rs
@@ -0,0 +1,527 @@
+//! Destinations written as strings (upstream `expo-router.ts` / `nextjs.ts` readers): a
+//! navigation's href, a client's request path. A literal, a template (its `${…}` parts become
+//! holes), an object's `pathname` / `to`, or a conditional whose every arm is one of those. The
+//! matcher pairs an href with the one route of a table that serves it: a literal segment beats
+//! a parameter, which beats a hole; a tie is no answer.
+
+use cg_core::NodeIdx;
+use rustc_hash::FxHashMap;
+
+/// Stands for a `${…}` hole inside a stored path.
+pub const HOLE: char = '\u{1}';
+
+/// One destination: the path (query and hash removed, holes kept) and the text as written.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Href {
+ pub path: String,
+}
+
+impl Href {
+ pub fn display(&self) -> String {
+ self.path.replace(HOLE, "${…}")
+ }
+}
+
+/// Byte offset of the `)`/`]`/`}` closing the bracket at `open`, skipping strings and
+/// templates; `None` when unbalanced.
+pub fn match_bracket(s: &str, open: usize) -> Option {
+ let b = s.as_bytes();
+ let mut depth = 0i32;
+ let mut i = open;
+ while i < b.len() {
+ match b[i] {
+ b'"' | b'\'' => i = string_end(s, i)?,
+ b'`' => i = template_end(s, i)?,
+ b'(' | b'[' | b'{' => depth += 1,
+ b')' | b']' | b'}' => {
+ depth -= 1;
+ if depth == 0 {
+ return Some(i);
+ }
+ }
+ _ => {}
+ }
+ i += 1;
+ }
+ None
+}
+
+/// Offset of the closing quote of the string opening at `at`.
+pub fn string_end(s: &str, at: usize) -> Option {
+ let b = s.as_bytes();
+ let q = b[at];
+ if q == b'`' {
+ return template_end(s, at);
+ }
+ let mut i = at + 1;
+ while i < b.len() {
+ match b[i] {
+ b'\\' => i += 1,
+ c if c == q => return Some(i),
+ b'\n' => return None,
+ _ => {}
+ }
+ i += 1;
+ }
+ None
+}
+
+/// Offset of the backtick closing the template opening at `open`.
+pub fn template_end(s: &str, open: usize) -> Option {
+ let b = s.as_bytes();
+ let mut i = open + 1;
+ while i < b.len() {
+ match b[i] {
+ b'\\' => i += 1,
+ b'`' => return Some(i),
+ b'$' if b.get(i + 1) == Some(&b'{') => {
+ let mut depth = 0;
+ i += 1;
+ while i < b.len() {
+ match b[i] {
+ b'{' => depth += 1,
+ b'}' => {
+ depth -= 1;
+ if depth == 0 {
+ break;
+ }
+ }
+ b'`' => i = template_end(s, i)?,
+ b'"' | b'\'' => i = string_end(s, i)?,
+ _ => {}
+ }
+ i += 1;
+ }
+ }
+ _ => {}
+ }
+ i += 1;
+ }
+ None
+}
+
+/// The string literal starting at `at`, with each `${…}` replaced by [`HOLE`]; `None` when
+/// `at` holds no string.
+pub fn read_string_at(s: &str, at: usize) -> Option {
+ let b = s.as_bytes();
+ let q = *b.get(at)?;
+ match q {
+ b'"' | b'\'' => {
+ let end = string_end(s, at)?;
+ Some(unescape(&s[at + 1..end]))
+ }
+ b'`' => {
+ let end = template_end(s, at)?;
+ let body = &s[at + 1..end];
+ let mut out = String::new();
+ let bb = body.as_bytes();
+ let mut i = 0;
+ let mut lit = 0;
+ while i < bb.len() {
+ if bb[i] == b'\\' {
+ i += 2;
+ continue;
+ }
+ if bb[i] == b'$' && bb.get(i + 1) == Some(&b'{') {
+ out.push_str(&unescape(&body[lit..i]));
+ let close = match_bracket(body, i + 1)?;
+ out.push(HOLE);
+ i = close + 1;
+ lit = i;
+ continue;
+ }
+ i += 1;
+ }
+ out.push_str(&unescape(&body[lit.min(body.len())..]));
+ Some(out)
+ }
+ _ => None,
+ }
+}
+
+fn unescape(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut chars = s.chars();
+ while let Some(c) = chars.next() {
+ if c == '\\' {
+ if let Some(n) = chars.next() {
+ out.push(n);
+ }
+ } else {
+ out.push(c);
+ }
+ }
+ out
+}
+
+/// Offset of the first `ch` at bracket depth 0 and outside strings at or after `from`.
+pub fn index_at_depth0(s: &str, ch: u8, from: usize) -> Option {
+ let b = s.as_bytes();
+ let mut depth = 0i32;
+ let mut i = from;
+ while i < b.len() {
+ match b[i] {
+ b'"' | b'\'' => i = string_end(s, i).unwrap_or(b.len()),
+ b'`' => i = template_end(s, i).unwrap_or(b.len()),
+ b'(' | b'[' | b'{' => depth += 1,
+ b')' | b']' | b'}' => depth -= 1,
+ b'?' if matches!(b.get(i + 1), Some(b'.' | b'?')) && ch == b'?' => i += 1,
+ c if depth == 0 && c == ch => return Some(i),
+ _ => {}
+ }
+ i += 1;
+ }
+ None
+}
+
+/// The `:` closing the ternary opened at `q`, nested ternaries paired.
+fn ternary_colon(s: &str, q: usize) -> Option {
+ let mut depth = 0;
+ let mut i = q + 1;
+ for _ in 0..64 {
+ let next_q = index_at_depth0(s, b'?', i);
+ let colon = index_at_depth0(s, b':', i)?;
+ if let Some(nq) = next_q.filter(|nq| *nq < colon) {
+ depth += 1;
+ i = nq + 1;
+ continue;
+ }
+ if depth == 0 {
+ return Some(colon);
+ }
+ depth -= 1;
+ i = colon + 1;
+ }
+ None
+}
+
+/// An href from a literal: the path before `?` / `#`.
+pub fn to_href(literal: &str) -> Option {
+ let cut = literal.find(['?', '#']).unwrap_or(literal.len());
+ let path = &literal[..cut];
+ (!path.is_empty()).then(|| Href { path: path.to_owned() })
+}
+
+fn strip_cast(s: &str) -> &str {
+ // `expr as any`, `expr satisfies Href`
+ for kw in [" as ", " satisfies "] {
+ if let Some(i) = s.rfind(kw) {
+ let tail = &s[i + kw.len()..];
+ if tail.chars().all(|c| c.is_alphanumeric() || "_$.<>[]|& ".contains(c)) {
+ return s[..i].trim_end();
+ }
+ }
+ }
+ s
+}
+
+/// Every destination an argument expression names (`key` reads an object's field: `pathname`
+/// for an `Href` object, `to` for TanStack's): one per arm of a conditional.
+pub fn parse_href_expression(expr: &str, key: &str) -> Vec {
+ let mut args = strip_cast(expr.trim()).trim();
+ while args.starts_with('(') && match_bracket(args, 0) == Some(args.len() - 1) {
+ args = strip_cast(args[1..args.len() - 1].trim()).trim();
+ }
+ if args.is_empty() {
+ return Vec::new();
+ }
+ if let Some(q) = index_at_depth0(args, b'?', 0).filter(|q| *q > 0) {
+ if let Some(colon) = ternary_colon(args, q) {
+ let mut arms = parse_href_expression(&args[q + 1..colon], key);
+ for arm in parse_href_expression(&args[colon + 1..], key) {
+ if !arms.contains(&arm) {
+ arms.push(arm);
+ }
+ }
+ return arms;
+ }
+ }
+ if args.starts_with('{') {
+ return object_field(args, key).and_then(|v| read_string_at(v, 0)).and_then(|l| to_href(&l)).into_iter().collect();
+ }
+ read_string_at(args, 0).and_then(|l| to_href(&l)).into_iter().collect()
+}
+
+/// The text of field `key`'s value in the object literal `obj` (`{ a: 1, key: 'x' }`).
+pub fn object_field<'a>(obj: &'a str, key: &str) -> Option<&'a str> {
+ let end = match_bracket(obj, 0)?;
+ let body = &obj[1..end];
+ let mut i = 0;
+ let b = body.as_bytes();
+ while i < b.len() {
+ let rest = &body[i..];
+ let trimmed = rest.trim_start();
+ let at = i + (rest.len() - trimmed.len());
+ let name_len = trimmed.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$')).unwrap_or(trimmed.len());
+ let name = &trimmed[..name_len];
+ let after = trimmed[name_len..].trim_start();
+ if name == key && after.starts_with(':') {
+ let value = after[1..].trim_start();
+ let start = body.len() - value.len();
+ let stop = index_at_depth0(body, b',', start).unwrap_or(body.len());
+ return Some(body[start..stop].trim());
+ }
+ // skip to the next entry
+ match index_at_depth0(body, b',', at.max(i)) {
+ Some(c) => i = c + 1,
+ None => break,
+ }
+ }
+ None
+}
+
+/// The directory of the app owning a file: everything before the first conventional source
+/// directory (upstream `appRootFor`).
+pub fn app_root_for(path: &str) -> &str {
+ let mut at = 0;
+ for seg in path.split('/') {
+ if matches!(seg, "src" | "pages" | "app" | "routes") && at + seg.len() < path.len() {
+ return &path[..at];
+ }
+ at += seg.len() + 1;
+ }
+ match path.rfind('/') {
+ Some(i) => &path[..=i],
+ None => "",
+ }
+}
+
+fn is_param(seg: &str) -> bool {
+ (seg.starts_with('[') && seg.ends_with(']')) || (seg.starts_with(':') && !seg.ends_with('*'))
+}
+
+fn is_catch_all(seg: &str) -> bool {
+ (seg.starts_with("[...") && seg.ends_with(']')) || (seg.starts_with(':') && seg.ends_with('*'))
+}
+
+/// Segments of an href path: `/users/${id}` -> `["users", "*"]`; an absolute URL keeps its
+/// path; a relative href is nothing.
+pub fn href_segments(path: &str) -> Option> {
+ let mut p = path;
+ if let Some(i) = p.find("//") {
+ let scheme = &p[..i];
+ if scheme.is_empty() || scheme.ends_with(':') && scheme[..scheme.len() - 1].chars().all(|c| c.is_ascii_alphanumeric() || "+.-".contains(c)) {
+ let rest = &p[i + 2..];
+ p = rest.find('/').map_or("/", |j| &rest[j..]);
+ }
+ }
+ if !p.starts_with('/') {
+ return None;
+ }
+ Some(p.split('/').filter(|s| !s.is_empty()).map(|s| if s.contains(HOLE) { "*".to_owned() } else { s.to_owned() }).collect())
+}
+
+/// Score of an href's segments against a route's, `None` when it does not match.
+fn score(href: &[String], route: &[&str]) -> Option {
+ let mut score = 0;
+ let mut i = 0;
+ for seg in route {
+ if is_catch_all(seg) {
+ if i >= href.len() {
+ return None;
+ }
+ score += (href.len() - i) as u32;
+ i = href.len();
+ continue;
+ }
+ let h = href.get(i)?;
+ if is_param(seg) {
+ score += 2;
+ } else if h == seg {
+ score += 3;
+ } else if h == "*" {
+ score += 1;
+ } else {
+ return None;
+ }
+ i += 1;
+ }
+ (i == href.len()).then_some(score)
+}
+
+/// Routes by path; dynamic ones are matched segment by segment.
+#[derive(Default)]
+pub struct RouteTable {
+ pub exact: FxHashMap,
+ pub dynamic: Vec<(NodeIdx, Vec)>,
+}
+
+impl RouteTable {
+ /// The first route to claim an address keeps it.
+ pub fn add(&mut self, path: &str, node: NodeIdx) {
+ self.exact.entry(path.to_owned()).or_insert(node);
+ if path.contains(':') || path.contains('[') {
+ self.dynamic.push((node, path.split('/').skip(1).map(str::to_owned).collect()));
+ }
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.exact.is_empty()
+ }
+
+ /// The one route the segments denote.
+ pub fn match_segments(&self, segs: &[String]) -> Option {
+ if let Some(n) = self.exact.get(&format!("/{}", segs.join("/"))) {
+ return Some(*n);
+ }
+ let mut best: Option<(NodeIdx, u32)> = None;
+ let mut tied = false;
+ for (node, route) in &self.dynamic {
+ let route: Vec<&str> = route.iter().map(String::as_str).collect();
+ let Some(s) = score(segs, &route) else { continue };
+ match best {
+ Some((_, b)) if s < b => {}
+ Some((_, b)) if s == b => tied = true,
+ _ => {
+ best = Some((*node, s));
+ tied = false;
+ }
+ }
+ }
+ best.filter(|_| !tied).map(|b| b.0)
+ }
+
+ /// The routes an href's arms name, each once, with the arm that named it.
+ pub fn destinations<'h>(&self, arms: &'h [Href]) -> Vec<(NodeIdx, &'h Href)> {
+ let mut out: Vec<(NodeIdx, &Href)> = Vec::new();
+ for arm in arms {
+ let Some(segs) = href_segments(&arm.path) else { continue };
+ if let Some(n) = self.match_segments(&segs) {
+ if !out.iter().any(|(m, _)| *m == n) {
+ out.push((n, arm));
+ }
+ }
+ }
+ out
+ }
+}
+
+/// Route tables split by the app each route belongs to (a monorepo has a `/` per app).
+#[derive(Default)]
+pub struct RootedTables {
+ pub by_root: Vec<(String, RouteTable)>,
+}
+
+impl RootedTables {
+ pub fn add(&mut self, root: &str, path: &str, node: NodeIdx) {
+ match self.by_root.iter_mut().find(|(r, _)| r == root) {
+ Some((_, t)) => t.add(path, node),
+ None => {
+ let mut t = RouteTable::default();
+ t.add(path, node);
+ self.by_root.push((root.to_owned(), t));
+ }
+ }
+ }
+
+ /// The table of the app `path` belongs to: the longest root it is under.
+ pub fn for_file(&self, path: &str) -> Option<&RouteTable> {
+ self.by_root.iter().filter(|(r, _)| path.starts_with(r.as_str())).max_by_key(|(r, _)| r.len()).map(|(_, t)| t)
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.by_root.is_empty()
+ }
+}
+
+/// Encode an href's arms for a site payload, one per line.
+pub fn encode_arms(arms: &[Href]) -> String {
+ arms.iter().map(|a| a.path.as_str()).collect::>().join("\n")
+}
+
+pub fn decode_arms(payload: &str) -> Vec {
+ payload.split('\n').filter(|p| !p.is_empty()).map(|p| Href { path: p.to_owned() }).collect()
+}
+
+/// React Router's nesting: a child path is relative unless it starts with `/`.
+pub fn compose_route_path(parts: &[&str]) -> String {
+ let mut path = String::new();
+ for part in parts {
+ if part.starts_with('/') {
+ path = (*part).to_owned();
+ } else if !part.is_empty() {
+ path = format!("{}/{part}", path.trim_end_matches('/'));
+ }
+ }
+ let mut out = format!("/{}", path.trim_start_matches('/'));
+ while out.contains("//") {
+ out = out.replace("//", "/");
+ }
+ if out.len() > 1 && out.ends_with('/') {
+ out.pop();
+ }
+ out
+}
+
+/// A TanStack path in the form the other routers use: `$id` -> `:id`, `$` -> a splat; `_auth`
+/// (pathless layout) and `(group)` segments are not in the URL; a trailing `_` un-nests.
+pub fn tanstack_path(raw: &str) -> Option {
+ if !raw.starts_with('/') {
+ return None;
+ }
+ let mut segs = Vec::new();
+ for seg in raw.split('/') {
+ if seg.is_empty() || seg.starts_with('_') || (seg.starts_with('(') && seg.ends_with(')')) {
+ continue;
+ }
+ let bare = seg.strip_suffix('_').unwrap_or(seg);
+ if bare == "$" {
+ segs.push(":splat*".to_owned());
+ } else if let Some(p) = bare.strip_prefix('$') {
+ segs.push(format!(":{p}"));
+ } else {
+ segs.push(bare.to_owned());
+ }
+ }
+ Some(format!("/{}", segs.join("/")))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn paths(v: &[Href]) -> Vec {
+ v.iter().map(Href::display).collect()
+ }
+
+ #[test]
+ fn reads_destinations() {
+ assert_eq!(paths(&parse_href_expression("'/users?tab=1'", "pathname")), vec!["/users"]);
+ assert_eq!(paths(&parse_href_expression("`/users/${u.id}/edit`", "pathname")), vec!["/users/${…}/edit"]);
+ assert_eq!(paths(&parse_href_expression("{ pathname: '/p/[id]', query: { id } }", "pathname")), vec!["/p/[id]"]);
+ assert_eq!(paths(&parse_href_expression("isAdmin ? '/admin' : ok ? '/a' : '/b'", "pathname")), vec!["/admin", "/a", "/b"]);
+ assert_eq!(paths(&parse_href_expression("{ to: '/posts/$postId', params }", "to")), vec!["/posts/$postId"]);
+ assert!(parse_href_expression("next", "pathname").is_empty());
+ assert_eq!(paths(&parse_href_expression("('/x' as any)", "pathname")), vec!["/x"]);
+ }
+
+ #[test]
+ fn matches_routes() {
+ let mut t = RouteTable::default();
+ t.add("/users", NodeIdx(1));
+ t.add("/users/:id", NodeIdx(2));
+ t.add("/users/top", NodeIdx(3));
+ t.add("/docs/:all*", NodeIdx(4));
+ let m = |p: &str| href_segments(p).and_then(|s| t.match_segments(&s));
+ assert_eq!(m("/users"), Some(NodeIdx(1)));
+ assert_eq!(m("/users/5"), Some(NodeIdx(2)));
+ assert_eq!(m("/users/top"), Some(NodeIdx(3)));
+ assert_eq!(m(&format!("/users/{HOLE}")), Some(NodeIdx(2)));
+ assert_eq!(m("/docs/a/b"), Some(NodeIdx(4)));
+ assert_eq!(m("https://x.com/users"), Some(NodeIdx(1)));
+ assert_eq!(m("users"), None);
+ assert_eq!(m("/nope"), None);
+ }
+
+ #[test]
+ fn paths_and_roots() {
+ assert_eq!(compose_route_path(&["/dashboard", "team", ""]), "/dashboard/team");
+ assert_eq!(compose_route_path(&["/a", "/b"]), "/b");
+ assert_eq!(compose_route_path(&["", ""]), "/");
+ assert_eq!(tanstack_path("/posts/$postId").as_deref(), Some("/posts/:postId"));
+ assert_eq!(tanstack_path("/_auth/invoices/").as_deref(), Some("/invoices"));
+ assert_eq!(app_root_for("apps/web/src/App.tsx"), "apps/web/");
+ assert_eq!(app_root_for("src/App.tsx"), "");
+ assert_eq!(app_root_for("lib/x.ts"), "lib/");
+ }
+}
diff --git a/crates/cg-resolve/src/frameworks/jsroutes.rs b/crates/cg-resolve/src/frameworks/jsroutes.rs
new file mode 100644
index 0000000..58e9f39
--- /dev/null
+++ b/crates/cg-resolve/src/frameworks/jsroutes.rs
@@ -0,0 +1,994 @@
+//! Route tables of the JavaScript frameworks (upstream `frameworks/{nextjs,nestjs,react,
+//! tanstack-router}.ts`): Next.js file routes, NestJS decorators across HTTP, GraphQL,
+//! microservice and WebSocket transports, React Router's `` markup and route objects,
+//! and TanStack Router's file and code routes. A page is named by its path alone and reaches
+//! the component it renders; a server route is `METHOD path` and references its handler.
+
+use super::href::{compose_route_path, match_bracket, object_field, read_string_at, tanstack_path};
+use super::routes::{Handler, Route};
+use cg_core::{EdgeKind, RefKind};
+use regex::Regex;
+use std::sync::OnceLock;
+
+macro_rules! re {
+ ($name:ident, $pat:expr) => {
+ fn $name() -> &'static Regex {
+ static R: OnceLock = OnceLock::new();
+ R.get_or_init(|| Regex::new($pat).expect("static regex"))
+ }
+ };
+}
+
+/// 1-based line of a byte offset.
+fn line_at(src: &str, off: usize) -> u32 {
+ src.as_bytes()[..off.min(src.len())].iter().filter(|b| **b == b'\n').count() as u32 + 1
+}
+
+// ------------------------------------------------------------------- Next.js
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum NextKind {
+ /// `app/**/page.tsx`, `pages/**`: a page component.
+ Page,
+ /// `app/**/route.ts`: one route per exported HTTP method.
+ Handler,
+ /// `pages/api/**`: `ANY /api/...` bound to the default export.
+ Api,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct NextRoute {
+ pub kind: NextKind,
+ /// `/blog/:slug`
+ pub path: String,
+ /// The directory the Next app lives in (`""`, `apps/web/`).
+ pub root: String,
+}
+
+/// `[slug]` -> `:slug`, `[...all]` / `[[...all]]` -> `:all*`.
+fn next_segment(seg: &str) -> String {
+ if let Some(inner) = seg.strip_prefix("[[...").and_then(|s| s.strip_suffix("]]")) {
+ return format!(":{inner}*");
+ }
+ if let Some(inner) = seg.strip_prefix("[...").and_then(|s| s.strip_suffix(']')) {
+ return format!(":{inner}*");
+ }
+ if let Some(inner) = seg.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
+ return format!(":{inner}");
+ }
+ seg.to_owned()
+}
+
+/// The prefix before the first `src//` or `/` directory, and the rest.
+fn split_at_dir<'a>(rel: &'a str, dir: &str) -> Option<(&'a str, &'a str)> {
+ let mut at = 0;
+ let segs: Vec<&str> = rel.split('/').collect();
+ for (i, seg) in segs.iter().enumerate() {
+ if i + 1 < segs.len() {
+ if *seg == dir {
+ return Some((&rel[..at], &rel[at + seg.len() + 1..]));
+ }
+ if *seg == "src" && segs.get(i + 1) == Some(&dir) && i + 2 < segs.len() {
+ return Some((&rel[..at], &rel[at + 4 + dir.len() + 1..]));
+ }
+ }
+ at += seg.len() + 1;
+ }
+ None
+}
+
+const NEXT_EXTS: &[&str] = &["tsx", "ts", "jsx", "js", "mjs", "cjs", "md", "mdx"];
+
+/// What a file is to the Next router, or `None` for a file that is no route.
+pub fn next_route_of(rel: &str) -> Option {
+ if rel.split('/').any(|s| matches!(s, "__tests__" | "__mocks__" | "node_modules")) {
+ return None;
+ }
+ if let Some((root, rest)) = split_at_dir(rel, "app") {
+ let (dir, file) = rest.rsplit_once('/').unwrap_or(("", rest));
+ let (stem, ext) = file.rsplit_once('.')?;
+ if !NEXT_EXTS.contains(&ext) || !matches!(stem, "page" | "route") {
+ return None;
+ }
+ let segs: Vec<&str> = dir.split('/').filter(|s| !s.is_empty()).collect();
+ // parallel (`@slot`) and intercepting (`(.)photo`) routes are not modelled
+ if segs.iter().any(|s| s.starts_with('@') || s.starts_with("(.)") || s.starts_with("(..)") || s.starts_with("(...)")) {
+ return None;
+ }
+ let kept: Vec = segs.iter().filter(|s| !(s.starts_with('(') && s.ends_with(')'))).map(|s| next_segment(s)).collect();
+ let kind = if stem == "page" { NextKind::Page } else { NextKind::Handler };
+ return Some(NextRoute { kind, path: format!("/{}", kept.join("/")), root: root.to_owned() });
+ }
+ let (root, rest) = split_at_dir(rel, "pages")?;
+ let (bare, ext) = rest.rsplit_once('.')?;
+ if !NEXT_EXTS.contains(&ext) {
+ return None;
+ }
+ let mut segs: Vec<&str> = bare.split('/').collect();
+ let base = *segs.last()?;
+ if base.starts_with('_') || [".test", ".spec", ".stories", ".config", ".d"].iter().any(|s| bare.ends_with(s)) {
+ return None;
+ }
+ if segs.last() == Some(&"index") {
+ segs.pop();
+ }
+ let kind = if segs.first() == Some(&"api") { NextKind::Api } else { NextKind::Page };
+ let path = format!("/{}", segs.iter().map(|s| next_segment(s)).collect::>().join("/"));
+ Some(NextRoute { kind, path, root: root.to_owned() })
+}
+
+re!(
+ next_handler_re,
+ r"\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b|\bexport\s+(?:const|let)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s*="
+);
+re!(default_fn_re, r"export\s+default\s+(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)");
+re!(default_class_re, r"export\s+default\s+class\s+([A-Za-z_$][\w$]*)");
+re!(default_wrapped_re, r"export\s+default\s+(?:[A-Za-z_$][\w$]*\.)?[A-Za-z_$][\w$]*\s*\(\s*([A-Za-z_$][\w$]*)\s*[,)]");
+re!(default_ident_re, r"(?m)export\s+default\s+([A-Za-z_$][\w$]*)\s*;?\s*$");
+re!(default_as_re, r"export\s*\{\s*([A-Za-z_$][\w$]*)\s+as\s+default\s*\}");
+
+/// The name the module exports as its default (a wrapper such as `memo(Page)` is looked
+/// through), with its offset.
+pub fn default_export_name(src: &str) -> Option<(String, usize)> {
+ for re in [default_fn_re(), default_class_re(), default_wrapped_re(), default_ident_re(), default_as_re()] {
+ if let Some(c) = re.captures(src) {
+ let g = c.get(1)?;
+ if g.as_str() != "default" {
+ return Some((g.as_str().to_owned(), c.get(0)?.start()));
+ }
+ }
+ }
+ None
+}
+
+pub fn scan_next(rel: &str, src: &str) -> Vec {
+ let Some(file) = next_route_of(rel) else { return Vec::new() };
+ let mut out = Vec::new();
+ match file.kind {
+ NextKind::Handler => {
+ let mut seen = Vec::new();
+ for c in next_handler_re().captures_iter(src) {
+ let Some(m) = c.get(1).or_else(|| c.get(2)) else { continue };
+ if seen.contains(&m.as_str()) {
+ continue;
+ }
+ seen.push(m.as_str());
+ let line = line_at(src, c.get(0).unwrap().start());
+ out.push(Route {
+ method: m.as_str().to_owned(),
+ path: file.path.clone(),
+ line,
+ handlers: vec![Handler { name: m.as_str().to_owned(), line, col: 0 }],
+ router: Some("next"),
+ ..Default::default()
+ });
+ }
+ }
+ NextKind::Page | NextKind::Api => {
+ let handlers = default_export_name(src).map(|(name, at)| Handler { name, line: line_at(src, at), col: 0 }).into_iter().collect();
+ let api = file.kind == NextKind::Api;
+ out.push(Route {
+ method: if api { "ANY".into() } else { String::new() },
+ path: file.path,
+ line: 1,
+ handlers,
+ ref_kind: if api { RefKind::FunctionRef } else { RefKind::Edge(EdgeKind::Calls) },
+ router: Some("next"),
+ });
+ }
+ }
+ out
+}
+
+// ------------------------------------------------------------------- NestJS
+
+/// `@Name(` at `at`: the arguments' text and the offset after `)`.
+fn decorator_args(src: &str, open: usize) -> Option<(&str, usize)> {
+ let close = match_bracket(src, open)?;
+ Some((&src[open + 1..close], close + 1))
+}
+
+/// Every `@Name(...)` decorator named in `names`: (name, args, start, end).
+fn decorators<'s>(src: &'s str, names: &[&str]) -> Vec<(&'s str, &'s str, usize, usize)> {
+ let mut out = Vec::new();
+ let b = src.as_bytes();
+ let mut i = 0;
+ while let Some(rel) = src[i..].find('@') {
+ let at = i + rel;
+ i = at + 1;
+ let name_end = src[at + 1..].find(|c: char| !(c.is_alphanumeric() || c == '_')).map_or(src.len(), |e| at + 1 + e);
+ let name = &src[at + 1..name_end];
+ if !names.contains(&name) {
+ continue;
+ }
+ let mut open = name_end;
+ while open < b.len() && b[open].is_ascii_whitespace() {
+ open += 1;
+ }
+ if b.get(open) != Some(&b'(') {
+ continue;
+ }
+ if let Some((args, end)) = decorator_args(src, open) {
+ out.push((name, args, at, end));
+ i = end;
+ }
+ }
+ out
+}
+
+/// The method a decorator ending at `from` sits on: skip stacked decorators and modifiers.
+fn method_after(src: &str, from: usize) -> Option<(String, usize)> {
+ let b = src.as_bytes();
+ let mut i = from;
+ let ws = |i: &mut usize| {
+ while *i < b.len() && b[*i].is_ascii_whitespace() {
+ *i += 1;
+ }
+ };
+ loop {
+ ws(&mut i);
+ if b.get(i) != Some(&b'@') {
+ break;
+ }
+ i += 1;
+ while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'.') {
+ i += 1;
+ }
+ ws(&mut i);
+ if b.get(i) == Some(&b'(') {
+ i = match_bracket(src, i)? + 1;
+ }
+ }
+ loop {
+ ws(&mut i);
+ let rest = &src[i..];
+ let m = ["public", "private", "protected", "async", "static", "readonly", "override"]
+ .iter()
+ .find(|m| rest.starts_with(**m) && rest[m.len()..].starts_with(|c: char| !(c.is_alphanumeric() || c == '_')));
+ match m {
+ Some(m) => i += m.len(),
+ None => break,
+ }
+ }
+ let rest = &src[i..];
+ let end = rest.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$')).unwrap_or(rest.len());
+ if end == 0 {
+ return None;
+ }
+ let after = rest[end..].trim_start();
+ (after.starts_with('(') || after.starts_with('<')).then(|| (rest[..end].to_owned(), i))
+}
+
+re!(first_string_re, r#"['"`]([^'"`]*)['"`]"#);
+re!(path_field_re, r#"path\s*:\s*['"`]([^'"`]*)['"`]"#);
+re!(namespace_re, r#"namespace\s*:\s*['"`]([^'"`]*)['"`]"#);
+re!(name_field_re, r#"name\s*:\s*['"`]([^'"`]*)['"`]"#);
+re!(lead_string_re, r#"^\s*['"`]([^'"`]*)['"`]"#);
+
+fn first_string(args: &str) -> String {
+ first_string_re().captures(args).map(|c| c[1].to_owned()).unwrap_or_default()
+}
+
+fn join_http(prefix: &str, sub: &str) -> String {
+ let parts: Vec<&str> = [prefix, sub].iter().map(|p| p.trim().trim_matches('/')).filter(|p| !p.is_empty()).collect();
+ format!("/{}", parts.join("/"))
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum NestClass {
+ Controller,
+ Resolver,
+ Gateway,
+ Other,
+}
+
+pub fn scan_nest(src: &str) -> Vec {
+ // class scopes: each runs from its decorator to the next class decorator
+ let mut raw: Vec<(NestClass, String, usize)> = Vec::new();
+ for (name, args, at, _) in decorators(src, &["Controller", "Resolver", "WebSocketGateway", "Injectable", "Module", "Catch"]) {
+ let (kind, prefix) = match name {
+ "Controller" => (NestClass::Controller, path_field_re().captures(args).map(|c| c[1].to_owned()).unwrap_or_else(|| first_string(args))),
+ "Resolver" => (NestClass::Resolver, String::new()),
+ "WebSocketGateway" => (NestClass::Gateway, namespace_re().captures(args).map(|c| c[1].to_owned()).unwrap_or_default()),
+ _ => (NestClass::Other, String::new()),
+ };
+ raw.push((kind, prefix, at));
+ }
+ raw.sort_by_key(|r| r.2);
+ let scope_for = |at: usize| -> Option<(NestClass, &str)> {
+ let i = raw.partition_point(|r| r.2 <= at);
+ (i > 0).then(|| (raw[i - 1].0, raw[i - 1].1.as_str()))
+ };
+ let mut out = Vec::new();
+ let mut add = |at: usize, method: String, path: String, handler: Option<(String, usize)>| {
+ let line = line_at(src, at);
+ let handlers = handler.map(|(h, _)| Handler { name: h, line, col: 0 }).into_iter().collect();
+ out.push(Route { method, path, line, handlers, ..Default::default() });
+ };
+ for (name, args, at, end) in decorators(src, &["Get", "Post", "Put", "Patch", "Delete", "Head", "Options", "All"]) {
+ let prefix = match scope_for(at) {
+ Some((NestClass::Controller, p)) => p,
+ _ => "",
+ };
+ add(at, name.to_ascii_uppercase(), join_http(prefix, &first_string(args)), method_after(src, end));
+ }
+ for (name, args, at, end) in decorators(src, &["Query", "Mutation", "Subscription"]) {
+ // `@Query()` is also REST's parameter decorator: only a resolver's is GraphQL
+ if !matches!(scope_for(at), Some((NestClass::Resolver, _))) {
+ continue;
+ }
+ let handler = method_after(src, end);
+ let op = name_field_re()
+ .captures(args)
+ .or_else(|| lead_string_re().captures(args))
+ .map(|c| c[1].to_owned())
+ .or_else(|| handler.as_ref().map(|h| h.0.clone()))
+ .unwrap_or_default();
+ add(at, name.to_ascii_uppercase(), op, handler);
+ }
+ for (name, args, at, end) in decorators(src, &["MessagePattern", "EventPattern"]) {
+ let handler = method_after(src, end);
+ let verb = if name == "EventPattern" { "EVENT" } else { "MESSAGE" };
+ let pattern = Some(first_string(args)).filter(|s| !s.is_empty()).or_else(|| handler.as_ref().map(|h| h.0.clone())).unwrap_or_default();
+ add(at, verb.into(), pattern, handler);
+ }
+ for (_, args, at, end) in decorators(src, &["SubscribeMessage"]) {
+ let ns = match scope_for(at) {
+ Some((NestClass::Gateway, p)) => p,
+ _ => "",
+ };
+ let handler = method_after(src, end);
+ let event = Some(first_string(args)).filter(|s| !s.is_empty()).or_else(|| handler.as_ref().map(|h| h.0.clone())).unwrap_or_default();
+ add(at, "WS".into(), if ns.is_empty() { event } else { format!("{ns}:{event}") }, handler);
+ }
+ out.sort_by_key(|r| r.line);
+ out
+}
+
+// ------------------------------------------------------------------- React Router
+
+/// A route-bearing `` or route object, with the span its children sit in.
+#[derive(Clone, Debug)]
+struct RrScope {
+ /// The path as written (`None`: a path the file does not spell out).
+ part: Option,
+ at: usize,
+ start: usize,
+ end: usize,
+ component: Option,
+ jsx: bool,
+ index: bool,
+ pathless: bool,
+ outlet: bool,
+}
+
+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");
+
+/// The component an `element` renders: the first tag that is no guard, provider or outlet.
+fn element_component(value: &str) -> Option {
+ let inner = value.trim().trim_start_matches('(').trim_start();
+ if !inner.starts_with('<') {
+ return None;
+ }
+ let tags: Vec<&str> = capital_tag_re().captures_iter(inner).filter_map(|c| c.get(1)).map(|m| m.as_str()).collect();
+ let content = |t: &&&str| !wrapper_re().is_match(t) && **t != "Outlet";
+ tags.iter().find(content).or_else(|| tags.iter().rev().find(|t| **t != "Outlet")).or(tags.first()).map(|t| t.to_string())
+}
+
+fn literal(value: &str) -> Option {
+ let v = value.trim();
+ let v = v.strip_prefix('{').and_then(|x| x.strip_suffix('}')).map(str::trim).unwrap_or(v);
+ if (v.starts_with('"') || v.starts_with('\'')) && v.len() >= 2 && v.ends_with(&v[..1]) {
+ return Some(v[1..v.len() - 1].to_owned());
+ }
+ None
+}
+
+struct RrScan<'a> {
+ s: &'a str,
+ b: &'a [u8],
+ jsx_ok: bool,
+ objects: bool,
+ scopes: Vec,
+ routers: Vec<(usize, usize)>,
+ route_tags: usize,
+ depth: u32,
+}
+
+impl<'a> RrScan<'a> {
+ fn trivia(&self, mut at: usize) -> usize {
+ while at < self.b.len() && self.b[at].is_ascii_whitespace() {
+ at += 1;
+ }
+ at
+ }
+
+ fn token_before(&self, at: usize) -> &'a str {
+ let mut j = at;
+ while j > 0 && self.b[j - 1].is_ascii_whitespace() {
+ j -= 1;
+ }
+ &self.s[j.saturating_sub(12)..j]
+ }
+
+ /// One syntactic unit starting at `at`: a string, a JSX element, a bracketed group or one
+ /// byte. Returns the offset after it.
+ fn unit(&mut self, at: usize) -> usize {
+ if self.depth > 200 {
+ return self.b.len();
+ }
+ let Some(&c) = self.b.get(at) else { return at };
+ match c {
+ b'"' | b'\'' => return super::href::string_end(self.s, at).map_or(at + 1, |e| e + 1),
+ b'`' => return super::href::template_end(self.s, at).map_or(self.b.len(), |e| e + 1),
+ b'<' if self.jsx_ok => {
+ let next = self.b.get(at + 1).copied().unwrap_or(0);
+ let before = self.token_before(at);
+ let opens = next.is_ascii_alphabetic() || next == b'>';
+ let after_value = before.ends_with(|ch: char| ch.is_alphanumeric() || "_$)]'\"".contains(ch)) && !before.ends_with("return");
+ if opens && !after_value {
+ self.depth += 1;
+ let e = self.jsx(at);
+ self.depth -= 1;
+ return e;
+ }
+ return at + 1;
+ }
+ b'{' | b'[' | b'(' => {}
+ _ => return at + 1,
+ }
+ 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 fields: Vec<(&'a str, &'a str, usize)> = Vec::new();
+ let mut i = at + 1;
+ self.depth += 1;
+ loop {
+ i = self.trivia(i);
+ if i >= self.b.len() || self.b[i] == close {
+ break;
+ }
+ let entry = i;
+ let key = if c == b'{' {
+ let rest = &self.s[i..];
+ let name_len = rest.find(|ch: char| !(ch.is_alphanumeric() || ch == '_' || ch == '$')).unwrap_or(0);
+ (name_len > 0 && rest[name_len..].trim_start().starts_with(':')).then(|| &rest[..name_len])
+ } else {
+ None
+ };
+ if let Some(name) = key {
+ i = self.s[i..].find(':').map_or(self.b.len(), |k| i + k + 1);
+ let value_at = self.trivia(i);
+ i = value_at;
+ let mut value_end = i;
+ loop {
+ i = self.trivia(i);
+ if i >= self.b.len() || self.b[i] == b',' || self.b[i] == close {
+ break;
+ }
+ i = self.unit(i);
+ value_end = i;
+ }
+ fields.push((name, self.s[value_at..value_end.max(value_at)].trim(), entry));
+ } else {
+ loop {
+ i = self.trivia(i);
+ if i >= self.b.len() || self.b[i] == b',' || self.b[i] == close {
+ break;
+ }
+ i = self.unit(i);
+ }
+ }
+ if self.b.get(i) == Some(&b',') {
+ i += 1;
+ }
+ }
+ self.depth -= 1;
+ if self.objects && c == b'{' && i < self.b.len() {
+ let get = |k: &str| fields.iter().find(|f| f.0 == k);
+ let path = get("path").and_then(|f| literal(f.1));
+ let shown = get("element")
+ .and_then(|f| element_component(f.1))
+ .or_else(|| get("Component").map(|f| f.1.trim().to_owned()).filter(|v| v.starts_with(|c: char| c.is_ascii_uppercase())));
+ let outlet = shown.as_deref() == Some("Outlet") && path.as_deref() != Some("");
+ let component = shown.filter(|s| s != "Outlet");
+ if let Some(p) = get("path") {
+ let opaque = path.is_none();
+ self.scopes.push(RrScope {
+ part: path,
+ at: p.2,
+ start: at,
+ end: i,
+ component,
+ jsx: false,
+ index: false,
+ pathless: false,
+ outlet: outlet && !opaque,
+ });
+ } else if get("index").is_some_and(|f| f.1 == "true") {
+ let at_index = get("index").map_or(at, |f| f.2);
+ self.scopes.push(RrScope {
+ part: Some(String::new()),
+ at: at_index,
+ start: at,
+ end: i,
+ component,
+ jsx: false,
+ index: true,
+ pathless: false,
+ outlet: false,
+ });
+ } else if component.is_some() && get("children").is_some() {
+ self.scopes.push(RrScope {
+ part: Some(String::new()),
+ at,
+ start: at,
+ end: i,
+ component,
+ jsx: false,
+ index: false,
+ pathless: true,
+ outlet: false,
+ });
+ }
+ }
+ if routers_call {
+ self.routers.push((at, i));
+ }
+ (i + 1).min(self.b.len())
+ }
+
+ fn jsx(&mut self, at: usize) -> usize {
+ let rest = &self.s[at + 1..];
+ let tag_len = rest.find(|c: char| !(c.is_alphanumeric() || "_.:-".contains(c))).unwrap_or(rest.len());
+ let tag = &rest[..tag_len];
+ let mut i = at + 1 + tag_len;
+ let mut attrs: Vec<(&'a str, &'a str)> = Vec::new();
+ loop {
+ i = self.trivia(i);
+ if i >= self.b.len() || self.b[i] == b'>' || self.s[i..].starts_with("/>") {
+ break;
+ }
+ let rest = &self.s[i..];
+ let name_len = rest.find(|c: char| !(c.is_alphanumeric() || "_:-".contains(c))).unwrap_or(0);
+ if name_len == 0 {
+ i = self.unit(i);
+ continue;
+ }
+ let name = &rest[..name_len];
+ i = self.trivia(i + name_len);
+ if self.b.get(i) != Some(&b'=') {
+ attrs.push((name, "{true}"));
+ continue;
+ }
+ i = self.trivia(i + 1);
+ let start = i;
+ i = self.unit(i);
+ attrs.push((name, &self.s[start..i.min(self.b.len())]));
+ }
+ let get = |k: &str| attrs.iter().find(|a| a.0 == k).map(|a| a.1);
+ let mut scope: Option = None;
+ let mut addressless: Option<(RrScope, usize, bool)> = None;
+ let router = router_element_re().is_match(tag).then(|| {
+ self.routers.push((at, self.b.len()));
+ self.routers.len() - 1
+ });
+ if tag == "Route" && i < self.b.len() {
+ let path_text = get("path");
+ let path = path_text.and_then(literal);
+ self.route_tags += 1;
+ let expr = |k: &str| get(k).map(|v| v.trim().trim_start_matches('{').trim_end_matches('}').trim());
+ let element = expr("element").and_then(element_component).filter(|c| c != "Outlet");
+ let component = expr("component")
+ .filter(|v| v.starts_with(|c: char| c.is_ascii_uppercase()) && v.chars().all(|c| c.is_alphanumeric() || c == '_'))
+ .map(str::to_owned)
+ .or(element.clone());
+ let route = RrScope {
+ part: Some(path.clone().unwrap_or_default()),
+ at,
+ start: at,
+ end: self.b.len(),
+ component,
+ jsx: true,
+ index: false,
+ pathless: false,
+ outlet: false,
+ };
+ match (&path, path_text) {
+ (Some(p), _) if !p.is_empty() => {
+ self.scopes.push(route);
+ scope = Some(self.scopes.len() - 1);
+ }
+ (_, None) | (Some(_), Some(_)) => {
+ if get("index").is_some_and(|v| v.trim_matches(['{', '}', ' ']) == "true") {
+ if route.component.is_some() {
+ self.scopes.push(RrScope { index: true, ..route });
+ scope = Some(self.scopes.len() - 1);
+ }
+ } else {
+ let page = path.as_deref() == Some("") && element.is_some();
+ addressless = Some((route, self.route_tags, page));
+ }
+ }
+ (None, Some(_)) => {
+ // `path={paths.home}`: an address the file does not spell out
+ self.scopes.push(RrScope { part: None, ..route });
+ scope = Some(self.scopes.len() - 1);
+ }
+ }
+ }
+ let mut close = |me: &mut Self, end: usize| -> usize {
+ if let Some(s) = scope {
+ me.scopes[s].end = end;
+ }
+ if let Some(r) = router {
+ me.routers[r].1 = end;
+ }
+ if let Some((mut route, tags, page)) = addressless.take() {
+ route.end = end;
+ if me.route_tags > tags {
+ if route.component.is_some() {
+ me.scopes.push(RrScope { pathless: true, ..route });
+ }
+ } else if page {
+ me.scopes.push(RrScope { index: true, ..route });
+ }
+ }
+ end
+ };
+ if self.s[i..].starts_with("/>") {
+ return close(self, i + 2);
+ }
+ i += 1;
+ while i < self.b.len() {
+ 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);
+ }
+ match self.b[i] {
+ b'<' if self.b.get(i + 1).is_some_and(|c| c.is_ascii_alphabetic() || *c == b'>') => {
+ self.depth += 1;
+ i = self.jsx(i);
+ self.depth -= 1;
+ }
+ b'{' => i = self.unit(i),
+ _ => i += 1,
+ }
+ }
+ close(self, i)
+ }
+}
+
+/// The routes a file's own text declares (upstream `scanRoutes` for one file).
+pub fn scan_react_router(rel: &str, src: &str) -> Vec {
+ let objects = router_call_re().is_match(src);
+ if !objects && !src.contains("= end;
+ let around = |start: usize, end: usize| -> Vec<&RrScope> {
+ let mut v: Vec<&RrScope> = scopes.iter().filter(|o| holds(o, start, end)).collect();
+ v.sort_by_key(|o| o.start);
+ v
+ };
+ let path_of = |s: &RrScope| -> Option {
+ let mut parts: Vec<&str> = Vec::new();
+ for o in around(s.start, s.end) {
+ parts.push(o.part.as_deref()?);
+ }
+ parts.push(s.part.as_deref()?);
+ Some(compose_route_path(&parts))
+ };
+ let in_router = |s: &RrScope| routers.iter().any(|r| r.0 < s.start && r.1 >= s.end);
+ let addressed = |s: &RrScope| {
+ if !s.index {
+ return true;
+ }
+ let outer = around(s.start, s.end);
+ !outer.iter().any(|c| c.part.is_none()) && (outer.iter().any(|c| c.part.as_deref().is_some_and(|p| !p.is_empty())) || in_router(s))
+ };
+ let pages: Vec<&RrScope> =
+ scopes.iter().filter(|s| !s.pathless && s.part.is_some() && (s.jsx || s.outlet || s.component.is_some()) && addressed(s)).collect();
+ let mut out = Vec::new();
+ for s in &pages {
+ let Some(path) = path_of(s) else { continue };
+ // a route around others is their layout when one of them claims its address
+ let claimed = pages.iter().any(|inner| {
+ !std::ptr::eq(*inner, *s)
+ && inner.jsx == s.jsx
+ && inner.component.is_some()
+ && holds(s, inner.start, inner.end)
+ && path_of(inner).as_deref() == Some(path.as_str())
+ });
+ if claimed || path.ends_with('*') {
+ continue;
+ }
+ 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") });
+ }
+ out.sort_by_key(|r| r.line);
+ out.dedup_by(|a, b| a.path == b.path && a.line == b.line);
+ out
+}
+
+// ------------------------------------------------------------------- TanStack Router
+
+re!(tanstack_factory_re, r"\bcreate(?:File|Lazy(?:File)?|Root)?Route\s*\(");
+re!(tanstack_file_re, r"\bcreate(?:Lazy)?FileRoute\s*\(");
+re!(tanstack_named_re, r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]*?)?=\s*create(Root)?Route\s*\(\s*\{");
+re!(tanstack_lazy_import_re, r#"\bimport\s*\(\s*['"`]([^'"`]+)['"`]"#);
+re!(tanstack_component_re, r"(?:^|[^\w$])component\s*:\s*([A-Z][A-Za-z0-9_]*)");
+re!(parent_arrow_re, r"=>\s*([A-Za-z_$][\w$]*)");
+
+/// The component a route names: an identifier, or the file a lazy import names.
+fn tanstack_component(text: &str) -> Option {
+ if let Some(c) = tanstack_lazy_import_re().captures(text) {
+ let file = c[1].rsplit('/').next().unwrap_or("");
+ let stem = file.rsplit_once('.').map_or(file, |x| x.0);
+ return (!stem.is_empty()).then(|| stem.to_owned());
+ }
+ if let Some(c) = tanstack_component_re().captures(text) {
+ return Some(c[1].to_owned());
+ }
+ let t = text.trim();
+ (t.starts_with(|c: char| c.is_ascii_uppercase()) && t.chars().all(|c| c.is_alphanumeric() || c == '_')).then(|| t.to_owned())
+}
+
+/// The call chain after a factory call: `({ … })` and any `.update({ … })` / `.lazy(…)`.
+fn chain_after(s: &str, at: usize) -> &str {
+ let b = s.as_bytes();
+ let mut i = at;
+ for _ in 0..8 {
+ while i < b.len() && b[i].is_ascii_whitespace() {
+ i += 1;
+ }
+ if b.get(i) == Some(&b'.') {
+ i += 1;
+ while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'$') {
+ i += 1;
+ }
+ while i < b.len() && b[i].is_ascii_whitespace() {
+ i += 1;
+ }
+ }
+ if b.get(i) != Some(&b'(') {
+ break;
+ }
+ match match_bracket(s, i) {
+ Some(c) => i = c + 1,
+ None => break,
+ }
+ }
+ &s[at..i.min(s.len())]
+}
+
+fn is_pathless_layout(raw: &str) -> bool {
+ if raw.len() > 1 && raw.ends_with('/') {
+ return false; // the index route inside the layout
+ }
+ raw.split('/').rfind(|s| !s.is_empty()).is_some_and(|l| l.starts_with('_'))
+}
+
+pub fn scan_tanstack(rel: &str, src: &str) -> Vec {
+ if !tanstack_factory_re().is_match(src) {
+ return Vec::new();
+ }
+ let base = rel.rsplit('/').next().unwrap_or(rel);
+ let layout_file =
+ base == "route.tsx" || base == "route.ts" || base == "route.jsx" || base == "route.js" || base.contains(".route.") || src.contains(", bool, u32)> = Vec::new();
+ for m in tanstack_file_re().find_iter(src) {
+ let open = m.end() - 1;
+ let Some(close) = match_bracket(src, open) else { continue };
+ let inner = src[open + 1..close].trim_start();
+ let Some(raw) = read_string_at(inner, 0) else { continue };
+ let Some(path) = tanstack_path(&raw) else { continue };
+ if is_pathless_layout(&raw) || layout_file {
+ continue;
+ }
+ let index = raw.len() > 1 && raw.ends_with('/');
+ entries.push((path, tanstack_component(chain_after(src, close + 1)), index, line_at(src, m.start())));
+ }
+ // code-based routes: a path per route, composed through `getParentRoute`
+ struct Decl {
+ name: String,
+ path: Option,
+ parent: Option,
+ component: Option,
+ root: bool,
+ at: usize,
+ }
+ let mut decls: Vec = Vec::new();
+ for c in tanstack_named_re().captures_iter(src) {
+ let whole = c.get(0).unwrap();
+ let brace = whole.end() - 1;
+ let Some(end) = match_bracket(src, brace) else { continue };
+ let obj = &src[brace..=end];
+ let root = c.get(2).is_some();
+ let path = if root { Some("/".to_owned()) } else { object_field(obj, "path").and_then(|v| read_string_at(v, 0)) };
+ let parent = object_field(obj, "getParentRoute").and_then(|v| parent_arrow_re().captures(v)).map(|p| p[1].to_owned());
+ let component = object_field(obj, "component").and_then(tanstack_component);
+ decls.push(Decl { name: c[1].to_owned(), path, parent, component, root, at: whole.start() });
+ }
+ let wraps_index: Vec<&str> = decls.iter().filter(|d| d.path.as_deref() == Some("/") && d.parent.is_some()).filter_map(|d| d.parent.as_deref()).collect();
+ for d in &decls {
+ let Some(own) = &d.path else { continue };
+ if d.root || wraps_index.contains(&d.name.as_str()) {
+ continue;
+ }
+ // compose through the parents declared in this file
+ let mut segs: Vec = Vec::new();
+ let mut cur = Some(d.name.as_str());
+ let mut ok = true;
+ for _ in 0..24 {
+ let Some(name) = cur else { break };
+ let Some(decl) = decls.iter().find(|x| x.name == name) else {
+ ok = false;
+ break;
+ };
+ if let Some(p) = &decl.path {
+ let mut own: Vec = p.split('/').filter(|s| !s.is_empty()).map(str::to_owned).collect();
+ own.extend(segs);
+ segs = own;
+ }
+ cur = decl.parent.as_deref();
+ }
+ if !ok {
+ continue;
+ }
+ let Some(path) = tanstack_path(&format!("/{}", segs.join("/"))) else { continue };
+ entries.push((path, d.component.clone(), own == "/", line_at(src, d.at)));
+ }
+ // one route per address: an index route outranks the layout that wraps it
+ let mut by_path: Vec<(String, Option, bool, u32)> = Vec::new();
+ for e in entries {
+ match by_path.iter_mut().find(|x| x.0 == e.0) {
+ Some(held) if e.2 && !held.2 => *held = e,
+ Some(_) => {}
+ None => by_path.push(e),
+ }
+ }
+ by_path
+ .into_iter()
+ .map(|(path, component, _, line)| Route {
+ method: String::new(),
+ path,
+ line,
+ handlers: component.map(|c| Handler { name: c, line, col: 0 }).into_iter().collect(),
+ ref_kind: RefKind::Edge(EdgeKind::Calls),
+ router: Some("tanstack-router"),
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn names(r: &[Route]) -> Vec {
+ r.iter()
+ .map(|r| {
+ format!(
+ "{}{} -> {}",
+ if r.method.is_empty() { String::new() } else { format!("{} ", r.method) },
+ r.path,
+ r.handlers.iter().map(|h| h.name.as_str()).collect::>().join("|")
+ )
+ })
+ .collect()
+ }
+
+ #[test]
+ fn next_files() {
+ let r = |p: &str| next_route_of(p).map(|n| (n.kind, n.path, n.root));
+ assert_eq!(r("app/users/[id]/page.tsx"), Some((NextKind::Page, "/users/:id".into(), "".into())));
+ assert_eq!(r("apps/web/src/app/(shop)/cart/page.tsx"), Some((NextKind::Page, "/cart".into(), "apps/web/".into())));
+ assert_eq!(r("app/docs/[...all]/page.mdx"), Some((NextKind::Page, "/docs/:all*".into(), "".into())));
+ assert_eq!(r("app/api/x/route.ts"), Some((NextKind::Handler, "/api/x".into(), "".into())));
+ assert_eq!(r("app/@modal/x/page.tsx"), None);
+ assert_eq!(r("app/layout.tsx"), None);
+ assert_eq!(r("pages/index.tsx"), Some((NextKind::Page, "/".into(), "".into())));
+ assert_eq!(r("pages/api/users.ts"), Some((NextKind::Api, "/api/users".into(), "".into())));
+ assert_eq!(r("pages/_app.tsx"), None);
+ assert_eq!(r("src/pages/blog/[slug].tsx"), Some((NextKind::Page, "/blog/:slug".into(), "".into())));
+ assert_eq!(names(&scan_next("app/cart/page.tsx", "export default function Cart() { return null }")), vec!["/cart -> Cart"]);
+ assert_eq!(names(&scan_next("app/a/page.tsx", "function A() {}\nexport default memo(A);")), vec!["/a -> A"]);
+ assert_eq!(
+ names(&scan_next("app/api/x/route.ts", "export async function GET(req) {}\nexport const POST = async () => {}")),
+ vec!["GET /api/x -> GET", "POST /api/x -> POST"]
+ );
+ }
+
+ #[test]
+ fn nest_decorators() {
+ let src = r#"
+@Controller('users')
+export class UsersController {
+ constructor(private readonly svc: UsersService) {}
+ @Get(':id')
+ @UseGuards(AuthGuard)
+ async findOne(@Param('id') id: string) {}
+ @Post()
+ create(@Body() dto: Dto) {}
+}
+@Resolver(() => User)
+export class UsersResolver {
+ @Query(() => [User], { name: 'users' })
+ all() {}
+}
+@WebSocketGateway({ namespace: 'chat' })
+export class ChatGateway {
+ @SubscribeMessage('message')
+ handle() {}
+}
+@Controller()
+export class Jobs {
+ @EventPattern('user.created')
+ onCreated() {}
+}
+"#;
+ assert_eq!(
+ names(&scan_nest(src)),
+ vec!["GET /users/:id -> findOne", "POST /users -> create", "QUERY users -> all", "WS chat:message -> handle", "EVENT user.created -> onCreated"]
+ );
+ }
+
+ #[test]
+ fn react_router_markup_and_objects() {
+ let src = r#"
+export function App() {
+ return (
+
+
+ }>
+ } />
+ }>
+ } />
+
+ } />
+
+
+
+
+ );
+}
+"#;
+ assert_eq!(
+ names(&scan_react_router("src/App.tsx", src)),
+ vec!["/ -> Home", "/dashboard -> Dashboard", "/dashboard/team -> Team", "/payment -> PaymentScreen"]
+ );
+ let objects = "const router = createBrowserRouter([\n { path: '/', element: , children: [\n { index: true, element: },\n { path: 'posts/:id', element: },\n ] },\n]);\n";
+ assert_eq!(names(&scan_react_router("src/router.tsx", objects)), vec!["/ -> Index", "/posts/:id -> Post"]);
+ // a menu list that never reaches the router is no route table
+ assert!(scan_react_router("src/menu.ts", "export const menu = [{ path: '/x', element: Foo }];").is_empty());
+ }
+
+ #[test]
+ fn tanstack_routes() {
+ let file = "export const Route = createFileRoute('/posts/$postId')({\n component: PostComponent,\n})\n";
+ assert_eq!(names(&scan_tanstack("src/routes/posts.$postId.tsx", file)), vec!["/posts/:postId -> PostComponent"]);
+ assert!(scan_tanstack("src/routes/_auth.tsx", "export const Route = createFileRoute('/_auth')({ component: A })").is_empty());
+ let code = "const rootRoute = createRootRoute({ component: Root })\nconst postsRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts', component: Posts })\nconst postRoute = createRoute({ getParentRoute: () => postsRoute, path: '$postId', component: Post })\n";
+ assert_eq!(names(&scan_tanstack("src/main.tsx", code)), vec!["/posts -> Posts", "/posts/:postId -> Post"]);
+ }
+}
diff --git a/crates/cg-resolve/src/frameworks/mod.rs b/crates/cg-resolve/src/frameworks/mod.rs
index 25e974a..436c1eb 100644
--- a/crates/cg-resolve/src/frameworks/mod.rs
+++ b/crates/cg-resolve/src/frameworks/mod.rs
@@ -1,6 +1,9 @@
//! Framework rules (design doc 6.7): detection from manifests, extract hooks that add route
//! nodes, resolve rules. The hook list is empty for projects that use none.
+pub mod href;
+pub mod jsroutes;
+pub mod nav;
pub mod routes;
use crate::project::ProjectInfo;
@@ -9,10 +12,24 @@ use routes::{Framework, RouteHook};
use std::sync::Arc;
pub fn hooks(project: &ProjectInfo) -> Vec> {
- let mut v: Vec> = Vec::new();
// synthesis site scanners: cheap literal prefilters keep them off files that cannot match
- v.push(Arc::new(crate::synth::sites::SiteScanner));
- for name in project.detect_frameworks() {
+ let mut v: Vec> = vec![
+ Arc::new(crate::synth::sites::SiteScanner),
+ Arc::new(crate::synth::sites::GoTypeSites),
+ Arc::new(crate::synth::dynamic::CallbackScanner),
+ Arc::new(crate::synth::dynamic::RegistryScanner),
+ Arc::new(crate::synth::dynamic::TierScanner),
+ Arc::new(crate::synth::dynamic::CeleryScanner),
+ Arc::new(crate::synth::dynamic::SpringEventScanner),
+ ];
+ let frameworks = project.detect_frameworks();
+ if frameworks.iter().any(|f| matches!(f.as_str(), "next" | "react-router" | "tanstack-router")) {
+ v.push(Arc::new(nav::NavScanner));
+ }
+ if frameworks.iter().any(|f| f == "next") {
+ v.push(Arc::new(nav::ProxyScanner));
+ }
+ for name in frameworks {
let fw = match name.as_str() {
"express" => Framework::Express,
"flask" => Framework::Flask,
@@ -22,6 +39,9 @@ pub fn hooks(project: &ProjectInfo) -> Vec> {
"spring" => Framework::Spring,
"axum" => Framework::Axum,
"next" => Framework::Next,
+ "nestjs" => Framework::Nest,
+ "react-router" => Framework::ReactRouter,
+ "tanstack-router" => Framework::TanStack,
_ => continue,
};
v.push(Arc::new(RouteHook { fw }));
diff --git a/crates/cg-resolve/src/frameworks/nav.rs b/crates/cg-resolve/src/frameworks/nav.rs
new file mode 100644
index 0000000..aae1592
--- /dev/null
+++ b/crates/cg-resolve/src/frameworks/nav.rs
@@ -0,0 +1,822 @@
+//! Navigation between pages (upstream `nextjs.ts`, `react-router.ts`, `tanstack-router.ts`
+//! resolvers and their link synthesizers) and the Next.js proxy (`next-proxy.ts`).
+//!
+//! A navigation is a string: `router.push('/users')`, `navigate({ to: '/posts/$id' })`,
+//! `redirect('/login')`, ``, ``. Extraction records each call
+//! and link with its destination expression (a bare identifier is read through its local
+//! `const`); the link step matches the destination against the router's own route table and
+//! draws a `navigates` edge from the function it is written in to the page. A computed
+//! destination, a path no page serves, or a tie between routes draws nothing.
+//!
+//! A Next proxy (`middleware.ts`, `proxy.ts`) is the one file nothing imports: each route its
+//! `config.matcher` accepts gets a `calls` edge to what runs in it.
+
+use super::href::{self, app_root_for, match_bracket, object_field, parse_href_expression, read_string_at, tanstack_path, Href, RootedTables, RouteTable};
+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::Out;
+use cg_core::{EdgeKind, FileId, Lang, LangFamily, NodeIdx, NodeKind, NONE};
+use cg_extract::{FileHook, HookCtx, HookOut, SiteFact};
+use regex::Regex;
+use rustc_hash::{FxHashMap, FxHashSet};
+use std::sync::OnceLock;
+
+pub const ROLE_NAV_CALL: u8 = 0;
+pub const ROLE_NAV_LINK: u8 = 1;
+
+/// Links a single component may carry before it is a navigation menu, not a decision.
+const MAX_LINKS_PER_COMPONENT: usize = 24;
+
+macro_rules! re {
+ ($name:ident, $pat:expr) => {
+ fn $name() -> &'static Regex {
+ static R: OnceLock = OnceLock::new();
+ R.get_or_init(|| Regex::new($pat).expect("static regex"))
+ }
+ };
+}
+
+re!(nav_call_re, r"((?:[A-Za-z_$][\w$]*\s*\??\.\s*)*)(push|replace|prefetch|navigate|redirect|permanentRedirect)\s*\(");
+re!(link_tag_re, r#"<(Link|NextLink|a|NavLink|Navigate|Redirect|LinkContainer|IndexLinkContainer)\b((?:[^>]|=>)*?)\b(href|to)\s*=\s*"#);
+re!(next_nav_re, r"(?:^|\.)(push|replace|prefetch)$|^(redirect|permanentRedirect)$|^(?:NextResponse|Response)\.(redirect)$");
+re!(router_word_re, r"(?i)(?:router|navigation|history)$");
+re!(rr_nav_re, r"^(?:history|navigate|router)\.(?:push|replace|navigate)$|^(?:navigate|redirect)$");
+re!(tanstack_nav_re, r"^(?:navigate|redirect)$|^(?:router|Route)\.navigate$");
+
+/// Destination text of a call's first argument, a bare identifier read through its local
+/// declaration in the enclosing function.
+fn destination_text<'a>(lines: &LineIndex<'a>, arg: &'a str, line: u32, floor: u32) -> &'a str {
+ let ident = arg.trim();
+ if ident.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$') && !ident.is_empty() {
+ if let Some(init) = local_initializer(lines, ident, line, floor) {
+ return init;
+ }
+ }
+ arg
+}
+
+/// Records navigation calls and link markup of JS / TS files.
+pub struct NavScanner;
+
+impl FileHook for NavScanner {
+ fn name(&self) -> &'static str {
+ "navigation-sites"
+ }
+ fn applies(&self, lang: Lang, rel: &str) -> bool {
+ lang.family() == LangFamily::Js && !cg_scan::testpath::is_test_path(rel)
+ }
+ fn triggers(&self) -> &'static [&'static str] {
+ &["push(", "replace(", "prefetch(", "navigate(", "redirect(", "Redirect(", "href", "to="]
+ }
+ fn run(&self, ctx: &HookCtx<'_>, out: &mut HookOut) {
+ if is_minified(ctx.src) {
+ return;
+ }
+ let safe = cg_extract::post::strip_js_comments(ctx.src);
+ let src = safe.as_str();
+ let lines = LineIndex::new(src);
+ for c in nav_call_re().captures_iter(src) {
+ let whole = c.get(0).unwrap();
+ if mid_chain(src, whole.start()) {
+ continue;
+ }
+ let callee: String = whole.as_str()[..whole.as_str().len() - 1].chars().filter(|ch| !ch.is_whitespace() && *ch != '?').collect();
+ let open = whole.end() - 1;
+ let Some(args) = call_args(src, open) else { continue };
+ let Some(first) = args.first().copied().filter(|a| !a.is_empty()) else { continue };
+ let line = lines.line(whole.start());
+ let row = enclosing_row(ctx, line, FN_KINDS);
+ let floor = row.and_then(|r| ctx.rows.nodes().nth(r as usize)).map_or(line.saturating_sub(40), |n| n.start_line());
+ let dest = destination_text(&lines, first, line, floor);
+ if dest.len() > 600 {
+ continue;
+ }
+ out.sites.push(SiteFact {
+ pass: PASS_NAV,
+ role: ROLE_NAV_CALL,
+ key_kind: 0,
+ key_a: c[2].to_owned(),
+ key_b: format!("{}|{callee}", lines.col(whole.start())),
+ node_row: row.unwrap_or(NONE),
+ line,
+ payload: dest.to_owned(),
+ });
+ }
+ for c in link_tag_re().captures_iter(src) {
+ let whole = c.get(0).unwrap();
+ let at = whole.end();
+ let value = match src.as_bytes().get(at) {
+ Some(b'"' | b'\'') => href::string_end(src, at).map(|e| &src[at..=e]),
+ Some(b'{') => match_bracket(src, at).map(|e| src[at + 1..e].trim()),
+ _ => None,
+ };
+ let Some(value) = value.filter(|v| v.len() <= 600) else { continue };
+ let line = lines.line(whole.start());
+ let Some(row) = enclosing_row(ctx, line, FN_KINDS) else { continue };
+ out.sites.push(SiteFact {
+ pass: PASS_NAV,
+ role: ROLE_NAV_LINK,
+ key_kind: 0,
+ key_a: c[1].to_owned(),
+ key_b: c[3].to_owned(),
+ node_row: row,
+ line,
+ payload: value.to_owned(),
+ });
+ }
+ }
+}
+
+/// A TanStack destination: `{ to: '/posts/$id' }` or a string, normalised as a route name.
+fn tanstack_destination(expr: &str) -> Vec {
+ let t = expr.trim();
+ let literal = if t.starts_with('{') { object_field(t, "to").and_then(|v| read_string_at(v, 0)) } else { read_string_at(t, 0) };
+ match literal.and_then(|l| tanstack_path(&l)) {
+ Some(p) => href::to_href(&p).into_iter().collect(),
+ None => parse_href_expression(t, "to"),
+ }
+}
+
+/// `new URL('/login', req.url)` -> `'/login'`.
+fn unwrap_url(expr: &str) -> &str {
+ let t = expr.trim();
+ if let Some(rest) = t.strip_prefix("new URL") {
+ let open = t.len() - rest.trim_start().len();
+ if t.as_bytes().get(open) == Some(&b'(') {
+ if let Some(args) = call_args(t, open) {
+ if let Some(first) = args.first() {
+ return first;
+ }
+ }
+ }
+ }
+ t
+}
+
+struct Tables {
+ next: RouteTable,
+ next_roots: Vec,
+ react: RootedTables,
+ tanstack: RootedTables,
+}
+
+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() };
+ let mut optional: Vec<(String, String, NodeIdx)> = Vec::new();
+ for f in view.files() {
+ if view.file(f).lang().family() != LangFamily::Js {
+ continue;
+ }
+ let path = view.file(f).path();
+ for n in view.nodes_in_file(f) {
+ let n = NodeIdx(n);
+ let node = view.node(n);
+ if node.kind() != NodeKind::Route || !node.name().starts_with('/') {
+ continue;
+ }
+ match node.signature() {
+ Some("next") => {
+ if let Some(r) = next_route_of(path) {
+ t.next.add(node.name(), n);
+ if !t.next_roots.contains(&r.root) {
+ t.next_roots.push(r.root);
+ }
+ }
+ }
+ Some("react-router") if !node.name().ends_with('*') => {
+ let root = app_root_for(path);
+ let name = node.name();
+ let p = if name.len() > 1 { name.trim_end_matches('/') } else { name };
+ t.react.add(root, p, n);
+ // `/cart/:id?` serves a bare `/cart` too, unless a route claims it
+ 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.to_owned(), format!("/{}", segs.join("/")), n));
+ }
+ }
+ Some("tanstack-router") => t.tanstack.add(app_root_for(path), node.name(), n),
+ _ => {}
+ }
+ }
+ }
+ 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);
+ }
+ }
+ t
+}
+
+fn registered(e: &Engine<'_>, f: FileId, line: u32) -> String {
+ format!("{}:{}", e.view.file(f).path(), line)
+}
+
+/// `navigates` edges for every recorded navigation call and link.
+pub(crate) fn navigation(e: &Engine<'_>, out: &mut Out) {
+ let view = e.view;
+ let tables = route_tables(e);
+ if tables.next.is_empty() && tables.react.is_empty() && tables.tanstack.is_empty() {
+ return;
+ }
+ let mut per_component: FxHashMap<(NodeIdx, &'static str), usize> = FxHashMap::default();
+ let mut seen: FxHashSet<(NodeIdx, NodeIdx, u32, &'static str)> = FxHashSet::default();
+ for f in view.files() {
+ let sites: Vec<_> = view.sites_of(f).iter().filter(|s| s.pass == PASS_NAV).collect();
+ if sites.is_empty() {
+ continue;
+ }
+ let path = view.file(f).path();
+ let in_next = !tables.next.is_empty() && tables.next_roots.iter().any(|r| path.starts_with(r.as_str()));
+ for s in sites {
+ let payload = view.text_str(s.payload);
+ let verb = view.text_str(cg_core::StrId(s.key_a));
+ let key_b = view.text_str(cg_core::StrId(s.key_b));
+ // (router, its routes, the arms, how it navigates)
+ let mut tries: Vec<(&'static str, &RouteTable, Vec, String)> = Vec::new();
+ if s.role == ROLE_NAV_CALL {
+ let (col, callee) = key_b.split_once('|').unwrap_or(("", key_b));
+ let _ = col;
+ // upstream takes any `x.push('/page')`; a receiver that is no router (an
+ // array, a queue) is not navigating, so it has to say so
+ let router_receiver = callee.rsplit_once('.').is_none_or(|(recv, _)| router_word_re().is_match(recv));
+ if in_next && router_receiver {
+ if let Some(c) = next_nav_re().captures(callee) {
+ let how = if c.get(3).is_some() { "response.redirect".to_owned() } else { verb.to_owned() };
+ tries.push(("next-navigation", &tables.next, parse_href_expression(unwrap_url(payload), "pathname"), how));
+ }
+ }
+ if rr_nav_re().is_match(callee) {
+ if let Some(t) = tables.react.for_file(path) {
+ tries.push(("react-router-navigation", t, parse_href_expression(payload, "pathname"), verb.to_owned()));
+ }
+ }
+ if tanstack_nav_re().is_match(callee) {
+ if let Some(t) = tables.tanstack.for_file(path) {
+ tries.push(("tanstack-navigation", t, tanstack_destination(payload), verb.to_owned()));
+ }
+ }
+ } else {
+ let how = match verb {
+ "a" => "a",
+ "Navigate" => "navigate",
+ "Redirect" => "redirect",
+ _ => "link",
+ };
+ match key_b {
+ "href" if in_next && matches!(verb, "Link" | "NextLink" | "a") => {
+ let arms: Vec =
+ parse_href_expression(payload, "pathname").into_iter().filter(|a| verb != "a" || a.path.starts_with('/')).collect();
+ tries.push(("next-link", &tables.next, arms, how.to_owned()));
+ }
+ "to" => {
+ if let Some(t) = tables.react.for_file(path) {
+ let arms = parse_href_expression(payload, "pathname").into_iter().filter(|a| a.path.starts_with('/')).collect();
+ tries.push(("react-router-link", t, arms, how.to_owned()));
+ }
+ if matches!(verb, "Link" | "Navigate") {
+ if let Some(t) = tables.tanstack.for_file(path) {
+ tries.push(("tanstack-link", t, tanstack_destination(payload), how.to_owned()));
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ let src = s.node;
+ for (by, table, arms, how) in tries {
+ let dests = table.destinations(&arms);
+ if dests.is_empty() {
+ continue;
+ }
+ let col = if s.role == ROLE_NAV_CALL { key_b.split_once('|').and_then(|(c, _)| c.parse::().ok()) } else { None };
+ for (route, arm) in dests {
+ if route == src || !seen.insert((src, route, s.line, by)) {
+ continue;
+ }
+ if s.role == ROLE_NAV_LINK {
+ let count = per_component.entry((src, by)).or_default();
+ *count += 1;
+ if *count > MAX_LINKS_PER_COMPONENT {
+ continue;
+ }
+ }
+ let meta = serde_json::json!({ "synthesizedBy": by, "href": arm.display(), "navMethod": how, "registeredAt": registered(e, f, s.line) });
+ out.push_meta(EdgeKind::Navigates, src, route, s.line, col.unwrap_or(NONE), meta, crate::synth::order_of(by));
+ }
+ // the first router that names a page answers the navigation
+ break;
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------------- Next proxy
+
+const PROXY_EXTS: &[&str] = &["ts", "tsx", "js", "jsx", "mjs", "cjs"];
+
+/// `middleware.ts` / `proxy.ts`: what runs in it and what its `config.matcher` accepts.
+pub struct ProxyScanner;
+
+re!(export_config_re, r"\bexport\s+const\s+config\b[^=;]*=\s*");
+re!(default_fn_re, r"\bexport\s+default\s+(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)");
+re!(default_ident_re, r"(?m)\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;?\s*$");
+re!(export_as_re, r"\bexport\s*\{[^}]*?\b([A-Za-z_$][\w$]*)\s+as\s+(?:default|middleware|proxy)\b[^}]*\}");
+
+fn proxy_file_kind(rel: &str) -> Option<&'static str> {
+ let base = rel.rsplit('/').next()?;
+ let (stem, ext) = base.rsplit_once('.')?;
+ if !PROXY_EXTS.contains(&ext) {
+ return None;
+ }
+ match stem {
+ "middleware" => Some("middleware"),
+ "proxy" => Some("proxy"),
+ _ => None,
+ }
+}
+
+impl FileHook for ProxyScanner {
+ fn name(&self) -> &'static str {
+ "next-proxy-sites"
+ }
+ fn applies(&self, lang: Lang, rel: &str) -> bool {
+ lang.family() == LangFamily::Js && proxy_file_kind(rel).is_some()
+ }
+ fn run(&self, ctx: &HookCtx<'_>, out: &mut HookOut) {
+ let Some(kind) = proxy_file_kind(ctx.rel) else { return };
+ let safe = cg_extract::post::strip_js_comments(ctx.src);
+ let src = safe.as_str();
+ let lines = LineIndex::new(src);
+ // what runs: the export named after the file, else the default export's function
+ let named = ctx
+ .rows
+ .nodes()
+ .any(|n| n.name() == kind && n.is_exported() == Some(true) && matches!(n.kind(), NodeKind::Function | NodeKind::Constant | NodeKind::Variable));
+ let entry = if named {
+ kind.to_owned()
+ } else {
+ default_fn_re()
+ .captures(src)
+ .or_else(|| default_ident_re().captures(src))
+ .or_else(|| export_as_re().captures(src).filter(|c| !src[c.get(0).unwrap().end()..].trim_start().starts_with("from")))
+ .map(|c| c[1].to_owned())
+ .unwrap_or_default()
+ };
+ // matcher entries: `line\tsource` per entry; `*` for no matcher (every request)
+ let payload = match export_config_re().find(src) {
+ None => "*".to_owned(),
+ Some(m) if src.as_bytes().get(m.end()) == Some(&b'{') => match match_bracket(src, m.end()) {
+ Some(close) => {
+ let obj = &src[m.end()..=close];
+ match object_field(obj, "matcher") {
+ None if !obj.contains("matcher") => "*".to_owned(),
+ None => String::new(),
+ Some(value) => {
+ let base = m.end() + (value.as_ptr() as usize - obj.as_ptr() as usize);
+ matcher_entries(value).into_iter().map(|(off, s)| format!("{}\t{s}", lines.line(base + off))).collect::>().join("\n")
+ }
+ }
+ }
+ None => String::new(),
+ },
+ Some(_) => String::new(),
+ };
+ out.sites.push(SiteFact { pass: PASS_PROXY, role: 0, key_kind: 0, key_a: entry, key_b: kind.to_owned(), node_row: NONE, line: 1, payload });
+ }
+}
+
+/// The strings a matcher value names, with their offsets: a string, or an array of strings
+/// and `{ source }` objects. A value it cannot read names nothing.
+fn matcher_entries(value: &str) -> Vec<(usize, String)> {
+ let v = value.trim();
+ let lead = value.len() - value.trim_start().len();
+ if !v.starts_with('[') {
+ return read_string_at(v, 0).filter(|s| !s.contains(href::HOLE)).map(|s| vec![(lead, s)]).unwrap_or_default();
+ }
+ let Some(end) = match_bracket(v, 0) else { return Vec::new() };
+ let mut out = Vec::new();
+ let body = &v[1..end];
+ let mut start = 0;
+ loop {
+ let stop = href::index_at_depth0(body, b',', start).unwrap_or(body.len());
+ let item = body[start..stop].trim();
+ let item_at = lead + 1 + start + (body[start..stop].len() - body[start..stop].trim_start().len());
+ if !item.is_empty() {
+ let s = if item.starts_with('{') { object_field(item, "source").and_then(|x| read_string_at(x, 0)) } else { read_string_at(item, 0) };
+ match s.filter(|s| !s.contains(href::HOLE)) {
+ Some(s) => out.push((item_at, s)),
+ None => return Vec::new(),
+ }
+ }
+ if stop >= body.len() {
+ break;
+ }
+ start = stop + 1;
+ }
+ out
+}
+
+/// A matcher entry compiled the way path-to-regexp reads it: anchored at both ends, `/:p*`
+/// any number of segments, `(?!api|_next).*` everything but the excluded prefixes. An entry
+/// this does not read matches nothing.
+#[derive(Debug, PartialEq)]
+enum Pat {
+ Lit(String),
+ /// `/:name` with an optional `(…)` body and a `?` / `*` / `+` modifier.
+ Param(Body, Option),
+ Group(Body),
+}
+
+#[derive(Debug, PartialEq)]
+enum Body {
+ Segment,
+ Any {
+ plus: bool,
+ },
+ Options(Vec),
+ /// `(?!a|b).*`: the rest must not start with one of the exclusions.
+ Except(Vec, bool),
+}
+
+#[derive(Debug, PartialEq)]
+enum Excl {
+ Prefix(String, Anchor),
+ /// A path whose last segment has a dot (a file with an extension).
+ FileExtension,
+}
+
+#[derive(Debug, PartialEq)]
+enum Anchor {
+ None,
+ End,
+ SegmentOrEnd,
+}
+
+fn closing_paren(s: &str, open: usize) -> Option {
+ let b = s.as_bytes();
+ let mut depth = 0;
+ let mut i = open;
+ while i < b.len() {
+ match b[i] {
+ b'\\' => i += 1,
+ b'[' => {
+ while i < b.len() && b[i] != b']' {
+ i += if b[i] == b'\\' { 2 } else { 1 };
+ }
+ }
+ b'(' => depth += 1,
+ b')' => {
+ depth -= 1;
+ if depth == 0 {
+ return Some(i);
+ }
+ }
+ _ => {}
+ }
+ i += 1;
+ }
+ None
+}
+
+fn top_level_bars(s: &str) -> Vec<&str> {
+ let b = s.as_bytes();
+ let mut out = Vec::new();
+ let (mut from, mut i) = (0, 0);
+ while i < b.len() {
+ match b[i] {
+ b'\\' => i += 1,
+ b'(' => match closing_paren(s, i) {
+ Some(c) => i = c,
+ None => return vec![s],
+ },
+ b'|' => {
+ out.push(&s[from..i]);
+ from = i + 1;
+ }
+ _ => {}
+ }
+ i += 1;
+ }
+ out.push(&s[from..]);
+ out
+}
+
+fn read_exclusion(branch: &str) -> Option {
+ for lead in ["[^?]*\\.", ".*\\.", ".+\\."] {
+ if branch.starts_with(lead) {
+ return Some(Excl::FileExtension);
+ }
+ }
+ if branch.starts_with('[') && branch.contains("]+\\.") {
+ return Some(Excl::FileExtension);
+ }
+ let (body, anchor) = if let Some(b) = branch.strip_suffix("(?:/|$)") {
+ (b, Anchor::SegmentOrEnd)
+ } else if let Some(b) = branch.strip_suffix('$') {
+ (b, Anchor::End)
+ } else {
+ (branch, Anchor::None)
+ };
+ let lit = body.replace("\\.", ".");
+ let ok = lit.chars().all(|c| c.is_alphanumeric() || "_/~.-".contains(c));
+ ok.then_some(Excl::Prefix(lit, anchor))
+}
+
+fn read_group(body: &str) -> Option {
+ match body {
+ ".*" => return Some(Body::Any { plus: false }),
+ ".+" => return Some(Body::Any { plus: true }),
+ _ => {}
+ }
+ if body.starts_with("(?!") {
+ let close = closing_paren(body, 0)?;
+ let tail = &body[close + 1..];
+ let plus = match tail {
+ ".*" => false,
+ ".+" => true,
+ _ => return None,
+ };
+ let excls = top_level_bars(&body[3..close]).into_iter().map(read_exclusion).collect::