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

Switch to kotlin.reflect.typeOf for configurate-extra-kotlin #422

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collector;

Expand Down Expand Up @@ -737,6 +734,69 @@ default <V> List<V> getList(final TypeToken<V> elementType, final Supplier<List<
return ret.isEmpty() ? storeDefault(this, type.getType(), defSupplier.get()) : ret;
}

/**
* If this node has list values, this function unwraps them and converts
* them to an appropriate type based on the provided function.
*
* <p>If this node has a scalar value, this function treats it as a list
* with one value.</p>
*
* @param elementType the expected type
* @return an immutable copy of the values contained
* @throws SerializationException if any value fails to be converted to the
* requested type
* @since TODO: version
*/
default @Nullable List<?> getList(Type elementType) throws SerializationException {
return (List<?>) this.get(TypeFactory.parameterizedClass(List.class, elementType));
}

/**
* If this node has list values, this function unwraps them and converts
* them to an appropriate type based on the provided function.
*
* <p>If this node has a scalar value, this function treats it as a list
* with one value.</p>
*
* @param elementType expected type
* @param def default value if no appropriate value is set
* @return an immutable copy of the values contained that could be
* successfully converted, or {@code def} if no values could be
* converted.
* @throws SerializationException if any value fails to be converted to the
* requested type
* @since TODO: version
*/
default List<?> getList(Type elementType, List<?> def) throws SerializationException {
final Type type = TypeFactory.parameterizedClass(List.class, elementType);
final List<?> ret = (List<?>) this.get(type, def);
return ret.isEmpty() ? storeDefault(this, type, def) : ret;
}

/**
* If this node has list values, this function unwraps them and converts
* them to an appropriate type based on the provided function.
*
* <p>If this node has a scalar value, this function treats it as a list
* with one value.</p>
*
* @param elementType expected type
* @param defSupplier function that will be called to calculate a default
* value only if there is no existing value of the
* correct type
* @return an immutable copy of the values contained that could be
* successfully converted, or {@code def} if no values could be
* converted.
* @throws SerializationException if any value fails to be converted to the
* requested type
* @since TODO: version
*/
default List<?> getList(Type elementType, Supplier<List<?>> defSupplier) throws SerializationException {
final Type type = TypeFactory.parameterizedClass(List.class, elementType);
final List<?> ret = (List<?>) this.get(type, defSupplier);
return ret.isEmpty() ? storeDefault(this, type, defSupplier.get()) : ret;
}

/**
* If this node has list values, this function unwraps them and converts
* them to an appropriate type based on the provided function.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.spongepowered.configurate.reactive.TransactionalSubscriber;
import org.spongepowered.configurate.serialize.SerializationException;

import java.lang.reflect.Type;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
Expand Down Expand Up @@ -271,6 +272,25 @@ default <T> void set(final NodePath path, final TypeToken<T> type, final @Nullab
this.node().node(path).set(type, value);
}

/**
* Create a reference to the node at the provided path. The value will be
* deserialized according to the provided {@link Type}.
*
* <p>The returned reference will update with reloads of and changes to the
* value of the provided configuration. Any serialization errors encountered
* will be submitted to the {@link #errors()} stream.
*
* @param type the value's type
* @param path the path from the root node to the node containing the value
* @return a deserializing reference to the node at the given path
* @throws SerializationException if a type serializer could not be found
* for the provided type
* @since TODO: version
*/
default ValueReference<?, N> referenceTo(final Type type, final Object... path) throws SerializationException {
return this.referenceTo(type, NodePath.of(path));
}

/**
* Create a reference to the node at the provided path. The value will be
* deserialized according to the provided TypeToken.
Expand Down Expand Up @@ -310,6 +330,25 @@ default <T> ValueReference<T, N> referenceTo(final TypeToken<T> type, final Obje
default <T> ValueReference<T, N> referenceTo(final Class<T> type, final Object... path) throws SerializationException {
return this.referenceTo(type, NodePath.of(path));
}

/**
* Create a reference to the node at the provided path. The value will be
* deserialized according to the provided {@link Type}.
*
* <p>The returned reference will update with reloads of and changes to the
* value of the provided configuration. Any serialization errors encountered
* will be submitted to the {@link #errors()} stream.
*
* @param type the value's type
* @param path the path from the root node to the node containing the value
* @return a deserializing reference to the node at the given path
* @throws SerializationException if a type serializer could not be found
* for the provided type
* @since TODO: version
*/
default ValueReference<?, N> referenceTo(final Type type, final NodePath path) throws SerializationException {
return this.referenceTo(type, path, null);
}

/**
* Create a reference to the node at the provided path. The value will be
Expand Down Expand Up @@ -351,6 +390,23 @@ default <T> ValueReference<T, N> referenceTo(final Class<T> type, final NodePath
return this.referenceTo(type, path, null);
}

/**
* Create a reference to the node at the provided path. The value will be
* deserialized according to the provided {@link Type}.
*
* <p>The returned reference will update with reloads of and changes to the
* value of the provided configuration. Any serialization errors encountered
* will be submitted to the {@link #errors()} stream.
*
* @param type the value's type
* @param path the path from the root node to the node containing the value
* @return a deserializing reference to the node at the given path
* @throws SerializationException if a type serializer could not be found
* for the provided type
* @since TODO: version
*/
ValueReference<?, N> referenceTo(Type type, NodePath path, @Nullable Object defaultValue) throws SerializationException;

/**
* Create a reference to the node at the provided path. The value will be
* deserialized according to the provided {@link TypeToken}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.spongepowered.configurate.reactive.Publisher;
import org.spongepowered.configurate.serialize.SerializationException;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.function.Function;
Expand Down Expand Up @@ -125,8 +126,13 @@ public final N get(final Iterable<?> path) {
}

@Override
public final <T> ValueReference<T, N> referenceTo(final TypeToken<T> type,
final NodePath path, final @Nullable T def) throws SerializationException {
public final ValueReference<?, N> referenceTo(final Type type,
final NodePath path, final @Nullable Object def) throws SerializationException {
return new ValueReferenceImpl<>(this, path, type, def);
}

@Override
public final <T> ValueReference<T, N> referenceTo(final TypeToken<T> type, final NodePath path, final @Nullable T def) throws SerializationException {
return new ValueReferenceImpl<>(this, path, type, def);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.spongepowered.configurate.serialize.TypeSerializer;
import org.spongepowered.configurate.util.UnmodifiableCollections;

import java.lang.reflect.Type;
import java.util.concurrent.Executor;
import java.util.function.Function;

Expand All @@ -38,18 +39,19 @@ class ValueReferenceImpl<@Nullable T, N extends ScopedConfigurationNode<N>> impl
// Information about the reference
private final ManualConfigurationReference<N> root;
private final NodePath path;
private final TypeToken<T> type;
private final Type type;
private final TypeSerializer<T> serializer;
private final Publisher.Cached<@Nullable T> deserialized;

ValueReferenceImpl(final ManualConfigurationReference<N> root, final NodePath path, final TypeToken<T> type,
@SuppressWarnings("unchecked")
ValueReferenceImpl(final ManualConfigurationReference<N> root, final NodePath path, final Type type,
final @Nullable T def) throws SerializationException {
this.root = root;
this.path = path;
this.type = type;
final @Nullable TypeSerializer<T> serializer = root.node().options().serializers().get(type);
final @Nullable TypeSerializer<T> serializer = (TypeSerializer<T>) root.node().options().serializers().get(type);
if (serializer == null) {
throw new SerializationException(this.path, type.getType(), "Unsupported type" + type);
throw new SerializationException(this.path, type, "Unsupported type" + type);
}
this.serializer = serializer;

Expand All @@ -63,19 +65,24 @@ class ValueReferenceImpl<@Nullable T, N extends ScopedConfigurationNode<N>> impl
}).cache(deserializedValueFrom(root.node(), def));
}

ValueReferenceImpl(final ManualConfigurationReference<N> root, final NodePath path, final TypeToken<T> type,
final @Nullable T def) throws SerializationException {
this(root, path, type.getType(), def);
}

ValueReferenceImpl(final ManualConfigurationReference<N> root, final NodePath path, final Class<T> type,
final @Nullable T def) throws SerializationException {
this(root, path, TypeToken.get(type), def);
this(root, path, (Type) type, def);
}

private @Nullable T deserializedValueFrom(final N parent, final @Nullable T defaultVal) throws SerializationException {
final N node = parent.node(this.path);
if (!node.virtual()) {
return this.serializer.deserialize(this.type.getType(), node);
return this.serializer.deserialize(this.type, node);
}
final @Nullable T defaultOrEmpty = defaultVal == null ? this.serializer.emptyValue(this.type.getType(), node.options()) : defaultVal;
final @Nullable T defaultOrEmpty = defaultVal == null ? this.serializer.emptyValue(this.type, node.options()) : defaultVal;
if (node.options().shouldCopyDefaults()) {
this.serializer.serialize(this.type.getType(), defaultOrEmpty, node);
this.serializer.serialize(this.type, defaultOrEmpty, node);
}
return defaultOrEmpty;
}
Expand All @@ -88,7 +95,7 @@ class ValueReferenceImpl<@Nullable T, N extends ScopedConfigurationNode<N>> impl
@Override
public boolean set(final @Nullable T value) {
try {
this.serializer.serialize(this.type.getType(), value, node());
this.serializer.serialize(this.type, value, node());
this.deserialized.submit(value);
return true;
} catch (final SerializationException e) {
Expand All @@ -113,7 +120,7 @@ public boolean setAndSave(final @Nullable T value) {
@Override
public Publisher<Boolean> setAndSaveAsync(final @Nullable T value) {
return Publisher.execute(() -> {
this.serializer.serialize(this.type.getType(), value, node());
this.serializer.serialize(this.type, value, node());
this.deserialized.submit(value);
this.root.save();
return true;
Expand All @@ -135,7 +142,7 @@ public Publisher<Boolean> updateAsync(final Function<@Nullable T, ? extends T> a
return Publisher.execute(() -> {
final @Nullable T orig = get();
final T updated = action.apply(orig);
this.serializer.serialize(this.type.getType(), updated, node());
this.serializer.serialize(this.type, updated, node());
this.deserialized.submit(updated);
this.root.save();
return true;
Expand Down
4 changes: 2 additions & 2 deletions extra/kotlin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ dependencies {
}

kotlin {
coreLibrariesVersion = "1.4.20"
coreLibrariesVersion = "1.8.20"
target {
compilations.configureEach {
kotlinOptions {
jvmTarget = "1.8"
languageVersion = "1.4"
languageVersion = "1.8"
freeCompilerArgs += ["-opt-in=kotlin.RequiresOptIn", "-Xemit-jvm-type-annotations"]
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import org.spongepowered.configurate.objectmapping.FieldDiscoverer
import org.spongepowered.configurate.objectmapping.ObjectMapper
import org.spongepowered.configurate.objectmapping.ObjectMapper.Factory
import org.spongepowered.configurate.util.Types.combinedAnnotations
import kotlin.reflect.jvm.javaType
import kotlin.reflect.typeOf

private val dataClassMapperFactory =
ObjectMapper.factoryBuilder().addDiscoverer(DataClassFieldDiscoverer).build()
Expand All @@ -60,17 +62,16 @@ fun dataClassFieldDiscoverer(): FieldDiscoverer<*> {
}

/** Get an object mapper for the type [T] using the default object mapper factory */
@Suppress("UNCHECKED_CAST")
inline fun <reified T> objectMapper(): ObjectMapper<T> {
return objectMapperFactory()[typeTokenOf()]
return objectMapperFactory()[typeOf<T>().javaType] as ObjectMapper<T>
}

/** Get an object mapper bound to the instance of [T], resolving type parameters */
inline fun <reified T> T.toNode(target: ConfigurationNode) {
return objectMapperFactory().get<T>().save(this, target)
}

@PublishedApi internal inline fun <reified T> typeTokenOf() = object : TypeToken<T>() {}

/**
* A field discoverer that gathers definitions from kotlin `data` classes.
*
Expand Down