GitNexus/gitnexus/tools/compiler-conformance/java/test/provider/java-const-route-parity.ts
Gergő Magyar 50228e11ab
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
fix(java): match javac resolution and move fixtures into conformance (#4056)
* test(java): compare overload resolution with javac in CI

* test(conformance): share call resolution reports across tools

* test(java): cover the overload conversion matrix with javac (#4057)

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>

* test(java): run Java-backed fixtures in dedicated CI shards

* test(java): replace handwritten resolution cases with javac comparisons

* test(java): compare lambda and receiver fixtures against javac

* fix(ci): restore Java test evidence and use locked toolchain commands

* test(skills): fail incomplete CLI generation checks (#4056)

* test(java): compare method references with javac

* fix(java): resolve qualified bases and static wildcard overloads

* test(java): preserve declared dollar names in compiler comparisons

* fix(java): preserve distinct call targets for colliding type names

* fix(conformance): resolve private nested bases and retain overload selections

* fix(java): distinguish variadic overloads in the published graph

* fix(java): match javac for nested types, imports and initializer calls

* Move Java fixture testing out of Vitest and into compiler conformance

* Verify Java graph endpoints and leave call selection to javac

* Match javac for annotated bases and legal static imports

* Resolve nested Java member types and clean up failed conformance fixtures

* Preserve qualified Java bases across unrelated static wildcard imports

* test(java): run inline source fixtures in compiler conformance

* test(conformance): check fetch callers, lexical bindings and cleanup

* test(java): move virtual source and text fixtures into conformance

* fix(java): resolve imported member types and qualified base collisions

* Match javac constructor overloads and preserve Java conformance coverage

* Compare recovered Java inheritance with javac in the conformance runner

* Run the Java query compilation smoke test in native conformance

* Clarify Java conformance expectations and check populated suites

* Write javac conformance records as UTF-8 on Windows

* Compile the Java conformance tools for SonarCloud analysis

* Compare Java method implementation edges with javac

* Resolve fixture writers and inherited Java methods in their lexical context

* Resolve qualified Java bases through their accessible type members

* Match local qualified Java bases and bounded varargs identities to javac

* Match Java call resolution to javac across the conformance corpus

Preserve generic declaration identity, follow nested call results, and type lambda aliases and enhanced-loop variables in their declaration scopes. Report proven JDK call targets without creating workspace edges. Compare every selected source and binary call against javac and remove the twelve mismatch lists.

* Compare Java recovery targets as sets and check empty destination addresses

Keep repeated uses of the same declaration equivalent across graph producers while detecting missing and extra targets. Check raw destination addresses and document the source and classpath inputs to the compiler comparison.

* Avoid extra native parent walks while capturing Java call facts

Index lambda origins by spelling before walking lexical scopes, and only check value shadowing for qualifiers rooted in an identifier. This restores the capture traversal budget for anonymous classes while preserving javac call targets.

* Refresh the Java capture fingerprint for corrected fixture comments

The module captures include the revised comments and the following declarations move to earlier lines. Both emitters produce the same 4,288 capture groups when given the same fixture revision.

* Preserve Java conformance assertions and use trusted fixture paths

Use explicit canonical sort orders, require missing evidence to fail assertions, and keep pending query results in the replay cache. Resolve the Git executable independently of the test repository and isolate the Spring workspace per test.

* Resolve inherited Java members through the scoped superclass

* Reuse validated analyzer build hashes for parser cache identity

* Resolve SonarCloud findings in Java resolution and compiler conformance

* Align Java compiler tool packages and pin benchmark baselines to the tested merge

* Honor wildcard method families and fixture ownership in Java conformance

* fix(java): resolve inherited and annotation member types against javac

Keep workspace links tied to import declarations and compare Java varargs overloads through comments. Make generated-project selection, method metadata checks and Java fixture ownership explicit in conformance.

* fix(java): resolve bounded and imported bases during dispatch

Keep the type selected from a qualified heritage clause available during overload resolution. Compare annotated bounds, inherited static imports, and String.valueOf arguments directly with javac. Detect Java fixture paths on either side of a filesystem rename.

* Conform Java method visibility and wildcard lambda bounds to javac

Compare method access at source positions, recognize CommonJS fixture reads, and preserve diagnostics when native conformance setup fails.

* Match javac for qualified member overloads and selective call diagnostics

* Track reassigned Java fixture paths at their point of use

* Respect Java visibility and Node path semantics in conformance checks

* Align Java graph benchmarks with compiler-verified visibility

* Record the public Java record accessor in the mixed-provider benchmark

* Address remaining Java conformance analysis findings

Keep repository import scans sequential, simplify Java header and overload resolution, and reuse Spring conformance measurements. Preserve compiler comparison assertions and emitted fixture contents.

* Match javac on nested binary names, null factories and recovered calls

Preserve the qualified annotation target in workspace links. Compare valid and invalid arguments separately so an attributed recovery symbol cannot mask a failed invocation.

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-25 18:03:32 +00:00

301 lines
11 KiB
TypeScript

/**
* Group ↔ ingestion parity for Java constant-valued Spring route paths (#2980).
*
* Drives `JAVA_HTTP_PLUGIN.prepareRepo` + `scan(tree, ctx, rel)` with all three
* arguments and compares the result against what `extractSpringRoutes` + the
* Java operand fold produce on the ingestion side. The existing Spring parity
* guards call `scan(tree)` with ONE argument, which makes them structurally
* blind here: without a repo context the plugin drops every constant-valued
* route, so no fixture they carry can exercise this feature.
*
* Asserted:
* • a constant-valued mapping resolves to the SAME path on both sides;
* • a CONSTANT class prefix suppresses the method route on both sides — the
* prefix cannot be folded at extraction time, and emitting the route
* unprefixed would publish a path the application does not serve;
* • without a repo context the group side emits nothing (the documented skip
* floor, and the branch that makes the 1-arg guards blind);
* • literal routes are untouched.
*/
import { compareCodeUnits } from '../../../compare.mjs';
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import Parser from 'tree-sitter';
import Java from 'tree-sitter-java';
import { JAVA_HTTP_PLUGIN } from '../../../../../src/core/group/extractors/http-patterns/java.js';
import type { HttpDetection } from '../../../../../src/core/group/extractors/http-patterns/types.js';
import { extractSpringRoutes } from '../../../../../src/core/ingestion/route-extractors/spring.js';
import { javaProvider } from '../../../../../src/core/ingestion/languages/java.js';
import {
expandJavaWildcardStaticImports,
extractJavaModuleConstants,
foldJavaOperands,
} from '../../../../../src/core/ingestion/route-extractors/java-const-resolver.js';
const parser = new Parser();
const parseSource = (p: Parser, src: string): Parser.Tree => {
p.setLanguage(Java);
return p.parse(src);
};
const parse = (src: string): Parser.Tree => parseSource(parser, src);
/** Group side: prepareRepo + a 3-argument scan over every .java file. */
async function groupProviders(files: Record<string, string>): Promise<string[]> {
const ctx = await JAVA_HTTP_PLUGIN.prepareRepo?.({
repoPath: '/repo',
files: Object.keys(files),
parser: new Parser(),
readFile: (rel: string) => files[rel] ?? null,
parseSource,
});
const out: string[] = [];
for (const rel of Object.keys(files)) {
const detections: HttpDetection[] = JAVA_HTTP_PLUGIN.scan(parse(files[rel]), ctx, rel);
for (const d of detections) {
if (d.role === 'provider') out.push(`${d.method} ${d.path}`);
}
}
return out.sort(compareCodeUnits);
}
/** Ingestion side: extract routes, then fold operands against the same map. */
function ingestionRoutes(files: Record<string, string>): string[] {
const repo = new Map<string, ReturnType<typeof extractJavaModuleConstants>>();
for (const [rel, src] of Object.entries(files)) {
repo.set(rel, extractJavaModuleConstants(parse(src)));
}
for (const [rel, mc] of repo) {
expandJavaWildcardStaticImports(mc, rel, repo);
}
const out: string[] = [];
for (const [rel, src] of Object.entries(files)) {
for (const route of extractSpringRoutes(parse(src), rel, 0)) {
const path = route.routePathOperands
? foldJavaOperands(rel, route.routePathOperands, repo)
: route.routePath;
if (path === null) continue;
const routePath = `${route.prefix ?? ''}${path}`.replace(/\/{2,}/g, '/');
out.push(`${route.httpMethod} ${routePath}`);
}
}
return out.sort(compareCodeUnits);
}
const CONSTS = 'src/main/java/com/example/ApiPaths.java';
const CTL = 'src/main/java/com/example/OrderController.java';
const CONSTS_SRC = `package com.example;
public class ApiPaths {
public static final String BASE = "/api/v1";
public static final String ORDERS = "/api/v1/orders";
}`;
describe('Java constant-valued routes: group ↔ ingestion parity (#2980)', () => {
it('resolves a constant-valued mapping to the same path on both sides', async () => {
const files = {
[CONSTS]: CONSTS_SRC,
[CTL]: `package com.example;
import com.example.ApiPaths;
public class OrderController {
@GetMapping(ApiPaths.ORDERS)
public void list() {}
}`,
};
assert.deepEqual(await groupProviders(files), ['GET /api/v1/orders']);
assert.deepEqual(ingestionRoutes(files), await groupProviders(files));
});
it('suppresses the method route under a CONSTANT class prefix on both sides', async () => {
// The class prefix needs the repo-wide constant map, which does not exist
// at extraction time on either side. Emitting the method route would drop
// the prefix and publish `GET /api/v1/orders`-without-its-base — a path the
// application never serves. On base such a route was not emitted at all, so
// shipping it unprefixed would turn a missing fact into a wrong one.
const files = {
[CONSTS]: CONSTS_SRC,
[CTL]: `package com.example;
import com.example.ApiPaths;
@RequestMapping(ApiPaths.BASE)
public class OrderController {
@GetMapping(ApiPaths.ORDERS)
public void list() {}
@GetMapping("/literal")
public void literal() {}
}`,
};
assert.deepEqual(await groupProviders(files), []);
assert.deepEqual(ingestionRoutes(files), []);
});
it('still applies a LITERAL class prefix', async () => {
const files = {
[CONSTS]: CONSTS_SRC,
[CTL]: `package com.example;
import com.example.ApiPaths;
@RequestMapping("/api/v1")
public class OrderController {
@GetMapping("/orders")
public void list() {}
}`,
};
assert.deepEqual(await groupProviders(files), ['GET /api/v1/orders']);
assert.deepEqual(ingestionRoutes(files), ['GET /api/v1/orders']);
});
it('emits nothing for a constant route when scanned without a repo context', () => {
// This is the branch that makes the 1-argument parity guards blind to the
// whole feature; pin it so it is not silently dead in the suite.
const src = `package com.example;
import com.example.ApiPaths;
public class OrderController {
@GetMapping(ApiPaths.ORDERS)
public void list() {}
}`;
const detections = JAVA_HTTP_PLUGIN.scan(parse(src));
assert.deepEqual(
detections.filter((d) => d.role === 'provider'),
[],
);
});
it('suppresses a NO-ARGUMENT mapping under a constant class prefix on both sides', async () => {
// A bare `@GetMapping` IS the class prefix, so an unfoldable class prefix
// leaves nothing to emit. Ingestion routes these through a separate loop
// from the path-carrying ones, and that loop needs the same guard — without
// it ingestion emitted an empty-path Route where the group emitted nothing.
const files = {
[CONSTS]: CONSTS_SRC,
[CTL]: `package com.example;
import com.example.ApiPaths;
@RequestMapping(ApiPaths.BASE)
public class OrderController {
@GetMapping public void list() {}
@PostMapping public void create() {}
}`,
};
assert.deepEqual(ingestionRoutes(files), []);
assert.deepEqual(await groupProviders(files), []);
});
it('measures import ambiguity over the same candidate set on both sides', async () => {
// Ingestion's harvest gate also admits import-only files, so its repo map is
// a superset of the group's. When ambiguity was measured over every key, a
// duplicate FQN belonging to a class that defines NOTHING was invisible to
// the group and made ingestion alone floor to skip — reopening the very
// parity break this feature exists to close. Both sides now measure over
// constant-DEFINING files only.
const files = {
'svc-a/src/main/java/com/x/ApiPaths.java': `package com.x;
public class ApiPaths { public static final String ORDERS = "/api/v1/orders"; }`,
// Same FQN, different module, defines no constant — must not create ambiguity.
'svc-b/src/main/java/com/x/ApiPaths.java': `package com.x;
import java.util.List;
public class ApiPaths {}`,
'svc-a/src/main/java/com/x/web/OrderController.java': `package com.x.web;
import com.x.ApiPaths;
public class OrderController {
@GetMapping(ApiPaths.ORDERS)
public void list() {}
}`,
};
// Guard the premise: the two maps really are different sizes.
const ingestionKeys = Object.entries(files).filter(([, src]) =>
javaProvider.moduleConstantHeuristic?.(src),
).length;
assert.equal(ingestionKeys, 3);
assert.deepEqual(await groupProviders(files), ['GET /api/v1/orders']);
assert.deepEqual(ingestionRoutes(files), ['GET /api/v1/orders']);
});
it('resolves a wildcard-static-imported mapping on both sides', async () => {
const files = {
[CONSTS]: CONSTS_SRC,
[CTL]: `package com.example;
import static com.example.ApiPaths.*;
public class OrderController {
@GetMapping(ORDERS)
public void list() {}
}`,
};
assert.equal(javaProvider.moduleConstantHeuristic?.(files[CTL]), true);
assert.deepEqual(await groupProviders(files), ['GET /api/v1/orders']);
assert.deepEqual(ingestionRoutes(files), await groupProviders(files));
});
it('keeps an unfoldable local field above a wildcard member on both sides', async () => {
const files = {
[CONSTS]: CONSTS_SRC,
[CTL]: `package com.example;
import static com.example.ApiPaths.*;
public class OrderController {
static final String ORDERS = runtimePath();
@GetMapping(ORDERS)
public void list() {}
}`,
};
assert.deepEqual(await groupProviders(files), []);
assert.deepEqual(ingestionRoutes(files), []);
});
it('imports only members owned by the wildcard target type on both sides', async () => {
const files = {
[CONSTS]: `package com.example;
public class ApiPaths { public static final String ORDERS = "/right"; }
class Other { public static final String ORDERS = "/wrong"; }`,
[CTL]: `package com.example;
import static com.example.ApiPaths.*;
public class OrderController {
@GetMapping(ORDERS)
public void list() {}
}`,
};
assert.deepEqual(await groupProviders(files), ['GET /right']);
assert.deepEqual(ingestionRoutes(files), ['GET /right']);
});
it('floors duplicate wildcard members on both sides', async () => {
const files = {
'src/main/java/a/A.java': `package a;
public class A { public static final String ROUTE = "/a"; }`,
'src/main/java/b/B.java': `package b;
public class B { public static final String ROUTE = "/b"; }`,
[CTL]: `package com.example;
import static a.A.*;
import static b.B.*;
public class OrderController {
@GetMapping(ROUTE)
public void list() {}
}`,
};
assert.deepEqual(await groupProviders(files), []);
assert.deepEqual(ingestionRoutes(files), []);
});
it('does not fold a type-qualified ref from a static wildcard alone', async () => {
const files = {
[CONSTS]: CONSTS_SRC,
[CTL]: `package com.example;
import static com.example.ApiPaths.*;
public class OrderController {
@GetMapping(ApiPaths.ORDERS)
public void list() {}
}`,
};
assert.deepEqual(await groupProviders(files), []);
assert.deepEqual(ingestionRoutes(files), []);
});
it('leaves literal routes unchanged with no constant map at all', async () => {
const files = {
[CTL]: `package com.example;
public class OrderController {
@PostMapping("/api/v1/orders")
public void create() {}
}`,
};
assert.deepEqual(await groupProviders(files), ['POST /api/v1/orders']);
assert.deepEqual(ingestionRoutes(files), ['POST /api/v1/orders']);
});
});