diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index be1116e0..42b8e092 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -84,6 +84,12 @@ jobs: - name: Build with Maven run: mvn -B install -Pmetrics --file pom.xml + - name: Check committed codegen DTO builders + run: | + mvn -B -pl processor -Dtest=CodegenDtoBuilderRegenerationTest -Dcodegen.regenerate=true test + mvn -B -pl codegen-core fmt:format + git diff --exit-code -- 'codegen-core/src/main/java/**/*Builder.java' + - name: License header check (incl. performance-test) run: mvn -B license:check -Pperformance-test --file pom.xml diff --git a/codegen-core/pom.xml b/codegen-core/pom.xml index e910d9bc..09b08690 100644 --- a/codegen-core/pom.xml +++ b/codegen-core/pom.xml @@ -101,7 +101,14 @@ commons-collections4 ${commons-collections.version} - + + + io.github.java-helpers + simple-builders-core + ${project.version} + + org.junit.jupiter diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java index ef066623..048ea092 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java @@ -47,6 +47,18 @@ */ public class JavadocDto implements JavadocDtoBuilder.With { + /** + * Replaces tags with a defensive copy; the DTO retains its own mutable collection. + * + * @param tags the replacement collection (not null) + * @throws NullPointerException if tags is null + */ + public void setTags(List tags) { + List copy = new ArrayList<>(tags); + this.tags.clear(); + this.tags.addAll(copy); + } + /** The main description text (everything before the first tag). */ private String description; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java index 4c584e82..5db1319f 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java @@ -45,6 +45,30 @@ */ public class NestedTypeDto implements NestedTypeDtoBuilder.With { + /** + * Replaces methods with a defensive copy; the DTO retains its own mutable collection. + * + * @param methods the replacement collection (not null) + * @throws NullPointerException if methods is null + */ + public void setMethods(List methods) { + List copy = new ArrayList<>(methods); + this.methods.clear(); + this.methods.addAll(copy); + } + + /** + * Replaces annotations with a defensive copy; the DTO retains its own mutable collection. + * + * @param annotations the replacement collection (not null) + * @throws NullPointerException if annotations is null + */ + public void setAnnotations(List annotations) { + List copy = new ArrayList<>(annotations); + this.annotations.clear(); + this.annotations.addAll(copy); + } + /** The simple name of the nested type (e.g., "With"). */ private String typeName; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java b/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java index 3e26b8c3..84cd03ae 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java @@ -92,6 +92,10 @@ public ImportCollector addTypeImports(TypeName type) { type.getAnnotations().forEach(this::addAnnotationImports); // Adding the type + if (type instanceof TypeNameWildcard wildcard) { + wildcard.getBound().ifPresent(this::addTypeImports); + return this; + } addImport(type); return this; diff --git a/codegen-roaster/pom.xml b/codegen-roaster/pom.xml index 886f27af..6f40ac6a 100644 --- a/codegen-roaster/pom.xml +++ b/codegen-roaster/pom.xml @@ -145,6 +145,12 @@ org.apache.maven.plugins maven-surefire-plugin ${plugin.maven.surefire.version} + + + + io.github.java-helpers.codegen:codegen-testing + + diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java new file mode 100644 index 00000000..ffe81824 --- /dev/null +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java @@ -0,0 +1,53 @@ +/* + * 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.roaster; + +import org.javahelpers.codegen.CodegenBackend; +import org.javahelpers.codegen.GenerationEnvironment; +import org.javahelpers.codegen.logging.ProcessingLogger; +import org.javahelpers.codegen.testing.TestBackendProvider; + +/** + * Registers the Roaster backend for the shared generator conformance suite (loaded via {@link + * java.util.ServiceLoader}). + */ +public class RoasterTestBackendProvider implements TestBackendProvider { + + @Override + public String name() { + return "Roaster"; + } + + @Override + public CodegenBackend create(GenerationEnvironment environment, ProcessingLogger logger) { + return new RoasterBackend( + environment, logger, RoasterSourceFormatter.DEFAULT_FORMATTER_PROFILE_RESOURCE); + } + + @Override + public String toString() { + return name(); + } +} diff --git a/codegen-roaster/src/test/resources/META-INF/services/org.javahelpers.codegen.testing.TestBackendProvider b/codegen-roaster/src/test/resources/META-INF/services/org.javahelpers.codegen.testing.TestBackendProvider new file mode 100644 index 00000000..f265fa8e --- /dev/null +++ b/codegen-roaster/src/test/resources/META-INF/services/org.javahelpers.codegen.testing.TestBackendProvider @@ -0,0 +1 @@ +org.javahelpers.codegen.roaster.RoasterTestBackendProvider diff --git a/codegen-testing/pom.xml b/codegen-testing/pom.xml index 4b5bfca6..dd147c83 100644 --- a/codegen-testing/pom.xml +++ b/codegen-testing/pom.xml @@ -131,7 +131,7 @@ org.junit.jupiter junit-jupiter-engine ${junit-jupiter.version} - compile + test diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java new file mode 100644 index 00000000..1aaf047d --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java @@ -0,0 +1,603 @@ +/* + * 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.testing; + +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.tools.DiagnosticCollector; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; +import org.javahelpers.codegen.ClassCodeGenerator; +import org.javahelpers.codegen.CodegenBackend; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; +import org.javahelpers.codegen.model.annotation.InterfaceName; +import org.javahelpers.codegen.model.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.ClassFieldDtoBuilder; +import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; +import org.javahelpers.codegen.model.imports.StaticImport; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.method.ConstructorDtoBuilder; +import org.javahelpers.codegen.model.method.MethodCodeDtoBuilder; +import org.javahelpers.codegen.model.method.MethodCodeStringPlaceholder; +import org.javahelpers.codegen.model.method.MethodCodeTypePlaceholder; +import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; +import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; +import org.javahelpers.codegen.model.type.GenericParameterDtoBuilder; +import org.javahelpers.codegen.model.type.NestedTypeDto; +import org.javahelpers.codegen.model.type.NestedTypeDtoBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameArray; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNamePrimitive; +import org.javahelpers.codegen.model.type.TypeNameVariable; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Shared conformance suite for {@link ClassCodeGenerator} implementations. + * + *

Backends under test are discovered via {@link ServiceLoader}: each backend module registers a + * {@link TestBackendProvider} on its test classpath (see {@link TestBackendProvider} for the + * contract). Every test in this class then runs once per discovered backend, with the provider's + * {@link TestBackendProvider#name() name} in the test display name — so a failure always identifies + * the failing generator. New backends (issue #364) gain identical coverage without writing or + * copying any test. + * + *

Each fixture is asserted on two levels: + * + *

+ * + *

Backend modules must configure surefire's {@code dependenciesToScan} to include {@code + * codegen-testing} so this class is discovered from the dependency jar. + */ +public class GeneratorConformanceTest { + + private static final String PACKAGE = "it.conformance"; + private static final Path WORK_DIR = Path.of("target", "generator-conformance"); + + /** + * Provides all backends registered via {@link ServiceLoader}, named for the test display. + * + * @return one named argument per discovered {@link TestBackendProvider} + */ + static Stream backends() { + return ServiceLoader.load(TestBackendProvider.class).stream() + .map(ServiceLoader.Provider::get) + .map(provider -> Arguments.of(Named.of(provider.name(), provider))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void simpleClassWithFieldsMethodsAndConstructor_compiles(TestBackendProvider backend) + throws Exception { + GenerationTargetClassDto classDef = + baseClass("SimpleClass") + .classField(field("name", TypeName.of(String.class))) + .classField(field("age", TypeNamePrimitive.INT)) + .classField(field("active", TypeNamePrimitive.BOOLEAN)) + .constructor( + ConstructorDtoBuilder.create() + .visibility(AccessModifier.PUBLIC) + .methodCodeDto( + MethodCodeDtoBuilder.create().codeFormat("this.name = name;").build()) + .parameter(param("name", TypeName.of(String.class))) + .build()) + .method( + MethodDtoBuilder.create() + .methodName("describe") + .returnType(TypeName.of(String.class)) + .modifier(AccessModifier.PUBLIC) + .code("return name + \"#\" + age;") + .build()) + .build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + "public class SimpleClass {", + "private String name;", + "private int age;", + "private boolean active;", + """ + public SimpleClass(String name) { + this.name = name; + }""", + """ + public String describe() { + return name + "#" + age; + }"""); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void genericClassAndMethodBounds_compile(TestBackendProvider backend) throws Exception { + var generic = + GenericParameterDtoBuilder.create() + .name("T") + .upperBounds( + new TypeNameGeneric(TypeName.of(Comparable.class), new TypeNameVariable("T"))) + .build(); + + MethodDto method = + MethodDtoBuilder.create() + .methodName("pick") + .returnType(new TypeNameVariable("R")) + .modifier(AccessModifier.PUBLIC) + .isStatic(true) + .code("return first;") + .genericParameter( + GenericParameterDtoBuilder.create() + .name("R") + .upperBounds(TypeName.of(Number.class)) + .build()) + .parameter(param("first", new TypeNameVariable("R"))) + .parameter(param("second", new TypeNameVariable("R"))) + .build(); + GenerationTargetClassDto classDef = + baseClass("GenericBox").generic(generic).method(method).build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + "public class GenericBox> {", + """ + public static R pick(R first, R second) { + return first; + }"""); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void collectionArrayAndOptionalTypes_compile(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = + baseClass("ContainerClass") + .classField(field("names", new TypeNameGeneric(List.class, String.class))) + .classField( + field( + "scores", + new TypeNameGeneric( + TypeName.of(java.util.Map.class), + TypeName.of(String.class), + TypeName.of(Integer.class)))) + .classField(field("numbers", new TypeNameArray(TypeNamePrimitive.INT))) + .classField( + field("nickname", new TypeNameGeneric(java.util.Optional.class, String.class))) + .build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + "private java.util.List names;", + "private java.util.Map scores;", + "private int[] numbers;", + "private java.util.Optional nickname;"); + } + + /** + * Two field types sharing the simple name {@code Date} from different packages must never be + * rendered ambiguously — at least one of them has to stay fully qualified (issue #417). + */ + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void collidingSimpleNames_areDisambiguated(TestBackendProvider backend) throws Exception { + MethodDto method = + MethodDtoBuilder.create() + .methodName("touch") + .returnType(TypeNamePrimitive.VOID) + .modifier(AccessModifier.PUBLIC) + .code("if (when == null) { return; }") + .parameter(param("when", new TypeName("java.sql", "Date"))) + .build(); + GenerationTargetClassDto classDef = + baseClass("CollidingDates") + .classField(field("utilDate", new TypeName("java.util", "Date"))) + .classField(field("sqlDate", new TypeName("java.sql", "Date"))) + .method(method) + .build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + // The colliding type that wins the import renders by simple name; the loser stays qualified. + assertNormalizedContent( + source, + "private java.util.Date utilDate;", + "private java.sql.Date sqlDate;", + """ + public void touch(java.sql.Date when) { + if (when == null) { + return; + } + }"""); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void nestedTypesWithMembers_compile(TestBackendProvider backend) throws Exception { + NestedTypeDto nested = + NestedTypeDtoBuilder.create() + .typeName("Helper") + .kind(NestedTypeDto.NestedTypeKind.CLASS) + .visibility(AccessModifier.PUBLIC) + .method( + MethodDtoBuilder.create() + .methodName("assist") + .returnType(TypeNamePrimitive.VOID) + .modifier(AccessModifier.PUBLIC) + .code("int touched = 0;") + .build()) + .build(); + GenerationTargetClassDto classDef = baseClass("OuterClass").nestedType(nested).build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + "public class Helper {", + """ + public void assist() { + int touched = 0; + }"""); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void annotationsOnClassMembersAndTypeUse_compile(TestBackendProvider backend) throws Exception { + AnnotationDto deprecated = + AnnotationDtoBuilder.create() + .annotationType(TypeName.of(Deprecated.class)) + .addMemberString("since", "0.9") + .addMemberBoolean("forRemoval", true) + .build(); + + AnnotationDto generated = + AnnotationDtoBuilder.create() + .annotationType(new TypeName("javax.annotation.processing", "Generated")) + .addMemberString("value", "conformance") + .build(); + + TypeName annotatedString = TypeName.of(String.class); + annotatedString.addAnnotation( + AnnotationDtoBuilder.create() + .annotationType(TypeName.of(TestTypeUseAnnotation.class)) + .build()); + GenerationTargetClassDto classDef = + baseClass("AnnotatedClass") + .classAnnotations(new LinkedHashSet<>(List.of(deprecated, generated))) + .classField(field("flagged", annotatedString)) + .build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + "@Deprecated(since = \"0.9\", forRemoval = true)", + "@javax.annotation.processing.Generated(\"conformance\")", + "public class AnnotatedClass {", + "@org.javahelpers.codegen.testing.TestTypeUseAnnotation", + "private String flagged;"); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void codeTemplatePlaceholders_resolve(TestBackendProvider backend) throws Exception { + MethodDto method = + MethodDtoBuilder.create() + .methodName("parse") + .returnType(TypeNamePrimitive.LONG) + .modifier(AccessModifier.PUBLIC) + .methodCodeDto( + MethodCodeDtoBuilder.create() + .codeFormat("int $l:L = 0;\n$b:B box = null;\nreturn $t:T.parseLong($s:S);") + .codeArguments( + new MethodCodeStringPlaceholder("l", "count"), + new MethodCodeTypePlaceholder("b", TypeNamePrimitive.INT), + new MethodCodeTypePlaceholder("t", TypeName.of(Long.class)), + new MethodCodeStringPlaceholder("s", "42")) + .build()) + .build(); + GenerationTargetClassDto classDef = baseClass("TemplateClass").method(method).build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + """ + public long parse() { + int count = 0; + Integer box = null; + return Long.parseLong("42"); + }"""); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void superTypeAndInterfaces_compile(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = + baseClass("DerivedClass") + .superType(new TypeNameGeneric(java.util.ArrayList.class, String.class)) + .interfaces( + new LinkedHashSet<>( + List.of( + new InterfaceName("java.io", "Serializable"), + new InterfaceName("java.lang", "Cloneable")))) + .build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + """ + public class DerivedClass extends java.util.ArrayList implements java.io.Serializable, Cloneable { + }"""); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void staticImportsAndStaticFactory_compile(TestBackendProvider backend) throws Exception { + ClassFieldDto field = + ClassFieldDtoBuilder.create() + .fieldName("initial") + .fieldType(new TypeNameGeneric(List.class, String.class)) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("emptyList()") + .build(); + + MethodDto factory = + MethodDtoBuilder.create() + .methodName("of") + .returnType(TypeNamePrimitive.INT) + .modifier(AccessModifier.PUBLIC) + .isStatic(true) + .code("return names.length;") + .parameter(param("names", new TypeNameArray(TypeName.of(String.class)))) + .build(); + GenerationTargetClassDto classDef = + baseClass("FactoryClass") + .imports(new StaticImport(TypeName.of(java.util.Collections.class), "emptyList")) + .classField(field) + .method(factory) + .build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + """ + import static java.util.Collections.emptyList; + """, + "private java.util.List initial = emptyList();", + """ + public static int of(String... names) { + return names.length; + } + """); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void javadocIsEmittedForClassAndMembers(TestBackendProvider backend) throws Exception { + var javadoc = + JavadocDtoBuilder.create() + .description("Echoes the value.") + .param("value", "the input") + .returns("the echoed value") + .build(); + MethodDto method = + MethodDtoBuilder.create() + .methodName("echo") + .returnType(TypeName.of(String.class)) + .modifier(AccessModifier.PUBLIC) + .javadoc(javadoc) + .code("return value;") + .parameter(param("value", TypeName.of(String.class))) + .build(); + GenerationTargetClassDto classDef = + baseClass("DocumentedClass") + .classJavadoc( + JavadocDtoBuilder.create().description("Documented conformance class.").build()) + .method(method) + .build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertNormalizedContent( + source, + """ + /** + * Documented conformance class. + */ + public class DocumentedClass { + /** + * Echoes the value. + * @param value the input + * @return the echoed value + */ + public String echo(String value) { + return value; + } + } + """); + } + + /** Generates {@code classDef} through {@code provider}'s backend and returns the source text. */ + private String generate(TestBackendProvider provider, GenerationTargetClassDto classDef) + throws Exception { + TestingGenerationEnvironment env = TestingGenerationEnvironment.create(); + CodegenBackend backend = provider.create(env, env.getLogger()); + backend.generator().generateClass(classDef, backend.formatterFor(FormattingMode.NONE)); + return env.generatedSource(); + } + + /** + * Compiles {@code source} with the JDK compiler on the test classpath; fails when javac reports + * an error. + */ + private void assertCompiles(GenerationTargetClassDto classDef, String source) throws IOException { + String qualifiedName = classDef.getTypeName().getFullQualifiedName(); + Path sourceFile = WORK_DIR.resolve(qualifiedName.replace('.', '/') + ".java"); + Files.createDirectories(sourceFile.getParent()); + Files.writeString(sourceFile, source, StandardCharsets.UTF_8); + Path classes = Files.createDirectories(WORK_DIR.resolve("classes")); + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + try (StandardJavaFileManager fileManager = + compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) { + boolean ok = + compiler + .getTask( + null, + fileManager, + diagnostics, + List.of( + "-proc:none", + "-classpath", + System.getProperty("java.class.path"), + "-d", + classes.toString()), + null, + fileManager.getJavaFileObjects(sourceFile)) + .call(); + assertTrue( + ok, + () -> + """ + generated source for %s must compile: + %s + --- source --- + %s""" + .formatted( + qualifiedName, + diagnostics.getDiagnostics().stream() + .map(Object::toString) + .collect(Collectors.joining("\n")), + source)); + } + } + + /** + * Collapses legal qualification variance out of generated source: fully qualified references to + * imported types are rewritten to their simple name, so backends may freely choose between + * importing a type and qualifying it in place. Types that lose a simple-name collision are never + * imported and therefore stay fully qualified, which keeps the collision-binding checks intact. + * Variance in which colliding type wins the import is deterministic per backend and out of scope. + * + * @param source generated Java source + * @return source with importable type references normalized to simple names + */ + static String normalizeQualificationVariance(String source) { + // canonical form is fully qualified everywhere: simple type names that come from imports + // are expanded, so import-style and in-place-qualified output converge. Types that lose a + // simple-name collision are never imported and stay qualified either way, which keeps the + // collision-binding checks intact. java.lang types are never imported and out of scope. + Map simpleToFq = new LinkedHashMap<>(); + java.util.regex.Matcher importStatement = + java.util.regex.Pattern.compile("import\\s+([\\w.]+)\\s*;").matcher(source); + StringBuilder body = new StringBuilder(); + while (importStatement.find()) { + String fq = importStatement.group(1); + simpleToFq.putIfAbsent(fq.substring(fq.lastIndexOf('.') + 1), fq); + importStatement.appendReplacement(body, ""); + } + importStatement.appendTail(body); + String result = body.toString(); + // longest simple names first so overlapping suffixes are not partially rewritten; + // a leading dot means the occurrence is already owner-qualified and stays untouched + List> entries = new ArrayList<>(simpleToFq.entrySet()); + entries.sort((left, right) -> right.getKey().length() - left.getKey().length()); + for (Map.Entry entry : entries) { + result = + result.replaceAll( + "(?Every backend module (Roaster today; JavaPoet or the built-in lightweight generator planned in + * issue #364) registers exactly one implementation in its test sources: + * + *

+ * + *

{@link GeneratorConformanceTest} discovers providers via {@link java.util.ServiceLoader}, so a + * new backend gains the complete conformance coverage by dropping its provider on the test + * classpath — no test code needs to be written or copied. + */ +public interface TestBackendProvider { + + /** + * Short display name of the backend under test (e.g. {@code "Roaster"}). Shown in the test name + * of every conformance test, so failures identify the failing backend. Implementations should + * also return this name from {@link #toString()} so the parameterized invocation renders as the + * backend name in all test reporters. + * + * @return the backend display name + */ + String name(); + + /** + * Creates the backend under test. + * + * @param environment the testing environment capturing generated source + * @param logger the processing logger to pass to the backend + * @return a ready-to-use backend instance + */ + CodegenBackend create(GenerationEnvironment environment, ProcessingLogger logger); +} diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestTypeUseAnnotation.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestTypeUseAnnotation.java new file mode 100644 index 00000000..36ffa813 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestTypeUseAnnotation.java @@ -0,0 +1,45 @@ +/* + * 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.testing; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marker annotation for generator conformance fixtures. Carries no semantics — it exists so that + * generated sources can annotate elements and type usages with a real, classpath-resolvable + * annotation. + */ +@Target({ + ElementType.TYPE, + ElementType.FIELD, + ElementType.METHOD, + ElementType.PARAMETER, + ElementType.TYPE_USE +}) +@Retention(RetentionPolicy.RUNTIME) +public @interface TestTypeUseAnnotation {} diff --git a/docs/CODEGEN_BUILDERS.md b/docs/CODEGEN_BUILDERS.md new file mode 100644 index 00000000..1a3eb3a1 --- /dev/null +++ b/docs/CODEGEN_BUILDERS.md @@ -0,0 +1,24 @@ +# Regenerating the codegen DTO builders + +The twelve `*DtoBuilder.java` files under `codegen-core/src/main/java` are +committed bootstrap sources: the processor itself depends on codegen-core. +Use Java 17 and run these commands from the repository root: + +```sh +mvn -pl processor -am install -Dmaven.test.skip=true +mvn -pl processor -Dtest=CodegenDtoBuilderRegenerationTest -Dcodegen.regenerate=true test +mvn -pl codegen-core fmt:format +git diff --exit-code -- 'codegen-core/src/main/java/**/*Builder.java' +``` + +The explicit regeneration test compiles the model sources and same-package +`@SimpleBuilderFor` holders with the current processor, asserts that exactly twelve +builders were emitted, and replaces only those committed builders. It is disabled +in ordinary builds. After intentional model or generator changes, review and +commit the regenerated files; otherwise the final command must report no changes. +Java CI runs regeneration after installing the reactor and rejects drift. + +Collection setters replace contents with a shallow defensive copy into each DTO's +own mutable collection. They reject null collections with `NullPointerException` +before modifying existing state. Empty collections clear the property, and passing +the DTO's own collection is supported. Existing `addX` methods remain available. diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java index 7d1cd2a8..a6af8b60 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java @@ -517,6 +517,147 @@ public class PersonDto { .onLine(4); } + @Test + void shouldWarnAndGenerateNoBuilderWhenOnlyConstructorIsPrivate() { + // Given: a DTO that is exclusively created through a hand-written builder, so its only + // constructor is private + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class PersonDto { + private String name; + private PersonDto(String name) { this.name = name; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = compile(source); + + // Then: compilation succeeds, but no builder is generated + assertThat(compilation).succeeded(); + assertThat(compilation).hadWarningContaining("No accessible constructor"); + assertNoBuilderGenerated( + compilation, "PersonDto", "A type without accessible constructor must not get a builder"); + } + + @Test + void shouldWarnAndGenerateNoBuilderWhenNoArgConstructorIsPrivate() { + // Given: a singleton-style DTO whose only constructor is a private no-arg constructor + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class SingletonDto { + private String name; + private SingletonDto() {} + public static SingletonDto getInstance() { return new SingletonDto(); } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = compile(source); + + // Then: compilation succeeds, but no builder is generated + assertThat(compilation).succeeded(); + assertThat(compilation).hadWarningContaining("No accessible constructor"); + assertNoBuilderGenerated( + compilation, + "SingletonDto", + "A type without accessible constructor must not get a builder"); + } + + @Test + void shouldGenerateBuilderWhenAccessibleConstructorExistsNextToPrivateOne() { + // Given: a DTO with a private constructor and an accessible public constructor + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class PersonDto { + private String name; + private PersonDto(String name) { this.name = name; } + public PersonDto() {} + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = compile(source); + + // Then: the builder is generated using the accessible constructor + String generatedCode = loadGeneratedSource(compilation, "PersonDtoBuilder"); + assertGenerationSucceeded(compilation, "PersonDtoBuilder", generatedCode); + } + + @Test + void + shouldWarnAndGenerateNoBuilderWhenPackagePrivateConstructorIsNotReachableFromGeneratedPackage() { + // Given: a DTO with a package-private constructor whose builder is generated into another + // package, so the constructor is not reachable from the generated code + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder(options = @SimpleBuilder.Options(packageName = "com.example.generated")) + public class WidgetDto { + private String name; + WidgetDto() {} + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = compile(source); + + // Then: compilation succeeds, but no builder is generated + assertThat(compilation).succeeded(); + assertThat(compilation).hadWarningContaining("No accessible constructor"); + assertNoBuilderGenerated( + compilation, "WidgetDto", "A type without accessible constructor must not get a builder"); + } + + @Test + void shouldFailInStrictModeWhenNoAccessibleConstructor() { + // Given: a DTO without an accessible constructor, compiled with strict mode enabled + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class PersonDto { + private String name; + private PersonDto(String name) { this.name = name; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = + ProcessorTestUtils.createCompiler() + .withOptions("-Asimplebuilder.strict=true") + .compile(source); + + // Then: compilation fails with an error + assertThat(compilation).failed(); + assertThat(compilation).hadErrorContaining("No accessible constructor"); + } + @Test void shouldGenerateBuilderForNestedPropertyTypeInSameClass() { // Given: a property whose type is a static nested class of the DTO itself diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/CodegenDtoBuilderRegenerationTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/CodegenDtoBuilderRegenerationTest.java new file mode 100644 index 00000000..07ad810f --- /dev/null +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/CodegenDtoBuilderRegenerationTest.java @@ -0,0 +1,134 @@ +/* + * 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.simple.builders.processor; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.google.testing.compile.Compilation; +import com.google.testing.compile.JavaFileObjects; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import javax.tools.JavaFileObject; +import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +/** Explicit regeneration entry point; ordinary builds never rewrite committed sources. */ +@EnabledIfSystemProperty(named = "codegen.regenerate", matches = "true") +class CodegenDtoBuilderRegenerationTest { + + @Test + void regenerateBuilders() throws Exception { + Path root = Path.of(System.getProperty("basedir")).getParent(); + Path sources = root.resolve("codegen-core/src/main/java"); + // only the twelve regeneration targets are excluded from the inputs: hand-written builders + // like ArrayListBuilder/HashSetBuilder must stay compilable because generated builders use them + List builderGroups = + List.of( + "core:GenerationTargetClassDto,ClassFieldDto", + "method:MethodDto,ConstructorDto,MethodParameterDto,CodeTemplateDto,MethodCodeDto", + "type:GenericParameterDto,NestedTypeDto", + "annotation:AnnotationDto", + "javadoc:JavadocDto,JavadocCodeBlockDto"); + List regenerationTargets = + builderGroups.stream() + .flatMap(group -> java.util.Arrays.stream(group.split(":")[1].split(","))) + .map(dto -> dto + "Builder.java") + .toList(); + List inputs = new ArrayList<>(); + try (var paths = Files.walk(sources)) { + for (Path path : + paths + .filter(p -> p.toString().endsWith(".java")) + .filter(p -> !regenerationTargets.contains(p.getFileName().toString())) + .sorted() + .toList()) { + String className = + sources.relativize(path).toString().replace('/', '.').replace(".java", ""); + inputs.add(JavaFileObjects.forSourceString(className, Files.readString(path))); + } + } + for (String group : builderGroups) { + String[] parts = group.split(":"); + String packageName = "org.javahelpers.codegen.model." + parts[0]; + String types = + java.util.Arrays.stream(parts[1].split(",")) + .map(name -> name + ".class") + .collect(java.util.stream.Collectors.joining(", ")); + inputs.add( + JavaFileObjects.forSourceString( + packageName + ".CodegenBuilders", + """ + package %s; + @org.javahelpers.simple.builders.core.annotations.SimpleBuilderFor({%s}) + class CodegenBuilders {} + """ + .formatted(packageName, types))); + } + + File codegenClasses = + new File( + GenerationTargetClassDto.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .toURI()); + List classpath = + Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator)) + .map(File::new) + .filter(file -> !file.equals(codegenClasses)) + .toList(); + Compilation compilation = + ProcessorTestUtils.createCompiler() + .withClasspath(classpath) + .withOptions("-Asimplebuilder.strict=true") + .compile(inputs); + assertThat(compilation).succeeded(); + List builders = + compilation.generatedSourceFiles().stream() + .filter(file -> file.getName().endsWith("Builder.java")) + .toList(); + assertEquals(12, builders.size()); + String header = + "/*\n%s\n */\n\n" + .formatted( + Files.readAllLines(root.resolve("LICENSE.txt")).stream() + .map(line -> line.isEmpty() ? " *" : " * %s".formatted(line)) + .collect(java.util.stream.Collectors.joining("\n"))); + for (JavaFileObject builder : builders) { + String source = builder.getCharContent(false).toString(); + String packageName = source.substring(source.indexOf("package ") + 8, source.indexOf(';')); + String fileName = Path.of(builder.toUri().getPath()).getFileName().toString(); + Files.writeString( + sources.resolve(packageName.replace('.', '/')).resolve(fileName), header + source); + } + } +}