package com.oracle.svm.polyglot.scala;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.function.BooleanSupplier;
import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins;
import org.graalvm.compiler.phases.util.Providers;
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.hosted.RuntimeClassInitialization;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import com.oracle.svm.core.annotate.AutomaticFeature;
import com.oracle.svm.core.graal.GraalFeature;
import com.oracle.svm.core.util.UserError;
import com.oracle.svm.hosted.FeatureImpl.BeforeAnalysisAccessImpl;
@AutomaticFeature
public class ScalaFeature implements GraalFeature {
public static final String UNSUPPORTED_SCALA_VERSION = "This is not a supported Scala version. native-image supports Scala 2.11.x and onwards.";
static class IsEnabled implements BooleanSupplier {
@Override
public boolean getAsBoolean() {
return ImageSingletons.contains(ScalaFeature.class);
}
}
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return access.findClassByName("scala.Predef") != null;
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
initializeScalaEnumerations(access);
RuntimeClassInitialization.initializeAtBuildTime("scala.Symbol");
}
@Override
public void registerGraphBuilderPlugins(Providers providers, Plugins plugins, boolean analysis, boolean hosted) {
if (hosted && analysis) {
plugins.appendNodePlugin(new ScalaAnalysisPlugin());
}
}
private static boolean isValDef(Field[] fields, Method m) {
return Arrays.stream(fields).anyMatch(fd -> fd.getName().equals(m.getName()) && fd.getType().equals(m.getReturnType()));
}
private static void initializeScalaEnumerations(BeforeAnalysisAccess beforeAnalysisAccess) {
BeforeAnalysisAccessImpl access = (BeforeAnalysisAccessImpl) beforeAnalysisAccess;
Class<?> scalaEnum = access.findClassByName("scala.Enumeration");
UserError.guarantee(scalaEnum != null, "%s", UNSUPPORTED_SCALA_VERSION);
Class<?> scalaEnumVal = access.findClassByName("scala.Enumeration$Val");
UserError.guarantee(scalaEnumVal != null, "%s", UNSUPPORTED_SCALA_VERSION);
Class<?> valueClass = access.findClassByName("scala.Enumeration$Value");
UserError.guarantee(valueClass != null, "%s", UNSUPPORTED_SCALA_VERSION);
access.findSubclasses(scalaEnum).forEach(enumClass -> {
RuntimeReflection.register(enumClass.getDeclaredFields());
Method[] relevantMethods = Arrays.stream(enumClass.getDeclaredMethods())
.filter(m -> m.getParameterTypes().length == 0 &&
m.getDeclaringClass() != scalaEnum &&
valueClass.isAssignableFrom(m.getReturnType()) &&
isValDef(enumClass.getDeclaredFields(), m))
.toArray(Method[]::new);
RuntimeReflection.register(relevantMethods);
try {
RuntimeReflection.register(scalaEnumVal.getDeclaredMethod("id"));
} catch (NoSuchMethodException e) {
throw UserError.abort("%s", UNSUPPORTED_SCALA_VERSION);
}
});
}
}