From d1925ada228525edfc08e9a4d94c45178913c7d8 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sat, 5 Dec 2026 05:08:12 +0800 Subject: [PATCH] feat(endpoints): list Spring routes a controller inherits from its interface (#8129) A controller implementing an interface that carries the request mappings (an OpenAPI-generated OwnersApi) declares none itself, so Search Everywhere's Endpoints tab found nothing for it. Controller methods without a mapping now take the one of the same-named interface method, under the controller's class-level @RequestMapping (else the interface's), with the interface's parameter annotations and constants resolved in the interface's file. The route scan also reads interface files and the build's generated sources (target/generated-sources, build/generated next to a build file), which the VCS usually ignores. Fixes #8110 --- crates/ide-host/src/ops/routes.rs | 124 ++++++++++++++---- src/features/http-client/spring/endpoints.ts | 92 ++++++++++++- src/features/http-client/spring/routeIndex.ts | 12 +- src/features/http-client/spring/source.ts | 13 ++ .../http-client/spring/spring.test.ts | 72 +++++++++- 5 files changed, 283 insertions(+), 30 deletions(-) diff --git a/crates/ide-host/src/ops/routes.rs b/crates/ide-host/src/ops/routes.rs index 30ceb03ad2..1e02384f4d 100644 --- a/crates/ide-host/src/ops/routes.rs +++ b/crates/ide-host/src/ops/routes.rs @@ -34,25 +34,30 @@ pub(crate) struct RouteFiles { owners: &'static [&'static str], /// Folders whose files declare no route of the project. skipped: &'static [&'static str], + /// Generated-source folders of a build, relative to the folder of its build file (`pom.xml`, + /// `build.gradle(.kts)`): ignored by the project's VCS rules, but sources all the same. + generated: &'static [&'static str], } /// Installed packages (a virtualenv the ignore rules don't cover) declare their own examples. const PACKAGES: &[&str] = &["site-packages"]; /// Spring mappings: Java and Kotlin sources that name a request mapping annotation and a -/// controller or Feign client, the only classes the UI reads them from. Other `…Mapping` -/// names (MapStruct's `@Mapping`, mappers, DTOs) would otherwise fill the file budget in a -/// large tree and push real controllers out. +/// controller, a Feign client or an interface (one a controller implements, such as an +/// OpenAPI-generated `…Api`), the only types the UI reads them from. Other `…Mapping` names +/// (MapStruct's `@Mapping`, mappers, DTOs) would otherwise fill the file budget in a large +/// tree and push real controllers out. Generated interfaces live in the build's output. pub(crate) const SPRING: RouteFiles = RouteFiles { extensions: &["java", "kt", "kts"], words: &["RequestMapping", "GetMapping", "PostMapping", "PutMapping", "DeleteMapping", "PatchMapping"], - owners: &["Controller", "FeignClient"], + owners: &["Controller", "FeignClient", "interface"], skipped: PACKAGES, + generated: &["target/generated-sources", "build/generated"], }; /// Flask and FastAPI routes: Python sources that import either (blueprints, routers and the /// modules registering them all do). pub(crate) const PYTHON: RouteFiles = - RouteFiles { extensions: &["py"], words: &["flask", "fastapi"], owners: &[], skipped: PACKAGES }; + RouteFiles { extensions: &["py"], words: &["flask", "fastapi"], owners: &[], skipped: PACKAGES, generated: &[] }; /// Laravel and Symfony routes: PHP sources that call the `Route` facade or carry a `Route` /// attribute or annotation, and the YAML files that give a route its controller. Not the /// installed packages, nor what the frameworks generate (Symfony's `var`, Laravel's `storage`). @@ -61,6 +66,7 @@ pub(crate) const PHP: RouteFiles = RouteFiles { words: &["Route::", "#[Route", "@Route", "controller:"], owners: &[], skipped: &["vendor", "node_modules", "var", "storage"], + generated: &[], }; impl RouteFiles { @@ -72,18 +78,20 @@ impl RouteFiles { } } -/// Files under `root` whose text names a route: `ignore` rules and `excludes` -/// decide what counts, and the UI ranks the matches itself. -pub(crate) fn sources_in(root: &Path, excludes: &[String], kind: RouteFiles) -> Vec { - let found: Mutex> = Mutex::new(Vec::new()); - let bytes = AtomicUsize::new(0); - let truncated = AtomicBool::new(false); - ide_vfs::walk_files(root, excludes, |path| { - if !kind.declares_routes(path.strip_prefix(root).unwrap_or(path)) { - return; - } - if bytes.load(Ordering::Relaxed) >= MAX_BYTES { - truncated.store(true, Ordering::Relaxed); +const BUILD_FILES: &[&str] = &["pom.xml", "build.gradle", "build.gradle.kts"]; + +/// What the scan has gathered: the route sources and their size, within the budgets. +struct Found { + files: Mutex>, + bytes: AtomicUsize, + truncated: AtomicBool, +} + +impl Found { + /// Keeps `path` when its text names a route of `kind`. + fn consider(&self, kind: RouteFiles, path: &Path) { + if self.bytes.load(Ordering::Relaxed) >= MAX_BYTES { + self.truncated.store(true, Ordering::Relaxed); return; } if std::fs::metadata(path).map_or(true, |m| m.len() > MAX_FILE_BYTES) { @@ -96,24 +104,68 @@ pub(crate) fn sources_in(root: &Path, excludes: &[String], kind: RouteFiles) -> { return; } - let Ok(mut found) = found.lock() else { return }; - if found.len() >= MAX_FILES { - truncated.store(true, Ordering::Relaxed); + let Ok(mut files) = self.files.lock() else { return }; + if files.len() >= MAX_FILES { + self.truncated.store(true, Ordering::Relaxed); return; } - bytes.fetch_add(text.len(), Ordering::Relaxed); - found.push(RouteSource { path: path.to_path_buf().into(), text }); + self.bytes.fetch_add(text.len(), Ordering::Relaxed); + files.push(RouteSource { path: path.to_path_buf().into(), text }); + } +} + +/// Files under `root` whose text names a route: `ignore` rules and `excludes` +/// decide what counts, and the UI ranks the matches itself. A build's generated sources +/// (`kind.generated`, next to a build file the walk met) are read although the VCS ignores them. +pub(crate) fn sources_in(root: &Path, excludes: &[String], kind: RouteFiles) -> Vec { + let found = Found { files: Mutex::new(Vec::new()), bytes: AtomicUsize::new(0), truncated: AtomicBool::new(false) }; + let builds: Mutex> = Mutex::new(Vec::new()); + ide_vfs::walk_files(root, excludes, |path| { + if !kind.generated.is_empty() + && path.file_name().and_then(|n| n.to_str()).is_some_and(|n| BUILD_FILES.contains(&n)) + && let (Some(dir), Ok(mut builds)) = (path.parent(), builds.lock()) + { + builds.push(dir.to_path_buf()); + } + if kind.declares_routes(path.strip_prefix(root).unwrap_or(path)) { + found.consider(kind, path); + } }); - let mut files = found.into_inner().unwrap_or_default(); - if truncated.into_inner() { + let mut builds = builds.into_inner().unwrap_or_default(); + builds.sort(); + builds.dedup(); + for dir in builds { + for generated in kind.generated { + walk_generated(&dir.join(generated), kind, &found, 0); + } + } + let mut files = found.files.into_inner().unwrap_or_default(); + if found.truncated.into_inner() { tracing::warn!( "routes: more than {MAX_FILES} files or {MAX_BYTES} bytes of route sources under {root:?}; the rest is left out" ); } files.sort_by(|a, b| a.path.cmp(&b.path)); + // A generated folder the VCS doesn't ignore was walked already. + files.dedup_by(|a, b| a.path == b.path); files } +/// The sources under a generated-source folder. Generators write a shallow tree (`openapi/src/ +/// main/java/`), so the depth is bounded instead of following VCS rules. +fn walk_generated(dir: &Path, kind: RouteFiles, found: &Found, depth: usize) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let Ok(file_type) = entry.file_type() else { continue }; + let path = entry.path(); + if file_type.is_dir() && depth < 16 { + walk_generated(&path, kind, found, depth + 1); + } else if file_type.is_file() && kind.declares_routes(&path) { + found.consider(kind, &path); + } + } +} + /// The folders to scan: the project folder itself first, then content roots outside it /// (`content_roots` lists only the ones outside, so the project folder is never implied — /// forgetting it scans nothing). @@ -185,6 +237,30 @@ mod tests { } } + /// #8110: an OpenAPI-generated interface sits in the build output, which the project + /// excludes; the controller implementing it names no mapping of its own. + #[test] + fn spring_reads_mapping_interfaces_also_from_generated_sources() { + let tmp = tempfile::tempdir().unwrap(); + let write = |rel: &str, text: &str| { + let path = tmp.path().join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + }; + write("pom.xml", ""); + write( + "target/generated-sources/openapi/src/main/java/api/OwnersApi.java", + "public interface OwnersApi { @GetMapping(\"/owners\") List list(); }", + ); + write("target/classes/Stale.java", "public interface Stale { @GetMapping(\"/x\") void x(); }"); + write("src/main/java/rest/OwnerRestController.java", "@RestController @RequestMapping(\"/api\") class C {}"); + write("src/main/java/rest/Mapper.java", "@Mapper class M { @Mapping(target = \"a\") A map(B b); }"); + let files = sources_in(tmp.path(), &["target".into()], SPRING); + let names: Vec<_> = + files.iter().map(|f| f.path.0.file_name().unwrap().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["OwnerRestController.java", "OwnersApi.java"]); + } + #[test] fn python_sources_that_import_flask_or_fastapi_are_read_outside_installed_packages() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/features/http-client/spring/endpoints.ts b/src/features/http-client/spring/endpoints.ts index 72fe1e8150..b5c1eb6390 100644 --- a/src/features/http-client/spring/endpoints.ts +++ b/src/features/http-client/spring/endpoints.ts @@ -12,6 +12,7 @@ import { type Expr, type Param, type SourceFile, + type Tok, } from "./source"; export interface QueryParam { @@ -299,12 +300,99 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const }; } -export function controllersOf(file: SourceFile, external?: ExternalConstant): Controller[] { +/** Interfaces whose methods carry request mappings (an OpenAPI-generated `OwnersApi`), by simple name. */ +export type MappedInterfaces = ReadonlyMap; + +/** The interfaces of `files` that declare request mappings, for [`controllersOf`] to inherit from. */ +export function mappedInterfaces( + files: readonly SourceFile[], + external?: (file: SourceFile) => ExternalConstant, +): Map { + const out = new Map(); + for (const file of files) { + let constants: Constants | undefined; + for (const cls of allClasses(file)) + if (cls.kind === "interface" && cls.methods.some((m) => mapping(m.annotations))) + out.set(cls.name, { cls, constants: (constants ??= new Constants(file, external?.(file))) }); + } + return out; +} + +const literal = (value: string): Tok => ({ + kind: "str", + text: JSON.stringify(value), + value, + start: 0, + end: 0, + nl: false, +}); +const punct = (text: string): Tok => ({ kind: "p", text, start: 0, end: 0, nl: false }); + +/** `ann` with its arguments resolved in the file that declares it: they may name that file's constants. */ +function resolvedIn(ann: Annotation, c: Constants): Annotation { + const args = new Map(); + for (const [key, expr] of ann.args) { + const values = c.strings(expr, key === "method"); + if (!values.length) args.set(key, expr); + else if (values.length === 1) args.set(key, [literal(values[0]!)]); + else + args.set(key, [ + punct("{"), + ...values.flatMap((v, i) => (i ? [punct(","), literal(v)] : [literal(v)])), + punct("}"), + ]); + } + return { ...ann, args }; +} + +const simpleName = (type: string) => type.slice(type.lastIndexOf(".") + 1); + +/** + * A controller method without a mapping of its own takes the one its interface declares, as Spring + * does (`OwnerRestController implements OwnersApi`): the interface method of the same name and + * parameter count. The class-level `@RequestMapping` is the controller's own, else the interface's. + */ +function inherited( + cls: ClassDecl, + method: ClassDecl["methods"][number], + interfaces: MappedInterfaces, +): { cls: ClassDecl; method: ClassDecl["methods"][number] } | null { + if (mapping(method.annotations)) return null; + for (const type of cls.supertypes ?? []) { + const entry = interfaces.get(simpleName(type)); + const iface = entry?.cls; + const declared = iface?.methods.find( + (m) => m.name === method.name && m.params.length === method.params.length && mapping(m.annotations), + ); + if (!entry || !iface || !declared) continue; + const own = cls.annotations.some((a) => a.name === "RequestMapping"); + const resolve = (a: Annotation) => resolvedIn(a, entry.constants); + const classMapping = own ? [] : iface.annotations.filter((a) => a.name === "RequestMapping").map(resolve); + // Parameter annotations (`@RequestParam`, `@RequestBody`) usually stay on the interface too. + const params = declared.params.map((p) => ({ ...p, annotations: p.annotations.map(resolve) })); + return { + cls: { ...cls, annotations: [...cls.annotations, ...classMapping] }, + method: { ...method, annotations: [...method.annotations, ...declared.annotations.map(resolve)], params }, + }; + } + return null; +} + +export function controllersOf( + file: SourceFile, + external?: ExternalConstant, + interfaces: MappedInterfaces = new Map(), +): Controller[] { const constants = new Constants(file, external); const out: Controller[] = []; for (const cls of allClasses(file)) { if (!cls.annotations.some((a) => CONTROLLER.has(a.name))) continue; - const endpoints = cls.methods.map((m) => endpoint(cls, m, constants)).filter((e): e is Endpoint => !!e); + const endpoints = cls.methods + .map((m) => { + const from = interfaces.size ? inherited(cls, m, interfaces) : null; + return from ? endpoint(from.cls, from.method, constants) : endpoint(cls, m, constants); + }) + .filter((e): e is Endpoint => !!e); out.push({ name: cls.name, offset: cls.nameStart, range: { from: cls.start, to: cls.end }, endpoints }); } return out; diff --git a/src/features/http-client/spring/routeIndex.ts b/src/features/http-client/spring/routeIndex.ts index 423975447a..8cb5d4e1e7 100644 --- a/src/features/http-client/spring/routeIndex.ts +++ b/src/features/http-client/spring/routeIndex.ts @@ -4,7 +4,7 @@ import { ipcPath, isSameOrInside } from "@/platform/paths"; import { projectFolder, relativePath, useProject } from "@/platform/project"; import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions"; import { constantPool, resetConstantPool } from "./constants"; -import { controllersOf } from "./endpoints"; +import { controllersOf, mappedInterfaces } from "./endpoints"; import { controllerMethods, feignMethods, type HttpShape } from "./feign"; import { parseSource } from "./source"; @@ -87,15 +87,21 @@ async function scan(root: string, project: ProjectInfo | null): Promise p.file)); + const interfaces = mappedInterfaces( + parsed.map((p) => p.file), + (file) => pool.resolverFor(file), + ); for (const { source, path, base, file } of parsed) { + if (!source.text.includes("Controller")) continue; controllers.push(...controllerMethods(source.text, file).map((method) => ({ ...method, path }))); - for (const controller of controllersOf(file, pool.resolverFor(file))) { + for (const controller of controllersOf(file, pool.resolverFor(file), interfaces)) { for (const endpoint of controller.endpoints) { const at = lineCol(source.text, endpoint.offset); // A mapping without a path answers nothing to look up by URL; the method diff --git a/src/features/http-client/spring/source.ts b/src/features/http-client/spring/source.ts index 3f81605a29..f1973b44ed 100644 --- a/src/features/http-client/spring/source.ts +++ b/src/features/http-client/spring/source.ts @@ -71,6 +71,8 @@ export interface ClassDecl { classes: ClassDecl[]; /** The class it extends (`extends Base` / Kotlin `: Base()`), as written. */ superclass?: string; + /** Every supertype it names (`extends` / `implements` / Kotlin `:` list), without type arguments. */ + supertypes?: string[]; } export interface SourceFile { @@ -449,6 +451,8 @@ class Reader { cls.ctorParams = this.params(j); j = this.match[j]! + 1; } + let inSupertypes = false; + let generics = 0; for (; j < to; j++) { if (this.is(j, "{") || this.is(j, ";") || this.startsMember(j)) break; // Java `extends Base`; Kotlin `: Base(…)` (a supertype called with arguments is the class). @@ -457,6 +461,15 @@ class Reader { const type = this.typeName(j + 1, to); if (type && (javaSuper || this.is(type.end, "("))) cls.superclass = type.name; } + if (this.is(j, "<")) generics++; + else if (this.is(j, ">")) generics = Math.max(0, generics - 1); + const opens = + javaSuper || (this.toks[j]!.kind === "id" && this.toks[j]!.text === "implements") || this.is(j, ":"); + if (opens) inSupertypes = true; + if (inSupertypes && generics === 0 && (opens || this.is(j, ","))) { + const type = this.typeName(j + 1, to); + if (type) (cls.supertypes ??= []).push(type.name.replace(/<.*$/s, "")); + } if (OPEN[this.toks[j]!.text] && this.toks[j]!.kind === "p") j = this.match[j]!; } if (this.is(j, "{")) { diff --git a/src/features/http-client/spring/spring.test.ts b/src/features/http-client/spring/spring.test.ts index 34061fdad1..67889f2a58 100644 --- a/src/features/http-client/spring/spring.test.ts +++ b/src/features/http-client/spring/spring.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { springAt, springControllers, type Endpoint } from "./endpoints"; +import { controllersOf, mappedInterfaces, springAt, springControllers, type Endpoint } from "./endpoints"; import { appendRequests, bodyLookup, @@ -387,3 +387,73 @@ describe("caret lookup", () => { expect(springAt(controllers, 0)).toEqual({ controller: null, endpoint: null }); }); }); + +describe("mappings inherited from an interface", () => { + // An OpenAPI-generated contract: the controller implements it and declares no mapping itself (#8110). + const api = parseSource(` +package org.example.api; +import org.springframework.web.bind.annotation.*; +@RequestMapping("/fallback") +public interface OwnersApi { + String PATH_LIST_OWNERS = "/owners"; + @RequestMapping(method = RequestMethod.GET, value = OwnersApi.PATH_LIST_OWNERS, produces = { "application/json" }) + default ResponseEntity> listOwners(@RequestParam(value = "lastName", required = false) String lastName) { + return null; + } + @RequestMapping(method = RequestMethod.GET, value = PATH_LIST_OWNERS + "/{ownerId}") + ResponseEntity getOwner(@PathVariable("ownerId") Integer ownerId); + @PostMapping("/owners") + ResponseEntity addOwner(@RequestBody OwnerFieldsDto owner); +} +`); + const controller = (classMapping: string) => + parseSource(` +package org.example.rest; +import org.example.api.OwnersApi; +import org.springframework.web.bind.annotation.*; +@RestController +${classMapping} +public class OwnerRestController implements OwnersApi, java.io.Serializable { + @Override + public ResponseEntity> listOwners(String lastName) { return null; } + @Override + public ResponseEntity getOwner(Integer ownerId) { return null; } + @Override + public ResponseEntity addOwner(OwnerFieldsDto owner) { return null; } + @GetMapping("/owners/count") + public int count() { return 0; } + public void helper() {} +} +`); + + it("records the supertypes a class implements", () => { + expect(controller("").classes[0]!.supertypes).toEqual(["OwnersApi", "java.io.Serializable"]); + }); + + it("gives the controller's methods the interface's mappings, under the controller's prefix", () => { + const file = controller('@RequestMapping("/api")'); + const [ctrl] = controllersOf(file, undefined, mappedInterfaces([api])); + const routes = ctrl!.endpoints.map((e) => `${e.httpMethod} ${e.paths.join(",")} ${e.methodName}`); + expect(routes).toEqual([ + "GET /api/owners listOwners", + "GET /api/owners/{ownerId} getOwner", + "POST /api/owners addOwner", + "GET /api/owners/count count", + ]); + const list = ctrl!.endpoints[0]!; + // The controller's method is the target; the interface's parameter annotations still count. + expect(file.classes[0]!.methods[0]!.nameStart).toBe(list.offset); + expect(list.query).toEqual([{ name: "lastName", value: null }]); + expect(list.produces).toBe("application/json"); + }); + + it("uses the interface's class mapping when the controller has none", () => { + const [ctrl] = controllersOf(controller(""), undefined, mappedInterfaces([api])); + expect(ctrl!.endpoints[0]!.paths).toEqual(["/fallback/owners"]); + }); + + it("finds nothing extra without the interface", () => { + const [ctrl] = controllersOf(controller('@RequestMapping("/api")')); + expect(ctrl!.endpoints.map((e) => e.methodName)).toEqual(["count"]); + }); +});