Skip to content

Commit d141ee9

Browse files
committed
fix(extract): preserve Go router group prefixes
Follow literal Group receivers through local bindings and compose their prefixes for both sequential and parallel route extraction. Keep current URL argument handling and reuse the existing Laravel prefix composition. Refs DeusData#686 Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
1 parent b05a68c commit d141ee9

2 files changed

Lines changed: 313 additions & 40 deletions

File tree

‎internal/cbm/extract_calls.c‎

Lines changed: 232 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1763,8 +1763,50 @@ static const char *php_chain_prefix_arg(CBMArena *a, TSNode call_node, const cha
17631763
return NULL;
17641764
}
17651765

1766+
/* Compose route-group prefix segments into one path. parts[] is inner-first;
1767+
* the result is outer-first with exactly one '/' between segments and a
1768+
* leading '/'. Returns NULL when no segment contributes or the result would
1769+
* be oversized (the route then stays un-prefixed). Shared by the Laravel
1770+
* (#952) and Go router-group (#686) prefix walks. */
1771+
static const char *route_prefix_compose(CBMArena *a, const char *const *parts, int part_count) {
1772+
char buf[CBM_SZ_256];
1773+
size_t pos = 0;
1774+
for (int i = part_count - 1; i >= 0; i--) {
1775+
const char *seg = parts[i];
1776+
while (*seg == '/') {
1777+
seg++;
1778+
}
1779+
size_t sl = strlen(seg);
1780+
if (sl == 0) {
1781+
continue;
1782+
}
1783+
if (pos + sl + 2 >= sizeof(buf)) {
1784+
return NULL; /* oversized — leave path un-prefixed */
1785+
}
1786+
buf[pos++] = '/';
1787+
memcpy(buf + pos, seg, sl);
1788+
pos += sl;
1789+
while (pos > 1 && buf[pos - 1] == '/') {
1790+
pos--; /* strip trailing slash per segment */
1791+
}
1792+
}
1793+
buf[pos] = '\0';
1794+
return pos ? cbm_arena_strndup(a, buf, pos) : NULL;
1795+
}
1796+
1797+
/* Prepend a composed group prefix to a route path ("/x" + "/users" ->
1798+
* "/x/users"; a bare "/" route becomes the prefix itself). */
1799+
static const char *route_path_with_prefix(CBMArena *a, const char *prefix, const char *path) {
1800+
const char *rel = path;
1801+
while (*rel == '/') {
1802+
rel++;
1803+
}
1804+
return rel[0] ? cbm_arena_sprintf(a, "%s/%s", prefix, rel)
1805+
: cbm_arena_strndup(a, prefix, strlen(prefix));
1806+
}
1807+
17661808
static const char *php_group_prefix_for_call(CBMArena *a, TSNode node, const char *source) {
1767-
const char *parts[PHP_PREFIX_PARTS_MAX];
1809+
const char *parts[PHP_PREFIX_PARTS_MAX] = {NULL};
17681810
int part_count = 0;
17691811
TSNode cur = ts_node_parent(node);
17701812
for (int depth = 0; depth < PHP_GROUP_WALK_MAX && !ts_node_is_null(cur); depth++) {
@@ -1813,34 +1855,200 @@ static const char *php_group_prefix_for_call(CBMArena *a, TSNode node, const cha
18131855
}
18141856
cur = ts_node_parent(cur);
18151857
}
1816-
if (part_count == 0) {
1858+
return route_prefix_compose(a, parts, part_count);
1859+
}
1860+
1861+
/* #686: compose Go router-group prefixes (Fiber, Gin, Echo: `g := app.Group("/admin")`
1862+
* then `g.Post("/x")`). Starting at the route call's receiver, follow:
1863+
* - an identifier to the latest binding before the use (`:=`, `=`, `var`)
1864+
* among the preceding statements of the enclosing blocks of the same
1865+
* function (a re-bound variable uses the binding in effect at the call),
1866+
* - a `recv.Group("<literal>", ...)` call to its literal prefix and receiver,
1867+
* until the root router (`fiber.New()`, `gin.Default()`, a parameter ...).
1868+
* A non-literal group prefix returns NULL: the route stays un-prefixed rather
1869+
* than carrying a guessed path. Groups passed across functions are not
1870+
* followed (parameters are roots). */
1871+
enum { GO_GROUP_HOPS_MAX = 32 };
1872+
1873+
static const char *go_string_literal_value(CBMArena *a, TSNode n, const char *source) {
1874+
const char *k = ts_node_type(n);
1875+
if (strcmp(k, "interpreted_string_literal") != 0 && strcmp(k, "raw_string_literal") != 0) {
18171876
return NULL;
18181877
}
1819-
/* parts[] is inner-first; compose outer-first. Ensure exactly one '/'
1820-
* between segments and a leading '/'. */
1821-
char buf[CBM_SZ_256];
1822-
size_t pos = 0;
1823-
for (int i = part_count - 1; i >= 0; i--) {
1824-
const char *seg = parts[i];
1825-
while (*seg == '/') {
1826-
seg++;
1878+
char *t = cbm_node_text(a, n, source);
1879+
size_t len = t ? strlen(t) : 0;
1880+
if (len < 2) {
1881+
return NULL;
1882+
}
1883+
t[len - 1] = '\0';
1884+
return t + 1;
1885+
}
1886+
1887+
/* 1 = `recv.Group("<lit>")` (receiver + literal written out), 0 = not a Group
1888+
* call, -1 = a Group call whose prefix is not a string literal. */
1889+
static int go_group_call(CBMArena *a, TSNode expr, const char *source, TSNode *recv_out,
1890+
const char **prefix_out) {
1891+
if (strcmp(ts_node_type(expr), "call_expression") != 0) {
1892+
return 0;
1893+
}
1894+
TSNode fn = ts_node_child_by_field_name(expr, TS_FIELD("function"));
1895+
if (ts_node_is_null(fn) || strcmp(ts_node_type(fn), "selector_expression") != 0) {
1896+
return 0;
1897+
}
1898+
TSNode field = ts_node_child_by_field_name(fn, TS_FIELD("field"));
1899+
const char *ft = ts_node_is_null(field) ? NULL : cbm_node_text(a, field, source);
1900+
if (!ft || strcmp(ft, "Group") != 0) {
1901+
return 0;
1902+
}
1903+
*recv_out = ts_node_child_by_field_name(fn, TS_FIELD("operand"));
1904+
TSNode args = ts_node_child_by_field_name(expr, TS_FIELD("arguments"));
1905+
*prefix_out = NULL;
1906+
if (!ts_node_is_null(args) && ts_node_named_child_count(args) > 0) {
1907+
*prefix_out = go_string_literal_value(a, ts_node_named_child(args, 0), source);
1908+
}
1909+
return *prefix_out ? 1 : -1;
1910+
}
1911+
1912+
/* Value bound to `name` by one var_spec (`var a, b = x, y`), or a null node. */
1913+
static TSNode go_var_spec_binding(CBMArena *a, TSNode spec, const char *name, const char *source) {
1914+
TSNode none = {0};
1915+
TSNode value = ts_node_child_by_field_name(spec, TS_FIELD("value"));
1916+
if (ts_node_is_null(value)) {
1917+
return none;
1918+
}
1919+
uint32_t idx = 0;
1920+
uint32_t nc = ts_node_named_child_count(spec);
1921+
for (uint32_t i = 0; i < nc; i++) {
1922+
TSNode c = ts_node_named_child(spec, i);
1923+
if (strcmp(ts_node_type(c), "identifier") != 0) {
1924+
continue;
18271925
}
1828-
size_t sl = strlen(seg);
1829-
if (sl == 0) {
1926+
const char *t = cbm_node_text(a, c, source);
1927+
if (t && strcmp(t, name) == 0) {
1928+
return idx < ts_node_named_child_count(value) ? ts_node_named_child(value, idx) : none;
1929+
}
1930+
idx++;
1931+
}
1932+
return none;
1933+
}
1934+
1935+
/* Value bound to `name` by statement `stmt`, or a null node. */
1936+
static TSNode go_stmt_binding(CBMArena *a, TSNode stmt, const char *name, const char *source) {
1937+
TSNode none = {0};
1938+
const char *k = ts_node_type(stmt);
1939+
if (strcmp(k, "var_declaration") == 0 || strcmp(k, "var_spec_list") == 0) {
1940+
for (uint32_t i = ts_node_named_child_count(stmt); i > 0; i--) {
1941+
TSNode c = ts_node_named_child(stmt, i - 1);
1942+
TSNode v = strcmp(ts_node_type(c), "var_spec") == 0
1943+
? go_var_spec_binding(a, c, name, source)
1944+
: go_stmt_binding(a, c, name, source);
1945+
if (!ts_node_is_null(v)) {
1946+
return v;
1947+
}
1948+
}
1949+
return none;
1950+
}
1951+
if (strcmp(k, "short_var_declaration") != 0 && strcmp(k, "assignment_statement") != 0) {
1952+
return none;
1953+
}
1954+
TSNode left = ts_node_child_by_field_name(stmt, TS_FIELD("left"));
1955+
TSNode right = ts_node_child_by_field_name(stmt, TS_FIELD("right"));
1956+
if (ts_node_is_null(left) || ts_node_is_null(right)) {
1957+
return none;
1958+
}
1959+
uint32_t nl = ts_node_named_child_count(left);
1960+
for (uint32_t i = 0; i < nl; i++) {
1961+
const char *t = cbm_node_text(a, ts_node_named_child(left, i), source);
1962+
if (t && strcmp(t, name) == 0) {
1963+
return i < ts_node_named_child_count(right) ? ts_node_named_child(right, i) : none;
1964+
}
1965+
}
1966+
return none;
1967+
}
1968+
1969+
static bool go_is_function_boundary(const char *k) {
1970+
return strcmp(k, "function_declaration") == 0 || strcmp(k, "method_declaration") == 0 ||
1971+
strcmp(k, "func_literal") == 0 || strcmp(k, "source_file") == 0;
1972+
}
1973+
1974+
/* Latest binding of `name` among the statements preceding `use` in its
1975+
* enclosing blocks, innermost block first; a null node when none. */
1976+
static TSNode go_find_binding(CBMArena *a, TSNode use, const char *name, const char *source) {
1977+
TSNode child = use;
1978+
TSNode cur = ts_node_parent(use);
1979+
while (!ts_node_is_null(cur) && !go_is_function_boundary(ts_node_type(cur))) {
1980+
const char *k = ts_node_type(cur);
1981+
if (strcmp(k, "block") == 0 || strcmp(k, "statement_list") == 0) {
1982+
for (TSNode s = ts_node_prev_named_sibling(child); !ts_node_is_null(s);
1983+
s = ts_node_prev_named_sibling(s)) {
1984+
TSNode v = go_stmt_binding(a, s, name, source);
1985+
if (!ts_node_is_null(v)) {
1986+
return v;
1987+
}
1988+
}
1989+
}
1990+
child = cur;
1991+
cur = ts_node_parent(cur);
1992+
}
1993+
TSNode none = {0};
1994+
return none;
1995+
}
1996+
1997+
static const char *go_group_prefix_for_call(CBMArena *a, TSNode call, const char *source) {
1998+
TSNode fn = ts_node_child_by_field_name(call, TS_FIELD("function"));
1999+
if (ts_node_is_null(fn) || strcmp(ts_node_type(fn), "selector_expression") != 0) {
2000+
return NULL;
2001+
}
2002+
const char *parts[GO_GROUP_HOPS_MAX] = {NULL};
2003+
int part_count = 0;
2004+
TSNode recv = ts_node_child_by_field_name(fn, TS_FIELD("operand"));
2005+
for (int hop = 0; !ts_node_is_null(recv); hop++) {
2006+
if (hop >= GO_GROUP_HOPS_MAX) {
2007+
return NULL; /* chain too deep to trust: never a partial prefix */
2008+
}
2009+
const char *k = ts_node_type(recv);
2010+
if (strcmp(k, "parenthesized_expression") == 0 && ts_node_named_child_count(recv) > 0) {
2011+
recv = ts_node_named_child(recv, 0);
18302012
continue;
18312013
}
1832-
if (pos + sl + 2 >= sizeof(buf)) {
1833-
return NULL; /* oversized — leave path un-prefixed */
2014+
if (strcmp(k, "identifier") == 0) {
2015+
const char *name = cbm_node_text(a, recv, source);
2016+
recv = name ? go_find_binding(a, recv, name, source) : (TSNode){0};
2017+
continue; /* unbound (parameter, package var): root reached */
18342018
}
1835-
buf[pos++] = '/';
1836-
memcpy(buf + pos, seg, sl);
1837-
pos += sl;
1838-
while (pos > 1 && buf[pos - 1] == '/') {
1839-
pos--; /* strip trailing slash per segment */
2019+
TSNode inner = {0};
2020+
const char *prefix = NULL;
2021+
int g = go_group_call(a, recv, source, &inner, &prefix);
2022+
if (g < 0) {
2023+
return NULL; /* dynamic prefix: do not guess */
2024+
}
2025+
if (g == 0) {
2026+
break; /* root router constructor or other expression */
18402027
}
2028+
parts[part_count++] = prefix; /* inner-first */
2029+
recv = inner;
18412030
}
1842-
buf[pos] = '\0';
1843-
return pos ? cbm_arena_strndup(a, buf, pos) : NULL;
2031+
return route_prefix_compose(a, parts, part_count);
2032+
}
2033+
2034+
/* Routes registered inside router groups must carry the composed path — the
2035+
* resolve passes only see the flat CBMCall, so the enclosing group chain can
2036+
* only be read here where the AST still exists. Laravel `prefix()->group()`
2037+
* closures (#952) and Go `x.Group("/p")` receivers (#686). Returns the route
2038+
* path to store (unchanged when no group prefix applies). */
2039+
static const char *route_path_with_group_prefix(CBMExtractCtx *ctx, TSNode node,
2040+
const char *callee_name, const char *path) {
2041+
if (!path || path[0] != '/' || !callee_name ||
2042+
cbm_service_pattern_route_method(callee_name) == NULL) {
2043+
return path;
2044+
}
2045+
const char *gp = NULL;
2046+
if (ctx->language == CBM_LANG_PHP) {
2047+
gp = php_group_prefix_for_call(ctx->arena, node, ctx->source);
2048+
} else if (ctx->language == CBM_LANG_GO) {
2049+
gp = go_group_prefix_for_call(ctx->arena, node, ctx->source);
2050+
}
2051+
return (gp && gp[0]) ? route_path_with_prefix(ctx->arena, gp, path) : path;
18442052
}
18452053

18462054
static bool is_nested_verilog_call_wrapper(CBMLanguage lang, TSNode node) {
@@ -3940,25 +4148,9 @@ CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBML
39404148
args = swift_call_args(node);
39414149
}
39424150
if (!ts_node_is_null(args)) {
3943-
call.first_string_arg = extract_url_or_topic_arg(ctx, args, call.callee_name);
3944-
/* #952: routes registered inside Laravel `prefix()->group()`
3945-
* closures must carry the composed path — the resolve passes
3946-
* only see the flat CBMCall, so the enclosing chain can only
3947-
* be read here where the AST still exists. */
3948-
if (ctx->language == CBM_LANG_PHP && call.first_string_arg &&
3949-
call.first_string_arg[0] == '/' && call.callee_name &&
3950-
cbm_service_pattern_route_method(call.callee_name) != NULL) {
3951-
const char *gp = php_group_prefix_for_call(ctx->arena, node, ctx->source);
3952-
if (gp && gp[0]) {
3953-
const char *rel = call.first_string_arg;
3954-
while (*rel == '/') {
3955-
rel++;
3956-
}
3957-
call.first_string_arg =
3958-
rel[0] ? cbm_arena_sprintf(ctx->arena, "%s/%s", gp, rel)
3959-
: cbm_arena_strndup(ctx->arena, gp, strlen(gp));
3960-
}
3961-
}
4151+
call.first_string_arg = route_path_with_group_prefix(
4152+
ctx, node, call.callee_name,
4153+
extract_url_or_topic_arg(ctx, args, call.callee_name));
39624154
if (call.first_string_arg && call.first_string_arg[0] == '/') {
39634155
call.second_arg_name = extract_handler_arg(ctx, args);
39644156
}

‎tests/test_edge_types_probe.c‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,84 @@ TEST(handles_gin_go) {
546546
PASS();
547547
}
548548

549+
/* #686: Go router groups. Fiber (and Gin/Echo, same syntax) build the external
550+
* path from `grp := app.Group("/admin")` plus `grp.Post("/x")`, so the full
551+
* path is never one literal at the registration site. The Route must carry
552+
* the composed path, including nested groups (`v1 := api.Group("/v1")`) and
553+
* groups built inline (`app.Group("/x").Get(...)`). Controls: a route on the
554+
* root app keeps its own path, a variable later re-bound to a different group
555+
* uses the binding in effect at the call, and a non-literal group prefix
556+
* leaves the route unprefixed (never guessed). Exact Route set on BOTH the
557+
* sequential and the parallel pipeline. */
558+
static const EtFile et_fiber_groups_issue686[] = {
559+
{"main.go",
560+
"package main\n\n"
561+
"import \"github.com/gofiber/fiber/v2\"\n\n"
562+
"func health(c *fiber.Ctx) error { return nil }\n"
563+
"func getUser(c *fiber.Ctx) error { return nil }\n"
564+
"func updateCustomer(c *fiber.Ctx) error { return nil }\n"
565+
"func listOrders(c *fiber.Ctx) error { return nil }\n"
566+
"func ping(c *fiber.Ctx) error { return nil }\n"
567+
"func report(c *fiber.Ctx) error { return nil }\n"
568+
"func dyn(c *fiber.Ctx) error { return nil }\n\n"
569+
"func main() {\n"
570+
" app := fiber.New()\n"
571+
" app.Get(\"/health\", health)\n"
572+
" api := app.Group(\"/api\")\n"
573+
" v1 := api.Group(\"/v1\", authMiddleware)\n"
574+
" v1.Get(\"/users/:id\", getUser)\n"
575+
" admin := app.Group(\"/admin\")\n"
576+
" admin.Post(\"/customers/:id\", updateCustomer)\n"
577+
" grp := api.Group(\"/shop\")\n"
578+
" grp.Get(\"/orders\", listOrders)\n"
579+
" grp = app.Group(\"/internal\")\n"
580+
" grp.Get(\"/ping\", ping)\n"
581+
" app.Group(\"/reports\").Get(\"/daily\", report)\n"
582+
" prefix := \"/p\"\n"
583+
" dg := app.Group(prefix)\n"
584+
" dg.Get(\"/dyn\", dyn)\n"
585+
" app.Listen(\":3000\")\n"
586+
"}\n\n"
587+
"func authMiddleware(c *fiber.Ctx) error { return c.Next() }\n"}};
588+
589+
static const char *et_fiber_groups_issue686_routes[] = {
590+
"/health", "/api/v1/users/:id", "/admin/customers/:id", "/api/shop/orders",
591+
"/internal/ping", "/reports/daily", "/dyn", NULL};
592+
593+
TEST(handles_fiber_group_prefix_sequential_issue686) {
594+
ASSERT_TRUE(et_routes_exact_mode(et_fiber_groups_issue686, 1, et_fiber_groups_issue686_routes,
595+
false, NULL));
596+
PASS();
597+
}
598+
599+
TEST(handles_fiber_group_prefix_parallel_issue686) {
600+
ASSERT_TRUE(et_routes_exact_mode(et_fiber_groups_issue686, 1, et_fiber_groups_issue686_routes,
601+
true, NULL));
602+
PASS();
603+
}
604+
605+
/* #686 control for the same mechanism on Gin: `v1 := r.Group("/v1")` with the
606+
* idiomatic brace block. */
607+
TEST(handles_gin_group_prefix_issue686) {
608+
static const EtFile f[] = {
609+
{"main.go",
610+
"package main\n\n"
611+
"import \"github.com/gin-gonic/gin\"\n\n"
612+
"func listOrders(c *gin.Context) {}\n"
613+
"func createOrder(c *gin.Context) {}\n\n"
614+
"func main() {\n"
615+
" r := gin.Default()\n"
616+
" v1 := r.Group(\"/v1\")\n"
617+
" {\n"
618+
" v1.GET(\"/orders\", listOrders)\n"
619+
" v1.POST(\"/orders\", createOrder)\n"
620+
" }\n"
621+
"}\n"}};
622+
static const char *routes[] = {"/v1/orders", "/v1/orders", NULL}; /* GET + POST */
623+
ASSERT_TRUE(et_routes_exact(f, 1, routes));
624+
PASS();
625+
}
626+
549627
/* Spring (Java) — class-level @RequestMapping must prefix method mappings.
550628
* Reproduce-first: a HANDLES count alone can pass with partial routes
551629
* ("/orders"), but callers/search_graph need the actual endpoint names
@@ -2121,6 +2199,9 @@ SUITE(edge_types_probe) {
21212199
RUN_TEST(handles_express_ts);
21222200
RUN_TEST(handles_fastify_js);
21232201
RUN_TEST(handles_gin_go);
2202+
RUN_TEST(handles_fiber_group_prefix_sequential_issue686);
2203+
RUN_TEST(handles_fiber_group_prefix_parallel_issue686);
2204+
RUN_TEST(handles_gin_group_prefix_issue686);
21242205
RUN_TEST(handles_spring_java);
21252206
RUN_TEST(handles_spring_java_path_attribute_fourth);
21262207
RUN_TEST(handles_spring_kotlin);

0 commit comments

Comments
 (0)