package jdk.nashorn.internal.runtime.linker;
import static jdk.nashorn.internal.lookup.Lookup.MH;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Modifier;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.function.Supplier;
import javax.script.Bindings;
import jdk.dynalink.CallSiteDescriptor;
import jdk.dynalink.SecureLookupSupplier;
import jdk.dynalink.linker.ConversionComparator;
import jdk.dynalink.linker.GuardedInvocation;
import jdk.dynalink.linker.GuardingTypeConverterFactory;
import jdk.dynalink.linker.LinkRequest;
import jdk.dynalink.linker.LinkerServices;
import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
import jdk.dynalink.linker.support.Guards;
import jdk.dynalink.linker.support.Lookup;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import jdk.nashorn.api.scripting.ScriptUtils;
import jdk.nashorn.internal.codegen.CompilerConstants.Call;
import jdk.nashorn.internal.objects.NativeArray;
import jdk.nashorn.internal.runtime.AccessControlContextFactory;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ListAdapter;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.Undefined;
final class NashornLinker implements TypeBasedGuardingDynamicLinker, GuardingTypeConverterFactory, ConversionComparator {
private static final AccessControlContext GET_LOOKUP_PERMISSION_CONTEXT =
AccessControlContextFactory.createAccessControlContext(SecureLookupSupplier.GET_LOOKUP_PERMISSION_NAME);
private static final ClassValue<MethodHandle> ARRAY_CONVERTERS = new ClassValue<MethodHandle>() {
@Override
protected MethodHandle computeValue(final Class<?> type) {
return createArrayConverter(type);
}
};
@Override
public boolean canLinkType(final Class<?> type) {
return canLinkTypeStatic(type);
}
static boolean canLinkTypeStatic(final Class<?> type) {
return ScriptObject.class.isAssignableFrom(type) || Undefined.class == type;
}
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
final CallSiteDescriptor desc = request.getCallSiteDescriptor();
return Bootstrap.asTypeSafeReturn(getGuardedInvocation(request, desc), linkerServices, desc);
}
private static GuardedInvocation getGuardedInvocation(final LinkRequest request, final CallSiteDescriptor desc) {
final Object self = request.getReceiver();
final GuardedInvocation inv;
if (self instanceof ScriptObject) {
inv = ((ScriptObject)self).lookup(desc, request);
} else if (self instanceof Undefined) {
inv = Undefined.lookup(desc);
} else {
throw new AssertionError(self.getClass().getName());
}
return inv;
}
@Override
public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType, lookupSupplier);
if(gi == null) {
gi = getSamTypeConverter(sourceType, targetType, lookupSupplier);
}
return gi == null ? null : gi.asType(MH.type(targetType, sourceType));
}
private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
final MethodHandle mh = JavaArgumentConverters.getConverter(targetType);
if (mh != null) {
return new GuardedInvocation(mh, canLinkTypeStatic(sourceType) ? null : IS_NASHORN_OR_UNDEFINED_TYPE);
}
final GuardedInvocation arrayConverter = getArrayConverter(sourceType, targetType, lookupSupplier);
if(arrayConverter != null) {
return arrayConverter;
}
return getMirrorConverter(sourceType, targetType);
}
private static GuardedInvocation getSamTypeConverter(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception {
final boolean isSourceTypeGeneric = sourceType.isAssignableFrom(ScriptObject.class);
if ((isSourceTypeGeneric || ScriptFunction.class.isAssignableFrom(sourceType)) && isAutoConvertibleFromFunction(targetType)) {
final Class<?> paramType = isSourceTypeGeneric ? Object.class : ScriptFunction.class;
final MethodHandle ctor = JavaAdapterFactory.getConstructor(paramType, targetType, getCurrentLookup(lookupSupplier));
assert ctor != null;
return new GuardedInvocation(ctor, isSourceTypeGeneric ? IS_FUNCTION : null);
}
return null;
}
private static MethodHandles.Lookup getCurrentLookup(final Supplier<MethodHandles.Lookup> lookupSupplier) {
return AccessController.doPrivileged(new PrivilegedAction<MethodHandles.Lookup>() {
@Override
public MethodHandles.Lookup run() {
return lookupSupplier.get();
}
}, GET_LOOKUP_PERMISSION_CONTEXT);
}
private static GuardedInvocation getArrayConverter(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) {
final boolean isSourceTypeNativeArray = sourceType == NativeArray.class;
final boolean isSourceTypeGeneric = !isSourceTypeNativeArray && sourceType.isAssignableFrom(NativeArray.class);
if (isSourceTypeNativeArray || isSourceTypeGeneric) {
final MethodHandle guard = isSourceTypeGeneric ? IS_NATIVE_ARRAY : null;
if(targetType.isArray()) {
final MethodHandle mh = ARRAY_CONVERTERS.get(targetType);
final MethodHandle mhWithLookup;
if (mh.type().parameterCount() == 2) {
assert mh.type().parameterType(1) == SecureLookupSupplier.class;
mhWithLookup = MH.insertArguments(mh, 1,
new SecureLookupSupplier(getCurrentLookup(lookupSupplier)));
} else {
mhWithLookup = mh;
}
return new GuardedInvocation(mhWithLookup, guard);
} else if(targetType == List.class) {
return new GuardedInvocation(TO_LIST, guard);
} else if(targetType == Deque.class) {
return new GuardedInvocation(TO_DEQUE, guard);
} else if(targetType == Queue.class) {
return new GuardedInvocation(TO_QUEUE, guard);
} else if(targetType == Collection.class) {
return new GuardedInvocation(TO_COLLECTION, guard);
}
}
return null;
}
private static MethodHandle createArrayConverter(final Class<?> type) {
assert type.isArray();
final Class<?> componentType = type.getComponentType();
final Call converterCall;
if (isComponentTypeAutoConvertibleFromFunction(componentType)) {
converterCall = JSType.TO_JAVA_ARRAY_WITH_LOOKUP;
} else {
converterCall = JSType.TO_JAVA_ARRAY;
}
final MethodHandle typeBoundConverter = MH.insertArguments(converterCall.methodHandle(), 1, componentType);
return MH.asType(typeBoundConverter, typeBoundConverter.type().changeReturnType(type));
}
private static boolean isComponentTypeAutoConvertibleFromFunction(final Class<?> targetType) {
if (targetType.isArray()) {
return isComponentTypeAutoConvertibleFromFunction(targetType.getComponentType());
}
return isAutoConvertibleFromFunction(targetType);
}
private static GuardedInvocation getMirrorConverter(final Class<?> sourceType, final Class<?> targetType) {
if (targetType == Map.class || targetType == Bindings.class || targetType == JSObject.class || targetType == ScriptObjectMirror.class) {
if (ScriptObject.class.isAssignableFrom(sourceType)) {
return new GuardedInvocation(CREATE_MIRROR);
} else if (sourceType.isAssignableFrom(ScriptObject.class) || sourceType.isInterface()) {
return new GuardedInvocation(CREATE_MIRROR, IS_SCRIPT_OBJECT);
}
}
return null;
}
private static boolean isAutoConvertibleFromFunction(final Class<?> clazz) {
return isAbstractClass(clazz) && !ScriptObject.class.isAssignableFrom(clazz) &&
JavaAdapterFactory.isAutoConvertibleFromFunction(clazz);
}
static boolean isAbstractClass(final Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers()) && !clazz.isArray();
}
@Override
public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) {
if(sourceType == NativeArray.class) {
if(isArrayPreferredTarget(targetType1)) {
if(!isArrayPreferredTarget(targetType2)) {
return Comparison.TYPE_1_BETTER;
}
} else if(isArrayPreferredTarget(targetType2)) {
return Comparison.TYPE_2_BETTER;
}
if(targetType1.isArray()) {
if(!targetType2.isArray()) {
return Comparison.TYPE_1_BETTER;
}
} else if(targetType2.isArray()) {
return Comparison.TYPE_2_BETTER;
}
}
if(ScriptObject.class.isAssignableFrom(sourceType)) {
if(targetType1.isInterface()) {
if(!targetType2.isInterface()) {
return Comparison.TYPE_1_BETTER;
}
} else if(targetType2.isInterface()) {
return Comparison.TYPE_2_BETTER;
}
}
return Comparison.INDETERMINATE;
}
private static boolean isArrayPreferredTarget(final Class<?> clazz) {
return clazz == List.class || clazz == Collection.class || clazz == Queue.class || clazz == Deque.class;
}
private static final MethodHandle IS_SCRIPT_OBJECT = Guards.isInstance(ScriptObject.class, MH.type(Boolean.TYPE, Object.class));
private static final MethodHandle IS_FUNCTION = findOwnMH("isFunction", boolean.class, Object.class);
private static final MethodHandle IS_NATIVE_ARRAY = Guards.isOfClass(NativeArray.class, MH.type(Boolean.TYPE, Object.class));
private static final MethodHandle IS_NASHORN_OR_UNDEFINED_TYPE = findOwnMH("isNashornTypeOrUndefined", Boolean.TYPE, Object.class);
private static final MethodHandle CREATE_MIRROR = findOwnMH("createMirror", Object.class, Object.class);
private static final MethodHandle TO_COLLECTION;
private static final MethodHandle TO_DEQUE;
private static final MethodHandle TO_LIST;
private static final MethodHandle TO_QUEUE;
static {
final MethodHandle listAdapterCreate = new Lookup(MethodHandles.lookup()).findStatic(
ListAdapter.class, "create", MethodType.methodType(ListAdapter.class, Object.class));
TO_COLLECTION = asReturning(listAdapterCreate, Collection.class);
TO_DEQUE = asReturning(listAdapterCreate, Deque.class);
TO_LIST = asReturning(listAdapterCreate, List.class);
TO_QUEUE = asReturning(listAdapterCreate, Queue.class);
}
private static MethodHandle asReturning(final MethodHandle mh, final Class<?> nrtype) {
return mh.asType(mh.type().changeReturnType(nrtype));
}
@SuppressWarnings("unused")
private static boolean isNashornTypeOrUndefined(final Object obj) {
return obj instanceof ScriptObject || obj instanceof Undefined;
}
@SuppressWarnings("unused")
private static Object createMirror(final Object obj) {
return obj instanceof ScriptObject? ScriptUtils.wrap((ScriptObject)obj) : obj;
}
@SuppressWarnings("unused")
private static boolean isFunction(final Object obj) {
return obj instanceof ScriptFunction || obj instanceof ScriptObjectMirror && ((ScriptObjectMirror) obj).isFunction();
}
private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
return MH.findStatic(MethodHandles.lookup(), NashornLinker.class, name, MH.type(rtype, types));
}
}