Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 6aa43c8be9 fix(http-client): resolve Spring mapping constants declared in other classes
Mapping paths were evaluated with the constants of the controller's own file
only, so a path built from another class's constants (a shared API prefix
interface, Routes.ORDERS, a static import or a superclass field) dropped out of
Endpoints search and the gutter showed a partial URL. A shared constant pool now
finds those classes by name in the index, preferring the imported package, reads
them and resolves their constants, following up to three hops.
2026-11-18 22:38:23 +08:00
5 змінених файлів з 343 додано та 14 видалено

No files matched your search

+107
Переглянути файл
@@ -0,0 +1,107 @@
import { describe, expect, it, vi } from "vitest";
import { ConstantPool, type ConstantFiles } from "./constants";
import { controllersOf } from "./endpoints";
import { parseSource } from "./source";
function project(files: Record<string, string>): ConstantFiles & { reads: string[] } {
const reads: string[] = [];
return {
reads,
filesNamed: vi.fn(async (name: string) => Object.keys(files).filter((p) => p.endsWith(`/${name}`))),
read: async (path) => {
reads.push(path);
return files[path] ?? null;
},
};
}
async function paths(text: string, files: ConstantFiles) {
const file = parseSource(text);
const pool = new ConstantPool(files);
await pool.load([file]);
return controllersOf(file, pool.resolverFor(file)).flatMap((c) =>
c.endpoints.map((e) => `${e.httpMethod} ${e.paths}`),
);
}
const defines = {
"/p/common/src/main/java/com/acme/common/AppServiceDefine.java": `package com.acme.common;
public interface AppServiceDefine {
String API_WEBAPI_PREFIX = "/api";
}`,
"/p/cockpit/src/main/java/com/acme/cockpit/CockpitApiDefine.java": `package com.acme.cockpit;
public interface CockpitApiDefine {
String API_COCKPIT_PREFIX = "/cockpit";
String PATH_MAP = "/map";
}`,
};
describe("mapping constants of other classes", () => {
it("joins constants of interfaces in other files and modules", async () => {
const files = project(defines);
const text = `package com.acme.cockpit.web;
import com.acme.common.AppServiceDefine;
import com.acme.cockpit.CockpitApiDefine;
@RestController
@RequestMapping(AppServiceDefine.API_WEBAPI_PREFIX + CockpitApiDefine.API_COCKPIT_PREFIX)
public class CockpitMapController {
@GetMapping(CockpitApiDefine.PATH_MAP + "/layers")
public MapLayerVO layers(@RequestParam(required = false) String type) { return null; }
}`;
expect(await paths(text, files)).toEqual(["GET /api/cockpit/map/layers"]);
});
it("follows static imports, superclasses and constants built from other classes", async () => {
const files = project({
...defines,
"/p/web/src/main/java/com/acme/web/Routes.java": `package com.acme.web;
import com.acme.common.AppServiceDefine;
public final class Routes {
public static final String ORDERS = AppServiceDefine.API_WEBAPI_PREFIX + "/orders";
}`,
"/p/web/src/main/java/com/acme/web/BaseController.java": `package com.acme.web;
public abstract class BaseController {
protected static final String ITEMS = "/items";
}`,
});
const text = `package com.acme.web;
import static com.acme.web.Routes.ORDERS;
@RestController
@RequestMapping(ORDERS)
public class OrderController extends BaseController {
@GetMapping(ITEMS + "/{id}")
public Item item(@PathVariable String id) { return null; }
}`;
expect(await paths(text, files)).toEqual(["GET /api/orders/items/{id}"]);
});
it("prefers the imported package when several classes share the name", async () => {
const files = project({
"/p/a/src/main/java/com/a/Paths.java": `package com.a;\npublic interface Paths { String ROOT = "/a"; }`,
"/p/b/src/main/java/com/b/Paths.java": `package com.b;\npublic interface Paths { String ROOT = "/b"; }`,
});
const text = `package com.app;
import com.b.Paths;
@RestController
class C {
@GetMapping(Paths.ROOT)
String get() { return ""; }
}`;
expect(await paths(text, files)).toEqual(["GET /b"]);
});
it("looks each class up once, and leaves out a constant no project file declares", async () => {
const files = project(defines);
const text = `@RestController
class C {
@GetMapping(Missing.PATH)
String a() { return ""; }
@GetMapping(CockpitApiDefine.PATH_MAP)
String b() { return ""; }
@PostMapping(CockpitApiDefine.PATH_MAP + "/x")
String c() { return ""; }
}`;
expect(await paths(text, files)).toEqual(["GET /", "GET /map", "POST /map/x"]);
expect(files.reads).toEqual(["/p/cockpit/src/main/java/com/acme/cockpit/CockpitApiDefine.java"]);
});
});
+172
Переглянути файл
@@ -0,0 +1,172 @@
/**
* Constants that mapping paths take from other classes: `Paths.API + "/orders"`,
* statically imported ones and those of a superclass. Their classes are found by
* file name in the index, read and kept until a Java / Kotlin file changes.
*/
import { call, commands } from "@/platform/ipc";
import { Constants, type ExternalConstant } from "./endpoints";
import { allClasses, parseSource, type Expr, type SourceFile } from "./source";
export interface ConstantFiles {
/** The project's files called `name`. */
filesNamed(name: string): Promise<string[]>;
read(path: string): Promise<string | null>;
}
const EXTENSIONS = [".java", ".kt"];
/** Classes looked up per pool, and how many hops from a controller to a constant's class. */
const MAX_CLASSES = 256;
const MAX_DEPTH = 3;
/** Qualifiers Spring and the JDK own: never project classes. */
const LIBRARY = new Set(["MediaType", "RequestMethod", "HttpMethod", "HttpHeaders", "HttpStatus", "String", "Integer"]);
const isClassName = (s: string | undefined): s is string => !!s && /^[A-Z]/.test(s);
const simpleType = (t: string) => t.replace(/<.*$/, "").replace(/\(.*$/, "").trim().split(".").pop() ?? "";
/** `C` of `a.b.C.NAME` / `a.b.C.*` (a static import; the parser drops the `static`). */
function staticImportClass(imp: string): string | null {
const parts = imp.split(".");
const owner = parts[parts.length - 2];
return parts.length >= 3 && isClassName(owner) ? owner : null;
}
/** Classes whose constants `file` can use without naming the class. */
function inheritedClasses(file: SourceFile): string[] {
const out = new Set<string>();
for (const imp of file.imports) {
const c = staticImportClass(imp);
if (c) out.add(c);
}
for (const c of allClasses(file)) if (c.superclass) out.add(simpleType(c.superclass));
return [...out].filter(isClassName);
}
function qualifiers(expr: Expr, out: Set<string>) {
for (let i = 0; i + 2 < expr.length; i++) {
const [a, dot, b] = [expr[i]!, expr[i + 1]!, expr[i + 2]!];
if (a.kind === "id" && dot.kind === "p" && dot.text === "." && b.kind === "id" && isClassName(a.text))
out.add(a.text);
}
}
/** Classes `file` takes constants from: qualifiers in annotations and constant initializers, and the inherited ones. */
export function referencedClasses(file: SourceFile): string[] {
const out = new Set(inheritedClasses(file));
const classes = allClasses(file);
for (const c of classes) {
for (const a of [...c.annotations, ...c.methods.flatMap((m) => m.annotations)])
for (const expr of a.args.values()) qualifiers(expr, out);
for (const f of c.fields) if (f.init) qualifiers(f.init, out);
}
for (const f of file.fields) if (f.init) qualifiers(f.init, out);
const own = new Set(classes.map((c) => c.name));
return [...out].filter((c) => !own.has(c) && !LIBRARY.has(c));
}
export class ConstantPool {
/** Class name → constants of its file; `null` when no project file declares it. */
private readonly classes = new Map<string, Constants | null>();
private readonly pending = new Map<string, Promise<SourceFile | null>>();
private readonly resolving = new Set<string>();
constructor(private readonly files: ConstantFiles) {}
/** Resolves the constants `file` takes from classes loaded so far. */
resolverFor(file: SourceFile): ExternalConstant {
const inherited = inheritedClasses(file);
return (qualifier, name) => {
for (const owner of qualifier ? [qualifier] : inherited) {
const key = `${owner}.${name}`;
const constants = this.classes.get(owner);
if (!constants || this.resolving.has(key)) continue;
this.resolving.add(key);
try {
const v = constants.named(name);
if (v != null) return v;
} finally {
this.resolving.delete(key);
}
}
return null;
};
}
/** Loads the classes `files` take constants from, and theirs in turn; true when one of them is now known. */
async load(files: readonly SourceFile[]): Promise<boolean> {
let added = false;
let round = [...files];
for (let depth = 0; depth < MAX_DEPTH && round.length; depth++) {
const next: SourceFile[] = [];
for (const file of round)
for (const name of referencedClasses(file)) {
if (this.classes.has(name) && !this.pending.has(name)) continue;
if (!this.pending.has(name) && this.classes.size >= MAX_CLASSES) continue;
const isNew = !this.pending.has(name);
const loaded = await this.lookup(name, file);
if (!loaded) continue;
added = true;
if (isNew) next.push(loaded);
}
round = next;
}
return added;
}
private lookup(name: string, from: SourceFile): Promise<SourceFile | null> {
const running = this.pending.get(name);
if (running) return running;
this.classes.set(name, null);
const promise = this.find(name, from)
.then((file) => {
if (file) {
const constants = new Constants(file, this.resolverFor(file));
// Nested classes too: `Outer.Inner.NAME` names `Inner`.
for (const c of allClasses(file))
if (c.name === name || !this.classes.get(c.name)) this.classes.set(c.name, constants);
}
return file;
})
.catch(() => null)
.finally(() => this.pending.delete(name));
this.pending.set(name, promise);
return promise;
}
/** The file declaring class `name`, preferring the package `from` imports it from, then its own package. */
private async find(name: string, from: SourceFile): Promise<SourceFile | null> {
const imported = from.imports.find((i) => i.endsWith(`.${name}`) || i.includes(`.${name}.`));
const pkg = imported ? imported.slice(0, imported.indexOf(`.${name}`)) : from.packageName;
for (const ext of EXTENSIONS) {
const paths = (await this.files.filesNamed(`${name}${ext}`)).map((p) => p.replace(/\\/g, "/"));
if (!paths.length) continue;
const suffix = `/${pkg.replace(/\./g, "/")}/${name}${ext}`;
const path = paths.find((p) => p.endsWith(suffix)) ?? paths[0]!;
const text = await this.files.read(path);
if (text != null) return parseSource(text);
}
return null;
}
}
const projectFiles: ConstantFiles = {
filesNamed: async (name) => (await call(commands.findFilesNamed(name))).map(String),
read: async (path) => {
try {
return await call(commands.fsReadText(path));
} catch {
return null;
}
},
};
let shared: ConstantPool | null = null;
/** The project's pool, shared by the route index and the editors. */
export function constantPool(): ConstantPool {
return (shared ??= new ConstantPool(projectFiles));
}
/** Forgets the loaded classes (a Java / Kotlin file changed, or the project closed). */
export function resetConstantPool() {
shared = null;
}
+19 -4
Переглянути файл
@@ -19,6 +19,7 @@ import { useProject } from "@/platform/project";
import { isVirtualUri } from "@/platform/virtualDocs";
import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";
import { notifications, type MenuGroupContext } from "@/workbench/contributions";
import { constantPool } from "./constants";
import { springAt, springControllers, type Controller, type Endpoint } from "./endpoints";
import { bodyLookup, findHost, renderRequest, skeleton, type SourceReader } from "./request";
import { parseSource } from "./source";
@@ -39,6 +40,11 @@ export const sourceReader: SourceReader = {
filesNamed: (name) => call(commands.findFilesNamed(name)),
};
/** Controllers of `text`, with the other classes' constants loaded so far. */
function controllersIn(text: string): Controller[] {
return springControllers(text, (file) => constantPool().resolverFor(file));
}
/** One request per endpoint (`paths[i]` picks another path of the mapping). */
export interface Target {
endpoint: Endpoint;
@@ -109,7 +115,7 @@ function controllerItems(sourcePath: string, text: string, c: Controller): MenuI
/** Editor context menu items for the caret at `offset`: the generate actions (a path choice for several paths). */
export function springMenuItems(sourcePath: string, text: string, offset: number): MenuItem[] {
const { controller, endpoint } = springAt(springControllers(text), offset);
const { controller, endpoint } = springAt(controllersIn(text), offset);
const items: MenuItem[] = [];
if (endpoint)
items.push(
@@ -136,7 +142,7 @@ export async function generateAtCaret(scope: "endpoint" | "controller"): Promise
const e = activeEditor();
if (!e || !SPRING_LANGUAGES.has(e.ctx.language)) return;
const text = e.view.state.doc.toString();
const { controller, endpoint } = springAt(springControllers(text), e.view.state.selection.main.head);
const { controller, endpoint } = springAt(controllersIn(text), e.view.state.selection.main.head);
const endpoints = scope === "endpoint" ? (endpoint ? [endpoint] : []) : (controller?.endpoints ?? []);
if (!endpoints.length) {
notifications().notify({
@@ -178,7 +184,7 @@ function computeMarks(state: EditorState): Mark[] {
const doc = state.doc;
const marks: Mark[] = [];
const lineStart = (offset: number) => doc.lineAt(Math.min(offset, doc.length)).from;
for (const c of springControllers(doc.toString())) {
for (const c of controllersIn(doc.toString())) {
if (c.endpoints.length)
marks.push({
pos: lineStart(c.offset),
@@ -239,9 +245,18 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
const same =
cur.length === found.length && cur.every((m, i) => m.pos === found[i]!.pos && m.key === found[i]!.key);
if (!same) this.view.dispatch({ effects: setMarks.of(found) });
// Paths built from other classes' constants: load those classes, then mark again.
if (found.length) {
const pool = constantPool();
void pool.load([parseSource(this.view.state.doc.toString())]).then((loaded) => {
if (loaded && pool === constantPool() && !this.destroyed) this.schedule(0);
});
}
}, delay);
}
destroyed = false;
destroy() {
this.destroyed = true;
clearTimeout(this.timer);
}
},
@@ -250,7 +265,7 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
// Only files that have mappings (the gutter found some) are parsed again here.
if (!view.state.field(marksField, false)?.length) return [];
const text = view.state.doc.toString();
const { controller, endpoint } = springAt(springControllers(text), view.state.selection.main.head);
const { controller, endpoint } = springAt(controllersIn(text), view.state.selection.main.head);
const out: ContributedIntention[] = [];
if (endpoint)
out.push({
+35 -8
Переглянути файл
@@ -1,7 +1,8 @@
/**
* Spring Web request mappings of a Java / Kotlin source: `@RequestMapping` /
* `@GetMapping`… methods of `@RestController` / `@Controller` classes, with
* the class-level mapping applied. Constants are resolved within the file.
* the class-level mapping applied. Constants are resolved within the file, and
* through an {@link ExternalConstant} in other classes (`constants.ts`).
*/
import {
allClasses,
@@ -86,12 +87,27 @@ const MEDIA_TYPES: Record<string, string> = {
TEXT_XML: "text/xml",
};
/** The value of constant `name` of another class (`qualifier`, or an inherited / statically imported one when absent). */
export type ExternalConstant = (qualifier: string | undefined, name: string) => string | null;
/** Evaluates string-valued annotation arguments within one file. */
export class Constants {
private readonly fields = new Map<string, Expr>();
constructor(file: SourceFile) {
for (const f of [...file.fields, ...allClasses(file).flatMap((c) => c.fields)])
private readonly classes: Set<string>;
constructor(
file: SourceFile,
private readonly external?: ExternalConstant,
) {
const classes = allClasses(file);
for (const f of [...file.fields, ...classes.flatMap((c) => c.fields)])
if (f.init && !this.fields.has(f.name)) this.fields.set(f.name, f.init);
this.classes = new Set(classes.map((c) => c.name));
}
/** The value of this file's constant `name`. */
named(name: string): string | null {
const init = this.fields.get(name);
return init ? this.value(init, false, new Set([name])) : null;
}
/** Every element of an array (`{a, b}`, `[a, b]`, `arrayOf(a, b)`) or the single value; unresolvable ones dropped. */
@@ -133,7 +149,8 @@ export class Constants {
(m, a: string | undefined, b: string | undefined) => {
const name = (a ?? b)!;
const init = seen.has(name) ? undefined : this.fields.get(name);
return init ? (this.value(init, false, new Set([...seen, name])) ?? m) : m;
if (init) return this.value(init, false, new Set([...seen, name])) ?? m;
return seen.has(name) ? m : (this.external?.(undefined, name) ?? m);
},
);
if (part.length === 1 && part[0]!.kind === "num") return part[0]!.text;
@@ -144,11 +161,20 @@ export class Constants {
const last = names[names.length - 1]!;
const qualifier = names[names.length - 2];
if (qualifier === "MediaType") return MEDIA_TYPES[last.replace(/_VALUE$/, "")] ?? null;
// `Other.NAME` of a class declared elsewhere.
if (qualifier && !this.classes.has(qualifier)) {
const v = this.external?.(qualifier, last);
if (v != null) return v;
}
const init = this.fields.get(last);
if (init && !seen.has(last)) {
seen.add(last);
return this.value(init, enums, seen);
}
if (!qualifier && !enums) {
const v = this.external?.(undefined, last);
if (v != null) return v;
}
return enums ? last : null;
}
}
@@ -267,8 +293,8 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const
};
}
export function controllersOf(file: SourceFile): Controller[] {
const constants = new Constants(file);
export function controllersOf(file: SourceFile, external?: ExternalConstant): 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;
@@ -279,10 +305,11 @@ export function controllersOf(file: SourceFile): Controller[] {
}
/** Controllers of a Java / Kotlin source, with their endpoints. */
export function springControllers(text: string): Controller[] {
export function springControllers(text: string, external?: (file: SourceFile) => ExternalConstant): Controller[] {
// Cheap guard: most files are not controllers.
if (!/@(?:[\w.]+\.)?(?:Rest)?Controller\b/.test(text)) return [];
return controllersOf(parseSource(text));
const file = parseSource(text);
return controllersOf(file, external?.(file));
}
/** The controller and endpoint whose declaration holds `offset`. */
+10 -2
Переглянути файл
@@ -3,6 +3,7 @@ import { call, commands, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
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 { controllerMethods, type ControllerMethod } from "./feign";
import { parseSource } from "./source";
@@ -38,6 +39,7 @@ export function isRouteSource(path: string): boolean {
/** Forgets the index, so the next search rescans the project. */
export function clearRouteIndex() {
cached = null;
resetConstantPool();
}
/** The project's routes, scanned once per project and kept in memory. */
@@ -67,6 +69,7 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
const sources = await call(commands.springRouteSources());
const routes: EndpointEntry[] = [];
const controllers: ControllerTarget[] = [];
const parsed = [];
for (const source of sources) {
const path = ipcPath(source.path);
const folder = project ? projectFolder(project, path)?.root : root;
@@ -74,9 +77,14 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
const base = ipcPath(folder).replace(/\/$/, "");
if (!isSameOrInside(path, base)) continue;
if (!source.text.includes("Controller")) continue;
const file = parseSource(source.text);
parsed.push({ source, path, base, file: parseSource(source.text) });
}
// Mapping paths built from other classes' constants need those classes first.
const pool = constantPool();
await pool.load(parsed.map((p) => p.file));
for (const { source, path, base, file } of parsed) {
controllers.push(...controllerMethods(source.text, file).map((method) => ({ ...method, path })));
for (const controller of controllersOf(file)) {
for (const controller of controllersOf(file, pool.resolverFor(file))) {
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