Repository navigation
feat: extend type kinds in codegen model — stage 1 (#489) - #492
igel-devin-ai wants to merge 30 commits into
Conversation
- new shared TypeKind enum (CLASS/INTERFACE/ENUM/RECORD/ANNOTATION_TYPE), kind property on GenerationTargetClassDto (defaults to CLASS) - NestedTypeKind extended with ENUM/RECORD/ANNOTATION_TYPE - enum constants on generation target + nested types, record components on generation target (model + builders incl. copy constructors) - Roaster renders nested enums (with constants) and nested annotation types (methods as annotation elements) Stage 1 scope: nested enum/annotation-type rendering. Top-level kinds need generalizing the generation pipeline beyond JavaClassSource; record RENDERING is blocked upstream — Roaster 2.31.1 has no JavaRecordSource.
- record components on NestedTypeDto + builder (incl. copy constructor) - nested records render via JavaRecordSource: components in the record header, constructors as regular canonical constructors with a warning logged (compact constructors unsupported upstream, forge/roaster#275) - fields on records throw with a link to forge/roaster#279 (static fields in records unsupported upstream; instance fields are illegal in records anyway) - 3 new rendering tests
- GenerationTargetValidator validates per-kind restrictions for target and nested types: interfaces reject constructors/fields/super type, enums and annotation types reject generics and super type, records reject fields and super type; enum constants only valid on enums, record components only valid on records - GenerationTargetClassDtoBuilder gains createInterface(), createEnum(), createRecord() and createAnnotationType() factory methods presetting the kind
A record's components ARE its fields (JLS 8.10) — the separate recordComponents list duplicated what classFields already models. Records now render their fields as components in the record header; the validator rejects literal initializers on record fields instead of rejecting fields altogether, since component values are assigned through the canonical constructor.
Constructors declared on records now have compact-constructor semantics: an empty parameter list is auto-completed from the record components (fields) in order, rendered as a regular canonical constructor since Roaster cannot emit the compact form. The validator rejects declared parameter lists that do not match the components in order and type.
Records may declare additional constructors with any parameter list as long as they delegate to the canonical constructor — checking the delegation is the compiler's job, not the validator's. Only the compact constructor semantics remain: an empty parameter list is auto-completed from the components at generation time.
| public class GenerationTargetClassDto implements GenerationTargetClassDtoBuilder.With { | ||
| /** Kind of the generated type, defaults to {@link TypeKind#CLASS}. */ | ||
| private org.javahelpers.codegen.model.type.TypeKind kind = | ||
| org.javahelpers.codegen.model.type.TypeKind.CLASS; | ||
|
|
||
| /** Enum constant names, only rendered when kind is {@link TypeKind#ENUM}. */ | ||
| private final java.util.List<String> enumConstants = new java.util.LinkedList<>(); | ||
|
|
||
| /** | ||
| * Record components as parameters (name + type), only rendered when kind is {@link | ||
| * TypeKind#RECORD}. | ||
| */ | ||
| private final java.util.List<org.javahelpers.codegen.model.method.MethodParameterDto> | ||
| recordComponents = new java.util.LinkedList<>(); |
There was a problem hiding this comment.
Could you do that with simple names instead of fullpackages? Please check other places of this PR too
There was a problem hiding this comment.
Done — simple names with imports everywhere in the DTOs; swept the whole PR for fully-qualified usages (the {@code} javadoc references intentionally keep the FQN since that's generated documentation text).
| private org.javahelpers.codegen.model.type.TypeKind kind; | ||
| private final java.util.List<String> enumConstants = new java.util.LinkedList<>(); | ||
| private final java.util.List<org.javahelpers.codegen.model.method.MethodParameterDto> | ||
| recordComponents = new java.util.LinkedList<>(); |
There was a problem hiding this comment.
Member variables to the top of the class and not below methods.
There was a problem hiding this comment.
Still full package here and on other places
There was a problem hiding this comment.
Done — kind and enumConstants now sit with the other member variables at the top of the class.
There was a problem hiding this comment.
Done — caught the remaining ones in the sweep (enumConstants/kind declarations in both DTOs and builders, plus a java.util.Arrays usage).
| this.superType.ifSet(result::setSuperType); | ||
| this.typeName.ifSet(result::setTypeName); | ||
| if (kind != null) { | ||
| result.setKind(kind); |
There was a problem hiding this comment.
Is kind default on dto set to class?
There was a problem hiding this comment.
Yes — GenerationTargetClassDto.kind is initialized to TypeKind.CLASS and the setter is null-guarded, so existing consumers that never set a kind behave exactly as before.
| private final java.util.List<String> enumConstants = new java.util.LinkedList<>(); | ||
| private final java.util.List<org.javahelpers.codegen.model.method.MethodParameterDto> | ||
| recordComponents = new java.util.LinkedList<>(); | ||
|
|
There was a problem hiding this comment.
Here the same, it needs to be move in class up
There was a problem hiding this comment.
Done — same move in NestedTypeDtoBuilder, the field is up with the other members now.
| if (nestedSource instanceof JavaEnumSource enumSource) { | ||
| for (String constant : nestedType.getEnumConstants()) { | ||
| enumSource.addEnumConstant(constant); | ||
| } | ||
| } | ||
| if (nestedSource instanceof JavaRecordSource recordSource) { | ||
| for (var component : nestedType.getRecordComponents()) { | ||
| recordSource.addRecordComponent( | ||
| RoasterMapper.mapType(component.getParameterType(), collidingSimpleNames), | ||
| component.getParameterName()); | ||
| } | ||
| if (!nestedType.getClassFields().isEmpty()) { | ||
| // instance fields are illegal in records, so any declared field would have to be static — | ||
| // but Roaster cannot render static fields in records yet | ||
| throw new UnsupportedOperationException( | ||
| ("Nested record '%s' declares fields, but Roaster does not support static fields in" | ||
| + " records yet — see https://github.com/forge/roaster/issues/279") | ||
| .formatted(nestedType.getTypeName())); | ||
| } | ||
| if (!nestedType.getConstructors().isEmpty()) { | ||
| // Roaster does not support compact constructors | ||
| // (https://github.com/forge/roaster/issues/275); | ||
| // they are rendered as regular canonical constructors instead — the workaround is source- | ||
| // compatible since a compact constructor is just syntactic sugar for the canonical one | ||
| logger.debug( | ||
| "Nested record '%s' declares constructors: rendered as regular canonical constructors" | ||
| + " because Roaster does not support compact constructors" | ||
| + " (https://github.com/forge/roaster/issues/275)", | ||
| nestedType.getTypeName()); | ||
| } |
There was a problem hiding this comment.
Move that in helper functions one for each type
There was a problem hiding this comment.
Done — extracted into per-kind helpers: appendEnumConstants / appendRecordComponents / appendRecordConstructors (the compact-constructor auto-completion lives there now, documented in its javadoc with the forge/roaster#275 link).
There was a problem hiding this comment.
But why not directly call that in the switch case instead of doing it afterwards in an instance of check?
There was a problem hiding this comment.
Done — the kind-specific rendering now happens directly in the switch arms: enum constants in the ENUM case, record components and the compact-constructor warning in the RECORD case. The redundant instanceof checks afterwards are gone.
| if (target.getSuperType() != null) { | ||
| addViolation( | ||
| "Interface '%s' declares a super type, but interfaces can only extend interfaces" | ||
| + " via the interfaces list", | ||
| target.getTypeName().getClassName()); | ||
| } |
There was a problem hiding this comment.
| if (target.getSuperType() != null) { | |
| addViolation( | |
| "Interface '%s' declares a super type, but interfaces can only extend interfaces" | |
| + " via the interfaces list", | |
| target.getTypeName().getClassName()); | |
| } | |
| rejectIfNotEmpty(target.getSuperType(), | |
| "Interface '%s' declares a super type, but interfaces can only extend interfaces" | |
| + " via the interfaces list", | |
| target.getTypeName().getClassName()); |
There was a problem hiding this comment.
Almost — rejectIfNotEmpty takes a collection, but superType is a single object. Introduced rejectIfNotNull as the single-value counterpart and applied it to all super type checks; generics/interfaces checks now use rejectIfNotEmpty as suggested.
| if (!target.getGenerics().isEmpty()) { | ||
| addViolation( |
There was a problem hiding this comment.
Done — generics and interfaces checks on enums/annotation types use rejectIfNotEmpty now.
| .nestedType( | ||
| n -> | ||
| n.typeName("Marker") | ||
| .kind(NestedTypeDto.NestedTypeKind.ANNOTATION_TYPE) |
There was a problem hiding this comment.
Adding static import for NestedTypeDto.NestedTypeKind.* for increasing readability?
There was a problem hiding this comment.
Done — static imports for ENUM/RECORD/ANNOTATION_TYPE, much easier to read.
- Specialized builders per target kind: GenerationTargetEnumDtoBuilder (enumConstant), GenerationTargetRecordDtoBuilder (recordComponent), GenerationTargetInterfaceDtoBuilder, GenerationTargetAnnotationTypeDtoBuilder; the kind-preset factories return them and enumConstant leaves the general builder — misplaced members are now impossible through the builder API, the validator remains as safety net for direct DTO use - Roaster nested-type rendering extracted into per-kind helpers (appendEnumConstants/appendRecordComponents/appendRecordConstructors/ appendAnnotationElements) - Member variables moved to the top of both builders; simple names instead of fully qualified ones across the PR - Validator: unified rejection pattern, rejectIfNotNull for single values next to rejectIfNotEmpty for collections - Test readability: static imports for NestedTypeKind constants
…arget - EnumConstantDto models a constant name plus optional constructor argument expressions — enumConstant(name, args...) on the enum and nested builders renders FAST(100), as required when the enum constructor has parameters - validator prohibits enum constants on the generation target regardless of kind: top-level enum rendering is not implemented yet, so constants would be silently dropped
Constructor arguments of enum constants reuse the AnnotationMember model: raw source expressions plus typed references (class/enum constants) whose imports are collected and which are qualified on simple-name collisions — the same semantics as annotation members. RoasterMapper.mapAnnotationMemberValue gained an overload for bare value expressions shared by both rendering paths.
| switch (target.getKind()) { | ||
| case INTERFACE -> { | ||
| rejectIfNotEmpty( | ||
| target.getConstructors(), | ||
| "Interface '%s' declares constructors, but interfaces cannot have constructors"); | ||
| rejectIfNotEmpty( | ||
| target.getClassFields(), | ||
| "Interface '%s' declares fields, but fields on interfaces are implicit constants" | ||
| + " and cannot be generated as declared"); | ||
| rejectIfNotNull( | ||
| target.getSuperType(), | ||
| "Interface '%s' declares a super type, but interfaces can only extend interfaces" | ||
| + " via the interfaces list"); | ||
| } | ||
| case ENUM -> { | ||
| rejectIfNotEmpty( | ||
| target.getGenerics(), | ||
| "Enum '%s' declares generic parameters, but enums cannot be generic"); | ||
| rejectIfNotNull( | ||
| target.getSuperType(), | ||
| "Enum '%s' declares a super type, but enums implicitly extend java.lang.Enum"); | ||
| } | ||
| case RECORD -> { | ||
| validateRecordComponents(target.getClassFields(), target.getTypeName().getClassName()); | ||
| rejectIfNotNull( | ||
| target.getSuperType(), | ||
| "Record '%s' declares a super type, but records implicitly extend java.lang.Record"); | ||
| } | ||
| case ANNOTATION_TYPE -> { | ||
| rejectIfNotEmpty( | ||
| target.getConstructors(), | ||
| "Annotation type '%s' declares constructors, but annotation types cannot have constructors"); | ||
| rejectIfNotEmpty( | ||
| target.getClassFields(), | ||
| "Annotation type '%s' declares fields, but fields are not supported on annotation types"); | ||
| rejectIfNotEmpty( | ||
| target.getGenerics(), | ||
| "Annotation type '%s' declares generic parameters, but annotation types cannot be generic"); | ||
| rejectIfNotNull( | ||
| target.getSuperType(), | ||
| "Annotation type '%s' declares a super type, but annotation types cannot extend types"); | ||
| rejectIfNotEmpty( | ||
| target.getInterfaces(), | ||
| "Annotation type '%s' declares interfaces, but annotation types cannot implement interfaces"); | ||
| } |
There was a problem hiding this comment.
Looking at this, the correct implementation with inheritance of builder is wrong. On builder for interfaces for example there should be no field helper function.
There was a problem hiding this comment.
Agreed — inheritance is replaced by composition: the four kind builders no longer extend GenerationTargetClassDtoBuilder. They compose it and expose only the delegate methods legal for their kind — the interface builder has no field/constructor/superType helpers at all, the enum builder no generics/superType, the record builder no superType, the annotation builder none of these and no interfaces. As a bonus, chaining now keeps the specialized type everywhere. The illegal-state validation tests construct their fixtures through the mutable DTO directly, since the builders rightly can't express them anymore.
| if (field.getLiteralInitializer() != null) { | ||
| addViolation( |
There was a problem hiding this comment.
Yes — aligned: null checks now use rejectIfNotNull, collection checks rejectIfNotEmpty (and the nested variants).
| } | ||
|
|
||
| private void validateMisplacedKindMembers() { | ||
| if (!target.getEnumConstants().isEmpty()) { |
There was a problem hiding this comment.
Done — the nested generics check uses rejectNestedIfNotEmpty now.
| nestedName); | ||
| } | ||
| case ENUM -> { | ||
| if (!nestedType.getGenericParameters().isEmpty()) { |
There was a problem hiding this comment.
Done — aligned on the reject helpers.
| "Nested annotation type '%s' in %s declares fields, but fields are not supported on" | ||
| + " annotation types", | ||
| nestedName); | ||
| if (!nestedType.getGenericParameters().isEmpty()) { |
There was a problem hiding this comment.
Done — aligned on the reject helpers here as well.
| CodeGenerationException exception = | ||
| assertThrows( | ||
| CodeGenerationException.class, | ||
| () -> |
There was a problem hiding this comment.
Having a helper function so that it could be assertFailsValidationWithMessage("message", GenerationTargetBuilder.build())
There was a problem hiding this comment.
Added — assertFailsValidationWithMessage(expectedMessage, target) and all single-message tests use it. One exception: allViolationsCollectedInOneException keeps the manual form since it asserts two fragments (documented in the test).
| var enumTarget = | ||
| GenerationTargetClassDtoBuilder.createEnum().typeName("com.example", "E").build(); | ||
| org.junit.jupiter.api.Assertions.assertEquals( | ||
| org.javahelpers.codegen.model.type.TypeKind.ENUM, enumTarget.getKind()); | ||
| var interfaceTarget = | ||
| GenerationTargetClassDtoBuilder.createInterface().typeName("com.example", "I").build(); | ||
| org.junit.jupiter.api.Assertions.assertEquals( | ||
| org.javahelpers.codegen.model.type.TypeKind.INTERFACE, interfaceTarget.getKind()); | ||
| var recordTarget = | ||
| GenerationTargetClassDtoBuilder.createRecord().typeName("com.example", "R").build(); | ||
| org.junit.jupiter.api.Assertions.assertEquals( | ||
| org.javahelpers.codegen.model.type.TypeKind.RECORD, recordTarget.getKind()); | ||
| var annotationTarget = | ||
| GenerationTargetClassDtoBuilder.createAnnotationType().typeName("com.example", "A").build(); | ||
| org.junit.jupiter.api.Assertions.assertEquals( | ||
| org.javahelpers.codegen.model.type.TypeKind.ANNOTATION_TYPE, annotationTarget.getKind()); |
There was a problem hiding this comment.
Remove full package names
There was a problem hiding this comment.
Removed — simple names with imports throughout the test.
| if (nestedSource instanceof JavaEnumSource enumSource) { | ||
| for (String constant : nestedType.getEnumConstants()) { | ||
| enumSource.addEnumConstant(constant); | ||
| } | ||
| } | ||
| if (nestedSource instanceof JavaRecordSource recordSource) { | ||
| for (var component : nestedType.getRecordComponents()) { | ||
| recordSource.addRecordComponent( | ||
| RoasterMapper.mapType(component.getParameterType(), collidingSimpleNames), | ||
| component.getParameterName()); | ||
| } | ||
| if (!nestedType.getClassFields().isEmpty()) { | ||
| // instance fields are illegal in records, so any declared field would have to be static — | ||
| // but Roaster cannot render static fields in records yet | ||
| throw new UnsupportedOperationException( | ||
| ("Nested record '%s' declares fields, but Roaster does not support static fields in" | ||
| + " records yet — see https://github.com/forge/roaster/issues/279") | ||
| .formatted(nestedType.getTypeName())); | ||
| } | ||
| if (!nestedType.getConstructors().isEmpty()) { | ||
| // Roaster does not support compact constructors | ||
| // (https://github.com/forge/roaster/issues/275); | ||
| // they are rendered as regular canonical constructors instead — the workaround is source- | ||
| // compatible since a compact constructor is just syntactic sugar for the canonical one | ||
| logger.debug( | ||
| "Nested record '%s' declares constructors: rendered as regular canonical constructors" | ||
| + " because Roaster does not support compact constructors" | ||
| + " (https://github.com/forge/roaster/issues/275)", | ||
| nestedType.getTypeName()); | ||
| } |
There was a problem hiding this comment.
But why not directly call that in the switch case instead of doing it afterwards in an instance of check?
| constructor.getParameters().isEmpty() | ||
| ? nestedType.getClassFields().stream() | ||
| .map( | ||
| field -> { | ||
| MethodParameterDto param = new MethodParameterDto(); | ||
| param.setParameterName(field.getFieldName()); | ||
| param.setParameterTypeName(field.getFieldType()); | ||
| return param; | ||
| }) | ||
| .toList() | ||
| : constructor.getParameters(); |
There was a problem hiding this comment.
I thought we decided not to have a constructor with all fields generated!
There was a problem hiding this comment.
Nothing is generated unless declared: the auto-completion only fills the parameters of a constructor that IS in the constructors list — that's the compact-constructor semantics you asked for ('could that not be done for the constructor with all fields?'). A record with no constructors gets no constructor output at all. If you'd rather drop the auto-completion and render declared constructors exactly as declared, say so and I'll simplify.
| Set<String> collidingSimpleNames) { | ||
| for (MethodDto methodDto : nestedType.getMethods()) { | ||
| appendNestedMethod(nestedSource, methodDto, isInterface, collidingSimpleNames); | ||
| org.jboss.forge.roaster.model.source.AnnotationElementSource element = |
There was a problem hiding this comment.
Again here and on other places full package names
There was a problem hiding this comment.
Removed — all roaster source types use simple names with imports now.
… names - nested kind validation aligned on rejectNestedIfNotEmpty - DtoBuilderCopyTest: enum constant added through the mutable DTO (superType on an enum is not a legal combination) - validator tests: assertFailsValidationWithMessage helper, simple names instead of full packages - RoasterCodeGenerator: simple names for roaster source types
The specialized builders no longer extend GenerationTargetClassDtoBuilder: they compose it and expose only the delegate methods that are legal for their kind. Interfaces have no field/constructor/superType helpers, enums no generics/superType, records no superType, annotation types none of these and no interfaces. enumConstant/recordComponent remain on their kind builders. Negative validation tests construct illegal state through the mutable DTO.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
conditional() now passes the specialized builder to its consumers instead of the base builder, so illegal helpers are not reachable inside conditional lambdas either.
Getters return an unmodifiable view; builder application uses the addEnumConstant mutator instead of mutating through the getter
Strict reviewblocking Reviewed head
Verification
Other-PR integration review
Recheck at
|
| # | Original finding (short) | Status | Remaining action |
|---|---|---|---|
| 1 | Enum fields/constructors dropped | fixed | — |
| 2 | Compact-record assignments lost | fixed; regression missing — minor | Compile a compact-emulation constructor, including component reassignment (NestedTypeKindGenerationTest.java:92–121,283–298). |
| 3 | Generic-record crash | Roaster backend gap — should be emulated in RoasterCodeGenerator like compact constructors | Track/emulate generic headers in the backend (RoasterCodeGenerator.java:430–435); do not restrict the general model/validator. |
| 4 | Invalid/lost annotation-element state | partially fixed — major | Validator must reject void returns and generic element methods: invalid Java for every backend (GenerationTargetValidator.java:288–300). |
| 5 | Top-level kinds silently become classes | fixed | — |
| 6 | Test-source string convention | partially fixed — nit | Replace diagnostic concatenation with a formatted text block (NestedTypeKindGenerationTest.java:325–329). |
| N1 | Literal %s in diagnostics |
open — minor | Format the complete message and assert its values (RoasterCodeGenerator.java:166–169,432–435). |
| N2 | Annotation-fix regressions missing | open — minor | Test parameter rejection and preserved annotation/Javadoc metadata (RoasterCodeGenerator.java:574–582). |
| N3 | Wrong generic-record issue link | open — minor | Correct the link at RoasterCodeGenerator.java:432–435: forge/roaster#275 concerns compact constructors, not generics. |
Build: Java 17 module install — BUILD SUCCESS; 1,397 tests, 0 failures/errors; void annotation probe still fails javac, generic element state is still dropped, generic records are rejected by Roaster.
Recheck at 0160611c (2026-12-06)
Verdict: changes needed
| Severity | What is missing | Where (file:line) |
|---|---|---|
| major (backend) | N1: Scope generic-record injection to declarations: valid return "record Box"; becomes return "record Box<T>"; (compiled probe). |
RoasterCodeGenerator.java:599–605 |
…roaster gap), compact-constructor component assignments
…lement metadata, validate element shapes and record generics
…ted for constructor-binding constants
The validator stays generator-agnostic: other future generators may support generic records. RoasterCodeGenerator now raises a generation error for nested records with generic parameters (roaster limitation, forge/roaster#275). Also drops the isFinal usage in the enum test (modifier modeling belongs to java-helpers#498).
|
Strict-review follow-up plus review feedback in 8774484:
Verified: 358 core + 94 roaster tests green. |
…record sources Both probes compile the generated source with the system compiler and fail with full diagnostics: the enum with constructor-binding constants (fields and constructor assignments present) and the record component generation.
|
Strict-review leftovers done: the nit (compact-constructor body fixture as text block) and the compile-probe regression tests — both the constructor-binding enum and the record generation now compile the generated source with the system compiler and fail with full diagnostics on regression. 10/10 green. |
… validator - Generic nested records: instead of a generation error, the generic header is now emulated — injected into the rendered record declaration, since Roaster's JavaRecordSource cannot model type variables. Emulated records compile. - Compact-constructor emulation: the canonical rendering inherits the record's access modifier (compact constructors do implicitly), fixing javac's 'invalid canonical constructor' rejection; regression test compiles the emulated constructor including component reassignment - Validator rejects void/missing-return and generic annotation elements at top level and nested — illegal Java shapes for every backend - Annotation element metadata: regression test proves javadoc and annotations survive rendering; nested element parameter rejection test added - Literal-%s diagnostic fixed (formatted bound only the second concatenated literal); diagnostic concatenation converted to a text block
|
Recheck items addressed:
All green: validator 44/44, roaster incl. 11/11 kind tests. |
…omplexity (S3776) - appendAnnotationElements javadoc was orphaned by the header-injection insertion - appendNestedType no longer declares CodeGenerationException (nothing throws it) - kind-specific source creation and member appending extracted into helpers
- appendNestedTypes no longer declares CodeGenerationException (S1130) - appendNestedMembers split further: shared fields/constructors loop extracted with generic holder bounds, annotation-element/method split separated (S3776)
|



Part of #489 — stage 1.
In this stage:
TypeKindenum (CLASS/INTERFACE/ENUM/RECORD/ANNOTATION_TYPE);GenerationTargetClassDto.kinddefaults to CLASS — no behavioral change for existing consumersNestedTypeKindextended with ENUM/RECORD/ANNOTATION_TYPEGenerationTargetClassDtoBuilder:createInterface(),createEnum(),createRecord(),createAnnotationType()GenerationTargetValidatorfor target and nested types:Deliberately not in this stage (follow-up on the same issue):
JavaClassSourceend to end (fields/constructors/methods/metadata appenders) — generalizing it toJavaSource<?>with per-kind capability handling is a bigger refactor that deserves its own reviewable change