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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion deconstructors.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ A deconstructor is either:
- is annotated with `@RecordBuilder.Deconstructor`
2. a class or interface that is:
- annotated with `@RecordBuilder.Deconstructor`
- has one or more accessor methods annotated with `@RecordBuilder.DeconstructorAccessor`
- has one or more accessor methods or fields annotated with `@RecordBuilder.DeconstructorAccessor`. If it is
a field that is annotated, there must be a matching public, non-static method that is named either the same as the field
or is prefixed with `get` or `is`.

When RecordBuilder encounters a deconstructor it generates a `record` that matches the deconstructor's parameters
and, optionally, creates a record builder for it.
Expand Down
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
<javax-el-version>3.0.1-b09</javax-el-version>
<central-publishing-maven-plugin-version>0.7.0</central-publishing-maven-plugin-version>
<jspecify-version>1.0.0</jspecify-version>
<lombok-version>1.18.42</lombok-version>
</properties>

<name>Record Builder</name>
Expand Down Expand Up @@ -177,6 +178,12 @@
<artifactId>jspecify</artifactId>
<version>${jspecify-version}</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok-version}</version>
</dependency>
</dependencies>
</dependencyManagement>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ enum ConcreteSettersForOptionalMode {
}

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Inherited
@interface DeconstructorAccessor {
/**
Expand All @@ -457,7 +457,8 @@ enum ConcreteSettersForOptionalMode {

/**
* The order of the component in the generated record. Components are ordered by this value (lowest to highest).
* Components with the same order value are then ordered alphabetically by component name.
* Components with the same order value are then ordered alphabetically by component name. Note: if
* {@code order()} is the default value, the order in which it occurs in the class is used.
*/
int order() default Integer.MAX_VALUE;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@

import static io.soabase.recordbuilder.processor.ElementUtils.generateName;
import static io.soabase.recordbuilder.processor.ElementUtils.hasAnnotationTarget;
import static io.soabase.recordbuilder.processor.InternalRecordBuilderProcessor.capitalize;
import static io.soabase.recordbuilder.processor.ParameterSpecUtil.createParameterSpec;
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.generatedRecordBuilderAnnotation;
import static io.soabase.recordbuilder.processor.RecordBuilderProcessor.recordBuilderGeneratedAnnotation;
Expand Down Expand Up @@ -145,60 +146,124 @@ private void addVisibility(Set<Modifier> modifiers) {
// is package-private
}

private List<RecordClassType> buildRecordComponents(TypeElement typeElement) {
List<RecordClassType> components = typeElement.getEnclosedElements().stream()
private static boolean isGetter(Name methodName, Name fieldName) {
return methodName.equals(fieldName) || methodName.toString().equals("get" + capitalize(fieldName.toString()))
|| methodName.toString().equals("is" + capitalize(fieldName.toString()));
}

private List<ExecutableElement> methodsInClass(TypeElement typeElement) {
return typeElement.getEnclosedElements().stream()
.flatMap(e -> (e.getKind() == ElementKind.METHOD) ? Stream.of((ExecutableElement) e) : Stream.empty())
.flatMap(executableElement -> {
DeconstructorAccessor deconstructorAccessor = executableElement
.getAnnotation(DeconstructorAccessor.class);
if (deconstructorAccessor == null) {
return Stream.empty();
}
.toList();
}

if (!executableElement.getModifiers().contains(Modifier.PUBLIC)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@DeconstructorAccessor methods must be public.", executableElement);
return Stream.empty();
}
private List<RecordClassType> buildRecordComponents(TypeElement typeElement) {
List<ExecutableElement> methods = methodsInClass(typeElement);

boolean isARecord = typeElement.getKind() == ElementKind.RECORD;

var accessorOrdinal = new Object() {
int value;
};
List<RecordClassType> components = typeElement.getEnclosedElements().stream().flatMap(element -> {
DeconstructorAccessor deconstructorAccessor = element.getAnnotation(DeconstructorAccessor.class);
if (deconstructorAccessor == null) {
return Stream.empty();
}

ExecutableElement executableElement;

if (element.getKind() == ElementKind.METHOD) {
executableElement = (ExecutableElement) element;
} else if (element.getKind() == ElementKind.FIELD) {
if (isARecord) {
return Stream.empty();
}

List<ExecutableElement> candidateGetters = methods.stream()
.filter(method -> method.getModifiers().contains(Modifier.PUBLIC)
&& !method.getModifiers().contains(Modifier.STATIC))
.filter(method -> processingEnv.getTypeUtils().isSameType(method.getReturnType(),
element.asType()))
.filter(method -> isGetter(method.getSimpleName(), element.getSimpleName())).toList();

if (candidateGetters.isEmpty()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"No public getter method found for field annotated with @DeconstructorAccessor: %s"
.formatted(element.getSimpleName()),
element);
return Stream.empty();
} else if (candidateGetters.size() > 1) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Multiple public getter methods found for field annotated with @DeconstructorAccessor: %s. %s"
.formatted(element.getSimpleName(), candidateGetters.stream()
.map(ExecutableElement::getSimpleName).collect(Collectors.joining(", "))),
element);
return Stream.empty();
}

executableElement = candidateGetters.get(0);
} else {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@DeconstructorAccessor can only be applied to methods or fields.", element);
return Stream.empty();
}

if (executableElement.getModifiers().contains(Modifier.STATIC)) {
if (!executableElement.getModifiers().contains(Modifier.PUBLIC)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@DeconstructorAccessor methods must be public.", executableElement);
return Stream.empty();
}

if (executableElement.getModifiers().contains(Modifier.STATIC)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@DeconstructorAccessor only valid for non-static methods.", executableElement);
return Stream.empty();
}

if (!executableElement.getParameters().isEmpty()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@DeconstructorAccessor methods cannot have parameters.", executableElement);
return Stream.empty();
}

TypeName typeName = TypeName.get(executableElement.getReturnType());
TypeName rawTypeName = TypeName
.get(processingEnv.getTypeUtils().erasure(executableElement.getReturnType()));

String name;
if (deconstructorAccessor.name().isEmpty()) {
name = executableElement.getSimpleName().toString();
if (!deconstructorAccessor.prefixPattern().isEmpty()) {
try {
name = extractAndLowercase(Pattern.compile(deconstructorAccessor.prefixPattern()), name);
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@DeconstructorAccessor only valid for non-static methods.", executableElement);
return Stream.empty();
"Invalid prefix pattern: " + deconstructorAccessor.prefixPattern(), element);
}
}
} else {
name = deconstructorAccessor.name();
}

TypeName typeName = TypeName.get(executableElement.getReturnType());
TypeName rawTypeName = TypeName
.get(processingEnv.getTypeUtils().erasure(executableElement.getReturnType()));

String name;
if (deconstructorAccessor.name().isEmpty()) {
name = executableElement.getSimpleName().toString();
if (!deconstructorAccessor.prefixPattern().isEmpty()) {
try {
name = extractAndLowercase(Pattern.compile(deconstructorAccessor.prefixPattern()),
name);
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Invalid prefix pattern: " + deconstructorAccessor.prefixPattern(), element);
}
}
} else {
name = deconstructorAccessor.name();
}
List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors().stream()
.filter(annotation -> !annotation.getAnnotationType().asElement().getSimpleName().toString()
.equals(DeconstructorAccessor.class.getSimpleName()))
.toList();
var type = new RecordClassType(typeName, rawTypeName, name, executableElement.getSimpleName().toString(),
annotationMirrors, List.of());

int order = deconstructorAccessor.order();
if (order == Integer.MAX_VALUE) {
order = accessorOrdinal.value++;
}

List<? extends AnnotationMirror> annotationMirrors = executableElement.getAnnotationMirrors()
.stream().filter(annotation -> !annotation.getAnnotationType().asElement().getSimpleName()
.toString().equals(DeconstructorAccessor.class.getSimpleName()))
.toList();
var type = new RecordClassType(typeName, rawTypeName, name,
executableElement.getSimpleName().toString(), annotationMirrors, List.of());
var orderedType = Map.entry(deconstructorAccessor.order(), type);
return Stream.of(orderedType);
}).sorted((o1, o2) -> {
int diff = o1.getKey().compareTo(o2.getKey());
return (diff == 0) ? o1.getValue().name().compareTo(o2.getValue().name()) : diff;
}).map(Map.Entry::getValue).toList();
var orderedType = Map.entry(order, type);
return Stream.of(orderedType);
}).sorted((o1, o2) -> {
int diff = o1.getKey().compareTo(o2.getKey());
return (diff == 0) ? o1.getValue().name().compareTo(o2.getValue().name()) : diff;
}).map(Map.Entry::getValue).toList();

if (components.isEmpty()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -955,7 +955,7 @@ private void addAccessorAnnotations(RecordClassType component, MethodSpec.Builde
}
}

private String capitalize(String s) {
public static String capitalize(String s) {
return (s.length() < 2) ? s.toUpperCase(Locale.ROOT) : (Character.toUpperCase(s.charAt(0)) + s.substring(1));
}

Expand Down
10 changes: 10 additions & 0 deletions record-builder-test/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@
<artifactId>record-builder-validator</artifactId>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
Expand Down Expand Up @@ -93,6 +98,11 @@
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok-version}</version>
</path>
<path>
<groupId>io.soabase.record-builder</groupId>
<artifactId>record-builder-processor</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2019 The original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.soabase.recordbuilder.test.deconstructors;

import io.soabase.recordbuilder.core.RecordBuilder.Deconstructor;
import io.soabase.recordbuilder.core.RecordBuilder.DeconstructorAccessor;
import lombok.Getter;
import lombok.experimental.Accessors;

@Deconstructor
@Getter
@Accessors(fluent = true)
public class LombokTest {
@DeconstructorAccessor
private final int qty;

@DeconstructorAccessor
private final String name;

public LombokTest(int qty, String name) {
this.qty = qty;
this.name = name;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2019 The original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.soabase.recordbuilder.test.deconstructors;

import io.soabase.recordbuilder.core.RecordBuilder.Deconstructor;
import io.soabase.recordbuilder.core.RecordBuilder.DeconstructorAccessor;
import lombok.Getter;

@Deconstructor
@Getter
public class LombokTest2 {
@DeconstructorAccessor
private final int qty;

@DeconstructorAccessor
private final String name;

public LombokTest2(int qty, String name) {
this.qty = qty;
this.name = name;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright 2019 The original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.soabase.recordbuilder.test.deconstructors;

import io.soabase.recordbuilder.core.RecordBuilder.Deconstructor;
import io.soabase.recordbuilder.core.RecordBuilder.DeconstructorAccessor;

@Deconstructor
public record RecordTest(@DeconstructorAccessor int a, @DeconstructorAccessor String b) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,24 @@ public class TestAccessors {
@Test
public void testAccessors() {
AccessorTest accessorTest = AccessorTest.create("hey", 42);
assertThat(AccessorTestDao(42, "hey")).isEqualTo(AccessorTestDao.from(accessorTest));
assertThat(AccessorTestDao("hey", 42)).isEqualTo(AccessorTestDao.from(accessorTest));
}

@Test
public void testAccessorsNoBuilder() {
AccessorTestNoBuilder accessorTest = new AccessorTestNoBuilder("hey", 42);
assertThat(new AccessorTestNoBuilderDao(42, "hey")).isEqualTo(AccessorTestNoBuilderDao.from(accessorTest));
assertThat(new AccessorTestNoBuilderDao("hey", 42)).isEqualTo(AccessorTestNoBuilderDao.from(accessorTest));
}

@Test
public void testLombok() {
LombokTest lombokTest = new LombokTest(42, "hey");
assertThat(new LombokTestDao(42, "hey")).isEqualTo(LombokTestDao.from(lombokTest));
}

@Test
public void testLombok2() {
LombokTest2 lombokTest = new LombokTest2(42, "hey");
assertThat(new LombokTest2Dao(42, "hey")).isEqualTo(LombokTest2Dao.from(lombokTest));
}
}