Skip to content

Suppress safe parameterized varargs warnings - #482

Open
igel-devin-ai wants to merge 12 commits into
java-helpers:mainfrom
igel-devin-ai:devin/1796198218-issue-467-safe-varargs
Open

igel-devin-ai wants to merge 12 commits into
java-helpers:mainfrom
igel-devin-ai:devin/1796198218-issue-467-safe-varargs

Conversation

@igel-devin-ai

Copy link
Copy Markdown
Contributor

Summary

Fixes #467.

Varargs helpers whose element type is parameterized, has a parameterized enclosing owner, or is a type variable now receive @SafeVarargs. The helpers only pass the varargs array through to List.of, OrderedSets.of, or Map.ofEntries, so the array is never stored or exposed.

RoasterCodeGenerator renders non-static methods carrying java.lang.SafeVarargs as final, which is required for valid Java. Only the affected helpers become final; varargs helpers with reifiable element types remain unchanged.

Regression coverage verifies zero unchecked warnings for parameterized nested types, Set/Map elements, and List<T> in a generic DTO. The configuration documentation now mentions the final/@SafeVarargs behavior.

mvn clean verify passes.

Comment on lines +604 to +611
// @SafeVarargs instance methods must be final to be legal Java.
method.setFinal(
!methodDto.isStatic()
&& methodDto.getAnnotations().stream()
.anyMatch(
annotation ->
"java.lang.SafeVarargs"
.equals(annotation.getAnnotationType().getFullQualifiedName())));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should not be set in generator. This should be set on methodDto creation!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in eeebff4: final is now modeled on MethodDto and assigned while the mapper creates that DTO; Roaster only renders the model flag.

field, transform, parameterType, builderType, context);
TypeName elementType = ((TypeNameArray) parameterType).getTypeOfArray();
if (requiresSafeVarargs(elementType)) {
method.addAnnotation(AnnotationDtoBuilder.create().annotationType(SafeVarargs.class).build());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't there a direct possible way for doing this?

Suggested change
method.addAnnotation(AnnotationDtoBuilder.create().annotationType(SafeVarargs.class).build());
method.addAnnotation(SafeVarargs.class);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in eeebff4 via the new direct addAnnotation(Class<?>) overload.

BuilderMethodDto method =
MethodGeneratorUtil.createBuilderMethodForFieldWithTransform(
field, transform, parameterType, builderType, context);
TypeName elementType = ((TypeNameArray) parameterType).getTypeOfArray();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to cast here? And why could we be sure that it is always this type?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in eeebff4: the cast is replaced by pattern matching. The array shape is guaranteed because this path creates a varargs array parameter, but the pattern match makes that assumption explicit and safe.

import org.javahelpers.simple.builders.core.annotations.SimpleBuilder;
@SimpleBuilder
public class GenericVarargsDto<T> {
private java.util.List<T> value;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put import of java.util.list on this class, improves reading.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in eeebff4; the test source imports java.util.List and uses List<...> directly.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No in this line it is still the full package name

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — the test source now imports java.util.List and uses simple names throughout.

assertThat(compilation).hadWarningCount(0);
String generated = loadGeneratedSource(compilation, "GenericVarargsDtoBuilder");
ProcessorAsserts.assertContaining(
generated, "@SafeVarargs", "public final GenericVarargsDtoBuilder<T> value(T... value)");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use a textblock with full function and annotation for assert

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in eeebff4 with a full annotation-plus-method textblock assertion.

Comment on lines +141 to +142
ProcessorAsserts.assertContaining(
generated, "@SafeVarargs", "public final InnerDtoBuilder value(");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, assert textblock

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in eeebff4 with a full annotation-plus-method textblock assertion.

Comment on lines +134 to +137
assertFalse(
compilation.diagnostics().stream()
.anyMatch(
d -> d.getMessage(null).contains("Possible heap pollution from parameterized")));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We had that in a different PR regarding assertion of diagnostics. Is there no helper function for it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes — that helper was added in #481 as ProcessorAsserts.assertNoDiagnosticsContaining. It is not present on this independent branch yet; I left this unchanged here to avoid duplicating/conflicting with #481 and will use it after that PR is merged or this branch is rebased.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be now on main

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now done in bfc4fc1: the branch is updated with main after #481, and the test uses ProcessorAsserts.assertNoDiagnosticsContaining. The merged array-signature behavior is covered by the updated nested-list regression test; full mvn clean verify passes.

@codecov

codecov Bot commented Dec 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

Comment on lines +323 to +331
/**
* Adds an annotation to this method.
*
* @param annotationType the annotation type to add
*/
public void addAnnotation(Class<?> annotationType) {
addAnnotation(AnnotationDtoBuilder.create().annotationType(annotationType).build());
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should only be a helper function in the builder of methodDto and from there this should be used (regarding my comment before)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — the convenience overload is removed from MethodDto; the Class-based helper now lives only on the builders (MethodDtoBuilder.annotation(Class) / BuilderMethodDtoBuilder.annotation(Class)). The one usage in VarArgsHelperGenerator constructs the annotation via AnnotationDtoBuilder.

*/
private record FieldMethod(BuilderFieldDto field, BuilderMethodDto method) {}

private static boolean requiresFinalForSafeVarargs(BuilderMethodDto method) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This Validation should be done in validator and not in the mapper.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The validation rule now lives in the validator: GenerationTargetValidator rejects methods annotated with @SafeVarargs that are neither final nor static. Note on the mapper: the generation model (BuilderMethodDto) has no final modifier at all, so the processor cannot express final there — the mapper derives it to guarantee valid generated code. That is generation necessity rather than validation; the distinction is documented in the code.

*
* @param annotationType the annotation type to add
*/
public void addAnnotation(Class<?> annotationType) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same topic here, it is for the builder of the method class not for the method class

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here — removed from BuilderMethodDto, helper exists only on BuilderMethodDtoBuilder.

Comment on lines +134 to +137
assertFalse(
compilation.diagnostics().stream()
.anyMatch(
d -> d.getMessage(null).contains("Possible heap pollution from parameterized")));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be now on main

import org.javahelpers.simple.builders.core.annotations.SimpleBuilder;
@SimpleBuilder
public class GenericVarargsDto<T> {
private java.util.List<T> value;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No in this line it is still the full package name

Comment on lines +128 to +129
"List<java.util.Set<String>>",
"List<java.util.List<String>>"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"List<java.util.Set<String>>",
"List<java.util.List<String>>"
"List<Set<String>>",
"List<List<String>>"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied — simple names everywhere now.

compilation.diagnostics().stream()
.anyMatch(
d -> d.getMessage(null).contains("Possible heap pollution from parameterized")));
if (!property.contains("List<java.util.List")) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!property.contains("List<java.util.List")) {
if (!property.contains("List<List")) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the restructure — the conditional is gone entirely.

Comment on lines +138 to +153
if (!property.contains("List<java.util.List")) {
assertThat(compilation).hadWarningCount(0);
String generated = loadGeneratedSource(compilation, "InnerDtoBuilder");
if (property.contains("other.Outer")) {
ProcessorAsserts.assertContaining(
generated,
"""
@SafeVarargs
public final InnerDtoBuilder value(other.Outer<java.lang.String>.Inner... value) {
this.value = changedValue(List.of(value));
return this;
}
""");
} else {
ProcessorAsserts.assertContaining(generated, "@SafeVarargs");
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code looks strange for me. We have several different properties for this test and it should check different things per property? Then build that easy to read!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restructured for readability: the test now uses @CsvSource mapping each property directly to its expected vararg type (List<Set> -> Set etc.), with a single uniform assertion of the full generated method per case.

@igel-devin-ai

igel-devin-ai commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Strict review

changes needed

Reviewed head 97e874a940a2af07a4b16ef06a5607f19dd520fd against upstream/main 4b696141058c97b8130c3ce3920a7faeafbb3bbd, including issue #467, the PR body and existing comments. The four explicitly requested element shapes have processor regression coverage, including generic DTOs; the final flag is modeled before rendering, and the documentation explains the user-visible final helpers. Previously resolved comments about mapper validation placement, annotation convenience helpers and test readability are not repeated.

  1. minor — verified — processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java:171–176: non-reifiability detection stops at array elements. List<T[]> and List<Set<String>[]> are valid collection properties whose varargs element types remain non-reifiable. requiresSafeVarargs handles generic, variable and nested types but not TypeNameArray, so it leaves value(T[]... value) and value(Set<String>[]... value) unannotated and non-final. Strict compile-testing probes both succeed with 2 unchecked warnings: one on this whole-collection helper and one on the separately generated addToValue(T... element) / addToValue(Set<String>... element). The non-array controls List<Set<String>> and List<Map<String,Integer>> both compile with 0 warnings and the expected @SafeVarargs public final method. Recurse through array components when deciding reifiability, and apply equivalent safety handling to the array-element adder if the intent is a warning-free builder for these shapes. Add array-element regressions; do not merely suppress warnings on the DTO or builder class. These are additional edge cases beyond the four explicitly enumerated examples, not a claim that those four still fail.

  2. minor — verified — codegen-core/src/main/java/org/javahelpers/codegen/validation/GenerationTargetValidator.java:141–151: the new legality rule rejects private @SafeVarargs methods. Since Java 9, @SafeVarargs is legal on private instance varargs methods without final. A generation model for @SafeVarargs private void collect(String... values) {} is rejected with Method 'collect' is annotated with @SafeVarargs but is neither final nor static in test.PrivateVarargs. Rendering the same model directly and compiling the resulting Java succeeds with 0 warnings, 0 errors on Java 17. Include the PRIVATE access modifier in the allowed cases, and test static, final, private and genuinely illegal overridable instance methods in the validator. This is a regression in the general codegen API, even though this processor currently chooses final public helpers.

  3. nit — verified — processor/src/test/java/org/javahelpers/simple/builders/processor/CustomCollectionTypeTest.java:290–291: the changed expected-source assertion is still an ordinary quoted Java fragment. Convert it to a text block, consistent with the complete annotation-plus-method expectations added in BuilderProcessorTest. No new + concatenation was found in the focused varargs regressions; this is the remaining source-string convention inconsistency, not the already resolved parameterized-test readability comment.

Verification

  • Java 17 / Maven 3.9.11: targeted Maven install of codegen-core,codegen-roaster,processor and reactor dependencies, formatting disabled, exited 0:
    PR 482: Tests run: 1376, Failures: 0, Errors: 0, Skipped: 0
    
  • External compile-testing probes used -Xlint:rawtypes -Xlint:unchecked -Asimplebuilder.strict=true:
    CASE NormalSet: SUCCESS warnings=0 errors=0
    CASE NormalMap: SUCCESS warnings=0 errors=0
    CASE GenericArray: SUCCESS warnings=2 errors=0
    CASE ParameterizedArray: SUCCESS warnings=2 errors=0
    Private SafeVarargs javac: SUCCESS warnings=0 errors=0
    
    The existing processor tests cover the required owner-parameterized inner type, List<List<String>> and List<T> with zero-warning assertions and complete final/annotation expectations.
  • git_pr_checks returns 0 passed, 0 failed, 0 pending, 0 skipped, not a passing build. Actions API: Java CI 47628098090 and CodeQL 47628098182 are action_required; dependency review 47628095598 is startup_failure. Author/Codecov/Sonar comments about earlier successful runs are not proof of current-head CI success.
  • The committed MethodDtoBuilder is updated for the new flag. No example-module file changes are included; I did not independently regenerate all examples, so I cannot certify the issue's regeneration criterion beyond inspecting the committed diff. The inspected simple/reifiable example varargs do not need to become final under the selected policy.
  • External probe sources deleted; no repository changes, commits, pushes or GitHub comments.

Other-PR integration review

Written by Devin


Recheck at 095ca345 (2026-12-06)

Verdict: minor changes

# Original finding (short) Status Remaining action
1 Array-element varargs warnings partially fixed — minor Apply safety annotation/finality to element adders (AddToCollectionGenerator.java:150–157); array probes still emit one warning each.
2 Legal private @SafeVarargs rejected fixed; regression missing — minor Test private/static/final acceptance and overridable rejection (GenerationTargetValidator.java:148–153).
3 Expected-source text block fixed —
N1 Array-recursion regression missing open — minor Add zero-warning processor compile tests protecting VarArgsHelperGenerator.java:171–179.

Build: Java 17 module install — BUILD SUCCESS; 1,376 tests, 0 failures/errors; example compile succeeds without tracked drift; array-element probes retain heap-pollution warnings.


Recheck at bc5b8f27 (2026-12-06)

Verdict: minor changes

Severity What is missing Where (file:line)
minor Partial: acceptance fixtures declare zero-parameter safe(), not varargs; give them actual varargs parameters. Javac rejects the current fixture. GenerationTargetValidatorTest.java:670–714

…lity, textblock nit

- requiresSafeVarargs recurses through array components: List<T[]> /
  List<Set<String>[]> collection helpers now get @SafeVarargs + final
- validator allows private @SafeVarargs methods (legal since Java 9)
- CustomCollectionTypeTest expectation converted to text block
@igel-devin-ai

Copy link
Copy Markdown
Contributor Author

Strict-review findings fixed:

  1. Array non-reifiability — requiresSafeVarargs now recurses through array components, so List<T[]>/List<Set<String>[]> collection helpers get @SafeVarargs + final
  2. Private @SafeVarargs — the validator now accepts private methods (legal since Java 9) alongside final and static
  3. Nit — the CustomCollectionTypeTest expectation is a text block now

Verified: full processor suite green (694 tests), validator tests green (29).

…tests

Array element types in last parameter position render as varargs (the generation
convention), so a collection of non-reifiable arrays (List<List<String>[]>) made
the single-element adder a non-reifiable varargs method emitting heap-pollution
warnings. The adder now carries @SafeVarargs when the array element is
non-reifiable — the mapper derives the required finality from it — and the
zero-warning probes for array-element fields pass (5/5). requiresSafeVarargs
exposed package-visible for reuse. Validator regression tests cover
final/static/private @SafeVarargs acceptance and overridable rejection
@igel-devin-ai

Copy link
Copy Markdown
Contributor Author

Recheck items addressed:

  • Finding 1 — array-element adders: root-caused with lint probes. Array types in last parameter position render as varargs (the generation convention — that's how the variadic helpers are built at all), so for a List<List<String>[]> field the element adder became addToValue(List<String>... element) — a non-reifiable varargs method emitting the heap-pollution warning. Fix per the review: @SafeVarargs is now applied to element adders when the array element type is non-reifiable; finality is derived by the mapper. New regression probes compile List<String[]>, List<int[]>, String[], List<List<String>[]>, List<Map<String,Integer>[]> with lint enabled — zero warnings, and @SafeVarargs verified in the generated source (covers N1's protection of the array recursion too)
  • Finding 2 regression: validator tests cover final/static/private acceptance and overridable rejection of @SafeVarargs methods

Full processor suite green.

- S5663: SafeVarargs violation message now uses the line-continuation pattern
  consistent with the other violations
- S9427: Java assert statements replaced with JUnit assertTrue in
  MethodConflictResolutionTest (5 occurrences)
…sue-467-safe-varargs

# Conflicts:
#	processor/src/test/java/org/javahelpers/simple/builders/processor/MethodConflictResolutionTest.java
@sonarqubecloud

sonarqubecloud Bot commented Dec 6, 2026

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Varargs helpers for parameterized element types cause heap-pollution warnings

2 participants