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

add java enums support #26

Merged
merged 1 commit into from
Jul 19, 2022
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.strategyobject.substrateclient.common.types;

import com.google.common.base.Preconditions;
import lombok.NonNull;

public class Enums {
public static <E extends Enum<E>> E lookup(E @NonNull [] enumValues, int index) {
Preconditions.checkArgument(enumValues.length > 0);
Preconditions.checkArgument(index >= 0);
Preconditions.checkArgument(index < enumValues.length,
enumValues[0].getClass().getSimpleName() + " has no value associated with index " + index);

return enumValues[index];
}

private Enums() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Stream<DynamicTest> toBytesThrows() {
}

@AllArgsConstructor(access = AccessLevel.PRIVATE)
static class Test extends TestSuite.TestCase {
static class Test implements TestSuite.TestCase {
private final String displayName;
private final Executable executable;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.strategyobject.substrateclient.common.types;

import lombok.val;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class EnumsTest {

enum TestEnum {
YES, NO, MAYBE
}

@Test
void lookup() {
val actual = Enums.lookup(TestEnum.values(), 0);

assertEquals(TestEnum.YES, actual);
}

@Test
void lookupOutOfBounds() {
val values = TestEnum.values();
val thrown = assertThrows(RuntimeException.class, () -> Enums.lookup(values, 10));

assertTrue(thrown.getMessage().contains("TestEnum"));
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
package com.strategyobject.substrateclient.rpc.api;

import lombok.Getter;
import com.strategyobject.substrateclient.scale.annotation.ScaleWriter;

@ScaleWriter
public enum AddressKind {
ID((byte) 0);

@Getter
private final byte value;

AddressKind(byte value) {
this.value = value;
}
ID
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Stream<DynamicTest> decodeRpcNull() {
}

@AllArgsConstructor(access = AccessLevel.PRIVATE)
static class Test<T> extends TestSuite.TestCase {
static class Test<T> implements TestSuite.TestCase {
private final RpcDecoder<T> decoder;
private final RpcObject given;
private final T expected;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ Stream<DynamicTest> encode() {
}

@AllArgsConstructor(access = AccessLevel.PRIVATE)
static class Test<T> extends TestSuite.TestCase {
static class Test<T> implements TestSuite.TestCase {
private static final Gson GSON = new Gson();

private final RpcEncoder<T> encoder;
Expand Down
2 changes: 2 additions & 0 deletions scale/scale-codegen/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@ dependencies {
annotationProcessor 'com.google.auto.service:auto-service:1.0.1'

implementation 'com.squareup:javapoet:1.13.0'

testImplementation project(':tests')
testImplementation 'com.google.testing.compile:compile-testing:0.19'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.strategyobject.substrateclient.scale.codegen.reader;

import com.squareup.javapoet.*;
import com.strategyobject.substrateclient.common.codegen.ProcessingException;
import com.strategyobject.substrateclient.common.codegen.ProcessorContext;
import com.strategyobject.substrateclient.common.io.Streamer;
import com.strategyobject.substrateclient.common.types.Enums;
import com.strategyobject.substrateclient.scale.ScaleReader;
import com.strategyobject.substrateclient.scale.annotation.AutoRegister;
import com.strategyobject.substrateclient.scale.codegen.ScaleProcessorHelper;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;

import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import java.io.IOException;
import java.io.InputStream;

@RequiredArgsConstructor
public class ScaleReaderAnnotatedEnum {
private static final String READERS_ARG = "readers";
private static final String ENUM_VALUES = "values";

private final @NonNull TypeElement enumElement;

public void generateReader(@NonNull ProcessorContext context) throws IOException, ProcessingException {
val readerName = ScaleProcessorHelper.getReaderName(enumElement.getSimpleName().toString());
val enumType = TypeName.get(enumElement.asType());

val typeSpecBuilder = TypeSpec.classBuilder(readerName)
.addAnnotation(AnnotationSpec.builder(AutoRegister.class)
.addMember("types", "{$L.class}", enumElement.getQualifiedName().toString())
.build())
.addModifiers(Modifier.PUBLIC)
.addSuperinterface(ParameterizedTypeName.get(ClassName.get(ScaleReader.class), enumType))
.addField(
FieldSpec.builder(ArrayTypeName.of(enumType), ENUM_VALUES, Modifier.PRIVATE, Modifier.FINAL)
.initializer("$T.values()", enumType)
.build())
.addMethod(generateReadMethod(enumType));

JavaFile.builder(
context.getPackageName(enumElement),
typeSpecBuilder.build()
).build().writeTo(context.getFiler());
}

private MethodSpec generateReadMethod(TypeName enumType) {
val methodSpec = MethodSpec.methodBuilder("read")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(enumType)
.addParameter(InputStream.class, "stream")
.addParameter(ArrayTypeName.of(
ParameterizedTypeName.get(
ClassName.get(ScaleReader.class),
WildcardTypeName.subtypeOf(Object.class))),
READERS_ARG)
.varargs(true)
.addException(IOException.class);

addValidationRules(methodSpec);
addMethodBody(methodSpec);
return methodSpec.build();
}

private void addValidationRules(MethodSpec.Builder methodSpec) {
methodSpec
.addStatement("if (stream == null) throw new IllegalArgumentException(\"stream is null\")")
.addStatement("if (readers != null && readers.length > 0) throw new IllegalArgumentException()");
}

private void addMethodBody(MethodSpec.Builder methodSpec) {
methodSpec.addStatement("return $T.lookup($L, $T.readByte(stream))", Enums.class, ENUM_VALUES, Streamer.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,23 @@ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
}

for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(ScaleReader.class)) {
if (annotatedElement.getKind() != ElementKind.CLASS) {
val elementKind = annotatedElement.getKind();
if (!elementKind.isClass()) {
context.error(
annotatedElement,
"Only classes can be annotated with `@%s`.",
"Only classes and enums can be annotated with `@%s`.",
ScaleReader.class.getSimpleName());

return true;
}

val typeElement = (TypeElement) annotatedElement;
try {
new ScaleReaderAnnotatedClass(typeElement).generateReader(context);
if (elementKind == ElementKind.CLASS) {
new ScaleReaderAnnotatedClass(typeElement).generateReader(context);
} else {
new ScaleReaderAnnotatedEnum(typeElement).generateReader(context);
}
} catch (ProcessingException e) {
context.error(typeElement, e);
return true;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.strategyobject.substrateclient.scale.codegen.writer;

import com.squareup.javapoet.*;
import com.strategyobject.substrateclient.common.codegen.ProcessingException;
import com.strategyobject.substrateclient.common.codegen.ProcessorContext;
import com.strategyobject.substrateclient.scale.ScaleWriter;
import com.strategyobject.substrateclient.scale.annotation.AutoRegister;
import com.strategyobject.substrateclient.scale.codegen.ScaleProcessorHelper;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;

import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import java.io.IOException;
import java.io.OutputStream;

@RequiredArgsConstructor
public class ScaleWriterAnnotatedEnum {
private static final String WRITERS_ARG = "writers";

private final @NonNull TypeElement enumElement;

public void generateWriter(@NonNull ProcessorContext context) throws IOException, ProcessingException {
val writerName = ScaleProcessorHelper.getWriterName(enumElement.getSimpleName().toString());
val enumType = TypeName.get(enumElement.asType());

val typeSpecBuilder = TypeSpec.classBuilder(writerName)
.addAnnotation(AnnotationSpec.builder(AutoRegister.class)
.addMember("types", "{$L.class}", enumElement.getQualifiedName().toString())
.build())
.addModifiers(Modifier.PUBLIC)
.addSuperinterface(ParameterizedTypeName.get(ClassName.get(ScaleWriter.class), enumType))
.addMethod(generateWriteMethod(enumType));

JavaFile.builder(
context.getPackageName(enumElement),
typeSpecBuilder.build()
).build().writeTo(context.getFiler());
}

private MethodSpec generateWriteMethod(TypeName classWildcardTyped) {
val methodSpec = MethodSpec.methodBuilder("write")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(TypeName.VOID)
.addParameter(classWildcardTyped, "value")
.addParameter(OutputStream.class, "stream")
.addParameter(ArrayTypeName.of(
ParameterizedTypeName.get(
ClassName.get(ScaleWriter.class),
WildcardTypeName.subtypeOf(Object.class))),
WRITERS_ARG)
.varargs(true)
.addException(IOException.class);

addValidationRules(methodSpec);
addMethodBody(methodSpec);
return methodSpec.build();
}

private void addValidationRules(MethodSpec.Builder methodSpec) {
methodSpec.addStatement("if (stream == null) throw new IllegalArgumentException(\"stream is null\")");
methodSpec.addStatement("if (value == null) throw new IllegalArgumentException(\"value is null\")");
methodSpec.addStatement("if (writers != null && writers.length > 0) throw new IllegalArgumentException()");
}

private void addMethodBody(MethodSpec.Builder methodSpec) {
methodSpec.addStatement("stream.write(value.ordinal())");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,23 @@ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
}

for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(ScaleWriter.class)) {
if (annotatedElement.getKind() != ElementKind.CLASS) {
val elementKind = annotatedElement.getKind();
if (!elementKind.isClass()) {
context.error(
annotatedElement,
"Only classes can be annotated with `@%s`.",
"Only classes and enums can be annotated with `@%s`.",
ScaleWriter.class.getSimpleName());

return true;
}

val typeElement = (TypeElement) annotatedElement;
try {
new ScaleWriterAnnotatedClass(typeElement).generateWriter(context);
if (elementKind == ElementKind.CLASS) {
new ScaleWriterAnnotatedClass(typeElement).generateWriter(context);
} else {
new ScaleWriterAnnotatedEnum(typeElement).generateWriter(context);
}
} catch (ProcessingException e) {
context.error(typeElement, e);
return true;
Expand Down
Loading