Example usage for org.objectweb.asm Opcodes ACC_FINAL

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

Introduction

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

Prototype

int ACC_FINAL

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

Click Source Link

Usage

From source file:org.apache.cxf.jaxb.JAXBUtils.java

License:Apache License

private static Class<?> createNamespaceWrapperInternal(ASMHelper helper, ClassWriter cw) {
    String className = "org.apache.cxf.jaxb.NamespaceMapperInternal";
    FieldVisitor fv;/*from ww w .jav a 2  s. c  o  m*/
    MethodVisitor mv;
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
            "org/apache/cxf/jaxb/NamespaceMapperInternal", null,
            "com/sun/xml/internal/bind/marshaller/NamespacePrefixMapper", null);

    cw.visitSource("NamespaceMapper.java", null);

    fv = cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "nspref", "Ljava/util/Map;",
            "Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", null);
    fv.visitEnd();

    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "(Ljava/util/Map;)V",
            "(Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;)V", null);
    mv.visitCode();
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitLineNumber(30, l0);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/sun/xml/internal/bind/marshaller/NamespacePrefixMapper",
            "<init>", "()V");
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLineNumber(31, l1);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitFieldInsn(Opcodes.PUTFIELD, "org/apache/cxf/jaxb/NamespaceMapperInternal", "nspref",
            "Ljava/util/Map;");
    Label l2 = new Label();
    mv.visitLabel(l2);
    mv.visitLineNumber(32, l2);
    mv.visitInsn(Opcodes.RETURN);
    Label l3 = new Label();
    mv.visitLabel(l3);
    mv.visitLocalVariable("this", "Lorg/apache/cxf/jaxb/NamespaceMapperInternal;", null, l0, l3, 0);
    mv.visitLocalVariable("nspref", "Ljava/util/Map;", "Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;",
            l0, l3, 1);
    mv.visitMaxs(2, 2);
    mv.visitEnd();

    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPreferredPrefix",
            "(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String;", null, null);
    mv.visitCode();
    l0 = new Label();
    mv.visitLabel(l0);
    mv.visitLineNumber(38, l0);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "org/apache/cxf/jaxb/NamespaceMapperInternal", "nspref",
            "Ljava/util/Map;");
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "get",
            "(Ljava/lang/Object;)Ljava/lang/Object;");
    mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/String");
    mv.visitVarInsn(Opcodes.ASTORE, 4);
    l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLineNumber(39, l1);
    mv.visitVarInsn(Opcodes.ALOAD, 4);
    l2 = new Label();
    mv.visitJumpInsn(Opcodes.IFNULL, l2);
    l3 = new Label();
    mv.visitLabel(l3);
    mv.visitLineNumber(40, l3);
    mv.visitVarInsn(Opcodes.ALOAD, 4);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitLabel(l2);
    mv.visitLineNumber(42, l2);
    mv.visitVarInsn(Opcodes.ALOAD, 2);
    mv.visitInsn(Opcodes.ARETURN);
    Label l4 = new Label();
    mv.visitLabel(l4);
    mv.visitLocalVariable("this", "Lorg/apache/cxf/jaxb/NamespaceMapperInternal;", null, l0, l4, 0);
    mv.visitLocalVariable("namespaceUri", "Ljava/lang/String;", null, l0, l4, 1);
    mv.visitLocalVariable("suggestion", "Ljava/lang/String;", null, l0, l4, 2);
    mv.visitLocalVariable("requirePrefix", "Z", null, l0, l4, 3);
    mv.visitLocalVariable("prefix", "Ljava/lang/String;", null, l1, l4, 4);
    mv.visitMaxs(2, 5);
    mv.visitEnd();
    cw.visitEnd();

    byte bts[] = cw.toByteArray();
    return helper.loadClass(className, JAXBUtils.class, bts);
}

From source file:org.apache.felix.ipojo.handler.temporal.ProxyGenerator.java

License:Apache License

/**
 * Generates a proxy class./*from  w  w w .j  a  v  a2  s.c om*/
 * @param spec the proxied service specification
 * @return the byte[] for the generated proxy class.
 */
public static byte[] dumpProxy(Class spec) {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String internalClassName = Type.getInternalName(spec); // Specification class internal name.
    String[] itfs = new String[] { internalClassName }; // Implemented interface.
    String className = internalClassName + "$$Proxy"; // Unique name.
    Method[] methods = spec.getMethods(); // Method to delegate

    cw.visit(Opcodes.V1_3, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, className, null, "java/lang/Object", itfs);
    addDependencyField(cw);
    generateConstructor(cw, className);

    // For each method, create the delegator code.
    for (int i = 0; i < methods.length; i++) {
        if ((methods[i].getModifiers() & (Modifier.STATIC | Modifier.FINAL)) == 0) {
            generateDelegator(cw, methods[i], className, internalClassName);
        }
    }

    cw.visitEnd();

    return cw.toByteArray();

}

From source file:org.apache.groovy.parser.antlr4.AstBuilder.java

License:Apache License

@Override
public ClassNode visitClassDeclaration(ClassDeclarationContext ctx) {
    String packageName = moduleNode.getPackageName();
    packageName = null != packageName ? packageName : "";

    List<ModifierNode> modifierNodeList = ctx.getNodeMetaData(TYPE_DECLARATION_MODIFIERS);
    Objects.requireNonNull(modifierNodeList, "modifierNodeList should not be null");

    ModifierManager modifierManager = new ModifierManager(this, modifierNodeList);
    int modifiers = modifierManager.getClassModifiersOpValue();

    boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0);
    modifiers &= ~Opcodes.ACC_SYNTHETIC;

    final ClassNode outerClass = classNodeStack.peek();
    ClassNode classNode;//from   w  w  w.  j  av a2 s.c  o m
    String className = this.visitIdentifier(ctx.identifier());

    if (VAR_STR.equals(className)) {
        throw createParsingFailedException("var cannot be used for type declarations", ctx.identifier());
    }

    if (asBoolean(ctx.ENUM())) {
        classNode = EnumHelper.makeEnumNode(asBoolean(outerClass) ? className : packageName + className,
                modifiers, null, outerClass);
    } else {
        if (asBoolean(outerClass)) {
            classNode = new InnerClassNode(outerClass, outerClass.getName() + "$" + className,
                    modifiers | (outerClass.isInterface() ? Opcodes.ACC_STATIC : 0), ClassHelper.OBJECT_TYPE);
        } else {
            classNode = new ClassNode(packageName + className, modifiers, ClassHelper.OBJECT_TYPE);
        }
    }

    configureAST(classNode, ctx);
    classNode.putNodeMetaData(CLASS_NAME, className);
    classNode.setSyntheticPublic(syntheticPublic);

    if (asBoolean(ctx.TRAIT())) {
        attachTraitAnnotation(classNode);
    }
    classNode.addAnnotations(modifierManager.getAnnotations());
    classNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters()));

    boolean isInterface = asBoolean(ctx.INTERFACE()) && !asBoolean(ctx.AT());
    boolean isInterfaceWithDefaultMethods = false;

    // declaring interface with default method
    if (isInterface && this.containsDefaultMethods(ctx)) {
        isInterfaceWithDefaultMethods = true;
        attachTraitAnnotation(classNode);
        classNode.putNodeMetaData(IS_INTERFACE_WITH_DEFAULT_METHODS, true);
    }

    if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()) || isInterfaceWithDefaultMethods) { // class OR trait OR interface with default methods
        classNode.setSuperClass(this.visitType(ctx.sc));
        classNode.setInterfaces(this.visitTypeList(ctx.is));

        this.initUsingGenerics(classNode);
    } else if (isInterface) { // interface(NOT annotation)
        classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT);

        classNode.setSuperClass(ClassHelper.OBJECT_TYPE);
        classNode.setInterfaces(this.visitTypeList(ctx.scs));

        this.initUsingGenerics(classNode);

        this.hackMixins(classNode);
    } else if (asBoolean(ctx.ENUM())) { // enum
        classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_ENUM | Opcodes.ACC_FINAL);

        classNode.setInterfaces(this.visitTypeList(ctx.is));

        this.initUsingGenerics(classNode);
    } else if (asBoolean(ctx.AT())) { // annotation
        classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT
                | Opcodes.ACC_ANNOTATION);

        classNode.addInterface(ClassHelper.Annotation_TYPE);

        this.hackMixins(classNode);
    } else {
        throw createParsingFailedException("Unsupported class declaration: " + ctx.getText(), ctx);
    }

    // we put the class already in output to avoid the most inner classes
    // will be used as first class later in the loader. The first class
    // there determines what GCL#parseClass for example will return, so we
    // have here to ensure it won't be the inner class
    if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT())) {
        classNodeList.add(classNode);
    }

    classNodeStack.push(classNode);
    ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
    this.visitClassBody(ctx.classBody());
    classNodeStack.pop();

    if (!(asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()))) {
        classNodeList.add(classNode);
    }

    groovydocManager.handle(classNode, ctx);

    return classNode;
}

From source file:org.apache.groovy.parser.antlr4.AstBuilder.java

License:Apache License

private DeclarationListStatement createFieldDeclarationListStatement(VariableDeclarationContext ctx,
        ModifierManager modifierManager, ClassNode variableType,
        List<DeclarationExpression> declarationExpressionList, ClassNode classNode) {
    for (int i = 0, n = declarationExpressionList.size(); i < n; i++) {
        DeclarationExpression declarationExpression = declarationExpressionList.get(i);
        VariableExpression variableExpression = (VariableExpression) declarationExpression.getLeftExpression();

        String fieldName = variableExpression.getName();

        int modifiers = modifierManager.getClassMemberModifiersOpValue();

        Expression initialValue = declarationExpression.getRightExpression() instanceof EmptyExpression ? null
                : declarationExpression.getRightExpression();
        Object defaultValue = findDefaultValueByType(variableType);

        if (classNode.isInterface()) {
            if (!asBoolean(initialValue)) {
                initialValue = !asBoolean(defaultValue) ? null : new ConstantExpression(defaultValue);
            }/* ww  w  . j ava 2s .  c o  m*/

            modifiers |= Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
        }

        if (isFieldDeclaration(modifierManager, classNode)) {
            declareField(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName,
                    modifiers, initialValue);
        } else {
            declareProperty(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName,
                    modifiers, initialValue);
        }
    }

    return null;
}

From source file:org.apache.groovy.parser.antlr4.AstBuilder.java

License:Apache License

@Override
public InnerClassNode visitAnonymousInnerClassDeclaration(AnonymousInnerClassDeclarationContext ctx) {
    ClassNode superClass = Objects.requireNonNull(ctx.getNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS),
            "superClass should not be null");
    ClassNode outerClass = Optional.ofNullable(classNodeStack.peek()).orElse(moduleNode.getScriptClassDummy());
    String innerClassName = nextAnonymousClassName(outerClass);

    InnerClassNode anonymousInnerClass;/*from ww  w .  ja  v a 2s. c o m*/
    if (1 == ctx.t) { // anonymous enum
        anonymousInnerClass = new EnumConstantClassNode(outerClass, innerClassName,
                superClass.getModifiers() | Opcodes.ACC_FINAL, superClass.getPlainNodeReference());
        // and remove the final modifier from classNode to allow the sub class
        superClass.setModifiers(superClass.getModifiers() & ~Opcodes.ACC_FINAL);
    } else { // anonymous inner class
        anonymousInnerClass = new InnerClassNode(outerClass, innerClassName, Opcodes.ACC_PUBLIC, superClass);
    }

    anonymousInnerClass.setUsingGenerics(false);
    anonymousInnerClass.setAnonymous(true);
    anonymousInnerClass.putNodeMetaData(CLASS_NAME, innerClassName);
    configureAST(anonymousInnerClass, ctx);

    classNodeStack.push(anonymousInnerClass);
    ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, anonymousInnerClass);
    this.visitClassBody(ctx.classBody());
    classNodeStack.pop();

    classNodeList.add(anonymousInnerClass);

    return anonymousInnerClass;
}

From source file:org.apache.groovy.parser.antlr4.TryWithResourcesASTTransformation.java

License:Apache License

private ExpressionStatement makeVariableDeclarationFinal(ExpressionStatement variableDeclaration) {
    if (!asBoolean(variableDeclaration)) {
        return variableDeclaration;
    }/*from w  ww  .ja va  2  s . c o  m*/

    if (!(variableDeclaration.getExpression() instanceof DeclarationExpression)) {
        throw new IllegalArgumentException("variableDeclaration is not a declaration statement");
    }

    DeclarationExpression declarationExpression = (DeclarationExpression) variableDeclaration.getExpression();
    if (!(declarationExpression.getLeftExpression() instanceof VariableExpression)) {
        throw astBuilder.createParsingFailedException(
                "The expression statement is not a variable delcaration statement", variableDeclaration);
    }

    VariableExpression variableExpression = (VariableExpression) declarationExpression.getLeftExpression();
    variableExpression.setModifiers(variableExpression.getModifiers() | Opcodes.ACC_FINAL);

    return variableDeclaration;
}

From source file:org.apache.lucene.expressions.js.JavascriptCompiler.java

License:Apache License

/**
 * Sends the bytecode of class file to {@link ClassWriter}.
 *///from ww w. j  av a 2s . c  o m
private void generateClass(final ParseTree parseTree, final ClassWriter classWriter,
        final Map<String, Integer> externalsMap) throws ParseException {
    classWriter.visit(CLASSFILE_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL,
            COMPILED_EXPRESSION_INTERNAL, null, EXPRESSION_TYPE.getInternalName(), null);
    final String clippedSourceText = (sourceText.length() <= MAX_SOURCE_LENGTH) ? sourceText
            : (sourceText.substring(0, MAX_SOURCE_LENGTH - 3) + "...");
    classWriter.visitSource(clippedSourceText, null);

    final GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ACC_PUBLIC, EXPRESSION_CTOR, null, null,
            classWriter);
    constructor.loadThis();
    constructor.loadArgs();
    constructor.invokeConstructor(EXPRESSION_TYPE, EXPRESSION_CTOR);
    constructor.returnValue();
    constructor.endMethod();

    final GeneratorAdapter gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC, EVALUATE_METHOD, null, null,
            classWriter);

    // to completely hide the ANTLR visitor we use an anonymous impl:
    new JavascriptBaseVisitor<Void>() {
        private final Deque<Type> typeStack = new ArrayDeque<>();

        @Override
        public Void visitCompile(JavascriptParser.CompileContext ctx) {
            typeStack.push(Type.DOUBLE_TYPE);
            visit(ctx.expression());
            typeStack.pop();

            return null;
        }

        @Override
        public Void visitPrecedence(JavascriptParser.PrecedenceContext ctx) {
            visit(ctx.expression());

            return null;
        }

        @Override
        public Void visitNumeric(JavascriptParser.NumericContext ctx) {
            if (ctx.HEX() != null) {
                pushLong(Long.parseLong(ctx.HEX().getText().substring(2), 16));
            } else if (ctx.OCTAL() != null) {
                pushLong(Long.parseLong(ctx.OCTAL().getText().substring(1), 8));
            } else if (ctx.DECIMAL() != null) {
                gen.push(Double.parseDouble(ctx.DECIMAL().getText()));
                gen.cast(Type.DOUBLE_TYPE, typeStack.peek());
            } else {
                throw new IllegalStateException("Unknown operation specified: " + ctx.getText());
            }

            return null;
        }

        @Override
        public Void visitExternal(JavascriptParser.ExternalContext ctx) {
            String text = ctx.VARIABLE().getText();
            int arguments = ctx.expression().size();
            boolean parens = ctx.LP() != null && ctx.RP() != null;
            Method method = parens ? functions.get(text) : null;

            try {
                if (method != null) {
                    int arity = method.getParameterTypes().length;

                    if (arguments != arity) {
                        throw new ParseException("Invalid expression '" + sourceText + "': Expected (" + arity
                                + ") arguments for function call (" + text + "), but found (" + arguments
                                + ").", ctx.start.getStartIndex());
                    }

                    typeStack.push(Type.DOUBLE_TYPE);

                    for (int argument = 0; argument < arguments; ++argument) {
                        visit(ctx.expression(argument));
                    }

                    typeStack.pop();

                    gen.invokeStatic(Type.getType(method.getDeclaringClass()),
                            org.objectweb.asm.commons.Method.getMethod(method));

                    gen.cast(Type.DOUBLE_TYPE, typeStack.peek());
                } else if (!parens || arguments == 0 && text.contains(".")) {
                    int index;

                    text = normalizeQuotes(ctx.getText());

                    if (externalsMap.containsKey(text)) {
                        index = externalsMap.get(text);
                    } else {
                        index = externalsMap.size();
                        externalsMap.put(text, index);
                    }

                    gen.loadArg(0);
                    gen.push(index);
                    gen.arrayLoad(FUNCTION_VALUES_TYPE);
                    gen.invokeVirtual(FUNCTION_VALUES_TYPE, DOUBLE_VAL_METHOD);
                    gen.cast(Type.DOUBLE_TYPE, typeStack.peek());
                } else {
                    throw new ParseException("Invalid expression '" + sourceText
                            + "': Unrecognized function call (" + text + ").", ctx.start.getStartIndex());
                }
                return null;
            } catch (ParseException e) {
                // The API doesn't allow checked exceptions here, so propagate up the stack. This is unwrapped
                // in getAntlrParseTree. 
                throw new RuntimeException(e);
            }
        }

        @Override
        public Void visitUnary(JavascriptParser.UnaryContext ctx) {
            if (ctx.BOOLNOT() != null) {
                Label labelNotTrue = new Label();
                Label labelNotReturn = new Label();

                typeStack.push(Type.INT_TYPE);
                visit(ctx.expression());
                typeStack.pop();
                gen.visitJumpInsn(Opcodes.IFEQ, labelNotTrue);
                pushBoolean(false);
                gen.goTo(labelNotReturn);
                gen.visitLabel(labelNotTrue);
                pushBoolean(true);
                gen.visitLabel(labelNotReturn);

            } else if (ctx.BWNOT() != null) {
                typeStack.push(Type.LONG_TYPE);
                visit(ctx.expression());
                typeStack.pop();
                gen.push(-1L);
                gen.visitInsn(Opcodes.LXOR);
                gen.cast(Type.LONG_TYPE, typeStack.peek());

            } else if (ctx.ADD() != null) {
                visit(ctx.expression());

            } else if (ctx.SUB() != null) {
                typeStack.push(Type.DOUBLE_TYPE);
                visit(ctx.expression());
                typeStack.pop();
                gen.visitInsn(Opcodes.DNEG);
                gen.cast(Type.DOUBLE_TYPE, typeStack.peek());

            } else {
                throw new IllegalStateException("Unknown operation specified: " + ctx.getText());
            }

            return null;
        }

        @Override
        public Void visitMuldiv(JavascriptParser.MuldivContext ctx) {
            int opcode;

            if (ctx.MUL() != null) {
                opcode = Opcodes.DMUL;
            } else if (ctx.DIV() != null) {
                opcode = Opcodes.DDIV;
            } else if (ctx.REM() != null) {
                opcode = Opcodes.DREM;
            } else {
                throw new IllegalStateException("Unknown operation specified: " + ctx.getText());
            }

            pushArith(opcode, ctx.expression(0), ctx.expression(1));

            return null;
        }

        @Override
        public Void visitAddsub(JavascriptParser.AddsubContext ctx) {
            int opcode;

            if (ctx.ADD() != null) {
                opcode = Opcodes.DADD;
            } else if (ctx.SUB() != null) {
                opcode = Opcodes.DSUB;
            } else {
                throw new IllegalStateException("Unknown operation specified: " + ctx.getText());
            }

            pushArith(opcode, ctx.expression(0), ctx.expression(1));

            return null;
        }

        @Override
        public Void visitBwshift(JavascriptParser.BwshiftContext ctx) {
            int opcode;

            if (ctx.LSH() != null) {
                opcode = Opcodes.LSHL;
            } else if (ctx.RSH() != null) {
                opcode = Opcodes.LSHR;
            } else if (ctx.USH() != null) {
                opcode = Opcodes.LUSHR;
            } else {
                throw new IllegalStateException("Unknown operation specified: " + ctx.getText());
            }

            pushShift(opcode, ctx.expression(0), ctx.expression(1));

            return null;
        }

        @Override
        public Void visitBoolcomp(JavascriptParser.BoolcompContext ctx) {
            int opcode;

            if (ctx.LT() != null) {
                opcode = GeneratorAdapter.LT;
            } else if (ctx.LTE() != null) {
                opcode = GeneratorAdapter.LE;
            } else if (ctx.GT() != null) {
                opcode = GeneratorAdapter.GT;
            } else if (ctx.GTE() != null) {
                opcode = GeneratorAdapter.GE;
            } else {
                throw new IllegalStateException("Unknown operation specified: " + ctx.getText());
            }

            pushCond(opcode, ctx.expression(0), ctx.expression(1));

            return null;
        }

        @Override
        public Void visitBooleqne(JavascriptParser.BooleqneContext ctx) {
            int opcode;

            if (ctx.EQ() != null) {
                opcode = GeneratorAdapter.EQ;
            } else if (ctx.NE() != null) {
                opcode = GeneratorAdapter.NE;
            } else {
                throw new IllegalStateException("Unknown operation specified: " + ctx.getText());
            }

            pushCond(opcode, ctx.expression(0), ctx.expression(1));

            return null;
        }

        @Override
        public Void visitBwand(JavascriptParser.BwandContext ctx) {
            pushBitwise(Opcodes.LAND, ctx.expression(0), ctx.expression(1));

            return null;
        }

        @Override
        public Void visitBwxor(JavascriptParser.BwxorContext ctx) {
            pushBitwise(Opcodes.LXOR, ctx.expression(0), ctx.expression(1));

            return null;
        }

        @Override
        public Void visitBwor(JavascriptParser.BworContext ctx) {
            pushBitwise(Opcodes.LOR, ctx.expression(0), ctx.expression(1));

            return null;
        }

        @Override
        public Void visitBooland(JavascriptParser.BoolandContext ctx) {
            Label andFalse = new Label();
            Label andEnd = new Label();

            typeStack.push(Type.INT_TYPE);
            visit(ctx.expression(0));
            gen.visitJumpInsn(Opcodes.IFEQ, andFalse);
            visit(ctx.expression(1));
            gen.visitJumpInsn(Opcodes.IFEQ, andFalse);
            typeStack.pop();
            pushBoolean(true);
            gen.goTo(andEnd);
            gen.visitLabel(andFalse);
            pushBoolean(false);
            gen.visitLabel(andEnd);

            return null;
        }

        @Override
        public Void visitBoolor(JavascriptParser.BoolorContext ctx) {
            Label orTrue = new Label();
            Label orEnd = new Label();

            typeStack.push(Type.INT_TYPE);
            visit(ctx.expression(0));
            gen.visitJumpInsn(Opcodes.IFNE, orTrue);
            visit(ctx.expression(1));
            gen.visitJumpInsn(Opcodes.IFNE, orTrue);
            typeStack.pop();
            pushBoolean(false);
            gen.goTo(orEnd);
            gen.visitLabel(orTrue);
            pushBoolean(true);
            gen.visitLabel(orEnd);

            return null;
        }

        @Override
        public Void visitConditional(JavascriptParser.ConditionalContext ctx) {
            Label condFalse = new Label();
            Label condEnd = new Label();

            typeStack.push(Type.INT_TYPE);
            visit(ctx.expression(0));
            typeStack.pop();
            gen.visitJumpInsn(Opcodes.IFEQ, condFalse);
            visit(ctx.expression(1));
            gen.goTo(condEnd);
            gen.visitLabel(condFalse);
            visit(ctx.expression(2));
            gen.visitLabel(condEnd);

            return null;
        }

        private void pushArith(int operator, ExpressionContext left, ExpressionContext right) {
            pushBinaryOp(operator, left, right, Type.DOUBLE_TYPE, Type.DOUBLE_TYPE, Type.DOUBLE_TYPE);
        }

        private void pushShift(int operator, ExpressionContext left, ExpressionContext right) {
            pushBinaryOp(operator, left, right, Type.LONG_TYPE, Type.INT_TYPE, Type.LONG_TYPE);
        }

        private void pushBitwise(int operator, ExpressionContext left, ExpressionContext right) {
            pushBinaryOp(operator, left, right, Type.LONG_TYPE, Type.LONG_TYPE, Type.LONG_TYPE);
        }

        private void pushBinaryOp(int operator, ExpressionContext left, ExpressionContext right, Type leftType,
                Type rightType, Type returnType) {
            typeStack.push(leftType);
            visit(left);
            typeStack.pop();
            typeStack.push(rightType);
            visit(right);
            typeStack.pop();
            gen.visitInsn(operator);
            gen.cast(returnType, typeStack.peek());
        }

        private void pushCond(int operator, ExpressionContext left, ExpressionContext right) {
            Label labelTrue = new Label();
            Label labelReturn = new Label();

            typeStack.push(Type.DOUBLE_TYPE);
            visit(left);
            visit(right);
            typeStack.pop();

            gen.ifCmp(Type.DOUBLE_TYPE, operator, labelTrue);
            pushBoolean(false);
            gen.goTo(labelReturn);
            gen.visitLabel(labelTrue);
            pushBoolean(true);
            gen.visitLabel(labelReturn);
        }

        private void pushBoolean(boolean truth) {
            switch (typeStack.peek().getSort()) {
            case Type.INT:
                gen.push(truth);
                break;
            case Type.LONG:
                gen.push(truth ? 1L : 0L);
                break;
            case Type.DOUBLE:
                gen.push(truth ? 1. : 0.);
                break;
            default:
                throw new IllegalStateException("Invalid expected type: " + typeStack.peek());
            }
        }

        private void pushLong(long i) {
            switch (typeStack.peek().getSort()) {
            case Type.INT:
                gen.push((int) i);
                break;
            case Type.LONG:
                gen.push(i);
                break;
            case Type.DOUBLE:
                gen.push((double) i);
                break;
            default:
                throw new IllegalStateException("Invalid expected type: " + typeStack.peek());
            }
        }
    }.visit(parseTree);

    gen.returnValue();
    gen.endMethod();

    classWriter.visitEnd();
}

From source file:org.apache.lucene.expressions.js.XJavascriptCompiler.java

License:Apache License

private void beginCompile() {
    classWriter.visit(CLASSFILE_VERSION,
            Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC,
            COMPILED_EXPRESSION_INTERNAL, null, EXPRESSION_TYPE.getInternalName(), null);
    String clippedSourceText = (sourceText.length() <= MAX_SOURCE_LENGTH) ? sourceText
            : (sourceText.substring(0, MAX_SOURCE_LENGTH - 3) + "...");
    classWriter.visitSource(clippedSourceText, null);

    GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC,
            EXPRESSION_CTOR, null, null, classWriter);
    constructor.loadThis();/*  w  w w .  ja  v a  2s .c  om*/
    constructor.loadArgs();
    constructor.invokeConstructor(EXPRESSION_TYPE, EXPRESSION_CTOR);
    constructor.returnValue();
    constructor.endMethod();

    gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, EVALUATE_METHOD, null, null,
            classWriter);
}

From source file:org.apache.tika.parser.asm.XHTMLClassVisitor.java

License:Apache License

private void writeAccess(int access) throws SAXException {
    writeAccess(access, Opcodes.ACC_PRIVATE, "private");
    writeAccess(access, Opcodes.ACC_PROTECTED, "protected");
    writeAccess(access, Opcodes.ACC_PUBLIC, "public");
    writeAccess(access, Opcodes.ACC_STATIC, "static");
    writeAccess(access, Opcodes.ACC_FINAL, "final");
    writeAccess(access, Opcodes.ACC_ABSTRACT, "abstract");
    writeAccess(access, Opcodes.ACC_SYNCHRONIZED, "synchronized");
    writeAccess(access, Opcodes.ACC_TRANSIENT, "transient");
    writeAccess(access, Opcodes.ACC_VOLATILE, "volatile");
    writeAccess(access, Opcodes.ACC_NATIVE, "native");
}

From source file:org.apache.twill.yarn.CustomClassLoader.java

License:Apache License

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    if (!CustomClassLoaderRunnable.GENERATED_CLASS_NAME.equals(name)) {
        return super.findClass(name);
    }/*from   w  w w .ja  v a 2s  .  c  om*/

    // Generate a class that look like this:
    //
    // public class Generated {
    //
    //   public void announce(ServiceAnnouncer announcer, String serviceName, int port) {
    //     announcer.announce(serviceName, port);
    //   }
    // }
    Type generatedClassType = Type
            .getObjectType(CustomClassLoaderRunnable.GENERATED_CLASS_NAME.replace('.', '/'));
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    cw.visit(Opcodes.V1_7, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, generatedClassType.getInternalName(), null,
            Type.getInternalName(Object.class), null);

    // Generate the default constructor, which just call super();
    Method constructor = new Method("<init>", Type.VOID_TYPE, new Type[0]);
    GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, constructor, null, null, cw);
    mg.loadThis();
    mg.invokeConstructor(Type.getType(Object.class), constructor);
    mg.returnValue();
    mg.endMethod();

    // Generate the announce method
    Method announce = new Method("announce", Type.VOID_TYPE,
            new Type[] { Type.getType(ServiceAnnouncer.class), Type.getType(String.class), Type.INT_TYPE });
    mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, announce, null, null, cw);
    mg.loadArg(0);
    mg.loadArg(1);
    mg.loadArg(2);
    mg.invokeInterface(Type.getType(ServiceAnnouncer.class), new Method("announce",
            Type.getType(Cancellable.class), new Type[] { Type.getType(String.class), Type.INT_TYPE }));
    mg.pop();
    mg.returnValue();
    mg.endMethod();
    cw.visitEnd();

    byte[] byteCode = cw.toByteArray();
    return defineClass(CustomClassLoaderRunnable.GENERATED_CLASS_NAME, byteCode, 0, byteCode.length);
}