Expand static-block route maps from putAll compile-time sources.

Resolve putAll arguments from Map.of literals and cross-class static map fields inside static initializers while failing closed on runtime-built maps.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-14 18:47:31 +02:00
parent 280c346761
commit dd25db0109
2 changed files with 274 additions and 17 deletions

View File

@@ -610,11 +610,31 @@ public final class EntryPointBindingExpander {
Expression receiver, Expression receiver,
MethodDeclaration ownerMethod, MethodDeclaration ownerMethod,
CodebaseContext context) { CodebaseContext context) {
CompilationUnit compilationUnit = null;
TypeDeclaration defaultDeclaringType = null;
if (ownerMethod != null) {
if (ownerMethod.getRoot() instanceof CompilationUnit cu) {
compilationUnit = cu;
}
defaultDeclaringType = AstUtils.findEnclosingType(ownerMethod);
}
return resolveCompileTimeMapEntries(
receiver, defaultDeclaringType, compilationUnit, context);
}
private static Map<String, String> resolveCompileTimeMapEntries(
Expression receiver,
TypeDeclaration defaultDeclaringType,
CompilationUnit compilationUnit,
CodebaseContext context) {
if (receiver == null) { if (receiver == null) {
return null; return null;
} }
TypeDeclaration literalDeclaringType = defaultDeclaringType != null
? defaultDeclaringType
: AstUtils.findEnclosingType(receiver);
Map<String, String> direct = extractMapOfLiteralEntries( Map<String, String> direct = extractMapOfLiteralEntries(
receiver, AstUtils.findEnclosingType(receiver), context); receiver, literalDeclaringType, context);
if (direct != null) { if (direct != null) {
return direct; return direct;
} }
@@ -632,7 +652,6 @@ public final class EntryPointBindingExpander {
if (declaringType == null) { if (declaringType == null) {
Expression qualifier = fieldAccess.getExpression(); Expression qualifier = fieldAccess.getExpression();
if (qualifier instanceof SimpleName typeName) { if (qualifier instanceof SimpleName typeName) {
CompilationUnit compilationUnit = (CompilationUnit) ownerMethod.getRoot();
declaringType = context.getTypeDeclaration(typeName.getIdentifier(), compilationUnit); declaringType = context.getTypeDeclaration(typeName.getIdentifier(), compilationUnit);
if (declaringType == null) { if (declaringType == null) {
declaringType = context.getTypeDeclaration(typeName.getIdentifier()); declaringType = context.getTypeDeclaration(typeName.getIdentifier());
@@ -651,11 +670,8 @@ public final class EntryPointBindingExpander {
declaringType = context.getTypeDeclaration(declaringClass.getQualifiedName()); declaringType = context.getTypeDeclaration(declaringClass.getQualifiedName());
} }
} }
if (declaringType == null && ownerMethod != null) { if (declaringType == null && compilationUnit != null) {
ASTNode root = ownerMethod.getRoot(); declaringType = context.resolveStaticImport(fieldName, compilationUnit);
if (root instanceof CompilationUnit compilationUnit) {
declaringType = context.resolveStaticImport(fieldName, compilationUnit);
}
} }
if (declaringType == null) { if (declaringType == null) {
declaringType = AstUtils.findEnclosingType(receiver); declaringType = AstUtils.findEnclosingType(receiver);
@@ -664,7 +680,6 @@ public final class EntryPointBindingExpander {
fieldName = qualifiedName.getName().getIdentifier(); fieldName = qualifiedName.getName().getIdentifier();
Name qualifier = qualifiedName.getQualifier(); Name qualifier = qualifiedName.getQualifier();
if (qualifier instanceof SimpleName typeName) { if (qualifier instanceof SimpleName typeName) {
CompilationUnit compilationUnit = (CompilationUnit) ownerMethod.getRoot();
declaringType = context.getTypeDeclaration(typeName.getIdentifier(), compilationUnit); declaringType = context.getTypeDeclaration(typeName.getIdentifier(), compilationUnit);
if (declaringType == null) { if (declaringType == null) {
declaringType = context.getTypeDeclaration(typeName.getIdentifier()); declaringType = context.getTypeDeclaration(typeName.getIdentifier());
@@ -771,21 +786,35 @@ public final class EntryPointBindingExpander {
block.accept(new ASTVisitor() { block.accept(new ASTVisitor() {
@Override @Override
public boolean visit(MethodInvocation node) { public boolean visit(MethodInvocation node) {
if (invalid[0] || !"put".equals(node.getName().getIdentifier()) if (invalid[0] || !mapReceiverReferencesAnyField(node.getExpression(), putReceivers)) {
|| node.arguments().size() != 2) {
return super.visit(node); return super.visit(node);
} }
if (!mapReceiverReferencesAnyField(node.getExpression(), putReceivers)) { String methodName = node.getName().getIdentifier();
if ("put".equals(methodName) && node.arguments().size() == 2) {
String key = resolveCompileTimeStringKey(
(Expression) node.arguments().get(0), typeDecl, context);
if (key == null) {
invalid[0] = true;
return super.visit(node);
}
entries.put(key, "*");
foundPut[0] = true;
return super.visit(node); return super.visit(node);
} }
String key = resolveCompileTimeStringKey( if ("putAll".equals(methodName) && node.arguments().size() == 1) {
(Expression) node.arguments().get(0), typeDecl, context); CompilationUnit compilationUnit = block.getRoot() instanceof CompilationUnit cu
if (key == null) { ? cu
invalid[0] = true; : null;
Map<String, String> merged = resolveCompileTimeMapEntries(
(Expression) node.arguments().get(0), typeDecl, compilationUnit, context);
if (merged == null || merged.isEmpty()) {
invalid[0] = true;
return super.visit(node);
}
entries.putAll(merged);
foundPut[0] = true;
return super.visit(node); return super.visit(node);
} }
entries.put(key, "*");
foundPut[0] = true;
return super.visit(node); return super.visit(node);
} }
}); });

View File

@@ -3429,4 +3429,232 @@ class EntryPointBindingExpanderTest {
assertThat(variants).isEmpty(); assertThat(variants).isEmpty();
} }
@Test
void shouldExpandCommandKeyFromStaticBlockPutAllWithMapOf(@TempDir Path tempDir) throws Exception {
String source = """
package com.example;
import java.util.HashMap;
import java.util.Map;
public class GenericCommandController {
OrderGateway gateway;
public void execute(String commandKey) {
gateway.trigger(commandKey);
}
}
class OrderGateway {
private static final Map<String, OrderEvent> ROUTES;
static {
ROUTES = new HashMap<>();
ROUTES.putAll(Map.of(
"order.pay", OrderEvent.PAY,
"order.ship", OrderEvent.SHIP
));
}
void trigger(String commandKey) {
StateMachine sm = new StateMachine();
sm.sendEvent(ROUTES.get(commandKey));
}
}
class StateMachine { void sendEvent(OrderEvent event) {} }
enum OrderEvent { PAY, SHIP }
""";
Files.writeString(tempDir.resolve("App.java"), source);
CodebaseContext context = new CodebaseContext();
context.setResolveBindings(true);
context.scan(tempDir);
HeuristicCallGraphEngine engine = new HeuristicCallGraphEngine(context);
Map<String, List<click.kamil.springstatemachineexporter.analysis.model.CallEdge>> graph = engine.buildCallGraph();
EntryPoint entryPoint = EntryPoint.builder()
.className("com.example.GenericCommandController")
.methodName("execute")
.name("POST /api/commands/{commandKey}")
.parameters(List.of(EntryPoint.Parameter.builder()
.name("commandKey")
.type("String")
.annotations(List.of("PathVariable"))
.build()))
.build();
List<Map<String, String>> variants =
EntryPointBindingExpander.expandPathVariableBindings(entryPoint, context, graph);
assertThat(variants).extracting(map -> map.get("commandKey"))
.containsExactlyInAnyOrder("order.pay", "order.ship");
}
@Test
void shouldExpandCommandKeyFromStaticBlockPutAllFromCrossClassMap(@TempDir Path tempDir) throws Exception {
String source = """
package com.example;
import java.util.HashMap;
import java.util.Map;
public class GenericCommandController {
OrderGateway gateway;
public void execute(String commandKey) {
gateway.trigger(commandKey);
}
}
class OrderGateway {
private static final Map<String, OrderEvent> ROUTES;
static {
ROUTES = new HashMap<>();
ROUTES.putAll(CommandRoutes.SEED);
}
void trigger(String commandKey) {
StateMachine sm = new StateMachine();
sm.sendEvent(ROUTES.get(commandKey));
}
}
class CommandRoutes {
static final Map<String, OrderEvent> SEED = Map.of(
"order.pay", OrderEvent.PAY,
"order.ship", OrderEvent.SHIP
);
}
class StateMachine { void sendEvent(OrderEvent event) {} }
enum OrderEvent { PAY, SHIP }
""";
Files.writeString(tempDir.resolve("App.java"), source);
CodebaseContext context = new CodebaseContext();
context.setResolveBindings(true);
context.scan(tempDir);
HeuristicCallGraphEngine engine = new HeuristicCallGraphEngine(context);
Map<String, List<click.kamil.springstatemachineexporter.analysis.model.CallEdge>> graph = engine.buildCallGraph();
EntryPoint entryPoint = EntryPoint.builder()
.className("com.example.GenericCommandController")
.methodName("execute")
.name("POST /api/commands/{commandKey}")
.parameters(List.of(EntryPoint.Parameter.builder()
.name("commandKey")
.type("String")
.annotations(List.of("PathVariable"))
.build()))
.build();
List<Map<String, String>> variants =
EntryPointBindingExpander.expandPathVariableBindings(entryPoint, context, graph);
assertThat(variants).extracting(map -> map.get("commandKey"))
.containsExactlyInAnyOrder("order.pay", "order.ship");
}
@Test
void shouldExpandCommandKeyFromStaticInitializerMapPutEntriesWithStaticFinalKeys(@TempDir Path tempDir) throws Exception {
String source = """
package com.example;
import java.util.HashMap;
import java.util.Map;
public class GenericCommandController {
OrderGateway gateway;
public void execute(String commandKey) {
gateway.trigger(commandKey);
}
}
class OrderGateway {
private static final String PAY_KEY = "order.pay";
private static final String SHIP_KEY = "order.ship";
private static final Map<String, OrderEvent> ROUTES;
static {
ROUTES = new HashMap<>();
ROUTES.put(PAY_KEY, OrderEvent.PAY);
ROUTES.put(SHIP_KEY, OrderEvent.SHIP);
}
void trigger(String commandKey) {
StateMachine sm = new StateMachine();
sm.sendEvent(ROUTES.get(commandKey));
}
}
class StateMachine { void sendEvent(OrderEvent event) {} }
enum OrderEvent { PAY, SHIP }
""";
Files.writeString(tempDir.resolve("App.java"), source);
CodebaseContext context = new CodebaseContext();
context.setResolveBindings(true);
context.scan(tempDir);
HeuristicCallGraphEngine engine = new HeuristicCallGraphEngine(context);
Map<String, List<click.kamil.springstatemachineexporter.analysis.model.CallEdge>> graph = engine.buildCallGraph();
EntryPoint entryPoint = EntryPoint.builder()
.className("com.example.GenericCommandController")
.methodName("execute")
.name("POST /api/commands/{commandKey}")
.parameters(List.of(EntryPoint.Parameter.builder()
.name("commandKey")
.type("String")
.annotations(List.of("PathVariable"))
.build()))
.build();
List<Map<String, String>> variants =
EntryPointBindingExpander.expandPathVariableBindings(entryPoint, context, graph);
assertThat(variants).extracting(map -> map.get("commandKey"))
.containsExactlyInAnyOrder("order.pay", "order.ship");
}
@Test
void shouldNotExpandCommandKeyFromStaticBlockPutAllWithRuntimeMap(@TempDir Path tempDir) throws Exception {
String source = """
package com.example;
import java.util.HashMap;
import java.util.Map;
public class GenericCommandController {
OrderGateway gateway;
public void execute(String commandKey) {
gateway.trigger(commandKey);
}
}
class OrderGateway {
private static final Map<String, OrderEvent> ROUTES;
static {
ROUTES = new HashMap<>();
ROUTES.putAll(buildRoutes());
}
static Map<String, OrderEvent> buildRoutes() {
Map<String, OrderEvent> routes = new HashMap<>();
routes.put("order.pay", OrderEvent.PAY);
return routes;
}
void trigger(String commandKey) {
StateMachine sm = new StateMachine();
sm.sendEvent(ROUTES.get(commandKey));
}
}
class StateMachine { void sendEvent(OrderEvent event) {} }
enum OrderEvent { PAY, SHIP }
""";
Files.writeString(tempDir.resolve("App.java"), source);
CodebaseContext context = new CodebaseContext();
context.setResolveBindings(true);
context.scan(tempDir);
HeuristicCallGraphEngine engine = new HeuristicCallGraphEngine(context);
Map<String, List<click.kamil.springstatemachineexporter.analysis.model.CallEdge>> graph = engine.buildCallGraph();
EntryPoint entryPoint = EntryPoint.builder()
.className("com.example.GenericCommandController")
.methodName("execute")
.name("POST /api/commands/{commandKey}")
.parameters(List.of(EntryPoint.Parameter.builder()
.name("commandKey")
.type("String")
.annotations(List.of("PathVariable"))
.build()))
.build();
List<Map<String, String>> variants =
EntryPointBindingExpander.expandPathVariableBindings(entryPoint, context, graph);
assertThat(variants).isEmpty();
}
} }