Expand static-block map bindings via locals and Map.of assignment.

Follow HashMap locals assigned to static route fields and direct Map.of or double-brace assignments inside static initializers while ignoring unlinked local puts and failing closed on computed keys.

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

View File

@@ -720,6 +720,54 @@ public final class EntryPointBindingExpander {
if (block == null) { if (block == null) {
continue; continue;
} }
LinkedHashSet<String> mapBuilderLocals = new LinkedHashSet<>();
LinkedHashSet<String> linkedLocals = new LinkedHashSet<>();
block.accept(new ASTVisitor() {
@Override
public boolean visit(VariableDeclarationStatement node) {
for (Object fragmentObj : node.fragments()) {
if (!(fragmentObj instanceof VariableDeclarationFragment fragment)) {
continue;
}
if (isPlainHashMapCreation(fragment.getInitializer())) {
mapBuilderLocals.add(fragment.getName().getIdentifier());
}
}
return super.visit(node);
}
@Override
public boolean visit(Assignment node) {
if (invalid[0] || node.getOperator() != Assignment.Operator.ASSIGN) {
return super.visit(node);
}
String assignedField = assignmentTargetName(node.getLeftHandSide());
if (!fieldName.equals(assignedField)) {
return super.visit(node);
}
Expression right = node.getRightHandSide();
Map<String, String> direct = extractMapOfLiteralEntries(right, typeDecl, context);
if (direct != null) {
entries.putAll(direct);
foundPut[0] = true;
return super.visit(node);
}
Map<String, String> doubleBrace = extractDoubleBraceMapPutEntries(right, typeDecl, context);
if (doubleBrace != null) {
entries.putAll(doubleBrace);
foundPut[0] = true;
return super.visit(node);
}
if (right instanceof SimpleName localName
&& mapBuilderLocals.contains(localName.getIdentifier())) {
linkedLocals.add(localName.getIdentifier());
}
return super.visit(node);
}
});
LinkedHashSet<String> putReceivers = new LinkedHashSet<>();
putReceivers.add(fieldName);
putReceivers.addAll(linkedLocals);
block.accept(new ASTVisitor() { block.accept(new ASTVisitor() {
@Override @Override
public boolean visit(MethodInvocation node) { public boolean visit(MethodInvocation node) {
@@ -727,7 +775,7 @@ public final class EntryPointBindingExpander {
|| node.arguments().size() != 2) { || node.arguments().size() != 2) {
return super.visit(node); return super.visit(node);
} }
if (!mapReceiverReferencesField(node.getExpression(), fieldName)) { if (!mapReceiverReferencesAnyField(node.getExpression(), putReceivers)) {
return super.visit(node); return super.visit(node);
} }
String key = resolveCompileTimeStringKey( String key = resolveCompileTimeStringKey(
@@ -748,6 +796,48 @@ public final class EntryPointBindingExpander {
return entries; return entries;
} }
private static String assignmentTargetName(Expression expression) {
if (expression instanceof SimpleName simpleName) {
return simpleName.getIdentifier();
}
if (expression instanceof FieldAccess fieldAccess) {
return fieldAccess.getName().getIdentifier();
}
return null;
}
private static boolean isPlainHashMapCreation(Expression expression) {
if (!(expression instanceof ClassInstanceCreation creation)) {
return false;
}
if (creation.getAnonymousClassDeclaration() != null) {
return false;
}
org.eclipse.jdt.core.dom.ITypeBinding typeBinding = creation.resolveTypeBinding();
if (typeBinding != null) {
String qualifiedName = typeBinding.getErasure().getQualifiedName();
return qualifiedName.endsWith("HashMap") || qualifiedName.endsWith("LinkedHashMap");
}
String typeName = creation.getType().toString();
return typeName.contains("HashMap") || typeName.contains("LinkedHashMap");
}
private static boolean mapReceiverReferencesAnyField(Expression receiver, Set<String> fieldNames) {
if (receiver == null) {
return false;
}
if (receiver instanceof SimpleName simpleName) {
return fieldNames.contains(simpleName.getIdentifier());
}
if (receiver instanceof FieldAccess fieldAccess) {
return fieldNames.contains(fieldAccess.getName().getIdentifier());
}
if (receiver instanceof QualifiedName qualifiedName) {
return fieldNames.contains(qualifiedName.getName().getIdentifier());
}
return false;
}
private static Map<String, String> extractDoubleBraceMapPutEntries( private static Map<String, String> extractDoubleBraceMapPutEntries(
Expression initializer, Expression initializer,
TypeDeclaration declaringType, TypeDeclaration declaringType,
@@ -809,19 +899,6 @@ public final class EntryPointBindingExpander {
return false; return false;
} }
private static boolean mapReceiverReferencesField(Expression receiver, String fieldName) {
if (receiver instanceof SimpleName simpleName) {
return fieldName.equals(simpleName.getIdentifier());
}
if (receiver instanceof FieldAccess fieldAccess) {
return fieldName.equals(fieldAccess.getName().getIdentifier());
}
if (receiver instanceof QualifiedName qualifiedName) {
return fieldName.equals(qualifiedName.getName().getIdentifier());
}
return false;
}
private static Map<String, String> extractMapOfLiteralEntries( private static Map<String, String> extractMapOfLiteralEntries(
Expression expression, Expression expression,
TypeDeclaration declaringType, TypeDeclaration declaringType,

View File

@@ -3208,4 +3208,225 @@ class EntryPointBindingExpanderTest {
assertThat(variants).isEmpty(); assertThat(variants).isEmpty();
} }
@Test
void shouldExpandCommandKeyFromStaticBlockLocalVariableMapPutEntries(@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 {
Map<String, OrderEvent> routes = new HashMap<>();
routes.put("order.pay", OrderEvent.PAY);
routes.put("order.ship", OrderEvent.SHIP);
ROUTES = 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).extracting(map -> map.get("commandKey"))
.containsExactlyInAnyOrder("order.pay", "order.ship");
}
@Test
void shouldExpandCommandKeyFromStaticBlockMapOfAssignment(@TempDir Path tempDir) throws Exception {
String source = """
package com.example;
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 = 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 shouldNotExpandCommandKeyFromStaticBlockLocalVariableWithUnlinkedPuts(@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 {
Map<String, OrderEvent> routes = new HashMap<>();
routes.put("order.pay", OrderEvent.PAY);
routes.put("order.ship", OrderEvent.SHIP);
ROUTES = Map.of("order.other", OrderEvent.PAY);
}
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"))
.containsExactly("order.other");
}
@Test
void shouldNotExpandCommandKeyFromStaticBlockLocalVariableWithComputedPutKeys(@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 {
Map<String, OrderEvent> routes = new HashMap<>();
routes.put(prefix("order.pay"), OrderEvent.PAY);
routes.put("order.ship", OrderEvent.SHIP);
ROUTES = routes;
}
static String prefix(String value) {
return value;
}
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();
}
} }