Skip to content

Commit

Permalink
SimpleExpression: fix possible return type conversion
Browse files Browse the repository at this point in the history
This fixes SimpleExpression not converting  possible return types that are not contained in the desired types array. For example, if an expression can return a Number or a String, and we want an Expression that is a Number or an World, it will now include converters for String->Number and String->World
  • Loading branch information
APickledWalrus committed Nov 9, 2024
1 parent c6773ba commit aad1339
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/main/java/ch/njol/skript/lang/util/SimpleExpression.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.jetbrains.annotations.Nullable;
import org.skriptlang.skript.lang.converter.Converter;
import org.skriptlang.skript.lang.converter.ConverterInfo;
import org.skriptlang.skript.lang.converter.Converters;

import java.lang.reflect.Array;
import java.util.ArrayList;
Expand Down Expand Up @@ -203,8 +204,9 @@ public static <T> boolean check(@Nullable T[] values, Checker<? super T> checker
@Nullable
@SuppressWarnings("unchecked")
public <R> Expression<? extends R> getConvertedExpression(Class<R>... to) {
Class<? extends T> returnType = getReturnType();
// check whether this expression is already of type R
if (CollectionUtils.containsSuperclass(to, getReturnType()))
if (CollectionUtils.containsSuperclass(to, returnType))
return (Expression<? extends R>) this;

// we might be to cast some of the possible return types to R
Expand All @@ -214,11 +216,18 @@ public <R> Expression<? extends R> getConvertedExpression(Class<R>... to) {
// build a converter that for casting to R
// safety check is present in the event that we do not get this type at runtime
final Class<R> toType = (Class<R>) type;
infos.add(new ConverterInfo<>(getReturnType(), toType, fromObject -> {
infos.add(new ConverterInfo<>(returnType, toType, fromObject -> {
if (toType.isInstance(fromObject))
return (R) fromObject;
return null;
}, 0));
} else { // this possible return type is not included in 'to'
// build all converters for converting the possible return type into any of the types of 'to'
for (Class<R> toType : to) {
ConverterInfo<? extends T, R> converter = Converters.getConverterInfo(type, toType);
if (converter != null)
infos.add(converter);
}
}
}
int size = infos.size();
Expand Down

0 comments on commit aad1339

Please sign in to comment.