Java Code Examples for java.lang.invoke.MethodHandle#bindTo()

The following examples show how to use java.lang.invoke.MethodHandle#bindTo() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: presto   File: MethodHandleUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static MethodHandle nativeValueGetter(Type type)
{
    Class<?> javaType = type.getJavaType();

    MethodHandle methodHandle;
    if (javaType == long.class) {
        methodHandle = GET_LONG;
    }
    else if (javaType == double.class) {
        methodHandle = GET_DOUBLE;
    }
    else if (javaType == boolean.class) {
        methodHandle = GET_BOOLEAN;
    }
    else if (javaType == Slice.class) {
        methodHandle = GET_SLICE;
    }
    else if (javaType == Block.class) {
        methodHandle = GET_BLOCK;
    }
    else {
        throw new IllegalArgumentException("Unknown java type " + javaType + " from type " + type);
    }

    return methodHandle.bindTo(type);
}
 
Example 2
Source Project: presto   File: MethodHandleUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static MethodHandle nativeValueWriter(Type type)
{
    Class<?> javaType = type.getJavaType();

    MethodHandle methodHandle;
    if (javaType == long.class) {
        methodHandle = WRITE_LONG;
    }
    else if (javaType == double.class) {
        methodHandle = WRITE_DOUBLE;
    }
    else if (javaType == boolean.class) {
        methodHandle = WRITE_BOOLEAN;
    }
    else if (javaType == Slice.class) {
        methodHandle = WRITE_SLICE;
    }
    else if (javaType == Block.class) {
        methodHandle = WRITE_BLOCK;
    }
    else {
        throw new IllegalArgumentException("Unknown java type " + javaType + " from type " + type);
    }

    return methodHandle.bindTo(type);
}
 
Example 3
private static MethodHandle buildVarargsArray(MethodHandle newArray, MethodHandle finisher, int nargs) {
    // Build up the result mh as a sequence of fills like this:
    //   finisher(fill(fill(newArrayWA(23,x1..x10),10,x11..x20),20,x21..x23))
    // The various fill(_,10*I,___*[J]) are reusable.
    int leftLen = Math.min(nargs, LEFT_ARGS);  // absorb some arguments immediately
    int rightLen = nargs - leftLen;
    MethodHandle leftCollector = newArray.bindTo(nargs);
    leftCollector = leftCollector.asCollector(Object[].class, leftLen);
    MethodHandle mh = finisher;
    if (rightLen > 0) {
        MethodHandle rightFiller = fillToRight(LEFT_ARGS + rightLen);
        if (mh == ARRAY_IDENTITY)
            mh = rightFiller;
        else
            mh = MethodHandles.collectArguments(mh, 0, rightFiller);
    }
    if (mh == ARRAY_IDENTITY)
        mh = leftCollector;
    else
        mh = MethodHandles.collectArguments(mh, 0, leftCollector);
    return mh;
}
 
Example 4
Source Project: presto   File: DecimalSumAggregation.java    License: Apache License 2.0 5 votes vote down vote up
private static InternalAggregationFunction generateAggregation(Type inputType, Type outputType)
{
    checkArgument(inputType instanceof DecimalType, "type must be Decimal");
    DynamicClassLoader classLoader = new DynamicClassLoader(DecimalSumAggregation.class.getClassLoader());
    List<Type> inputTypes = ImmutableList.of(inputType);
    MethodHandle inputFunction;
    Class<? extends AccumulatorState> stateInterface = LongDecimalWithOverflowState.class;
    AccumulatorStateSerializer<?> stateSerializer = new LongDecimalWithOverflowStateSerializer();

    if (((DecimalType) inputType).isShort()) {
        inputFunction = SHORT_DECIMAL_INPUT_FUNCTION;
    }
    else {
        inputFunction = LONG_DECIMAL_INPUT_FUNCTION;
    }

    AggregationMetadata metadata = new AggregationMetadata(
            generateAggregationName(NAME, outputType.getTypeSignature(), inputTypes.stream().map(Type::getTypeSignature).collect(toImmutableList())),
            createInputParameterMetadata(inputType),
            inputFunction.bindTo(inputType),
            Optional.empty(),
            COMBINE_FUNCTION,
            LONG_DECIMAL_OUTPUT_FUNCTION.bindTo(outputType),
            ImmutableList.of(new AccumulatorStateDescriptor(
                    stateInterface,
                    stateSerializer,
                    new LongDecimalWithOverflowStateFactory())),
            outputType);

    Type intermediateType = stateSerializer.getSerializedType();
    GenericAccumulatorFactoryBinder factory = AccumulatorCompiler.generateAccumulatorFactoryBinder(metadata, classLoader);
    return new InternalAggregationFunction(NAME, inputTypes, ImmutableList.of(intermediateType), outputType, true, false, factory);
}
 
Example 5
private static InternalAggregationFunction generateAggregation(Type type)
{
    checkArgument(type instanceof DecimalType, "type must be Decimal");
    DynamicClassLoader classLoader = new DynamicClassLoader(DecimalAverageAggregation.class.getClassLoader());
    List<Type> inputTypes = ImmutableList.of(type);
    MethodHandle inputFunction;
    MethodHandle outputFunction;
    Class<? extends AccumulatorState> stateInterface = LongDecimalWithOverflowAndLongState.class;
    AccumulatorStateSerializer<?> stateSerializer = new LongDecimalWithOverflowAndLongStateSerializer();

    if (((DecimalType) type).isShort()) {
        inputFunction = SHORT_DECIMAL_INPUT_FUNCTION;
        outputFunction = SHORT_DECIMAL_OUTPUT_FUNCTION;
    }
    else {
        inputFunction = LONG_DECIMAL_INPUT_FUNCTION;
        outputFunction = LONG_DECIMAL_OUTPUT_FUNCTION;
    }
    inputFunction = inputFunction.bindTo(type);
    outputFunction = outputFunction.bindTo(type);

    AggregationMetadata metadata = new AggregationMetadata(
            generateAggregationName(NAME, type.getTypeSignature(), inputTypes.stream().map(Type::getTypeSignature).collect(toImmutableList())),
            createInputParameterMetadata(type),
            inputFunction,
            Optional.empty(),
            COMBINE_FUNCTION,
            outputFunction,
            ImmutableList.of(new AccumulatorStateDescriptor(
                    stateInterface,
                    stateSerializer,
                    new LongDecimalWithOverflowAndLongStateFactory())),
            type);

    Type intermediateType = stateSerializer.getSerializedType();
    GenericAccumulatorFactoryBinder factory = AccumulatorCompiler.generateAccumulatorFactoryBinder(metadata, classLoader);
    return new InternalAggregationFunction(NAME, inputTypes, ImmutableList.of(intermediateType), type, true, false, factory);
}
 
Example 6
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type type = boundVariables.getTypeVariable("E");
    MethodHandle methodHandle;
    if (type.getJavaType() == boolean.class) {
        methodHandle = METHOD_HANDLE_BOOLEAN;
    }
    else if (type.getJavaType() == long.class) {
        methodHandle = METHOD_HANDLE_LONG;
    }
    else if (type.getJavaType() == double.class) {
        methodHandle = METHOD_HANDLE_DOUBLE;
    }
    else if (type.getJavaType() == Slice.class) {
        methodHandle = METHOD_HANDLE_SLICE;
    }
    else {
        methodHandle = METHOD_HANDLE_OBJECT;
    }
    methodHandle = methodHandle.bindTo(type);

    return new ScalarFunctionImplementation(
            false,
            ImmutableList.of(
                    valueTypeArgumentProperty(RETURN_NULL_ON_NULL),
                    valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
            methodHandle);
}
 
Example 7
@Override
public void bind(Context ctx) throws IllegalAccessException {
    log.debug("bind %s to context", method);
    MethodHandle boundHandle = MethodHandles.publicLookup().unreflect(method).bindTo(ctx.getProcessor(processorClass));
    if (hasContextParameter()) {
        boundHandle = boundHandle.bindTo(ctx);
    }
    this.methodHandle = boundHandle.asSpreader(Object[].class, arity);
}
 
Example 8
Source Project: presto   File: ArraySubscriptOperator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type elementType = boundVariables.getTypeVariable("E");

    MethodHandle methodHandle;
    if (elementType.getJavaType() == boolean.class) {
        methodHandle = METHOD_HANDLE_BOOLEAN;
    }
    else if (elementType.getJavaType() == long.class) {
        methodHandle = METHOD_HANDLE_LONG;
    }
    else if (elementType.getJavaType() == double.class) {
        methodHandle = METHOD_HANDLE_DOUBLE;
    }
    else if (elementType.getJavaType() == Slice.class) {
        methodHandle = METHOD_HANDLE_SLICE;
    }
    else {
        methodHandle = METHOD_HANDLE_OBJECT;
    }
    methodHandle = methodHandle.bindTo(elementType);
    requireNonNull(methodHandle, "methodHandle is null");
    return new ScalarFunctionImplementation(
            true,
            ImmutableList.of(
                    valueTypeArgumentProperty(RETURN_NULL_ON_NULL),
                    valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
            methodHandle);
}
 
Example 9
Source Project: presto   File: ExpressionInterpreter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object visitArithmeticUnary(ArithmeticUnaryExpression node, Object context)
{
    Object value = process(node.getValue(), context);
    if (value == null) {
        return null;
    }
    if (value instanceof Expression) {
        return new ArithmeticUnaryExpression(node.getSign(), toExpression(value, type(node.getValue())));
    }

    switch (node.getSign()) {
        case PLUS:
            return value;
        case MINUS:
            ResolvedFunction resolvedOperator = metadata.resolveOperator(OperatorType.NEGATION, types(node.getValue()));
            MethodHandle handle = metadata.getScalarFunctionInvoker(resolvedOperator, Optional.empty()).getMethodHandle();

            if (handle.type().parameterCount() > 0 && handle.type().parameterType(0) == ConnectorSession.class) {
                handle = handle.bindTo(session);
            }
            try {
                return handle.invokeWithArguments(value);
            }
            catch (Throwable throwable) {
                throwIfInstanceOf(throwable, RuntimeException.class);
                throwIfInstanceOf(throwable, Error.class);
                throw new RuntimeException(throwable.getMessage(), throwable);
            }
    }

    throw new UnsupportedOperationException("Unsupported unary operator: " + node.getSign());
}
 
Example 10
private static MethodHandle throwException(Supplier<Throwable> supplier, MethodType type) throws Exception {
    MethodHandle makeExn = PRIVATE_LOOKUP.findVirtual(Supplier.class, "get", methodType(Object.class));
    makeExn = makeExn.bindTo(supplier);
    makeExn = makeExn.asType(methodType(Throwable.class));

    MethodHandle throwExn = MethodHandles.throwException(type.returnType(), Throwable.class);
    throwExn = MethodHandles.foldArguments(throwExn, makeExn);

    // discard arguments specified by the provided type
    return MethodHandles.dropArguments(throwExn, 0, type.parameterArray());
}
 
Example 11
private <D> InjectableMethod(@Nullable TypeLiteral<D> targetType, @Nullable D target, Method method, @Nullable T result) {
    final Errors errors = new Errors(method);

    if(Members.isStatic(method)) {
        checkArgument(target == null);
    } else {
        checkArgument(target != null);
    }

    targetType = targetType(targetType, target, method);

    checkArgument(method.getDeclaringClass().isAssignableFrom(targetType.getRawType()));

    this.method = method;
    this.dependencies = ImmutableSet.copyOf(InjectionPoint.forMethod(method, targetType).getDependencies());

    if(result != null) {
        this.result = result;
        this.providedKey = Keys.forInstance(result);
    } else {
        final TypeLiteral<T> returnType = (TypeLiteral<T>) targetType.getReturnType(method);
        if(!Void.class.equals(returnType.getRawType())) {
            final Annotation qualifier = Annotations.findBindingAnnotation(errors, method, method.getAnnotations());
            this.result = null;
            this.providedKey = Keys.get(returnType, qualifier);
        } else {
            this.result = (T) this;
            this.providedKey = Keys.forInstance(this.result);
        }
    }

    this.scope = Annotations.findScopeAnnotation(errors, method.getAnnotations());

    MethodHandle handle = MethodHandleUtils.privateUnreflect(method);
    if(target != null) {
        handle = handle.bindTo(target);
    }
    this.handle = handle;
}
 
Example 12
static void testExtendCustomizedBMH() throws Exception {
    // Construct BMH
    MethodHandle mh = MethodHandleHelper.IMPL_LOOKUP.findVirtual(String.class, "concat",
            MethodType.methodType(String.class, String.class))
            .bindTo("a");
    MethodHandleHelper.customize(mh);
    mh.bindTo("b"); // Try to extend customized BMH
}
 
Example 13
private static MethodHandle bind(VarHandle vh, MethodHandle mh, MethodType emt) {
    assertEquals(mh.type(), emt.insertParameterTypes(0, VarHandle.class),
                 "MethodHandle type differs from access mode type");

    MethodHandleInfo info = MethodHandles.lookup().revealDirect(mh);
    assertEquals(info.getMethodType(), emt,
                 "MethodHandleInfo method type differs from access mode type");

    return mh.bindTo(vh);
}
 
Example 14
@Override
public MethodHandle bindTo(final MethodHandle handle, final Object x) {
    return handle.bindTo(x);
}
 
Example 15
Source Project: presto   File: ArrayJoin.java    License: Apache License 2.0 4 votes vote down vote up
private static ScalarFunctionImplementation specializeArrayJoin(BoundVariables types, Metadata metadata, List<Boolean> nullableArguments, MethodHandle methodHandle)
{
    Type type = types.getTypeVariable("T");
    List<ArgumentProperty> argumentProperties = nullableArguments.stream()
            .map(nullable -> nullable
                    ? valueTypeArgumentProperty(USE_BOXED_TYPE)
                    : valueTypeArgumentProperty(RETURN_NULL_ON_NULL))
            .collect(toImmutableList());

    if (type instanceof UnknownType) {
        return new ScalarFunctionImplementation(
                false,
                argumentProperties,
                methodHandle.bindTo(null),
                Optional.of(STATE_FACTORY));
    }
    else {
        try {
            ResolvedFunction resolvedFunction = metadata.getCoercion(type, VARCHAR);
            MethodHandle cast = metadata.getScalarFunctionInvoker(resolvedFunction, Optional.empty()).getMethodHandle();

            MethodHandle getter;
            Class<?> elementType = type.getJavaType();
            if (elementType == boolean.class) {
                getter = GET_BOOLEAN;
            }
            else if (elementType == double.class) {
                getter = GET_DOUBLE;
            }
            else if (elementType == long.class) {
                getter = GET_LONG;
            }
            else if (elementType == Slice.class) {
                getter = GET_SLICE;
            }
            else {
                throw new UnsupportedOperationException("Unsupported type: " + elementType.getName());
            }

            // if the cast doesn't take a ConnectorSession, create an adapter that drops the provided session
            if (cast.type().parameterArray()[0] != ConnectorSession.class) {
                cast = MethodHandles.dropArguments(cast, 0, ConnectorSession.class);
            }

            // Adapt a target cast that takes (ConnectorSession, ?) to one that takes (Block, int, ConnectorSession), which will be invoked by the implementation
            // The first two arguments (Block, int) are filtered through the element type's getXXX method to produce the underlying value that needs to be passed to
            // the cast.
            cast = MethodHandles.permuteArguments(cast, MethodType.methodType(Slice.class, cast.type().parameterArray()[1], cast.type().parameterArray()[0]), 1, 0);
            cast = MethodHandles.dropArguments(cast, 1, int.class);
            cast = MethodHandles.dropArguments(cast, 1, Block.class);
            cast = MethodHandles.foldArguments(cast, getter.bindTo(type));

            MethodHandle target = MethodHandles.insertArguments(methodHandle, 0, cast);
            return new ScalarFunctionImplementation(
                    false,
                    argumentProperties,
                    target,
                    Optional.of(STATE_FACTORY));
        }
        catch (PrestoException e) {
            throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Input type %s not supported", type), e);
        }
    }
}
 
Example 16
@Override
public MethodHandle bindTo(final MethodHandle handle, final Object x) {
    return handle.bindTo(x);
}
 
Example 17
@Override
public MethodHandle bindTo(final MethodHandle handle, final Object x) {
    final MethodHandle mh = handle.bindTo(x);
    return debug(mh, "bindTo", handle, x);
}
 
Example 18
@Override
public MethodHandle bindTo(final MethodHandle handle, final Object x) {
    final MethodHandle mh = handle.bindTo(x);
    return debug(mh, "bindTo", handle, x);
}
 
Example 19
@Override
public MethodHandle bindTo(final MethodHandle handle, final Object x) {
    final MethodHandle mh = handle.bindTo(x);
    return debug(mh, "bindTo", handle, x);
}
 
Example 20
@Override
public MethodHandle bindTo(final MethodHandle handle, final Object x) {
    return handle.bindTo(x);
}