graphlore 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
graphlore/routes.py ADDED
@@ -0,0 +1,1417 @@
1
+ """Framework route extraction: URL pattern -> handler, per source file.
2
+
3
+ Web-framework routing is a graph edge no AST extractor emits: the URL pattern
4
+ lives in a decorator or a registration call, the handler is an ordinary
5
+ function, and the "this URL hits that code" link exists only in the framework's
6
+ conventions. This module recognizes the common registration idioms so
7
+ ``graphlore_routes`` can answer "where is this endpoint" in one hop.
8
+
9
+ Recognized idioms (v1):
10
+ * **Python** (stdlib ``ast``): Flask ``@app.route("/x", methods=[...])``,
11
+ verb decorators ``@app.get("/x")`` / ``@router.post(...)`` — only in files
12
+ that import a known web framework (fastapi/flask/sanic/quart/litestar,
13
+ which also picks the label), so a registry-style ``@hooks.post("event")``
14
+ in a framework-free file never fabricates a route; Django ``path()`` /
15
+ ``re_path()`` / ``url()`` calls — only in files that import django, which
16
+ kills false positives from local functions named ``path``.
17
+ * **JS/TS** (tree-sitter): Express/Koa-router style ``app.get('/x', h)`` and
18
+ ``router.route('/x').get(h)`` — in files that import/require a server
19
+ framework (express/fastify/koa-router/…, which also picks the label), or,
20
+ flagged ``needs_server_import``, on a receiver named like a router or
21
+ passed in as a parameter (``module.exports = function (app) {…}``); the
22
+ first argument must be a string literal starting with ``/`` (that filter is
23
+ what keeps ``map.get('key')`` out); NestJS ``@Controller('prefix')`` +
24
+ ``@Get(':id')`` method decorators.
25
+ * **Go** (tree-sitter): verb methods (gin/echo ``r.GET``, chi ``r.Get``),
26
+ ``Handle``/``HandleFunc`` (with the Go 1.22 ``"GET /items/{id}"`` pattern
27
+ split into method + path, and the gin 3-arg ``r.Handle("GET", "/x", h)``
28
+ form), and chi ``r.Route("/api", func(r) {...})`` nesting via
29
+ prefix-carrying recursion. Framework labelled from the import paths
30
+ (gin/echo/chi/gorilla, else net-http).
31
+ * **Java** (tree-sitter): Spring ``@GetMapping``-family + ``@RequestMapping``
32
+ (class-level prefix joined onto method-level paths); JAX-RS ``@Path`` +
33
+ ``@GET`` in files that import ``javax.ws.rs`` / ``jakarta.ws.rs``.
34
+ * **Kotlin**: Spring annotations and the Ktor ``routing { route("/x") {…} }``
35
+ DSL, each gated on its import.
36
+ * **C#**: ASP.NET Core ``[Route]`` / ``[HttpGet]`` controllers (``[controller]``
37
+ and ``[action]`` filled in) and minimal APIs (``app.MapGet``, ``MapGroup``
38
+ prefixes held in a variable).
39
+ * **Rust**: actix-web ``#[get("/x")]`` macros and ``web::scope`` / ``resource``
40
+ builders; axum ``Router::new().route("/x", get(h)).nest(...)``.
41
+ * **Ruby**: Sinatra ``get '/x' do`` and the Rails ``routes.draw`` DSL
42
+ (``resources`` with ``only:`` / ``except:`` / ``param:`` and nesting,
43
+ ``namespace``, ``scope``, ``root``).
44
+ * **PHP**: Laravel ``Route::get`` chains (``prefix`` / ``group`` /
45
+ ``resource``) and Symfony ``#[Route]`` attributes.
46
+
47
+ Honest limits: the result is a LOWER BOUND. Non-literal patterns, dynamic
48
+ registration, gorilla ``.Methods("GET")``, Flask ``add_url_rule``, Django
49
+ ``include()`` recursion, prefixes that cross files (NestJS global prefixes,
50
+ Laravel's ``/api`` for ``routes/api.php``, axum routers built in another
51
+ function, Rails ``draw(:admin)``), docblock ``@Route`` annotations and
52
+ Kotlin ``router {}`` DSLs are all invisible; gorilla chains surface as method
53
+ ``ANY``, and gin's variable-bound groups (``api := r.Group("/api")``) are not
54
+ resolved.
55
+ Zero routes reads "no visibility", not "no routes".
56
+
57
+ Python via the stdlib ``ast``; JS/TS, Go and Java via the optional tree-sitter
58
+ backend. Results are cached per (path, mtime) like the span index.
59
+ """
60
+ from __future__ import annotations
61
+
62
+ import ast
63
+ import re
64
+ from typing import Any
65
+
66
+ from .apis import _strip_quotes
67
+ from .spans import _cached_file_analysis, _ts_parser_for
68
+
69
+ # One recognized registration: framework label, upper-cased HTTP method (ANY
70
+ # when the idiom doesn't pin one), URL pattern, handler name ("<inline>" for
71
+ # anonymous handlers), and the 1-based line of the handler definition (or the
72
+ # registration call when the handler is inline/remote) for the graph join.
73
+ RouteRow = dict[str, Any]
74
+
75
+ # Per-file route index, keyed by absolute path -> (mtime, rows). Same bounded
76
+ # FIFO scheme as spans._SPAN_CACHE (see there for the rationale).
77
+ _ROUTES_CACHE: dict[str, tuple[float, list[RouteRow]]] = {}
78
+ _ROUTES_CACHE_MAX = 4096
79
+
80
+ _HTTP_METHODS = frozenset({"get", "post", "put", "delete", "patch", "options", "head", "trace"})
81
+ # Go 1.22 net/http pattern syntax: "GET /items/{id}" -> method + path.
82
+ _GO_122_PATTERN = re.compile(r"^([A-Z]+) (/.*)$")
83
+
84
+ # Python web frameworks sharing the @app.get/@router.post verb-decorator idiom,
85
+ # in label priority order (fastapi first: with both flask and fastapi imported,
86
+ # the shortcut style is fastapi's). The import both GATES the match — a file
87
+ # importing none of these must not turn @hooks.post("event") into a route — and
88
+ # picks the framework label.
89
+ _PY_VERB_FRAMEWORKS = (
90
+ ("fastapi", "fastapi"),
91
+ ("flask", "flask"),
92
+ ("sanic", "sanic"),
93
+ ("quart", "quart"),
94
+ ("litestar", "litestar"),
95
+ )
96
+
97
+ # JS/TS server frameworks whose import/require gates Express-style verb-call
98
+ # detection; without the gate, HTTP-client request sites (axios.get('/api/x'),
99
+ # apiClient.post('/login', body)) are indistinguishable from registrations.
100
+ _JS_SERVER_FRAMEWORKS = ("express", "fastify", "koa-router", "@koa/router", "restify", "polka")
101
+ # The label a row gets for the framework the file imports.
102
+ _JS_FRAMEWORK_LABELS = {"koa-router": "koa", "@koa/router": "koa"}
103
+ # Without a framework import in the file, `x.get('/p', handler)` is taken for a
104
+ # registration only when `x` reads like a server object or is a parameter of the
105
+ # function around it (`module.exports = function (app) { app.get(...) }`), and
106
+ # only in a project where some file imports a server framework: the row carries
107
+ # `needs_server_import` and graphlore_routes drops it otherwise.
108
+ _JS_ROUTER_NAMES = frozenset({"app", "router", "server", "api", "routes", "route", "r"})
109
+ _JS_HANDLER_TYPES = frozenset({
110
+ "identifier", "member_expression", "arrow_function", "function_expression",
111
+ "function", "call_expression",
112
+ })
113
+
114
+
115
+ def _row(framework: str, method: str, pattern: str, handler: str, line: int) -> RouteRow:
116
+ return {
117
+ "framework": framework,
118
+ "method": method.upper(),
119
+ "pattern": pattern,
120
+ "handler": handler,
121
+ "line": line,
122
+ }
123
+
124
+
125
+ def _join_path(prefix: str, sub: str) -> str:
126
+ combined = "/".join(p.strip("/") for p in (prefix, sub) if p and p.strip("/"))
127
+ return "/" + combined if combined else "/"
128
+
129
+
130
+ # ---------------------------------------------------------------------------
131
+ # Python (stdlib ast)
132
+ # ---------------------------------------------------------------------------
133
+
134
+
135
+ def _routes_python(src: bytes) -> list[RouteRow]:
136
+ rows: list[RouteRow] = []
137
+ try:
138
+ tree = ast.parse(src)
139
+ except Exception:
140
+ return rows
141
+
142
+ # Which frameworks does this file import? Gates Django call matching (a local
143
+ # `path()` must not register) and labels the shared verb-decorator shortcut.
144
+ imported: set[str] = set()
145
+ for node in ast.walk(tree):
146
+ if isinstance(node, ast.Import):
147
+ imported.update(a.name.split(".")[0] for a in node.names)
148
+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
149
+ imported.add(node.module.split(".")[0])
150
+ # The import set gates AND labels verb-decorator matching (see
151
+ # _PY_VERB_FRAMEWORKS); None = no web framework imported, no verb rows.
152
+ verb_framework = next(
153
+ (label for mod, label in _PY_VERB_FRAMEWORKS if mod in imported), None
154
+ )
155
+
156
+ def _first_pattern(call: ast.Call) -> str | None:
157
+ if call.args and isinstance(call.args[0], ast.Constant) and \
158
+ isinstance(call.args[0].value, str):
159
+ return call.args[0].value
160
+ for kw in call.keywords:
161
+ if kw.arg == "path" and isinstance(kw.value, ast.Constant) and \
162
+ isinstance(kw.value.value, str):
163
+ return kw.value.value
164
+ return None # non-literal pattern: invisible, per the lower-bound contract
165
+
166
+ for node in ast.walk(tree):
167
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
168
+ for dec in node.decorator_list:
169
+ if not (isinstance(dec, ast.Call) and isinstance(dec.func, ast.Attribute)):
170
+ continue
171
+ attr = dec.func.attr
172
+ pattern = _first_pattern(dec)
173
+ if pattern is None or verb_framework is None:
174
+ continue
175
+ if attr == "route": # Flask style, one row per declared method
176
+ methods = ["GET"]
177
+ for kw in dec.keywords:
178
+ if kw.arg == "methods" and isinstance(kw.value, ast.List | ast.Tuple):
179
+ declared = [
180
+ e.value for e in kw.value.elts
181
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)
182
+ ]
183
+ methods = declared or methods
184
+ label = "flask" if "flask" in imported else verb_framework
185
+ rows += [_row(label, m, pattern, node.name, node.lineno)
186
+ for m in methods]
187
+ elif attr in _HTTP_METHODS:
188
+ rows.append(_row(verb_framework, attr, pattern, node.name, node.lineno))
189
+ elif (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
190
+ and node.func.id in ("path", "re_path", "url") and "django" in imported
191
+ and node.args and isinstance(node.args[0], ast.Constant)
192
+ and isinstance(node.args[0].value, str) and len(node.args) > 1):
193
+ try:
194
+ handler = ast.unparse(node.args[1])
195
+ except Exception:
196
+ handler = "<unknown>"
197
+ rows.append(_row("django", "ANY", node.args[0].value, handler, node.lineno))
198
+ return rows
199
+
200
+
201
+ # ---------------------------------------------------------------------------
202
+ # JS/TS, Go, Java (optional tree-sitter backend)
203
+ # ---------------------------------------------------------------------------
204
+
205
+
206
+ def _text(node: Any) -> str:
207
+ return node.text.decode("utf-8", "replace")
208
+
209
+
210
+ def _routes_js(root: Any) -> list[RouteRow]:
211
+ """Express/Koa-router verb calls + NestJS controller decorators (JS/TS/TSX)."""
212
+ rows: list[RouteRow] = []
213
+ verbs = _HTTP_METHODS | {"all"}
214
+ nest_verbs = {"Get": "GET", "Post": "POST", "Put": "PUT", "Delete": "DELETE",
215
+ "Patch": "PATCH", "Options": "OPTIONS", "Head": "HEAD", "All": "ANY"}
216
+
217
+ imports: set[str] = set()
218
+
219
+ def collect_imports(node: Any) -> None:
220
+ for child in node.named_children:
221
+ if child.type == "import_statement":
222
+ src = child.child_by_field_name("source")
223
+ if src is not None:
224
+ imports.add(_strip_quotes(_text(src)))
225
+ elif child.type == "call_expression":
226
+ fn = child.child_by_field_name("function")
227
+ args = child.child_by_field_name("arguments")
228
+ if (fn is not None and args is not None and fn.type == "identifier"
229
+ and _text(fn) == "require"):
230
+ strings = [a for a in args.named_children if "string" in a.type]
231
+ if strings:
232
+ imports.add(_strip_quotes(_text(strings[0])))
233
+ collect_imports(child)
234
+
235
+ collect_imports(root)
236
+ # Same gate idea as the Python verb decorators: without a server-framework
237
+ # import in the file, identifier.verb('/x', …) is far likelier an HTTP-client
238
+ # request site than a route registration.
239
+ framework = next(
240
+ (fw for fw in _JS_SERVER_FRAMEWORKS for imp in sorted(imports)
241
+ if imp == fw or imp.startswith(fw + "/")), None)
242
+ label = _JS_FRAMEWORK_LABELS.get(framework or "", framework or "express")
243
+
244
+ def string_arg(args: Any, index: int = 0) -> str | None:
245
+ strings = [a for a in args.named_children if "string" in a.type]
246
+ if index >= len(strings):
247
+ return None
248
+ return _strip_quotes(_text(strings[index]))
249
+
250
+ def decorator_call(dec: Any) -> Any | None:
251
+ return next((c for c in dec.named_children if c.type == "call_expression"), None)
252
+
253
+ def handle_class(cls: Any, pending: list[Any]) -> None:
254
+ prefix = ""
255
+ decs = pending + [c for c in cls.named_children if c.type == "decorator"]
256
+ for dec in decs:
257
+ call = decorator_call(dec)
258
+ if call is None:
259
+ continue
260
+ fn = call.child_by_field_name("function")
261
+ args = call.child_by_field_name("arguments")
262
+ if fn is not None and fn.type == "identifier" and _text(fn) == "Controller":
263
+ prefix = (string_arg(args) or "") if args is not None else ""
264
+ body = cls.child_by_field_name("body")
265
+ if body is None:
266
+ return
267
+ # Grammar versions differ on whether a method's decorators are siblings in
268
+ # the class body or children of the method_definition — handle both.
269
+ method_pending: list[Any] = []
270
+ for child in body.named_children:
271
+ if child.type == "decorator":
272
+ method_pending.append(child)
273
+ continue
274
+ if child.type != "method_definition":
275
+ method_pending = []
276
+ continue
277
+ decs = method_pending + [c for c in child.named_children if c.type == "decorator"]
278
+ method_pending = []
279
+ for dec in decs:
280
+ call = decorator_call(dec)
281
+ if call is None:
282
+ continue
283
+ fn = call.child_by_field_name("function")
284
+ args = call.child_by_field_name("arguments")
285
+ if fn is None or fn.type != "identifier" or _text(fn) not in nest_verbs:
286
+ continue
287
+ sub = (string_arg(args) or "") if args is not None else ""
288
+ name = child.child_by_field_name("name")
289
+ rows.append(_row(
290
+ "nestjs", nest_verbs[_text(fn)], _join_path(prefix, sub),
291
+ _text(name) if name is not None else "<unknown>",
292
+ child.start_point[0] + 1,
293
+ ))
294
+
295
+ def parameters(fn: Any) -> set[str]:
296
+ """Names a function binds as parameters (plain identifiers only)."""
297
+ out: set[str] = set()
298
+ one = fn.child_by_field_name("parameter") # `app => …`
299
+ if one is not None and one.type == "identifier":
300
+ out.add(_text(one))
301
+ params = fn.child_by_field_name("parameters")
302
+ for p in params.named_children if params is not None else ():
303
+ if p.type == "identifier":
304
+ out.add(_text(p))
305
+ elif p.type in ("required_parameter", "optional_parameter"): # TypeScript
306
+ pat = p.child_by_field_name("pattern")
307
+ if pat is not None and pat.type == "identifier":
308
+ out.add(_text(pat))
309
+ return out
310
+
311
+ def chain_root(call: Any) -> tuple[Any, str] | None:
312
+ """For `x.route('/p').get(h).post(h2)`: (`x`, '/p') from any verb call of it."""
313
+ fn = call.child_by_field_name("function")
314
+ while fn is not None and fn.type == "member_expression":
315
+ obj = fn.child_by_field_name("object")
316
+ if obj is None or obj.type != "call_expression":
317
+ return None
318
+ inner = obj.child_by_field_name("function")
319
+ args = obj.child_by_field_name("arguments")
320
+ if inner is None or inner.type != "member_expression" or args is None:
321
+ return None
322
+ prop = inner.child_by_field_name("property")
323
+ recv = inner.child_by_field_name("object")
324
+ if prop is not None and _text(prop) == "route":
325
+ pattern = string_arg(args)
326
+ if recv is not None and recv.type == "identifier" and pattern is not None:
327
+ return recv, pattern
328
+ return None
329
+ if prop is None or _text(prop) not in verbs:
330
+ return None
331
+ fn = inner
332
+ return None
333
+
334
+ def registration(call: Any, params: set[str]) -> None:
335
+ fn = call.child_by_field_name("function")
336
+ args = call.child_by_field_name("arguments")
337
+ if fn is None or args is None or fn.type != "member_expression":
338
+ return
339
+ obj = fn.child_by_field_name("object")
340
+ prop = fn.child_by_field_name("property")
341
+ if obj is None or prop is None or _text(prop) not in verbs:
342
+ return
343
+ chained = chain_root(call) if obj.type == "call_expression" else None
344
+ if chained is not None:
345
+ recv, pattern = chained
346
+ elif obj.type == "identifier":
347
+ # a plain receiver only: `this.x.get(...)` and `a.b.get(...)` are not
348
+ recv, found = obj, string_arg(args)
349
+ if found is None:
350
+ return
351
+ pattern = found
352
+ else:
353
+ return
354
+ if not pattern.startswith("/"):
355
+ return
356
+ last = args.named_children[-1] if args.named_children else None
357
+ if framework is None:
358
+ # no framework import here: ask more of the call (see _JS_ROUTER_NAMES)
359
+ name = _text(recv)
360
+ handlers = args.named_children[0 if chained else 1:]
361
+ if not handlers or last is None or last.type not in _JS_HANDLER_TYPES:
362
+ return
363
+ if name not in _JS_ROUTER_NAMES and name not in params:
364
+ return
365
+ handler = "<inline>"
366
+ if last is not None and last.type in ("identifier", "member_expression"):
367
+ handler = _text(last)
368
+ method = _text(prop)
369
+ row = _row(label, "ANY" if method == "all" else method, pattern, handler,
370
+ prop.start_point[0] + 1)
371
+ if framework is None:
372
+ row["needs_server_import"] = True
373
+ rows.append(row)
374
+
375
+ def walk(node: Any, pending: list[Any], params: set[str]) -> None:
376
+ for child in node.named_children:
377
+ t = child.type
378
+ if t == "decorator":
379
+ pending.append(child)
380
+ continue
381
+ if t == "class_declaration":
382
+ handle_class(child, pending)
383
+ pending = []
384
+ continue
385
+ if t == "call_expression":
386
+ registration(child, params)
387
+ inner = params
388
+ if t in ("function_declaration", "function_expression", "function",
389
+ "arrow_function", "method_definition", "generator_function"):
390
+ inner = params | parameters(child)
391
+ walk(child, pending, inner)
392
+ pending = []
393
+
394
+ walk(root, [], set())
395
+ return rows
396
+
397
+
398
+ def _routes_go(root: Any) -> list[RouteRow]:
399
+ """Verb methods (gin/echo/chi), Handle/HandleFunc (+ Go 1.22 method patterns),
400
+ chi ``Route``/``Group``/``With`` nesting via prefix-carrying recursion."""
401
+ rows: list[RouteRow] = []
402
+ verb_upper = {"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"}
403
+ verb_title = {"Get", "Post", "Put", "Delete", "Patch", "Options", "Head"}
404
+
405
+ framework = "net-http"
406
+ imports: list[str] = []
407
+
408
+ def collect_imports(node: Any) -> None:
409
+ for child in node.named_children:
410
+ if child.type == "import_spec":
411
+ path_node = child.child_by_field_name("path")
412
+ if path_node is not None:
413
+ imports.append(_strip_quotes(_text(path_node)))
414
+ else:
415
+ collect_imports(child)
416
+
417
+ collect_imports(root)
418
+ for path, label in (("gin-gonic/gin", "gin"), ("labstack/echo", "echo"),
419
+ ("go-chi/chi", "chi"), ("gorilla/mux", "gorilla")):
420
+ if any(path in imp for imp in imports):
421
+ framework = label
422
+ break
423
+
424
+ def first_string(args: Any) -> tuple[str | None, int]:
425
+ for i, a in enumerate(args.named_children):
426
+ if a.type in ("interpreted_string_literal", "raw_string_literal"):
427
+ return _strip_quotes(_text(a)), i
428
+ return None, -1
429
+
430
+ def handler_text(args: Any) -> str:
431
+ last = args.named_children[-1] if args.named_children else None
432
+ if last is None or last.type == "func_literal":
433
+ return "<inline>"
434
+ return _text(last) if last.type in ("identifier", "selector_expression") else "<inline>"
435
+
436
+ def walk(node: Any, prefix: str) -> None:
437
+ for child in node.named_children:
438
+ if child.type == "call_expression":
439
+ fn = child.child_by_field_name("function")
440
+ args = child.child_by_field_name("arguments")
441
+ if fn is not None and args is not None and fn.type == "selector_expression":
442
+ field = fn.child_by_field_name("field")
443
+ name = _text(field) if field is not None else ""
444
+ pattern, _idx = first_string(args)
445
+ n_args = len(args.named_children)
446
+ if name == "Route" and pattern is not None:
447
+ # chi: r.Route("/api", func(r chi.Router) {...}) — recurse
448
+ # with the joined prefix, no row for the mount itself.
449
+ inner = next((a for a in args.named_children
450
+ if a.type == "func_literal"), None)
451
+ if inner is not None:
452
+ walk(inner, _join_path(prefix, pattern))
453
+ continue
454
+ if name in ("Group", "With"):
455
+ inner = next((a for a in args.named_children
456
+ if a.type == "func_literal"), None)
457
+ if inner is not None:
458
+ walk(inner, prefix)
459
+ continue
460
+ if (name in verb_upper or name in verb_title) and n_args >= 2 \
461
+ and pattern is not None and pattern.startswith("/"):
462
+ rows.append(_row(framework, name, _join_path(prefix, pattern),
463
+ handler_text(args), child.start_point[0] + 1))
464
+ # fall through: the receiver may itself be a call chain
465
+ elif name in ("Handle", "HandleFunc") and n_args >= 2 \
466
+ and pattern is not None:
467
+ m = _GO_122_PATTERN.match(pattern)
468
+ strings = [
469
+ _strip_quotes(_text(a)) for a in args.named_children
470
+ if a.type in ("interpreted_string_literal", "raw_string_literal")
471
+ ]
472
+ if m:
473
+ method, pat = m.group(1), m.group(2)
474
+ elif pattern.startswith("/"):
475
+ method, pat = "ANY", pattern
476
+ elif (len(strings) >= 2 and strings[0].upper() in verb_upper
477
+ and strings[1].startswith("/")):
478
+ # gin 3-arg form: r.Handle("GET", "/x", handler) — the
479
+ # first literal is the METHOD, the second the path.
480
+ method, pat = strings[0].upper(), strings[1]
481
+ else:
482
+ walk(child, prefix)
483
+ continue
484
+ rows.append(_row(framework, method, _join_path(prefix, pat),
485
+ handler_text(args), child.start_point[0] + 1))
486
+ walk(child, prefix)
487
+
488
+ walk(root, "")
489
+ return rows
490
+
491
+
492
+ _JAXRS_VERBS = frozenset({"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"})
493
+
494
+
495
+ def _routes_java(root: Any) -> list[RouteRow]:
496
+ """Spring ``@GetMapping``-family and ``@RequestMapping`` (class prefix joined),
497
+ and JAX-RS ``@Path`` + ``@GET`` — gated on a ``javax.ws.rs`` /
498
+ ``jakarta.ws.rs`` import, since Retrofit's client interfaces say ``@GET`` too."""
499
+ rows: list[RouteRow] = []
500
+ jaxrs = any(
501
+ "javax.ws.rs" in (t := _text(imp)) or "jakarta.ws.rs" in t
502
+ for imp in _all(root, "import_declaration"))
503
+ mappings = {"GetMapping": "GET", "PostMapping": "POST", "PutMapping": "PUT",
504
+ "DeleteMapping": "DELETE", "PatchMapping": "PATCH"}
505
+
506
+ def annotations_of(decl: Any) -> list[Any]:
507
+ mods = next((c for c in decl.named_children if c.type == "modifiers"), None)
508
+ if mods is None:
509
+ return []
510
+ return [c for c in mods.named_children
511
+ if c.type in ("annotation", "marker_annotation")]
512
+
513
+ def annotation_name(ann: Any) -> str:
514
+ name = ann.child_by_field_name("name")
515
+ return _text(name).rsplit(".", 1)[-1] if name is not None else ""
516
+
517
+ def annotation_path(ann: Any) -> str:
518
+ """First string in the arguments — bare value, value=/path= pair, or the
519
+ first element of an array initializer (v1 keeps only the first)."""
520
+ args = ann.child_by_field_name("arguments")
521
+ if args is None:
522
+ return ""
523
+ pairs: dict[str, Any] = {}
524
+ bare: list[Any] = []
525
+ for p in args.named_children:
526
+ if p.type == "element_value_pair":
527
+ key = p.child_by_field_name("key")
528
+ if key is not None:
529
+ pairs[_text(key)] = p
530
+ else:
531
+ bare.append(p)
532
+ # value=/path= pairs first; otherwise only BARE values, so a string in an
533
+ # unrelated pair (produces="application/json") is never read as the path.
534
+ scopes = [pairs[k] for k in ("value", "path") if k in pairs] or bare
535
+ for scope in scopes:
536
+ stack = [scope]
537
+ while stack:
538
+ n = stack.pop(0)
539
+ if n.type == "string_literal":
540
+ return _strip_quotes(_text(n))
541
+ stack.extend(n.named_children)
542
+ return ""
543
+
544
+ def request_methods(ann: Any) -> list[str]:
545
+ args = ann.child_by_field_name("arguments")
546
+ if args is None:
547
+ return ["ANY"]
548
+ for p in args.named_children:
549
+ key = p.child_by_field_name("key")
550
+ value = p.child_by_field_name("value")
551
+ if key is not None and _text(key) == "method" and value is not None:
552
+ # method = RequestMethod.GET, or an array
553
+ # method = {RequestMethod.GET, RequestMethod.POST} — one row each,
554
+ # never the raw array text (which would yield a garbage 'POST}').
555
+ elems = (list(value.named_children)
556
+ if value.type == "element_value_array_initializer" else [value])
557
+ methods = [_text(el).rsplit(".", 1)[-1].upper() for el in elems]
558
+ return [m for m in methods if m] or ["ANY"]
559
+ return ["ANY"]
560
+
561
+ def walk(node: Any) -> None:
562
+ for child in node.named_children:
563
+ if child.type in ("class_declaration", "interface_declaration"):
564
+ prefix = ""
565
+ path_prefix: str | None = None
566
+ for ann in annotations_of(child):
567
+ if annotation_name(ann) == "RequestMapping":
568
+ prefix = annotation_path(ann)
569
+ elif annotation_name(ann) == "Path":
570
+ path_prefix = annotation_path(ann)
571
+ body = child.child_by_field_name("body")
572
+ for member in (body.named_children if body is not None else []):
573
+ if member.type != "method_declaration":
574
+ continue
575
+ name = member.child_by_field_name("name")
576
+ handler = _text(name) if name is not None else "<unknown>"
577
+ line = member.start_point[0] + 1
578
+ if jaxrs:
579
+ anns = {annotation_name(a): a for a in annotations_of(member)}
580
+ sub = anns.get("Path")
581
+ if path_prefix is not None or sub is not None:
582
+ for verb in sorted(_JAXRS_VERBS & anns.keys()):
583
+ rows.append(_row(
584
+ "jax-rs", verb, _join_path(
585
+ path_prefix or "",
586
+ annotation_path(sub) if sub is not None else ""),
587
+ handler, line))
588
+ for ann in annotations_of(member):
589
+ ann_name = annotation_name(ann)
590
+ if ann_name in mappings:
591
+ rows.append(_row(
592
+ "spring", mappings[ann_name],
593
+ _join_path(prefix, annotation_path(ann)), handler, line))
594
+ elif ann_name == "RequestMapping":
595
+ for meth in request_methods(ann):
596
+ rows.append(_row(
597
+ "spring", meth,
598
+ _join_path(prefix, annotation_path(ann)), handler, line))
599
+ walk(child) # nested classes
600
+ else:
601
+ walk(child)
602
+
603
+ walk(root)
604
+ return rows
605
+
606
+
607
+ # ---------------------------------------------------------------------------
608
+ # Shared helpers for the tree-sitter route extractors below
609
+ # ---------------------------------------------------------------------------
610
+
611
+ _STRING_PARTS = frozenset({
612
+ "string_content", "string_fragment", "string_literal_content", "string_value",
613
+ })
614
+ _STRING_TYPES = frozenset({
615
+ "string_literal", "string", "encapsed_string", "raw_string_literal",
616
+ "verbatim_string_literal",
617
+ })
618
+
619
+
620
+ def _lit(node: Any) -> str | None:
621
+ """The value of a string literal with nothing interpolated; None otherwise."""
622
+ if node is None or node.type not in _STRING_TYPES:
623
+ return None
624
+ parts: list[str] = []
625
+ for c in node.named_children:
626
+ if c.type in _STRING_PARTS:
627
+ parts.append(_text(c))
628
+ elif c.type != "escape_sequence":
629
+ return None # `"${x}/users"`, `"#{id}"`: not a literal pattern
630
+ if parts or not node.named_children:
631
+ return "".join(parts) if parts else _strip_quotes(_text(node))
632
+ return None
633
+
634
+
635
+ def _kid(node: Any, *types: str) -> Any | None:
636
+ return next((c for c in node.named_children if c.type in types), None)
637
+
638
+
639
+ def _kids(node: Any, *types: str) -> list[Any]:
640
+ return [c for c in node.named_children if c.type in types]
641
+
642
+
643
+ def _all(root: Any, *types: str) -> list[Any]:
644
+ """Every node of these types under ``root``, in source order, iteratively."""
645
+ out: list[Any] = []
646
+ stack = [root]
647
+ while stack:
648
+ n = stack.pop()
649
+ if n.type in types:
650
+ out.append(n)
651
+ stack.extend(reversed(n.named_children))
652
+ return out
653
+
654
+
655
+ def _first_lit(node: Any) -> str | None:
656
+ """The first string literal at or under ``node``, breadth first."""
657
+ queue = [node]
658
+ while queue:
659
+ n = queue.pop(0)
660
+ value = _lit(n)
661
+ if value is not None:
662
+ return value
663
+ queue.extend(n.named_children)
664
+ return None
665
+
666
+
667
+ # ---------------------------------------------------------------------------
668
+ # Kotlin: Spring annotations and the Ktor routing DSL
669
+ # ---------------------------------------------------------------------------
670
+
671
+ _SPRING_MAPPINGS = {"GetMapping": "GET", "PostMapping": "POST", "PutMapping": "PUT",
672
+ "DeleteMapping": "DELETE", "PatchMapping": "PATCH"}
673
+
674
+
675
+ def _routes_kotlin(root: Any) -> list[RouteRow]:
676
+ """Spring ``@GetMapping`` / ``@RequestMapping`` (class prefix joined) and Ktor
677
+ ``routing { route("/api") { get("/x") { } } }``. Each is gated on its import
678
+ (``org.springframework.web…``, ``io.ktor…routing``), since the grammar has no
679
+ fields to tell a `get("/x")` route from any other call."""
680
+ imports = [_text(i) for h in _all(root, "import_header")
681
+ if (i := _kid(h, "identifier")) is not None]
682
+ rows: list[RouteRow] = []
683
+ if any(i.startswith("org.springframework.web") for i in imports):
684
+ rows += _kotlin_spring(root)
685
+ if any(i.startswith("io.ktor") and "routing" in i for i in imports):
686
+ rows += _kotlin_ktor(root)
687
+ return rows
688
+
689
+
690
+ def _kotlin_annotations(decl: Any) -> list[tuple[str, Any | None]]:
691
+ """(name, value_arguments) of each annotation on a Kotlin declaration."""
692
+ mods = _kid(decl, "modifiers")
693
+ out: list[tuple[str, Any | None]] = []
694
+ for ann in _kids(mods, "annotation") if mods is not None else []:
695
+ ci = _kid(ann, "constructor_invocation")
696
+ ut = _kid(ci if ci is not None else ann, "user_type")
697
+ if ut is not None:
698
+ out.append((_text(ut).rsplit(".", 1)[-1],
699
+ _kid(ci, "value_arguments") if ci is not None else None))
700
+ return out
701
+
702
+
703
+ def _kotlin_args(va: Any | None) -> tuple[dict[str, Any], list[Any]]:
704
+ named: dict[str, Any] = {}
705
+ bare: list[Any] = []
706
+ for arg in _kids(va, "value_argument") if va is not None else []:
707
+ kids = arg.named_children
708
+ if len(kids) >= 2 and kids[0].type == "simple_identifier":
709
+ named[_text(kids[0])] = kids[-1]
710
+ elif kids:
711
+ bare.append(kids[-1])
712
+ return named, bare
713
+
714
+
715
+ def _kotlin_spring(root: Any) -> list[RouteRow]:
716
+ rows: list[RouteRow] = []
717
+
718
+ def path(va: Any | None) -> str:
719
+ named, bare = _kotlin_args(va)
720
+ scope = named.get("value") or named.get("path") or (bare[0] if bare else None)
721
+ return (_first_lit(scope) or "") if scope is not None else ""
722
+
723
+ def methods(va: Any | None) -> list[str]:
724
+ named, _bare = _kotlin_args(va)
725
+ value = named.get("method")
726
+ if value is None:
727
+ return ["ANY"]
728
+ elems = _kids(value, *[c.type for c in value.named_children]) \
729
+ if value.type == "collection_literal" else [value]
730
+ return [_text(e).rsplit(".", 1)[-1].upper() for e in elems] or ["ANY"]
731
+
732
+ for cls in _all(root, "class_declaration", "object_declaration"):
733
+ prefix = next((path(va) for n, va in _kotlin_annotations(cls)
734
+ if n == "RequestMapping"), "")
735
+ body = _kid(cls, "class_body")
736
+ for fn in _kids(body, "function_declaration") if body is not None else []:
737
+ name = _kid(fn, "simple_identifier")
738
+ handler = _text(name) if name is not None else "<unknown>"
739
+ line = (name or fn).start_point[0] + 1
740
+ for ann, va in _kotlin_annotations(fn):
741
+ if ann in _SPRING_MAPPINGS:
742
+ rows.append(_row("spring", _SPRING_MAPPINGS[ann],
743
+ _join_path(prefix, path(va)), handler, line))
744
+ elif ann == "RequestMapping":
745
+ rows += [_row("spring", m, _join_path(prefix, path(va)), handler, line)
746
+ for m in methods(va)]
747
+ return rows
748
+
749
+
750
+ def _kotlin_ktor(root: Any) -> list[RouteRow]:
751
+ rows: list[RouteRow] = []
752
+
753
+ def walk(node: Any, prefix: str) -> None:
754
+ for ch in node.named_children:
755
+ ident = ch.named_children[0] if ch.type == "call_expression" and \
756
+ ch.named_children else None
757
+ suffix = _kid(ch, "call_suffix") if ident is not None else None
758
+ if ident is None or ident.type != "simple_identifier" or suffix is None \
759
+ or _kid(suffix, "type_arguments") is not None:
760
+ walk(ch, prefix)
761
+ continue
762
+ name = _text(ident)
763
+ va = _kid(suffix, "value_arguments")
764
+ lam = _kid(suffix, "annotated_lambda")
765
+ args = [a.named_children[-1] for a in _kids(va, "value_argument")
766
+ if a.named_children] if va is not None else []
767
+ pattern = _lit(args[0]) if args else None
768
+ if name == "route" and lam is not None and pattern is not None:
769
+ walk(lam, _join_path(prefix, pattern))
770
+ continue
771
+ if name in _HTTP_METHODS and (lam is not None or len(args) >= 2) and (
772
+ pattern is not None or (not args and prefix)):
773
+ handler = "<inline>" if lam is not None else _text(args[-1]).lstrip(":")
774
+ rows.append(_row("ktor", name, _join_path(prefix, pattern or ""), handler,
775
+ ident.start_point[0] + 1))
776
+ continue
777
+ walk(ch, prefix)
778
+
779
+ walk(root, "")
780
+ return rows
781
+
782
+
783
+ # ---------------------------------------------------------------------------
784
+ # C#: ASP.NET Core attribute routing and minimal APIs
785
+ # ---------------------------------------------------------------------------
786
+
787
+ _ASPNET_VERBS = {"HttpGet": "GET", "HttpPost": "POST", "HttpPut": "PUT",
788
+ "HttpDelete": "DELETE", "HttpPatch": "PATCH", "HttpHead": "HEAD",
789
+ "HttpOptions": "OPTIONS"}
790
+ _MINIMAL_VERBS = {"MapGet": "GET", "MapPost": "POST", "MapPut": "PUT",
791
+ "MapDelete": "DELETE", "MapPatch": "PATCH", "Map": "ANY"}
792
+
793
+
794
+ def _routes_csharp(root: Any) -> list[RouteRow]:
795
+ """``[Route("api/[controller]")]`` controllers with ``[HttpGet("{id}")]``
796
+ actions, and minimal APIs (``app.MapGet("/x", h)``, prefixes through
797
+ ``var g = app.MapGroup("/api")``). Gated on the names themselves: implicit
798
+ usings leave many such files without a `using` of ASP.NET."""
799
+ rows: list[RouteRow] = []
800
+
801
+ def attributes(decl: Any) -> list[tuple[str, Any]]:
802
+ out = []
803
+ for al in _kids(decl, "attribute_list"):
804
+ for a in _kids(al, "attribute"):
805
+ name = a.child_by_field_name("name")
806
+ if name is not None:
807
+ short = _text(name).rsplit(".", 1)[-1]
808
+ out.append((short[:-9] if short.endswith("Attribute") else short, a))
809
+ return out
810
+
811
+ def template(attr: Any) -> str:
812
+ args = _kid(attr, "attribute_argument_list")
813
+ for arg in _kids(args, "attribute_argument") if args is not None else []:
814
+ if arg.child_by_field_name("name") is None:
815
+ return _first_lit(arg) or ""
816
+ return ""
817
+
818
+ for cls in _all(root, "class_declaration"):
819
+ name_node = cls.child_by_field_name("name")
820
+ cname = _text(name_node) if name_node is not None else ""
821
+ attrs = attributes(cls)
822
+ if not (cname.endswith("Controller") or any(n in ("ApiController", "Route")
823
+ for n, _a in attrs)):
824
+ continue
825
+ ctrl = cname[:-len("Controller")] if cname.endswith("Controller") else cname
826
+ prefix = next((template(a) for n, a in attrs if n == "Route"), "")
827
+ body = cls.child_by_field_name("body")
828
+ for m in _kids(body, "method_declaration") if body is not None else []:
829
+ mname_node = m.child_by_field_name("name")
830
+ mname = _text(mname_node) if mname_node is not None else "<unknown>"
831
+ mattrs = attributes(m)
832
+ routes = [template(a) for n, a in mattrs if n == "Route"] or [""]
833
+ line = (mname_node or m).start_point[0] + 1
834
+ for n, a in mattrs:
835
+ if n not in _ASPNET_VERBS:
836
+ continue
837
+ for route in routes:
838
+ t = template(a)
839
+ pat = t.lstrip("~") if t.startswith(("/", "~/")) else \
840
+ _join_path(_join_path(prefix, route), t)
841
+ pat = re.sub(r"\[controller\]", ctrl, pat, flags=re.I)
842
+ pat = re.sub(r"\[action\]", mname, pat, flags=re.I)
843
+ rows.append(_row("aspnet", _ASPNET_VERBS[n], _join_path("", pat), mname,
844
+ line))
845
+
846
+ groups: dict[str, str] = {}
847
+
848
+ def map_call(inv: Any) -> tuple[str, Any, Any, Any] | None:
849
+ """(method name, receiver, arguments, name node) of `recv.MapX(...)`."""
850
+ fn = inv.child_by_field_name("function")
851
+ args = inv.child_by_field_name("arguments")
852
+ if fn is None or args is None or fn.type != "member_access_expression":
853
+ return None
854
+ name = fn.child_by_field_name("name")
855
+ recv = fn.child_by_field_name("expression")
856
+ if name is None or recv is None:
857
+ return None
858
+ return _text(name), recv, args, name
859
+
860
+ def group_prefix(recv: Any) -> str:
861
+ if recv.type == "identifier":
862
+ return groups.get(_text(recv), "")
863
+ if recv.type == "invocation_expression":
864
+ got = map_call(recv)
865
+ if got is not None:
866
+ name, inner, args, _n = got
867
+ base = group_prefix(inner)
868
+ if name == "MapGroup":
869
+ first = next(iter(_kids(args, "argument")), None)
870
+ return _join_path(base, (_first_lit(first) or "") if first else "")
871
+ return base
872
+ return ""
873
+
874
+ for node in _all(root, "variable_declarator", "invocation_expression"):
875
+ if node.type == "variable_declarator":
876
+ name = node.child_by_field_name("name") or _kid(node, "identifier")
877
+ value = next((c for c in node.named_children
878
+ if c.type == "invocation_expression"), None)
879
+ if name is not None and value is not None:
880
+ prefix = group_prefix(value)
881
+ if prefix not in ("", "/") or "MapGroup" in _text(value):
882
+ groups[_text(name)] = prefix
883
+ continue
884
+ got = map_call(node)
885
+ if got is None or got[0] not in _MINIMAL_VERBS:
886
+ continue
887
+ name, recv, args, name_node = got
888
+ arglist = _kids(args, "argument")
889
+ pattern = _lit(arglist[0].named_children[0]) if arglist and \
890
+ arglist[0].named_children else None
891
+ if pattern is None or len(arglist) < 2:
892
+ continue
893
+ last = arglist[-1].named_children[-1] if arglist[-1].named_children else None
894
+ handler = _text(last) if last is not None and last.type in (
895
+ "identifier", "member_access_expression") else "<inline>"
896
+ rows.append(_row("aspnet", _MINIMAL_VERBS[name],
897
+ _join_path(group_prefix(recv), pattern), handler,
898
+ name_node.start_point[0] + 1))
899
+ return rows
900
+
901
+
902
+ # ---------------------------------------------------------------------------
903
+ # Rust: axum and actix-web
904
+ # ---------------------------------------------------------------------------
905
+
906
+ _RUST_VERB_ATTR = re.compile(
907
+ r"^#\s*\[\s*(?:actix_web::)?(get|post|put|delete|patch|head|options|trace|route)"
908
+ r"\s*\(\s*\"([^\"]*)\"(.*)\)\s*\]\s*$", re.S)
909
+ _RUST_METHOD_ARG = re.compile(r"method\s*=\s*\"(\w+)\"")
910
+
911
+
912
+ def _routes_rust(root: Any) -> list[RouteRow]:
913
+ """actix-web ``#[get("/x")] async fn f`` and builders
914
+ (``web::scope("/api").service(web::resource("/x").route(web::get().to(f)))``),
915
+ axum ``Router::new().route("/x", get(h).post(h2)).nest("/api", r)``. Gated on
916
+ the crate being used in the file; the crate also picks the label."""
917
+ used = " ".join(_text(u) for u in _all(root, "use_declaration"))
918
+ label = "axum" if "axum" in used else "actix-web" if "actix_web" in used else None
919
+ if label is None:
920
+ return []
921
+ rows: list[RouteRow] = []
922
+
923
+ for fn in _all(root, "function_item"):
924
+ name = fn.child_by_field_name("name")
925
+ prev = fn.prev_named_sibling
926
+ while prev is not None and (prev.type == "attribute_item" or "comment" in prev.type):
927
+ m = _RUST_VERB_ATTR.match(_text(prev)) if prev.type == "attribute_item" else None
928
+ if m is not None and name is not None:
929
+ verb, path, rest = m.groups()
930
+ methods = _RUST_METHOD_ARG.findall(rest) if verb == "route" else [verb]
931
+ rows += [_row("actix-web", meth, _join_path("", path), _text(name),
932
+ name.start_point[0] + 1) for meth in methods or ["ANY"]]
933
+ prev = prev.prev_named_sibling
934
+
935
+ def last_segment(fn: Any) -> str:
936
+ return _text(fn).rsplit("::", 1)[-1]
937
+
938
+ def call_parts(call: Any) -> tuple[str, Any | None, list[Any], Any | None]:
939
+ """(method name, receiver, arguments, name node) of `recv.name(args)` or
940
+ `path::name(args)` (no receiver)."""
941
+ fn = call.child_by_field_name("function")
942
+ args = call.child_by_field_name("arguments")
943
+ arglist = list(args.named_children) if args is not None else []
944
+ if fn is None:
945
+ return "", None, arglist, None
946
+ if fn.type == "field_expression":
947
+ field = fn.child_by_field_name("field")
948
+ return (_text(field) if field is not None else "", fn.child_by_field_name("value"),
949
+ arglist, field)
950
+ return last_segment(fn), None, arglist, fn
951
+
952
+ def methods_of(expr: Any, pending: str = "") -> list[tuple[str, str]]:
953
+ """`get(h).post(h2)` / `web::get().to(f)` -> [(method, handler), ...]."""
954
+ if expr is None or expr.type != "call_expression":
955
+ return []
956
+ name, recv, args, _n = call_parts(expr)
957
+ first = _text(args[0]) if args else ""
958
+ if name in ("to", "to_async"):
959
+ return methods_of(recv, first)
960
+ if name in _HTTP_METHODS or name == "any":
961
+ here = [("ANY" if name == "any" else name, first or pending or "<unknown>")]
962
+ return here + methods_of(recv, pending)
963
+ return []
964
+
965
+ def chain_path(recv: Any, kinds: tuple[str, ...]) -> str:
966
+ """The literal of the first `kind("/p")` call down a receiver chain."""
967
+ node = recv
968
+ while node is not None and node.type == "call_expression":
969
+ name, inner, args, _n = call_parts(node)
970
+ if name in kinds and args:
971
+ return _lit(args[0]) or ""
972
+ node = inner
973
+ return ""
974
+
975
+ def walk(node: Any, prefix: str) -> None:
976
+ if node.type == "call_expression":
977
+ name, recv, args, name_node = call_parts(node)
978
+ line = (name_node or node).start_point[0] + 1
979
+ scope = _join_path(prefix, chain_path(recv, ("scope",))) if recv is not None \
980
+ else prefix
981
+ if name == "route" and recv is not None and len(args) == 2 \
982
+ and _lit(args[0]) is not None:
983
+ path = _join_path(scope, _lit(args[0]) or "") # axum
984
+ rows.extend(_row(label, m, path, h, line) for m, h in methods_of(args[1]))
985
+ walk(recv, prefix)
986
+ return
987
+ if name == "route" and recv is not None and len(args) == 1:
988
+ path = _join_path(scope, chain_path(recv, ("resource",))) # actix
989
+ rows.extend(_row(label, m, path, h, line) for m, h in methods_of(args[0]))
990
+ walk(recv, prefix)
991
+ return
992
+ if name in ("to", "to_async") and recv is not None and args \
993
+ and chain_path(recv, ("resource",)) and not methods_of(recv):
994
+ path = _join_path(scope, chain_path(recv, ("resource",)))
995
+ rows.append(_row(label, "ANY", path, _text(args[0]), line))
996
+ walk(recv, prefix)
997
+ return
998
+ if name == "nest" and recv is not None and len(args) == 2 \
999
+ and _lit(args[0]) is not None:
1000
+ walk(args[1], _join_path(prefix, _lit(args[0]) or ""))
1001
+ walk(recv, prefix)
1002
+ return
1003
+ if name == "service" and recv is not None and args:
1004
+ for a in args:
1005
+ walk(a, scope)
1006
+ walk(recv, prefix)
1007
+ return
1008
+ for ch in node.named_children:
1009
+ walk(ch, prefix)
1010
+
1011
+ try:
1012
+ walk(root, "")
1013
+ except RecursionError:
1014
+ pass
1015
+ return rows
1016
+
1017
+
1018
+ # ---------------------------------------------------------------------------
1019
+ # Ruby: Sinatra and the Rails routes DSL
1020
+ # ---------------------------------------------------------------------------
1021
+
1022
+ _RUBY_VERBS = frozenset({"get", "post", "put", "patch", "delete", "options", "head"})
1023
+ # What `resources :articles` declares: (method, path under the resource, action).
1024
+ _RAILS_REST = (
1025
+ ("GET", "", "index"), ("GET", "new", "new"), ("POST", "", "create"),
1026
+ ("GET", ":id", "show"), ("GET", ":id/edit", "edit"), ("PATCH", ":id", "update"),
1027
+ ("PUT", ":id", "update"), ("DELETE", ":id", "destroy"),
1028
+ )
1029
+ _RAILS_REST_ONE = (
1030
+ ("GET", "new", "new"), ("POST", "", "create"), ("GET", "", "show"),
1031
+ ("GET", "edit", "edit"), ("PATCH", "", "update"), ("PUT", "", "update"),
1032
+ ("DELETE", "", "destroy"),
1033
+ )
1034
+
1035
+
1036
+ def _ruby_value(node: Any) -> str | None:
1037
+ """A string literal or a symbol (`:feed` -> feed)."""
1038
+ if node is None:
1039
+ return None
1040
+ if node.type in ("simple_symbol", "hash_key_symbol"):
1041
+ return _text(node).lstrip(":")
1042
+ return _lit(node)
1043
+
1044
+
1045
+ def _ruby_call(node: Any) -> tuple[str, list[Any], dict[str, Any], Any | None]:
1046
+ """(method, positional args, keyword args, block) of a receiver-less call."""
1047
+ method = node.child_by_field_name("method")
1048
+ args = node.child_by_field_name("arguments")
1049
+ positional: list[Any] = []
1050
+ keywords: dict[str, Any] = {}
1051
+ for a in args.named_children if args is not None else []:
1052
+ if a.type == "pair":
1053
+ key, value = a.child_by_field_name("key"), a.child_by_field_name("value")
1054
+ k = _ruby_value(key)
1055
+ if key is not None and key.type in ("string",) and value is not None:
1056
+ positional.append(key) # `get 'x' => 'c#a'`
1057
+ keywords.setdefault("to", value)
1058
+ elif k is not None and value is not None:
1059
+ keywords[k] = value
1060
+ else:
1061
+ positional.append(a)
1062
+ return (_text(method) if method is not None else "", positional, keywords,
1063
+ node.child_by_field_name("block"))
1064
+
1065
+
1066
+ def _routes_ruby(root: Any) -> list[RouteRow]:
1067
+ """Sinatra ``get '/x' do … end`` (in a file that requires sinatra, or under a
1068
+ ``Sinatra::Base`` subclass) and the Rails ``routes.draw`` DSL: verbs,
1069
+ ``root``, ``resources`` / ``resource`` (``only:`` / ``except:``, nested),
1070
+ ``namespace`` and ``scope``."""
1071
+ rows: list[RouteRow] = []
1072
+ calls = _all(root, "call")
1073
+ sinatra = any(
1074
+ c.child_by_field_name("receiver") is None
1075
+ and _text(m) == "require" and "sinatra" in _text(c)
1076
+ for c in calls if (m := c.child_by_field_name("method")) is not None
1077
+ ) or any("Sinatra" in _text(s) for s in _all(root, "superclass"))
1078
+
1079
+ def body_calls(block: Any) -> list[Any]:
1080
+ out: list[Any] = []
1081
+ stack = list(block.named_children)
1082
+ while stack:
1083
+ n = stack.pop(0)
1084
+ if n.type == "call" and n.child_by_field_name("receiver") is None:
1085
+ out.append(n)
1086
+ elif n.type != "call":
1087
+ stack = list(n.named_children) + stack
1088
+ return out
1089
+
1090
+ def sinatra_walk(block: Any, prefix: str) -> None:
1091
+ for call in body_calls(block):
1092
+ name, pos, _kw, blk = _ruby_call(call)
1093
+ first = _lit(pos[0]) if pos else None
1094
+ line = call.start_point[0] + 1
1095
+ if name in _RUBY_VERBS and blk is not None and first is not None:
1096
+ rows.append(_row("sinatra", name, _join_path(prefix, first), "<inline>", line))
1097
+ elif name == "namespace" and blk is not None and first is not None:
1098
+ sinatra_walk(blk, _join_path(prefix, first))
1099
+ elif blk is not None and name not in _RUBY_VERBS:
1100
+ sinatra_walk(blk, prefix)
1101
+
1102
+ if sinatra:
1103
+ sinatra_walk(root, "")
1104
+
1105
+ def handler(kw: dict[str, Any], default: str, ns: str) -> str:
1106
+ to = _ruby_value(kw.get("to"))
1107
+ return ns + (to if to else default)
1108
+
1109
+ def resources(call: Any, name: str, pos: list[Any], kw: dict[str, Any], blk: Any,
1110
+ prefix: str, ns: str) -> None:
1111
+ line = call.start_point[0] + 1
1112
+ plural = name == "resources"
1113
+ table = _RAILS_REST if plural else _RAILS_REST_ONE
1114
+ only = [v for e in (kw["only"].named_children if "only" in kw else [])
1115
+ if (v := _ruby_value(e))]
1116
+ if not only and "only" in kw and (one := _ruby_value(kw["only"])):
1117
+ only = [one]
1118
+ except_ = [v for e in (kw["except"].named_children if "except" in kw else [])
1119
+ if (v := _ruby_value(e))]
1120
+ param = _ruby_value(kw.get("param")) or "id"
1121
+ for arg in pos:
1122
+ res = _ruby_value(arg)
1123
+ if not res:
1124
+ continue
1125
+ base = _join_path(prefix, res)
1126
+ for method, sub, action in table:
1127
+ if (only and action not in only) or action in except_:
1128
+ continue
1129
+ rows.append(_row("rails", method, _join_path(base, sub.replace(":id", f":{param}")),
1130
+ f"{ns}{res}#{action}", line))
1131
+ if blk is not None:
1132
+ member = _join_path(base, f":{res.rstrip('s')}_{param}") if plural else base
1133
+ rails_walk(blk, member, ns, collection=base, controller=res)
1134
+
1135
+ def rails_walk(block: Any, prefix: str, ns: str, collection: str = "",
1136
+ controller: str = "") -> None:
1137
+ for call in body_calls(block):
1138
+ name, pos, kw, blk = _ruby_call(call)
1139
+ line = call.start_point[0] + 1
1140
+ if name in _RUBY_VERBS or name == "match":
1141
+ first = _ruby_value(pos[0]) if pos else None
1142
+ if first is None:
1143
+ continue
1144
+ base = collection if collection and _ruby_value(kw.get("on")) == "collection" \
1145
+ else prefix
1146
+ methods = [v.upper() for e in kw["via"].named_children
1147
+ if (v := _ruby_value(e))] if "via" in kw else []
1148
+ default = f"{controller}#{first}" if controller else first
1149
+ for method in methods or ([name] if name != "match" else ["ANY"]):
1150
+ rows.append(_row("rails", method, _join_path(base, first),
1151
+ handler(kw, default, ns), line))
1152
+ elif name == "root":
1153
+ to = _ruby_value(pos[0]) if pos else None
1154
+ rows.append(_row("rails", "GET", prefix or "/",
1155
+ ns + (to or _ruby_value(kw.get("to")) or "<unknown>"), line))
1156
+ elif name in ("resources", "resource"):
1157
+ resources(call, name, pos, kw, blk, prefix, ns)
1158
+ elif name in ("namespace", "scope") and blk is not None:
1159
+ first = _ruby_value(pos[0]) if pos else None
1160
+ path = _ruby_value(kw.get("path")) or first or ""
1161
+ module = _ruby_value(kw.get("module")) or (first if name == "namespace" else "")
1162
+ rails_walk(blk, _join_path(prefix, path), ns + (f"{module}/" if module else ""))
1163
+ elif blk is not None: # constraints, concerns, ...: routes inside count
1164
+ rails_walk(blk, prefix, ns, collection, controller)
1165
+
1166
+ for call in calls:
1167
+ method = call.child_by_field_name("method")
1168
+ recv = call.child_by_field_name("receiver")
1169
+ blk = call.child_by_field_name("block")
1170
+ if method is not None and _text(method) == "draw" and recv is not None \
1171
+ and "routes" in _text(recv) and blk is not None:
1172
+ rails_walk(blk, "", "")
1173
+ return rows
1174
+
1175
+
1176
+ # ---------------------------------------------------------------------------
1177
+ # PHP: Laravel's Route facade and Symfony #[Route] attributes
1178
+ # ---------------------------------------------------------------------------
1179
+
1180
+ _LARAVEL_VERBS = frozenset({"get", "post", "put", "patch", "delete", "options", "any"})
1181
+ _LARAVEL_REST = (
1182
+ ("GET", "", "index"), ("GET", "create", "create"), ("POST", "", "store"),
1183
+ ("GET", "{id}", "show"), ("GET", "{id}/edit", "edit"), ("PUT", "{id}", "update"),
1184
+ ("PATCH", "{id}", "update"), ("DELETE", "{id}", "destroy"),
1185
+ )
1186
+
1187
+
1188
+ def _php_args(args: Any | None) -> tuple[list[Any], dict[str, Any]]:
1189
+ positional: list[Any] = []
1190
+ named: dict[str, Any] = {}
1191
+ for a in _kids(args, "argument") if args is not None else []:
1192
+ key = a.child_by_field_name("name")
1193
+ # Node wrappers are new objects per access: compare by value, not identity
1194
+ value = next((c for c in a.named_children if key is None or c != key), None)
1195
+ if value is None:
1196
+ continue
1197
+ if key is not None:
1198
+ named[_text(key)] = value
1199
+ else:
1200
+ positional.append(value)
1201
+ return positional, named
1202
+
1203
+
1204
+ def _php_strings(node: Any | None) -> list[str]:
1205
+ """`['GET', 'POST']` / `'GET'` -> its strings."""
1206
+ if node is None:
1207
+ return []
1208
+ if node.type == "array_creation_expression":
1209
+ return [v for e in node.named_children if (v := _first_lit(e)) is not None]
1210
+ one = _lit(node)
1211
+ return [one] if one is not None else []
1212
+
1213
+
1214
+ def _php_array_get(node: Any | None, key: str) -> Any | None:
1215
+ """The value under 'key' in a PHP array literal."""
1216
+ if node is None or node.type != "array_creation_expression":
1217
+ return None
1218
+ for e in node.named_children:
1219
+ kids = e.named_children
1220
+ if len(kids) == 2 and _lit(kids[0]) == key:
1221
+ return kids[1]
1222
+ return None
1223
+
1224
+
1225
+ def _php_handler(node: Any | None) -> str:
1226
+ if node is None:
1227
+ return "<unknown>"
1228
+ if node.type in ("anonymous_function", "arrow_function",
1229
+ "anonymous_function_creation_expression"):
1230
+ return "<inline>"
1231
+ if node.type == "array_creation_expression":
1232
+ parts = [e.named_children[0] for e in node.named_children if e.named_children]
1233
+ if len(parts) == 2:
1234
+ cls = _text(parts[0]).removesuffix("::class")
1235
+ meth = _lit(parts[1]) or _text(parts[1])
1236
+ return f"{cls}::{meth}"
1237
+ value = _lit(node)
1238
+ return value if value is not None else _text(node).removesuffix("::class")
1239
+
1240
+
1241
+ def _routes_php(root: Any) -> list[RouteRow]:
1242
+ """Laravel ``Route::get('/x', [C::class, 'm'])``, ``Route::prefix('api')
1243
+ ->group(...)``, ``Route::group(['prefix' => ...], ...)``, ``resource`` /
1244
+ ``apiResource``; Symfony ``#[Route('/x', methods: ['GET'])]`` on a controller
1245
+ class and its methods (gated on a Symfony ``Route`` import)."""
1246
+ rows: list[RouteRow] = []
1247
+
1248
+ def chain(node: Any) -> list[tuple[str, Any, Any]] | None:
1249
+ """[(name, arguments, name node), ...] root first, for a call chain that
1250
+ starts at `Route::…`; None otherwise."""
1251
+ links: list[tuple[str, Any, Any]] = []
1252
+ while node is not None and node.type == "member_call_expression":
1253
+ name = node.child_by_field_name("name")
1254
+ links.append((_text(name) if name is not None else "",
1255
+ node.child_by_field_name("arguments"), name))
1256
+ node = node.child_by_field_name("object")
1257
+ if node is None or node.type != "scoped_call_expression":
1258
+ return None
1259
+ scope = node.child_by_field_name("scope")
1260
+ name = node.child_by_field_name("name")
1261
+ if scope is None or name is None:
1262
+ return None
1263
+ if _text(scope).lstrip("\\").rsplit("\\", 1)[-1] != "Route":
1264
+ return None
1265
+ links.append((_text(name), node.child_by_field_name("arguments"), name))
1266
+ return list(reversed(links))
1267
+
1268
+ def laravel(node: Any, prefix: str) -> None:
1269
+ if node.type in ("member_call_expression", "scoped_call_expression"):
1270
+ links = chain(node)
1271
+ if links is not None:
1272
+ laravel_chain(links, prefix)
1273
+ return
1274
+ for ch in node.named_children:
1275
+ laravel(ch, prefix)
1276
+
1277
+ def laravel_chain(links: list[tuple[str, Any, Any]], prefix: str) -> None:
1278
+ pre = prefix
1279
+ only = [v for n, a, _ in links if n == "only" for v in _php_strings(
1280
+ next(iter(_php_args(a)[0]), None))]
1281
+ except_ = [v for n, a, _ in links if n == "except" for v in _php_strings(
1282
+ next(iter(_php_args(a)[0]), None))]
1283
+ for name, args, name_node in links:
1284
+ pos, _named = _php_args(args)
1285
+ line = (name_node or args).start_point[0] + 1
1286
+ first = _lit(pos[0]) if pos else None
1287
+ if name == "prefix" and first is not None:
1288
+ pre = _join_path(pre, first)
1289
+ elif name == "group":
1290
+ inner = pre
1291
+ for a in pos:
1292
+ p = _lit(_php_array_get(a, "prefix")) if a.type == \
1293
+ "array_creation_expression" else None
1294
+ if p is not None:
1295
+ inner = _join_path(inner, p)
1296
+ for a in pos:
1297
+ if a.type != "array_creation_expression":
1298
+ laravel(a, inner)
1299
+ elif name in _LARAVEL_VERBS and first is not None and len(pos) >= 2:
1300
+ rows.append(_row("laravel", "ANY" if name == "any" else name,
1301
+ _join_path(pre, first), _php_handler(pos[1]), line))
1302
+ elif name == "match" and len(pos) >= 3 and _lit(pos[1]) is not None:
1303
+ for verb in _php_strings(pos[0]):
1304
+ rows.append(_row("laravel", verb, _join_path(pre, _lit(pos[1]) or ""),
1305
+ _php_handler(pos[2]), line))
1306
+ elif name in ("resource", "apiResource") and first is not None and len(pos) >= 2:
1307
+ opts = pos[2] if len(pos) > 2 else None
1308
+ keep = only + _php_strings(_php_array_get(opts, "only"))
1309
+ drop = except_ + _php_strings(_php_array_get(opts, "except"))
1310
+ base = _join_path(pre, first)
1311
+ ctrl = _php_handler(pos[1])
1312
+ for method, sub, action in _LARAVEL_REST:
1313
+ if name == "apiResource" and action in ("create", "edit"):
1314
+ continue
1315
+ if (keep and action not in keep) or action in drop:
1316
+ continue
1317
+ rows.append(_row("laravel", method, _join_path(base, sub),
1318
+ f"{ctrl}@{action}", line))
1319
+
1320
+ laravel(root, "")
1321
+
1322
+ if not any("Symfony" in (t := _text(u)) and "Route" in t
1323
+ for u in _all(root, "namespace_use_declaration")):
1324
+ return rows
1325
+
1326
+ def route_attrs(decl: Any) -> list[tuple[str, list[str]]]:
1327
+ found = []
1328
+ for al in _kids(decl, "attribute_list"):
1329
+ for group in _kids(al, "attribute_group"):
1330
+ for attr in _kids(group, "attribute"):
1331
+ name = _kid(attr, "name", "qualified_name")
1332
+ if name is None or _text(name).rsplit("\\", 1)[-1] != "Route":
1333
+ continue
1334
+ pos, named = _php_args(attr.child_by_field_name("parameters"))
1335
+ path = _lit(named.get("path")) if "path" in named else (
1336
+ _lit(pos[0]) if pos else None)
1337
+ found.append((path or "", _php_strings(named.get("methods")) or ["ANY"]))
1338
+ return found
1339
+
1340
+ for cls in _all(root, "class_declaration"):
1341
+ prefix = next((p for p, _m in route_attrs(cls)), "")
1342
+ body = cls.child_by_field_name("body")
1343
+ for m in _kids(body, "method_declaration") if body is not None else []:
1344
+ name = m.child_by_field_name("name")
1345
+ for path, methods in route_attrs(m):
1346
+ rows += [_row("symfony", meth, _join_path(prefix, path),
1347
+ _text(name) if name is not None else "<unknown>",
1348
+ (name or m).start_point[0] + 1) for meth in methods]
1349
+ return rows
1350
+
1351
+
1352
+ _TS_ROUTE_EXTRACTORS = {
1353
+ "javascript": _routes_js,
1354
+ "typescript": _routes_js,
1355
+ "tsx": _routes_js,
1356
+ "jsx": _routes_js,
1357
+ "go": _routes_go,
1358
+ "java": _routes_java,
1359
+ "kotlin": _routes_kotlin,
1360
+ "csharp": _routes_csharp,
1361
+ "rust": _routes_rust,
1362
+ "ruby": _routes_ruby,
1363
+ "php": _routes_php,
1364
+ }
1365
+
1366
+
1367
+ def _routes_treesitter(src: bytes, rel: str) -> list[RouteRow]:
1368
+ parser, lang = _ts_parser_for(rel)
1369
+ extractor = _TS_ROUTE_EXTRACTORS.get(str(lang or "").lower())
1370
+ if parser is None or extractor is None:
1371
+ return []
1372
+ try:
1373
+ root = parser.parse(src).root_node
1374
+ return extractor(root)
1375
+ except Exception: # parse failure / grammar drift: degrade to no visibility
1376
+ return []
1377
+
1378
+
1379
+ # ---------------------------------------------------------------------------
1380
+ # Public entry points
1381
+ # ---------------------------------------------------------------------------
1382
+
1383
+
1384
+ def routes_for_source(src: bytes | str, rel: str) -> list[RouteRow]:
1385
+ """PUBLIC: framework routes for one source blob — the stable contract for
1386
+ external consumers (importable as ``from graphlore.routes import
1387
+ routes_for_source``); the underscore-prefixed extractors behind it are
1388
+ internal and may be renamed.
1389
+
1390
+ ``rel`` is the file's (relative) path and only selects the parser — ``.py``
1391
+ goes through the stdlib ``ast``, anything else through the optional
1392
+ tree-sitter backend (empty result when that backend or the language is
1393
+ unavailable). No file IO, no caching, no project-dir confinement: the caller
1394
+ owns the source bytes.
1395
+
1396
+ Returns rows ``{framework, method, pattern, handler, line}`` sorted by line;
1397
+ a lower bound — see the module docstring for what is invisible.
1398
+ """
1399
+ data = src if isinstance(src, bytes) else src.encode("utf-8", "replace")
1400
+ if str(rel).lower().endswith(".py"):
1401
+ rows = _routes_python(data)
1402
+ else:
1403
+ rows = _routes_treesitter(data, str(rel))
1404
+ return sorted(rows, key=lambda r: (r["line"], r["method"], r["pattern"]))
1405
+
1406
+
1407
+ def _routes_for_file(file_path: str) -> list[RouteRow]:
1408
+ """Routes for one source file under PROJECT_DIR.
1409
+
1410
+ Python via stdlib ``ast``; JS/TS, Go and Java via the optional tree-sitter
1411
+ backend when present; empty for other / missing / unparseable files (cached
1412
+ either way). Confined to PROJECT_DIR like the span index. Cached by
1413
+ (path, mtime).
1414
+ """
1415
+ return _cached_file_analysis(
1416
+ _ROUTES_CACHE, file_path, routes_for_source, list, _ROUTES_CACHE_MAX
1417
+ )