Example usage for org.objectweb.asm Opcodes INVOKESTATIC

List of usage examples for org.objectweb.asm Opcodes INVOKESTATIC

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes INVOKESTATIC.

Prototype

int INVOKESTATIC

To view the source code for org.objectweb.asm Opcodes INVOKESTATIC.

Click Source Link

Usage

From source file:com.triage.bytecodemaster.TestObjectReferenceSwitches.java

public void testMergedInReplacingThisWithOtherVariable() throws Exception {

    final String FIELDPROXYWORKED = "FIELDPROXYWORKED";

    //set up the proxy object. this is the object that will receive
    //the proxied calls
    TestSubClass tcc = new TestSubClass();
    tcc.setBaseString(FIELDPROXYWORKED);

    TestBaseClassHolder.setTestBase(tcc);

    //get the dynamic source that has the donor body in it
    ClassNode donorSource = loadGroovyTestClassAsBytecode(GROOVY_CLASS_FIELDREF);
    MethodNode donorMethod = findMethod(donorSource, "before_whatDoIThinkAbout");

    //load the target class
    String TARGETCLASSNAME = "com.triage.bytecodemaster.fortesting.TestFriend";
    ClassNode targetSource = loadLocalClass(TARGETCLASSNAME);
    MethodNode targetMethod = findMethod(targetSource, "whatDoIThinkAbout");

    System.out.println("Target");
    printMethodNode(targetMethod);/*w w w.  j  a  va2s.co  m*/

    System.out.println("Donor");
    printMethodNode(donorMethod);

    //alright here's the strategy:  (1) inject a new local variable that points 
    //   to our remote instance,
    //  (2) inject code that sets this local to the value of a method call,
    //  (3) change references to 'this' ( ALOAD0 or ALOAD 0 ) to ALOAD1

    InsnList instructionsToInject = donorMethod.instructions;

    //make a new local variable
    LabelNode begin = new LabelNode();
    LabelNode end = new LabelNode();
    instructionsToInject.insertBefore(instructionsToInject.getFirst(), begin);
    instructionsToInject.add(end);

    Type type = Type.getObjectType("com/triage/bytecodemaster/fortesting/TestBaseClass");
    int variableIndex = donorMethod.maxLocals;
    donorMethod.maxLocals += type.getSize();
    donorMethod.visitLocalVariable("proxy", type.getDescriptor(), null, begin.getLabel(), end.getLabel(),
            variableIndex);

    //set the value of the local variable with a new instruction at the top
    //fetch a reference to our proxy object
    MethodInsnNode getTestBase = new MethodInsnNode(Opcodes.INVOKESTATIC,
            "com/triage/bytecodemaster/fortesting/TestBaseClassHolder", "getTestBase",
            "()Lcom/triage/bytecodemaster/fortesting/TestBaseClass;");

    //insert after begin label
    instructionsToInject.insert(begin, getTestBase);

    //store reference
    VarInsnNode setRef = new VarInsnNode(Opcodes.ASTORE, variableIndex);

    //insert store after fetch
    instructionsToInject.insert(getTestBase, setRef);

    //replace all references to 'this'  with the new variable

    for (int currentIndex = 0; currentIndex < instructionsToInject.size(); currentIndex++) {
        AbstractInsnNode node = instructionsToInject.get(currentIndex);
        if (node.getOpcode() == Opcodes.ALOAD) {
            VarInsnNode vin = (VarInsnNode) node;

            //'this' is var index 0. ours is var index varindex
            if (vin.var == 0) {
                vin.var = variableIndex;
            }
        }
    }

    System.out.println(">>>>>>>>>Finished Modifying<<<<<<<<");
    printMethodNode(donorMethod);

    //insert the donorMethod
    targetMethod.instructions.insert(instructionsToInject);

    System.out.println(">>>>>>>>>Final Method<<<<<<<<");
    printMethodNode(targetMethod);

    //write a class 
    Class c = createClassFromClassNode(targetSource, TARGETCLASSNAME);

    Object o = c.newInstance();
    Method m = o.getClass().getDeclaredMethod("whatDoIThinkAbout", TestPerson.class);
    TestPerson testPerson = new TestPerson();
    testPerson.setName("AAAA");
    //should return HAHAHA not baseStringValue 
    String result = (String) m.invoke(o, new Object[] { testPerson });
    System.out.println("TestFriend.whatDoIThinkAbout Result: " + result);
    assertTrue(result.equals(FIELDPROXYWORKED + "AAAA"));
}

From source file:com.trigersoft.jaque.expression.ExpressionMethodVisitor.java

License:Apache License

@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {

    Type[] argsTypes = Type.getArgumentTypes(desc);

    Class<?>[] parameterTypes = new Class<?>[argsTypes.length];
    for (int i = 0; i < argsTypes.length; i++)
        parameterTypes[i] = _classVisitor.getClass(argsTypes[i]);

    Expression[] arguments = new Expression[argsTypes.length];
    for (int i = argsTypes.length; i > 0;) {
        i--;//www. j ava  2s .c om
        arguments[i] = TypeConverter.convert(_exprStack.pop(), parameterTypes[i]);
    }

    Expression e;

    switch (opcode) {
    case Opcodes.INVOKESPECIAL:
        if (name.equals("<init>")) {
            try {
                e = Expression.newInstance(_exprStack.pop().getResultType(), parameterTypes, arguments);
            } catch (NoSuchMethodException nsme) {
                throw new RuntimeException(nsme);
            }
            _exprStack.pop(); // going to re-add it, which is not the JVM
                              // semantics
            break;
        }
    case Opcodes.INVOKEVIRTUAL:
    case Opcodes.INVOKEINTERFACE:
        try {
            e = Expression.invoke(
                    TypeConverter.convert(_exprStack.pop(), _classVisitor.getClass(Type.getObjectType(owner))),
                    name, parameterTypes, arguments);
        } catch (NoSuchMethodException nsme) {
            throw new RuntimeException(nsme);
        }
        break;

    case Opcodes.INVOKESTATIC:
    case Opcodes.INVOKEDYNAMIC:
        try {
            e = Expression.invoke(_classVisitor.getClass(Type.getObjectType(owner)), name, parameterTypes,
                    arguments);
        } catch (NoSuchMethodException nsme) {
            throw new RuntimeException(nsme);
        }
        break;

    default:
        throw new IllegalArgumentException("opcode: " + opcode);
    }

    _exprStack.push(e);
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.DynamicBootstrapUnit.java

public void init() {
    ProgramValueTypeAdapter types = environment.getValueTypeAdapter();
    BytecodeExpression classSource = types.constant(getEnvironment());
    TypeWidget dynamicLinker = types.adaptInternal(DynamicLinker.class);
    FieldDefinition field = createField(dynamicLinker, "bootstrap");
    field.addModifier(Opcodes.ACC_STATIC | Opcodes.ACC_FINAL);
    MethodGenerator sl = createMethod("<clinit>");
    sl.setModifier(Opcodes.ACC_STATIC);/*from w w  w.j a v a  2  s. com*/
    sl.add(classSource);
    sl.add(new BytecodeSequence() {
        @Override
        public void generate(CodeEmitter code) {
            final MethodVisitor mv = code.getMethodVisitor();
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Dynamic.class), "createDynamicLinker",
                    MethodType.methodType(DynamicLinker.class, ASMClassSource.class).toMethodDescriptorString(),
                    false);
            mv.visitFieldInsn(Opcodes.PUTSTATIC, Dynamic.DYNAMIC_INTERNAL_NAME, "bootstrap",
                    Type.getDescriptor(DynamicLinker.class));
            mv.visitInsn(Opcodes.RETURN);

        }
    });

    MethodGenerator mgen = createStaticMethod(Dynamic.DYNAMIC_BOOTSTRAP_METHOD);
    TypeWidget callSite = types.adaptInternal(CallSite.class);
    TypeWidget lookup = types.adaptInternal(MethodHandles.Lookup.class);
    TypeWidget methodType = types.adaptInternal(MethodType.class);
    mgen.setReturnType(callSite);
    AssignableValue lu = mgen.addArgument("lookup", lookup);
    AssignableValue name = mgen.addArgument("name", BaseTypeAdapter.STRING);
    AssignableValue sig = mgen.addArgument("sig", methodType);
    final String desc = MethodType.methodType(CallSite.class, // ...that will return a CallSite object, ...
            MethodHandles.Lookup.class, // ... when given a lookup object, ...
            String.class, // ... the operation name, ...
            MethodType.class, // ... and the signature at the call site.
            DynamicLinker.class).toMethodDescriptorString();

    mgen.add(lu.read());
    mgen.add(name.read());
    mgen.add(sig.read());

    mgen.add(new BytecodeSequence() {
        @Override
        public void generate(CodeEmitter code) {
            final MethodVisitor mv = code.getMethodVisitor();
            mv.visitFieldInsn(Opcodes.GETSTATIC, Dynamic.DYNAMIC_INTERNAL_NAME, "bootstrap",
                    Type.getDescriptor(DynamicLinker.class));
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Dynamic.class), "link", desc, false);
            mv.visitInsn(Opcodes.ARETURN);
        }
    });

}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.RecordMapPropertyAdapter.java

@Override
public AssignableValue index(final BytecodeExpression target, final BytecodeExpression propertyName) {
    return new AssignableValue() {
        @Override//from   w  w w  .  j ava 2 s  .  c  om
        public TypeWidget getType() {
            return AnyTypeWidget.getInstance();
        }

        @Override
        public BytecodeSequence write(BytecodeExpression value) {
            return new PopExpression(new InvokeExpression(Map.class, Opcodes.INVOKEINTERFACE, "put",
                    Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class),
                            Type.getType(Object.class)),
                    AnyTypeWidget.getInstance(), target, ImmutableList.of(propertyName, value)));
        }

        @Override
        public BytecodeSequence write(final TypeWidget top) {
            return new BytecodeSequence() {
                @Override
                public void generate(CodeEmitter code) {
                    AssignableValue out = code.allocate(top);
                    out.write(top);
                    write(out);
                }
            };
        }

        @Override
        public void generate(CodeEmitter code) {
            read().generate(code);
        }

        @Override
        public BytecodeExpression read() {
            return new InvokeExpression(RecordPropertyAdapter.class, Opcodes.INVOKESTATIC, "get",
                    Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Record.class),
                            Type.getType(Object.class)),
                    AnyTypeWidget.getInstance(), null, ImmutableList.of(target, propertyName));
        }
    };
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.RecordPropertyAdapter.java

@Override
public AssignableValue index(final BytecodeExpression target, final BytecodeExpression propertyName) {
    return new ReadOnlyAssignableValue(AnyTypeWidget.getInstance()) {
        @Override//  w  w w  .ja  va  2  s.  co  m
        public BytecodeExpression read() {
            return new InvokeExpression(RecordPropertyAdapter.class, Opcodes.INVOKESTATIC, "get",
                    Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Record.class),
                            Type.getType(Object.class)),
                    AnyTypeWidget.getInstance(), null, ImmutableList.of(target, propertyName));
        }
    };
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.StreamOperatorCompilerTest.java

@Test
public void requireGroupbyAggregate() throws Exception {
    List<MyRecord> input = ImmutableList.of(new MyRecord(1, "a"), new MyRecord(5, "c"), new MyRecord(10, "c"),
            new MyRecord(1, "a"), new MyRecord(3, "d"));
    Callable<Object> invoker = compileStream(input,
            OperatorNode.create(StreamOperator.GROUPBY, accumulate(),
                    OperatorNode.create(FunctionOperator.FUNCTION, ImmutableList.of("$row"),
                            OperatorNode.create(PhysicalExprOperator.PROPREF,
                                    OperatorNode.create(PhysicalExprOperator.LOCAL, "$row"), "sval")),
                    OperatorNode.create(FunctionOperator.FUNCTION, ImmutableList.of("$key", "$rows"),
                            OperatorNode.create(PhysicalExprOperator.INVOKE,
                                    ExactInvocation.exactInvoke(Opcodes.INVOKESTATIC, "aggregate",
                                            scope.adapt(StreamOperatorCompilerTest.class, false),
                                            scope.adapt(MyRecord.class, false), BaseTypeAdapter.STRING,
                                            scope.adapt(List.class, false)),
                                    ImmutableList.of(OperatorNode.create(PhysicalExprOperator.LOCAL, "$key"),
                                            OperatorNode.create(PhysicalExprOperator.LOCAL, "$rows"))))));
    Assert.assertEquals(ImmutableList.of(new MyRecord(2, "a"), new MyRecord(15, "c"), new MyRecord(3, "d")),
            invoker.call());//  w w w.j  a  v a  2  s.c  o  m
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.StreamOperatorCompilerTest.java

private OperatorNode<PhysicalExprOperator> doSingleLookupImage(OperatorNode<PhysicalExprOperator> key) {
    return OperatorNode.create(PhysicalExprOperator.INVOKE,
            ExactInvocation.exactInvoke(Opcodes.INVOKESTATIC, "lookupImage",
                    scope.adapt(StreamOperatorCompilerTest.class, false),
                    new ListTypeWidget(scope.adapt(Image.class, false)), BaseTypeAdapter.INT32),
            ImmutableList.of(key));//  w w  w  .ja  v  a 2s.c  o  m
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.types.gambit.ExpressionHandler.java

@Override
public BytecodeExpression invokeStatic(Location loc, String methodName, Class<?> owner, TypeWidget returnType,
        List<BytecodeExpression> args) {
    return invoke(loc, ExactInvocation.boundInvoke(Opcodes.INVOKESTATIC, methodName, adapt(owner, false),
            returnType, args), ImmutableList.<BytecodeExpression>of());
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.types.gambit.PhysicalExprOperatorCompiler.java

public BytecodeExpression evaluateExpression(final BytecodeExpression program, final BytecodeExpression context,
        final OperatorNode<PhysicalExprOperator> expr) {
    switch (expr.getOperator()) {
    case ASYNC_INVOKE:
    case INVOKE: {
        GambitCreator.Invocable invocable = expr.getArgument(0);
        List<OperatorNode<PhysicalExprOperator>> args = expr.getArgument(1);
        List<BytecodeExpression> arguments = evaluateExpressions(program, context, args);
        BytecodeExpression result = scope.invoke(expr.getLocation(), invocable, arguments);
        if (expr.getOperator() == PhysicalExprOperator.ASYNC_INVOKE) {
            return scope.resolve(expr.getLocation(), getTimeout(context, expr.getLocation()), result);
        }/*  w  ww .ja v  a2  s .co m*/
        return result;
    }
    case CALL: {
        TypeWidget outputType = expr.getArgument(0);
        String name = expr.getArgument(1);
        List<OperatorNode<PhysicalExprOperator>> arguments = expr.getArgument(2);
        List<BytecodeExpression> argumentExprs = evaluateExpressions(program, context, arguments);
        return scope.call(expr.getLocation(), outputType, name, argumentExprs);
    }
    case CONSTANT: {
        TypeWidget t = expr.getArgument(0);
        Object cval = expr.getArgument(1);
        return scope.constant(t, cval);
    }
    case ROOT_CONTEXT: {
        return scope.propertyValue(expr.getLocation(), program, "rootContext");
    }
    case CURRENT_CONTEXT:
        return context;
    case TRACE_CONTEXT: {
        OperatorNode<PhysicalExprOperator> attrs = expr.getArgument(0);
        final BytecodeExpression metricDimension = asMetricDimension(program, context, attrs);
        return scope.invokeExact(expr.getLocation(), "start", TaskContext.class, context.getType(), context,
                metricDimension);
    }
    case TIMEOUT_MAX: {
        final BytecodeExpression timeout = scope.cast(BaseTypeAdapter.INT64,
                evaluateExpression(program, context, expr.<OperatorNode<PhysicalExprOperator>>getArgument(0)));
        final BytecodeExpression units = evaluateExpression(program, context,
                expr.<OperatorNode<PhysicalExprOperator>>getArgument(1));
        return scope.invokeExact(expr.getLocation(), "timeout", TaskContext.class, context.getType(), context,
                timeout, units);
    }
    case TIMEOUT_GUARD: {
        final BytecodeExpression min = scope.cast(BaseTypeAdapter.INT64,
                evaluateExpression(program, context, expr.<OperatorNode<PhysicalExprOperator>>getArgument(0)));
        final BytecodeExpression minUnits = evaluateExpression(program, context,
                expr.<OperatorNode<PhysicalExprOperator>>getArgument(1));
        final BytecodeExpression max = scope.cast(BaseTypeAdapter.INT64,
                evaluateExpression(program, context, expr.<OperatorNode<PhysicalExprOperator>>getArgument(2)));
        final BytecodeExpression maxUnits = evaluateExpression(program, context,
                expr.<OperatorNode<PhysicalExprOperator>>getArgument(3));
        return scope.invokeExact(expr.getLocation(), "timeout", TaskContext.class, context.getType(), context,
                min, minUnits, max, maxUnits);
    }
    case END_CONTEXT: {
        final BytecodeExpression output = evaluateExpression(program, context,
                expr.<OperatorNode<PhysicalExprOperator>>getArgument(0));
        GambitCreator.ScopeBuilder child = scope.scope();
        BytecodeExpression result = child.evaluateInto(output);
        child.exec(
                child.invokeExact(expr.getLocation(), "end", TaskContext.class, BaseTypeAdapter.VOID, context));
        return child.complete(result);
    }
    case VALUE: {
        OperatorValue value = expr.getArgument(0);
        return resolveValue(expr.getLocation(), program, context, value);
    }
    case CAST: {
        final TypeWidget outputType = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> input = expr.getArgument(1);
        final BytecodeExpression output = evaluateExpression(program, context, input);
        return scope.cast(expr.getLocation(), outputType, output);
    }
    case FOREACH: {
        BytecodeExpression inputExpr = evaluateExpression(program, context,
                expr.<OperatorNode<PhysicalExprOperator>>getArgument(0));
        OperatorNode<FunctionOperator> function = expr.getArgument(1);
        TypeWidget itemType = inputExpr.getType().getIterableAdapter().getValue();
        GambitCreator.Invocable functionImpl = compileFunction(program.getType(), context.getType(),
                ImmutableList.of(itemType), function);
        return scope.transform(expr.getLocation(), inputExpr, functionImpl.prefix(program, context));
    }
    case FIRST: {
        BytecodeExpression inputExpr = evaluateExpression(program, context,
                expr.<OperatorNode<PhysicalExprOperator>>getArgument(0));
        return scope.first(expr.getLocation(), inputExpr);
    }
    case SINGLETON: {
        OperatorNode<PhysicalExprOperator> value = expr.getArgument(0);
        BytecodeExpression targetExpression = evaluateExpression(program, context, value);
        return scope.invokeExact(expr.getLocation(), "singleton", ProgramInvocation.class,
                new ListTypeWidget(targetExpression.getType()), program,
                scope.cast(AnyTypeWidget.getInstance(), targetExpression));
    }
    case LENGTH: {
        BytecodeExpression inputExpr = evaluateExpression(program, context,
                expr.<OperatorNode<PhysicalExprOperator>>getArgument(0));
        return scope.length(expr.getLocation(), inputExpr);
    }
    case PROPREF: {
        OperatorNode<PhysicalExprOperator> target = expr.getArgument(0);
        String propertyName = expr.getArgument(1);
        BytecodeExpression targetExpr = evaluateExpression(program, context, target);
        return scope.propertyValue(expr.getLocation(), targetExpr, propertyName);
    }
    case INDEX: {
        OperatorNode<PhysicalExprOperator> target = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> index = expr.getArgument(1);
        BytecodeExpression targetExpr = evaluateExpression(program, context, target);
        BytecodeExpression indexExpr = evaluateExpression(program, context, index);
        return scope.indexValue(expr.getLocation(), targetExpr, indexExpr);
    }
    case WITH_CONTEXT: {
        GambitCreator.ScopeBuilder contextScope = scope.scope();
        PhysicalExprOperatorCompiler compiler = new PhysicalExprOperatorCompiler(contextScope);
        BytecodeExpression ctxExpr = contextScope.evaluateInto(compiler.evaluateExpression(program, context,
                expr.<OperatorNode<PhysicalExprOperator>>getArgument(0)));
        OperatorNode<PhysicalExprOperator> exprTarget = expr.getArgument(1);
        BytecodeExpression resultExpr = compiler.evaluateExpression(program, ctxExpr,
                OperatorNode.create(PhysicalExprOperator.END_CONTEXT, exprTarget));
        return contextScope.complete(resultExpr);
    }
    case CONCAT: {
        List<OperatorNode<PhysicalExprOperator>> iterables = expr.getArgument(0);
        List<BytecodeExpression> exprs = evaluateExpressions(program, context, iterables);
        List<TypeWidget> types = Lists.newArrayList();
        for (BytecodeExpression e : exprs) {
            types.add(e.getType().getIterableAdapter().getValue());
        }

        return scope
                .cast(expr.getLocation(), new IterableTypeWidget(scope.unify(types)),
                        ExactInvocation
                                .boundInvoke(Opcodes.INVOKESTATIC, "concat",
                                        scope.adapt(Iterables.class, false), scope.adapt(Iterable.class, false),
                                        scope.cast(scope.adapt(Iterable.class, false),
                                                scope.list(expr.getLocation(), exprs)))
                                .invoke(expr.getLocation()));
    }
    case ENFORCE_TIMEOUT: {
        List<BytecodeExpression> localExprs = Lists.newArrayList();
        List<TypeWidget> types = Lists.newArrayList();
        List<String> localNames = expr.getOperator().localsFor(expr);
        localExprs.add(program);
        localExprs.add(context);
        for (String local : localNames) {
            BytecodeExpression arg = scope.local(expr.getLocation(), local);
            localExprs.add(arg);
            types.add(arg.getType());
        }
        CallableInvocable invocation = compileCallable(program.getType(), context.getType(), types,
                OperatorNode.create(FunctionOperator.FUNCTION, localNames, expr.getArgument(0)));
        final BytecodeExpression timeout = getTimeout(context, expr.getLocation());
        return scope.resolve(expr.getLocation(), timeout,
                scope.fork(expr.getLocation(), getRuntime(scope, program, context), invocation, localExprs));
    }
    case LOCAL: {
        String localName = expr.getArgument(0);
        return scope.local(expr.getLocation(), localName);
    }
    case EQ:
    case NEQ: {
        OperatorNode<PhysicalExprOperator> left = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> right = expr.getArgument(1);
        final BytecodeExpression leftExpr = evaluateExpression(program, context, left);
        final BytecodeExpression rightExpr = evaluateExpression(program, context, right);
        return expr.getOperator() == PhysicalExprOperator.EQ ? scope.eq(expr.getLocation(), leftExpr, rightExpr)
                : scope.neq(expr.getLocation(), leftExpr, rightExpr);
    }
    case BOOLEAN_COMPARE: {
        final BinaryComparison booleanComparison = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> left = expr.getArgument(1);
        OperatorNode<PhysicalExprOperator> right = expr.getArgument(2);
        final BytecodeExpression leftExpr = evaluateExpression(program, context, left);
        final BytecodeExpression rightExpr = evaluateExpression(program, context, right);
        return scope.compare(expr.getLocation(), booleanComparison, leftExpr, rightExpr);
    }

    case BINARY_MATH: {
        final ArithmeticOperation arithmeticOperation = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> left = expr.getArgument(1);
        OperatorNode<PhysicalExprOperator> right = expr.getArgument(2);
        final BytecodeExpression leftExpr = evaluateExpression(program, context, left);
        final BytecodeExpression rightExpr = evaluateExpression(program, context, right);
        return scope.arithmetic(expr.getLocation(), arithmeticOperation, leftExpr, rightExpr);
    }
    case COMPARE: {
        OperatorNode<PhysicalExprOperator> left = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> right = expr.getArgument(1);
        final BytecodeExpression leftExpr = evaluateExpression(program, context, left);
        final BytecodeExpression rightExpr = evaluateExpression(program, context, right);
        return scope.compare(expr.getLocation(), leftExpr, rightExpr);
    }
    case MULTICOMPARE: {
        List<OperatorNode<PhysicalExprOperator>> exprs = expr.getArgument(0);
        List<BytecodeExpression> expressions = evaluateExpressions(program, context, exprs);
        return scope.composeCompare(expressions);
    }
    case COALESCE: {
        List<OperatorNode<PhysicalExprOperator>> exprs = expr.getArgument(0);
        List<BytecodeExpression> expressions = evaluateExpressions(program, context, exprs);
        return scope.coalesce(expr.getLocation(), expressions);
    }
    case IF: {
        OperatorNode<PhysicalExprOperator> test = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> ifTrue = expr.getArgument(1);
        OperatorNode<PhysicalExprOperator> ifFalse = expr.getArgument(2);
        return handleIfTail(program, context, scope.createCase(), test, ifTrue, ifFalse);
    }
    case STREAM_EXECUTE: {
        OperatorNode<PhysicalExprOperator> input = expr.getArgument(0);
        OperatorNode<StreamOperator> stream = expr.getArgument(1);
        return streamExecute(program, context, input, stream);
    }
    case STREAM_CREATE: {
        OperatorNode<StreamOperator> t = expr.getArgument(0);
        return compileStreamCreate(program, context, t);
    }
    case STREAM_COMPLETE: {
        OperatorNode<PhysicalExprOperator> streamExpression = expr.getArgument(0);
        BytecodeExpression streamExpr = evaluateExpression(program, context, streamExpression);
        return scope.invoke(expr.getLocation(),
                ExactInvocation.boundInvoke(Opcodes.INVOKEVIRTUAL, "complete", streamExpr.getType(),
                        // ideally this would unify the types of the input streams
                        new ListTypeWidget(AnyTypeWidget.getInstance()), streamExpr));
    }
    case RECORD: {
        List<String> names = expr.getArgument(0);
        List<OperatorNode<PhysicalExprOperator>> exprs = expr.getArgument(1);
        List<BytecodeExpression> evaluated = evaluateExpressions(program, context, exprs);
        GambitCreator.RecordBuilder recordBuilder = scope.record();
        for (int i = 0; i < names.size(); ++i) {
            recordBuilder.add(expr.getLocation(), names.get(i), evaluated.get(i));
        }
        return recordBuilder.build();
    }
    case RECORD_AS: {
        TypeWidget recordType = expr.getArgument(0);
        List<String> names = expr.getArgument(1);
        List<OperatorNode<PhysicalExprOperator>> exprs = expr.getArgument(2);
        List<BytecodeExpression> evaluated = evaluateExpressions(program, context, exprs);
        Map<String, BytecodeExpression> sets = Maps.newLinkedHashMap();
        for (int i = 0; i < names.size(); ++i) {
            sets.put(names.get(i), evaluated.get(i));
        }
        if (!recordType.hasProperties()) {
            throw new ProgramCompileException(expr.getLocation(), "Type passed to RECORD_AS has no properties",
                    recordType.getTypeName());
        }
        return recordType.getPropertyAdapter().construct(sets);
    }
    case PROJECT: {
        List<OperatorNode<PhysicalProjectOperator>> operations = expr.getArgument(0);
        GambitCreator.RecordBuilder recordBuilder;
        if ("map".equals(expr.getAnnotation("project:type"))) {
            recordBuilder = scope.dynamicRecord();
        } else {
            recordBuilder = scope.record();
        }
        for (OperatorNode<PhysicalProjectOperator> op : operations) {
            switch (op.getOperator()) {
            case FIELD: {
                OperatorNode<PhysicalExprOperator> fieldValue = op.getArgument(0);
                String fieldName = op.getArgument(1);
                recordBuilder.add(expr.getLocation(), fieldName,
                        evaluateExpression(program, context, fieldValue));
                break;
            }
            case MERGE: {
                OperatorNode<PhysicalExprOperator> fieldValue = op.getArgument(0);
                recordBuilder.merge(expr.getLocation(), evaluateExpression(program, context, fieldValue));
                break;
            }
            default:
                throw new UnsupportedOperationException("Unknown PhysicalProjectOperator: " + op.getOperator());
            }
        }
        return recordBuilder.build();

    }
    case NULL: {
        TypeWidget type = expr.getArgument(0);
        return scope.nullFor(type);
    }
    case GENERATE_KEYS: {
        List<String> names = expr.getArgument(0);
        List<OperatorNode<PhysicalExprOperator>> valueLists = expr.getArgument(1);
        List<BytecodeExpression> insns = Lists.newArrayListWithCapacity(names.size() * 2);
        for (int i = 0; i < names.size(); ++i) {
            insns.add(scope.constant(names.get(i)));
            BytecodeExpression keyExpr = evaluateExpression(program, context, valueLists.get(i));
            insns.add(scope.cast(AnyTypeWidget.getInstance(), keyExpr));
        }

        BytecodeExpression arr = scope.array(expr.getLocation(), BaseTypeAdapter.ANY, insns);
        GambitCreator.Invocable factory = scope.constructor(keyCursorFor(scope, names), arr.getType());
        return scope.invoke(expr.getLocation(), factory, arr);
    }
    case OR: {
        List<OperatorNode<PhysicalExprOperator>> args = expr.getArgument(0);
        return scope.or(expr.getLocation(), evaluateExpressions(program, context, args));
    }
    case AND: {
        List<OperatorNode<PhysicalExprOperator>> args = expr.getArgument(0);
        return scope.and(expr.getLocation(), evaluateExpressions(program, context, args));
    }
    case IN: {
        OperatorNode<PhysicalExprOperator> left = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> right = expr.getArgument(1);
        return scope.in(expr.getLocation(), evaluateExpression(program, context, left),
                evaluateExpression(program, context, right));
    }
    case CONTAINS: {
        OperatorNode<PhysicalExprOperator> left = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> right = expr.getArgument(1);
        return scope.contains(expr.getLocation(), evaluateExpression(program, context, left),
                evaluateExpression(program, context, right));
    }
    case MATCHES: {
        OperatorNode<PhysicalExprOperator> left = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> right = expr.getArgument(1);
        return scope.matches(expr.getLocation(), evaluateExpression(program, context, left),
                evaluateExpression(program, context, right));
    }
    case NOT: {
        OperatorNode<PhysicalExprOperator> target = expr.getArgument(0);
        return scope.not(expr.getLocation(), evaluateExpression(program, context, target));
    }
    case NEGATE: {
        OperatorNode<PhysicalExprOperator> target = expr.getArgument(0);
        return scope.negate(expr.getLocation(), evaluateExpression(program, context, target));
    }
    case IS_NULL: {
        OperatorNode<PhysicalExprOperator> target = expr.getArgument(0);
        return scope.isNull(expr.getLocation(), evaluateExpression(program, context, target));
    }
    case BOOL: {
        OperatorNode<PhysicalExprOperator> target = expr.getArgument(0);
        return scope.bool(expr.getLocation(), evaluateExpression(program, context, target));
    }
    case ARRAY: {
        List<OperatorNode<PhysicalExprOperator>> args = expr.getArgument(0);
        return scope.list(expr.getLocation(), evaluateExpressions(program, context, args));
    }
    case CATCH: {
        OperatorNode<PhysicalExprOperator> primary = expr.getArgument(0);
        OperatorNode<PhysicalExprOperator> fallback = expr.getArgument(1);
        return scope.fallback(expr.getLocation(), evaluateExpression(program, context, primary),
                evaluateExpression(program, context, fallback));
    }
    case NEW: {
        TypeWidget type = expr.getArgument(0);
        List<OperatorNode<PhysicalExprOperator>> valueLists = expr.getArgument(1);
        List<BytecodeExpression> exprs = evaluateExpressions(program, context, valueLists);
        List<TypeWidget> types = Lists.newArrayList();
        for (BytecodeExpression e : exprs) {
            types.add(e.getType());
        }
        return scope.invoke(expr.getLocation(), scope.constructor(type, types), exprs);
    }
    case INJECT_MEMBERS: {
        OperatorNode<PhysicalExprOperator> value = expr.getArgument(0);
        final BytecodeExpression result = evaluateExpression(program, context, value);
        final BytecodeExpression injector = getInjector(program, context);
        return new BaseTypeExpression(result.getType()) {
            @Override
            public void generate(CodeEmitter code) {
                code.exec(result);
                code.dup(result.getType());
                code.exec(injector);
                code.swap(injector.getType(), result.getType());
                code.getMethodVisitor().visitMethodInsn(Opcodes.INVOKEINTERFACE,
                        Type.getInternalName(Injector.class), "injectMembers",
                        Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class)), true);
            }
        };

    }
    default:
        throw new ProgramCompileException("Unimplemented PhysicalExprOperator: " + expr.toString());
    }
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.types.gambit.TypesHandler.java

@Override
public GambitCreator.Invocable findStaticInvoker(Class<?> owner, String methodName, TypeWidget returnType,
        List<TypeWidget> argumentTypes) {
    return ExactInvocation.exactInvoke(Opcodes.INVOKESTATIC, methodName, adapt(owner, false), returnType,
            argumentTypes);// w w w  .jav  a  2 s.  co  m
}