Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HackWeek] Generated builders understand default field values from IR #2338

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
buildscript {
repositories {
mavenCentral() { metadataSources { mavenPom(); ignoreGradleMetadataRedirection() } }
mavenLocal() { metadataSources { mavenPom(); ignoreGradleMetadataRedirection() } }
gradlePluginPortal() { metadataSources { mavenPom(); ignoreGradleMetadataRedirection() } }
}

Expand Down Expand Up @@ -56,6 +57,7 @@ allprojects {

repositories {
mavenCentral() { metadataSources { mavenPom(); ignoreGradleMetadataRedirection() } }
mavenLocal() { metadataSources { mavenPom(); ignoreGradleMetadataRedirection() } }
}

configurations.all {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import com.palantir.conjure.java.util.TypeFunctions;
import com.palantir.conjure.java.visitor.DefaultPrimitiveTypeVisitor;
import com.palantir.conjure.java.visitor.DefaultTypeVisitor;
import com.palantir.conjure.java.visitor.DefaultValueCodeBlockExtractor;
import com.palantir.conjure.java.visitor.DefaultableTypeVisitor;
import com.palantir.conjure.java.visitor.MoreVisitors;
import com.palantir.conjure.spec.ExternalReference;
Expand Down Expand Up @@ -151,7 +152,8 @@ public static void addStagedBuilder(

public static boolean stagedBuilderFieldShouldBeInFinalStage(EnrichedField field) {
Type type = field.conjureDef().getType();
return type.accept(TypeVisitor.IS_LIST)
return field.hasDefault()
|| type.accept(TypeVisitor.IS_LIST)
|| type.accept(TypeVisitor.IS_SET)
|| type.accept(TypeVisitor.IS_MAP)
|| type.accept(TypeVisitor.IS_OPTIONAL);
Expand Down Expand Up @@ -458,8 +460,9 @@ private TypeSpec generateBuilderImplementation(
}

private Collection<MethodSpec> maybeCreateValidateFieldsMethods(Collection<EnrichedField> enrichedFields) {
List<EnrichedField> primitives =
enrichedFields.stream().filter(EnrichedField::isPrimitive).collect(Collectors.toList());
List<EnrichedField> primitives = enrichedFields.stream()
.filter(BeanBuilderGenerator::isUninitializedPrimitive)
.collect(Collectors.toList());

if (primitives.isEmpty()) {
return Collections.emptyList();
Expand Down Expand Up @@ -520,7 +523,7 @@ private static MethodSpec createAddFieldIfMissing(int fieldCount) {

private Collection<FieldSpec> primitivesInitializedFields(Collection<EnrichedField> enrichedFields) {
return enrichedFields.stream()
.filter(EnrichedField::isPrimitive)
.filter(BeanBuilderGenerator::isUninitializedPrimitive)
.map(field -> FieldSpec.builder(TypeName.BOOLEAN, deriveFieldInitializedName(field), Modifier.PRIVATE)
.initializer("false")
.build())
Expand Down Expand Up @@ -561,7 +564,12 @@ private EnrichedField createField(FieldName fieldName, FieldDefinition field) {
TypeName typeName =
ConjureAnnotations.withSafety(typeMapper.getClassName(type), safetyEvaluator.getUsageTimeSafety(field));
FieldSpec.Builder spec = FieldSpec.builder(typeName, JavaNameSanitizer.sanitize(fieldName), Modifier.PRIVATE);
if (type.accept(TypeVisitor.IS_LIST) || type.accept(TypeVisitor.IS_SET)) {

if (field.getDefault().isPresent()) {
spec.initializer(field.getDefault()
.get()
.accept(new DefaultValueCodeBlockExtractor(type, asRawType(typeMapper.getClassName(type)))));
} else if (type.accept(TypeVisitor.IS_LIST) || type.accept(TypeVisitor.IS_SET)) {
CollectionType collectionType = getCollectionType(type);
if (collectionType.useNonNullFactory()) {
spec.initializer(
Expand Down Expand Up @@ -647,7 +655,7 @@ private MethodSpec createSetter(
.addCode(verifyNotBuilt())
.addCode(typeAwareAssignment(enriched, type, shouldClearFirst));

if (enriched.isPrimitive()) {
if (isUninitializedPrimitive(enriched)) {
setterBuilder.addCode("this.$L = true;", deriveFieldInitializedName(enriched));
}

Expand Down Expand Up @@ -821,12 +829,16 @@ private CodeBlock optionalAssignmentStatement(EnrichedField enriched, OptionalTy
EnumSet.of(PrimitiveType.Value.INTEGER, PrimitiveType.Value.DOUBLE, PrimitiveType.Value.BOOLEAN);

/** Check if the optionalType contains a primitive boolean, double or integer. */
private boolean isPrimitiveOptional(OptionalType optionalType) {
private static boolean isPrimitiveOptional(OptionalType optionalType) {
return optionalType.getItemType().accept(TypeVisitor.IS_PRIMITIVE)
&& OPTIONAL_PRIMITIVES.contains(
optionalType.getItemType().accept(TypeVisitor.PRIMITIVE).get());
}

private static boolean isUninitializedPrimitive(EnrichedField field) {
return field.isPrimitive() && !field.hasDefault();
}

private MethodSpec createItemSetter(
EnrichedField enriched, Type itemType, boolean override, Optional<LogSafety> safety) {
FieldSpec field = enriched.poetSpec();
Expand Down Expand Up @@ -864,7 +876,7 @@ private MethodSpec createBuild(
.addCode(verifyNotBuilt())
.addStatement("this.$N = true", BUILT_FIELD);

if (enrichedFields.stream().anyMatch(EnrichedField::isPrimitive)) {
if (enrichedFields.stream().anyMatch(BeanBuilderGenerator::isUninitializedPrimitive)) {
method.addStatement("validatePrimitiveFieldsHaveBeenInitialized()");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,11 @@ default boolean isPrimitive() {
return Primitives.isPrimitive(poetSpec().type);
}

@Value.Derived
default boolean hasDefault() {
return conjureDef().getDefault().isPresent();
}

static EnrichedField of(FieldName fieldName, FieldDefinition conjureDef, FieldSpec poetSpec) {
return ImmutableEnrichedField.of(fieldName, conjureDef, poetSpec);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* (c) Copyright 2024 Palantir Technologies Inc. All rights reserved.
*
* 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 com.palantir.conjure.java.visitor;

import com.palantir.conjure.java.lib.SafeLong;
import com.palantir.conjure.spec.DefaultValue;
import com.palantir.conjure.spec.Type;
import com.palantir.conjure.visitor.TypeVisitor;
import com.palantir.logsafe.Safe;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.exceptions.SafeIllegalStateException;
import com.palantir.ri.ResourceIdentifier;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.TypeName;
import java.util.UUID;

public final class DefaultValueCodeBlockExtractor implements DefaultValue.Visitor<CodeBlock> {
private final Type expectedType;
private final TypeName expectedClass;

public DefaultValueCodeBlockExtractor(Type expectedType, TypeName expectedClass) {
this.expectedType = expectedType;
this.expectedClass = expectedClass;
}

@Override
public CodeBlock visitEnum(String value) {
validateTypeSafety(expectedType.accept(TypeVisitor.IS_REFERENCE));
return CodeBlock.of("$1T.valueOf($2S)", expectedClass, value);
}

@Override
public CodeBlock visitString(String value) {
validateTypeSafety(expectedType.accept(TypeVisitor.IS_PRIMITIVE)
&& expectedType.accept(TypeVisitor.PRIMITIVE).accept(PrimitiveTypeVisitor.IS_STRING));
return CodeBlock.of("$S", value);
}

@Override
public CodeBlock visitInteger(int value) {
validateTypeSafety(expectedType.accept(TypeVisitor.IS_PRIMITIVE)
&& expectedType.accept(TypeVisitor.PRIMITIVE).accept(PrimitiveTypeVisitor.IS_INTEGER));
return CodeBlock.of("$L", value);
}

@Override
public CodeBlock visitDouble(double value) {
validateTypeSafety(expectedType.accept(TypeVisitor.IS_PRIMITIVE)
&& expectedType.accept(TypeVisitor.PRIMITIVE).accept(PrimitiveTypeVisitor.IS_DOUBLE));
return CodeBlock.of("$L", value);
}

@Override
public CodeBlock visitSafelong(SafeLong value) {
validateTypeSafety(expectedType.accept(TypeVisitor.IS_PRIMITIVE)
&& expectedType.accept(TypeVisitor.PRIMITIVE).accept(PrimitiveTypeVisitor.IS_SAFELONG));
return CodeBlock.of("$LL", value.longValue());
}

@Override
public CodeBlock visitBoolean(boolean value) {
validateTypeSafety(expectedType.accept(TypeVisitor.IS_PRIMITIVE)
&& expectedType.accept(TypeVisitor.PRIMITIVE).accept(PrimitiveTypeVisitor.IS_BOOLEAN));
return CodeBlock.of("$L", value);
}

@Override
public CodeBlock visitUuid(UUID value) {
validateTypeSafety(expectedType.accept(TypeVisitor.IS_PRIMITIVE)
&& expectedType.accept(TypeVisitor.PRIMITIVE).accept(PrimitiveTypeVisitor.IS_UUID));
return CodeBlock.of("$1T.fromString($2S)", UUID.class, value.toString());
}

@Override
public CodeBlock visitRid(ResourceIdentifier value) {
validateTypeSafety(expectedType.accept(TypeVisitor.IS_PRIMITIVE)
&& expectedType.accept(TypeVisitor.PRIMITIVE).accept(PrimitiveTypeVisitor.IS_RID));
return CodeBlock.of("$1T.of($2S)", ResourceIdentifier.class, value.toString());
}

@Override
public CodeBlock visitUnknown(@Safe String unknownType) {
throw new SafeIllegalStateException("Encountered unknown type", SafeArg.of("type", unknownType));
}

private static void validateTypeSafety(boolean typesMatch) {
if (!typesMatch) {
throw new SafeIllegalStateException("Encountered default value that does not match its field type");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* (c) Copyright 2024 Palantir Technologies Inc. All rights reserved.
*
* 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 com.palantir.conjure.java.visitor;

public final class PrimitiveTypeVisitor {
private PrimitiveTypeVisitor() {}

public static final IsStringVisitor IS_STRING = new IsStringVisitor();
public static final IsIntegerVisitor IS_INTEGER = new IsIntegerVisitor();
public static final IsDoubleVisitor IS_DOUBLE = new IsDoubleVisitor();
public static final IsSafeLongVisitor IS_SAFELONG = new IsSafeLongVisitor();
public static final IsBooleanVisitor IS_BOOLEAN = new IsBooleanVisitor();
public static final IsUuidVisitor IS_UUID = new IsUuidVisitor();
public static final IsRidVisitor IS_RID = new IsRidVisitor();

private static final class IsStringVisitor extends IsPrimitiveTypeVisitor {
@Override
public Boolean visitString() {
return true;
}
}

private static final class IsIntegerVisitor extends IsPrimitiveTypeVisitor {
@Override
public Boolean visitInteger() {
return true;
}
}

private static final class IsDoubleVisitor extends IsPrimitiveTypeVisitor {
@Override
public Boolean visitDouble() {
return true;
}
}

private static final class IsSafeLongVisitor extends IsPrimitiveTypeVisitor {
@Override
public Boolean visitSafelong() {
return true;
}
}

private static final class IsBooleanVisitor extends IsPrimitiveTypeVisitor {
@Override
public Boolean visitBoolean() {
return true;
}
}

private static final class IsUuidVisitor extends IsPrimitiveTypeVisitor {
@Override
public Boolean visitUuid() {
return true;
}
}

private static final class IsRidVisitor extends IsPrimitiveTypeVisitor {
@Override
public Boolean visitRid() {
return true;
}
}

private static class IsPrimitiveTypeVisitor extends DefaultPrimitiveTypeVisitor<Boolean> {
@Override
public Boolean visitDefault() {
return false;
}
}
}
30 changes: 15 additions & 15 deletions versions.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,25 @@
com.atlassian.commonmark:commonmark:0.12.1 (1 constraints: 36052a3b)
com.fasterxml.jackson.core:jackson-annotations:2.17.2 (24 constraints: 62955713)
com.fasterxml.jackson.core:jackson-core:2.17.2 (22 constraints: 25c16b02)
com.fasterxml.jackson.core:jackson-databind:2.17.2 (35 constraints: f79a74f7)
com.fasterxml.jackson.core:jackson-databind:2.17.2 (35 constraints: ff9a7b18)
com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:2.17.2 (4 constraints: e9653a50)
com.fasterxml.jackson.dataformat:jackson-dataformat-smile:2.17.2 (1 constraints: 811ca2a4)
com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2 (3 constraints: 3b25da0f)
com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2 (3 constraints: 3f25a410)
com.fasterxml.jackson.datatype:jackson-datatype-guava:2.17.2 (3 constraints: f839a026)
com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.17.2 (4 constraints: 2c3f6790)
com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.17.2 (4 constraints: 303f5192)
com.fasterxml.jackson.datatype:jackson-datatype-joda:2.17.2 (2 constraints: 322b47b0)
com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.17.2 (2 constraints: 322b47b0)
com.github.ben-manes.caffeine:caffeine:3.1.8 (10 constraints: 63b008f3)
com.google.auto:auto-common:1.2.2 (2 constraints: 1d175731)
com.google.code.findbugs:jsr305:3.0.2 (35 constraints: b94940f6)
com.google.errorprone:error_prone_annotations:2.7.1 (27 constraints: aec23fbb)
com.google.errorprone:error_prone_annotations:2.7.1 (27 constraints: b5c2e9d8)
com.google.guava:failureaccess:1.0.2 (1 constraints: 150ae2b4)
com.google.guava:guava:33.2.0-jre (36 constraints: 5f9b9378)
com.google.guava:guava:33.2.1-jre (36 constraints: 239ca7f2)
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava (1 constraints: bd17c918)
com.google.j2objc:j2objc-annotations:3.0.0 (1 constraints: 150aeab4)
com.palantir.common:streams:2.3.0 (1 constraints: 0705fe35)
com.palantir.conjure:conjure-api-objects:4.36.0 (3 constraints: 9f27d521)
com.palantir.conjure:conjure-generator-common:4.36.0 (2 constraints: 05146783)
com.palantir.conjure:conjure-api-objects:4.48.0-41-g943f587 (3 constraints: 18302e78)
com.palantir.conjure:conjure-generator-common:4.48.0-41-g943f587 (2 constraints: ab19cc71)
com.palantir.conjure.java.api:errors:2.53.0 (6 constraints: dc7150a5)
com.palantir.conjure.java.api:service-config:2.53.0 (6 constraints: 3166aed4)
com.palantir.conjure.java.api:ssl-config:2.53.0 (5 constraints: af4fdb29)
Expand Down Expand Up @@ -64,7 +64,7 @@ javax.annotation:javax.annotation-api:1.3.2 (7 constraints: 396987f4)
javax.inject:javax.inject:1 (12 constraints: b6c96528)
javax.ws.rs:javax.ws.rs-api:2.1.1 (14 constraints: b4f4b54a)
joda-time:joda-time:2.12.7 (3 constraints: ef293f47)
org.apache.commons:commons-lang3:3.14.0 (4 constraints: 483074c5)
org.apache.commons:commons-lang3:3.14.0 (4 constraints: 4a301ec6)
org.apache.httpcomponents.client5:httpclient5:5.3.1 (1 constraints: cd13996e)
org.apache.httpcomponents.core5:httpcore5:5.2.4 (3 constraints: 6639870e)
org.apache.httpcomponents.core5:httpcore5-h2:5.2.4 (1 constraints: 3f130d3c)
Expand All @@ -80,10 +80,10 @@ org.jboss.logging:jboss-logging:3.4.1.Final (4 constraints: a24557a8)
org.jboss.threads:jboss-threads:3.5.0.Final (3 constraints: b52a2fe5)
org.jboss.xnio:xnio-api:3.8.7.Final (2 constraints: 771a3146)
org.jboss.xnio:xnio-nio:3.8.7.Final (1 constraints: c80dcb30)
org.jetbrains:annotations:24.1.0 (4 constraints: ff397696)
org.jetbrains:annotations:24.1.0 (4 constraints: 013a3c97)
org.mpierce.metrics.reservoir:hdrhistogram-metrics-reservoir:1.1.3 (1 constraints: 0d10f991)
org.slf4j:slf4j-api:1.7.36 (26 constraints: 1471d65d)
org.slf4j:slf4j-simple:1.7.36 (1 constraints: 43054b3b)
org.slf4j:slf4j-api:2.0.11 (26 constraints: d370aa21)
org.slf4j:slf4j-simple:2.0.11 (1 constraints: 43054b3b)
org.wildfly.client:wildfly-client-config:1.0.1.Final (1 constraints: 940c6308)
org.wildfly.common:wildfly-common:1.7.0.Final (3 constraints: 9523cba3)
org.yaml:snakeyaml:2.2 (1 constraints: 3c178b10)
Expand All @@ -106,7 +106,7 @@ com.google.truth:truth:1.1.3 (1 constraints: 18120efb)
com.helger:profiler:1.1.1 (1 constraints: e21053b8)
com.netflix.feign:feign-core:8.18.0 (3 constraints: de3f76e0)
com.netflix.feign:feign-jackson:8.18.0 (1 constraints: c718909e)
com.palantir.conjure:conjure-core:4.36.0 (1 constraints: 3f05553b)
com.palantir.conjure:conjure-core:4.48.0-41-g943f587 (1 constraints: 12082a8c)
com.palantir.conjure.java.api:test-utils:2.53.0 (1 constraints: 3b05453b)
com.palantir.conjure.java.runtime:conjure-java-annotations:8.9.0 (1 constraints: 9718cf85)
com.palantir.conjure.java.runtime:conjure-java-jaxrs-client:8.9.0 (1 constraints: 11052836)
Expand Down Expand Up @@ -192,6 +192,6 @@ org.mockito:mockito-junit-jupiter:5.12.0 (1 constraints: 3905443b)
org.objenesis:objenesis:3.3 (1 constraints: b20a14bd)
org.opentest4j:opentest4j:1.3.0 (2 constraints: cf209249)
org.ow2.asm:asm:9.1 (1 constraints: 040aa7a4)
org.slf4j:jcl-over-slf4j:1.7.36 (1 constraints: b90e9c5e)
org.slf4j:jul-to-slf4j:1.7.36 (1 constraints: b90e9c5e)
org.slf4j:log4j-over-slf4j:1.7.36 (1 constraints: b90e9c5e)
org.slf4j:jcl-over-slf4j:2.0.11 (1 constraints: b90e9c5e)
org.slf4j:jul-to-slf4j:2.0.11 (1 constraints: b90e9c5e)
org.slf4j:log4j-over-slf4j:2.0.11 (1 constraints: b90e9c5e)
2 changes: 1 addition & 1 deletion versions.props
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ com.palantir.common:streams = 2.3.0
com.palantir.conjure.java.api:* = 2.52.0
com.palantir.conjure.java.runtime:* = 8.7.0
com.palantir.conjure.verification:* = 0.19.0
com.palantir.conjure:* = 4.36.0
com.palantir.conjure:* = 4.48.0-41-g943f587
com.palantir.dialogue:* = 3.135.0
com.palantir.goethe:* = 0.12.0
com.palantir.human-readable-types:* = 1.7.0
Expand Down