Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.javahelpers.codegen.model.javadoc.JavadocDto;
import org.javahelpers.codegen.model.type.GenericParameterDto;
import org.javahelpers.codegen.model.type.TypeName;
import org.javahelpers.codegen.util.JavaSignatures;

/**
* Rendering-side DTO containing all information to generate a method in a generated class.
Expand Down Expand Up @@ -244,22 +245,15 @@ public void setReturnType(TypeName returnType) {
}

/**
* Returns a unique signature key for the method based on name and parameter types. Used for
* conflict resolution. The signature matches Java's method signature rules (name + parameter
* types, ignoring generics due to type erasure).
* Returns a signature key for the method based on name and erased parameter types. Used for
* conflict resolution. Type variables declared by this method are erased; type variables declared
* by the owning type require owner context and are resolved by validation/conflict-resolution
* callers through {@link JavaSignatures}.
*
* @return the signature key (e.g., "fieldName(java.lang.String,java.util.List)")
*/
public String getSignatureKey() {
StringBuilder sb = new StringBuilder();
sb.append(methodName).append('(');
for (int i = 0; i < parameters.size(); i++) {
if (i > 0) sb.append(',');
TypeName tn = parameters.get(i).getParameterType();
sb.append(tn.getRawQualifiedName());
}
sb.append(')');
return sb.toString();
return JavaSignatures.methodSignature(this);
}

public JavadocDto getJavadoc() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/*
* MIT License
*
* Copyright (c) 2025-2026 Andreas Igel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package org.javahelpers.codegen.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.javahelpers.codegen.model.core.GenerationTargetClassDto;
import org.javahelpers.codegen.model.method.MethodDto;
import org.javahelpers.codegen.model.method.MethodParameterDto;
import org.javahelpers.codegen.model.type.GenericParameterDto;
import org.javahelpers.codegen.model.type.TypeName;
import org.javahelpers.codegen.model.type.TypeNameArray;
import org.javahelpers.codegen.model.type.TypeNameVariable;

/**
* Calculates Java source-level constructor and method signatures from generation DTOs.
*
* <p>Signatures follow Java's type erasure rules (JLS §4.6): during compilation the compiler
* replaces every type variable with its first upper bound — {@code T extends Number} becomes {@code
* Number}, an unbounded {@code T} becomes {@code Object}. As a consequence two methods like {@code
* m(T)} and {@code m(Number)} in a {@code <T extends Number>} class are the same method to the
* compiler. Because the generated source is compiled with exactly these rules, signatures here are
* calculated with the same substitution, so collisions are detected the way javac would see them.
*/
public final class JavaSignatures {
Comment thread
AndreasIgel marked this conversation as resolved.
Resolved

private JavaSignatures() {}

/**
* Returns the signature of a method using type erasure for its declared type variables.
*
* @param method method model
* @return method signature
*/
public static String methodSignature(MethodDto method) {
return methodSignature(method, Map.of());
}

/**
* Returns the signature of a method using type erasure for owner and method type variables.
*
* @param method method model
* @param ownerTypeVariableUpperBounds upper bounds of type variables declared by the owner
* @return method signature
*/
public static String methodSignature(
MethodDto method, Map<String, TypeName> ownerTypeVariableUpperBounds) {
return methodSignature(
method.getMethodName(),
method.getParameters(),
method.getGenericParameters(),
ownerTypeVariableUpperBounds);
}

/**
* Returns the signature of a method using type erasure for owner and method type variables.
*
* @param methodName method name
* @param parameters method parameters
* @param genericParameters type variables declared by the method
* @param ownerTypeVariableUpperBounds upper bounds of type variables declared by the owner
* @return method signature
*/
public static String methodSignature(
String methodName,
List<MethodParameterDto> parameters,
List<GenericParameterDto> genericParameters,
Map<String, TypeName> ownerTypeVariableUpperBounds) {
Map<String, TypeName> signatureTypeVariableUpperBounds =
new HashMap<>(ownerTypeVariableUpperBounds);
addTypeVariableUpperBounds(genericParameters, signatureTypeVariableUpperBounds);
return methodName + parametersSignature(parameters, signatureTypeVariableUpperBounds);
}

/**
* Returns the signature of constructor parameters using type erasure for owner type variables.
*
* @param parameters constructor parameters
* @param ownerTypeVariableUpperBounds upper bounds of type variables declared by the owner
* @return constructor parameter signature
*/
public static String constructorSignature(
List<MethodParameterDto> parameters, Map<String, TypeName> ownerTypeVariableUpperBounds) {
return parametersSignature(parameters, ownerTypeVariableUpperBounds);
}

/**
* Creates a lookup of type-variable names to their first upper bound for a generation target.
*
* @param target generation target class
* @return upper bounds by type-variable name
*/
public static Map<String, TypeName> typeVariableUpperBounds(GenerationTargetClassDto target) {
return typeVariableUpperBounds(target.getGenerics());
}

/**
* Creates a lookup of type-variable names to their first upper bound.
*
* @param generics type variables
* @return upper bounds by type-variable name
*/
public static Map<String, TypeName> typeVariableUpperBounds(List<GenericParameterDto> generics) {
Map<String, TypeName> result = new HashMap<>();
addTypeVariableUpperBounds(generics, result);
return result;
}

/**
* Adds type-variable names and their first upper bounds to a lookup.
*
* @param generics type variables
* @param typeVariableUpperBounds target lookup
*/
public static void addTypeVariableUpperBounds(
List<GenericParameterDto> generics, Map<String, TypeName> typeVariableUpperBounds) {
for (GenericParameterDto generic : generics) {
typeVariableUpperBounds.put(
generic.getName(),
generic.getUpperBounds().stream().findFirst().orElse(TypeName.of(Object.class)));
}
}

private static String parametersSignature(
List<MethodParameterDto> parameters, Map<String, TypeName> typeVariableUpperBounds) {
StringBuilder signature = new StringBuilder("(");
for (int i = 0; i < parameters.size(); i++) {
if (i > 0) {
signature.append(',');
}
signature.append(typeErasure(parameters.get(i).getParameterType(), typeVariableUpperBounds));
}
return signature.append(')').toString();
}

/**
* Resolves a type to its erasure (JLS §4.6): type variables are replaced by their first upper
* bound, applied recursively through array types; all other types are already their own erasure.
*/
private static String typeErasure(TypeName type, Map<String, TypeName> typeVariableUpperBounds) {
if (type instanceof TypeNameVariable) {
TypeName bound = typeVariableUpperBounds.get(type.getClassName());
return bound == null
? type.getRawQualifiedName()
: typeErasure(bound, typeVariableUpperBounds);
}
if (type instanceof TypeNameArray arrayType) {
return typeErasure(arrayType.getTypeOfArray(), typeVariableUpperBounds) + "[]";
}
return type.getRawQualifiedName();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
import org.javahelpers.codegen.model.type.TypeName;
import org.javahelpers.codegen.model.type.TypeNameArray;
import org.javahelpers.codegen.util.ImportCollector;
import org.javahelpers.codegen.util.JavaSignatures;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.AnnotationSource;
import org.jboss.forge.roaster.model.source.FieldSource;
Expand Down Expand Up @@ -300,7 +301,8 @@ private void appendMethods(
logger.debugStartOperation("Generating %d method candidates", classDef.getMethods().size());

// Resolve method conflicts by signature and priority
List<MethodDto> resolvedMethods = resolveMethodConflicts(classDef.getMethods());
Map<String, TypeName> classGenerics = JavaSignatures.typeVariableUpperBounds(classDef);
List<MethodDto> resolvedMethods = resolveMethodConflicts(classDef.getMethods(), classGenerics);
logger.debug("Resolved to %d methods after conflict resolution", resolvedMethods.size());

for (MethodDto methodDto : resolvedMethods) {
Expand All @@ -324,16 +326,18 @@ private void appendMethods(
* simply keeps the first occurrence for any remaining duplicate signatures and reports it as a
* warning (an error in strict mode).
*/
private List<MethodDto> resolveMethodConflicts(List<MethodDto> methods) {
private List<MethodDto> resolveMethodConflicts(
List<MethodDto> methods, Map<String, TypeName> typeVariableUpperBounds) {
Set<String> seenSignatures = new HashSet<>();
List<MethodDto> deduplicated = new ArrayList<>(methods.size());
for (MethodDto method : methods) {
if (seenSignatures.add(method.getSignatureKey())) {
String signature = JavaSignatures.methodSignature(method, typeVariableUpperBounds);
if (seenSignatures.add(signature)) {
deduplicated.add(method);
} else {
issueReporter.report(
"Unexpected duplicate method signature: '%s' — keeping first occurrence (safety net)",
method.getSignatureKey());
signature);
}
}
return deduplicated;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.javahelpers.codegen.model.method.MethodParameterDto;
import org.javahelpers.codegen.model.type.GenericParameterDto;
import org.javahelpers.codegen.model.type.TypeName;
import org.javahelpers.simple.builders.processor.util.BuilderSignatures;

/**
* BuilderMethodDto containing all information for generating a method in the builder class,
Expand Down Expand Up @@ -370,22 +371,15 @@ public void setReturnType(TypeName returnType) {
}

/**
* Returns a unique signature key for the method based on name and parameter types. Used for
* conflict resolution. The signature matches Java's method signature rules (name + parameter
* types, ignoring generics due to type erasure).
* Returns a signature key for the method based on name and erased parameter types. Used for
* conflict resolution. Type variables declared by this method are erased; type variables declared
* by the owning type require owner context and are resolved by validation/conflict-resolution
* callers through {@link JavaSignatures}.
*
* @return the signature key (e.g., "fieldName(java.lang.String,java.util.List)")
*/
public String getSignatureKey() {
StringBuilder sb = new StringBuilder();
sb.append(methodName).append('(');
for (int i = 0; i < parameters.size(); i++) {
if (i > 0) sb.append(',');
TypeName tn = parameters.get(i).getParameterType();
sb.append(tn.getRawQualifiedName());
}
sb.append(')');
return sb.toString();
return BuilderSignatures.methodSignature(this);
}

public JavadocDto getJavadoc() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
import org.javahelpers.codegen.model.method.MethodParameterDto;
import org.javahelpers.codegen.model.type.TypeName;
import org.javahelpers.codegen.model.type.TypeNameGeneric;
import org.javahelpers.codegen.util.JavaSignatures;
import org.javahelpers.simple.builders.core.annotations.IgnoreInBuilder;
import org.javahelpers.simple.builders.core.annotations.SimpleBuilderConstructor;
import org.javahelpers.simple.builders.core.util.TrackedValue;
Expand All @@ -71,6 +72,7 @@
import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDtoBuilder;
import org.javahelpers.simple.builders.processor.model.core.GetterInfoDtoBuilder;
import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto;
import org.javahelpers.simple.builders.processor.util.BuilderSignatures;

/** Class for creating a specific BuilderDefinitionDto for an annotated DTO class. */
public class BuilderDefinitionCreator {
Expand Down Expand Up @@ -384,24 +386,32 @@ private static void resolveMethodConflicts(
private static Map<String, List<BuilderMethodDto>> collectMethodsBySignature(
BuilderDefinitionDto builderDto) {
Map<String, List<BuilderMethodDto>> methodsBySignature = new HashMap<>();
Map<String, TypeName> typeVariableUpperBounds =
JavaSignatures.typeVariableUpperBounds(builderDto.getGenerics());

for (BuilderFieldDto field : builderDto.getConstructorFieldsForBuilder()) {
for (BuilderMethodDto method : field.getMethods()) {
methodsBySignature
.computeIfAbsent(method.getSignatureKey(), k -> new ArrayList<>())
.computeIfAbsent(
BuilderSignatures.methodSignature(method, typeVariableUpperBounds),
k -> new ArrayList<>())
.add(method);
}
}
for (BuilderFieldDto field : builderDto.getSetterFieldsForBuilder()) {
for (BuilderMethodDto method : field.getMethods()) {
methodsBySignature
.computeIfAbsent(method.getSignatureKey(), k -> new ArrayList<>())
.computeIfAbsent(
BuilderSignatures.methodSignature(method, typeVariableUpperBounds),
k -> new ArrayList<>())
.add(method);
}
}
for (BuilderMethodDto classMethod : builderDto.getMethods()) {
methodsBySignature
.computeIfAbsent(classMethod.getSignatureKey(), k -> new ArrayList<>())
.computeIfAbsent(
BuilderSignatures.methodSignature(classMethod, typeVariableUpperBounds),
k -> new ArrayList<>())
.add(classMethod);
}

Expand Down
Loading