Java Code Examples for org.codehaus.groovy.ast.ClassHelper#OBJECT_TYPE

The following examples show how to use org.codehaus.groovy.ast.ClassHelper#OBJECT_TYPE . 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 File: JavaStubGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void printDefaultValue(PrintWriter out, ClassNode type) {
    if (type.redirect() != ClassHelper.OBJECT_TYPE && type.redirect() != ClassHelper.boolean_TYPE) {
        out.print("(");
        printType(out, type);
        out.print(")");
    }

    if (ClassHelper.isPrimitiveType(type)) {
        if (type == ClassHelper.boolean_TYPE) {
            out.print("false");
        } else {
            out.print("0");
        }
    } else {
        out.print("null");
    }
}
 
Example 2
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void printDefaultValue(PrintWriter out, ClassNode type) {
    if (type.redirect() != ClassHelper.OBJECT_TYPE) {
        out.print("(");
        printType(type, out);
        out.print(")");
    }

    if (ClassHelper.isPrimitiveType(type)) {
        if (type == ClassHelper.boolean_TYPE) {
            out.print("false");
        } else {
            out.print("0");
        }
    } else {
        out.print("null");
    }
}
 
Example 3
Source File: Verifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static FieldNode getMetaClassField(ClassNode node) {
    FieldNode ret = node.getDeclaredField("metaClass");
    if (ret != null) {
        ClassNode mcFieldType = ret.getType();
        if (!mcFieldType.equals(ClassHelper.METACLASS_TYPE)) {
            throw new RuntimeParserException("The class " + node.getName() +
                    " cannot declare field 'metaClass' of type " + mcFieldType.getName() + " as it needs to be of " +
                    "the type " + ClassHelper.METACLASS_TYPE.getName() + " for internal groovy purposes", ret);
        }
        return ret;
    }
    ClassNode current = node;
    while (current != ClassHelper.OBJECT_TYPE) {
        current = current.getSuperClass();
        if (current == null) break;
        ret = current.getDeclaredField("metaClass");
        if (ret == null) continue;
        if (isPrivate(ret.getModifiers())) continue;
        return ret;
    }
    return null;
}
 
Example 4
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void addHolderClassIdiomBody(BlockStatement body, FieldNode fieldNode, Expression initExpr) {
    final ClassNode declaringClass = fieldNode.getDeclaringClass();
    final ClassNode fieldType = fieldNode.getType();
    final int visibility = ACC_PRIVATE | ACC_STATIC;
    final String fullName = declaringClass.getName() + "$" + fieldType.getNameWithoutPackage() + "Holder_" + fieldNode.getName().substring(1);
    final InnerClassNode holderClass = new InnerClassNode(declaringClass, fullName, visibility, ClassHelper.OBJECT_TYPE);
    final String innerFieldName = "INSTANCE";

    // we have two options:
    // (1) embed initExpr within holder class but redirect field access/method calls to declaring class members
    // (2) keep initExpr within a declaring class method that is only called by the holder class
    // currently we have gone with (2) for simplicity with only a slight memory footprint increase in the declaring class
    final String initializeMethodName = (fullName + "_initExpr").replace('.', '_');
    addGeneratedMethod(declaringClass, initializeMethodName, ACC_PRIVATE | ACC_STATIC | ACC_FINAL, fieldType,
            Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(initExpr));
    holderClass.addField(innerFieldName, ACC_PRIVATE | ACC_STATIC | ACC_FINAL, fieldType,
            callX(declaringClass, initializeMethodName));

    final Expression innerField = propX(classX(holderClass), innerFieldName);
    declaringClass.getModule().addClass(holderClass);
    body.addStatement(returnS(innerField));
}
 
Example 5
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Expression serialize(Expression e) {
    if (e instanceof AnnotationConstantExpression) {
        AnnotationConstantExpression ace = (AnnotationConstantExpression) e;
        return serialize((AnnotationNode) ace.getValue());
    } else if (e instanceof ListExpression) {
        boolean annotationConstant = false;
        ListExpression le = (ListExpression) e;
        List<Expression> list = le.getExpressions();
        List<Expression> newList = new ArrayList<>(list.size());
        for (Expression exp: list) {
            annotationConstant = annotationConstant || exp instanceof AnnotationConstantExpression;
            newList.add(serialize(exp));
        }
        ClassNode type = ClassHelper.OBJECT_TYPE;
        if (annotationConstant) type = type.makeArray();
        return new ArrayExpression(type, newList);
    }
    return e;
}
 
Example 6
Source File: ClosureWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
public boolean addGeneratedClosureConstructorCall(final ConstructorCallExpression call) {
    ClassNode classNode = controller.getClassNode();
    if (!classNode.declaresInterface(ClassHelper.GENERATED_CLOSURE_Type)) return false;

    AsmClassGenerator acg = controller.getAcg();
    OperandStack operandStack = controller.getOperandStack();

    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitVarInsn(ALOAD, 0);
    ClassNode callNode = classNode.getSuperClass();
    TupleExpression arguments = (TupleExpression) call.getArguments();
    if (arguments.getExpressions().size()!=2) throw new GroovyBugError("expected 2 arguments for closure constructor super call, but got"+arguments.getExpressions().size());
    arguments.getExpression(0).visit(acg);
    operandStack.box();
    arguments.getExpression(1).visit(acg);
    operandStack.box();
    //TODO: replace with normal String, p not needed
    Parameter p = new Parameter(ClassHelper.OBJECT_TYPE,"_p");
    String descriptor = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, new Parameter[]{p,p});
    mv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(callNode), "<init>", descriptor, false);
    operandStack.remove(2);
    return true;
}
 
Example 7
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addSimpleCloneHelperMethod(ClassNode cNode, List<FieldNode> fieldNodes, List<String> excludes) {
    Parameter methodParam = new Parameter(GenericsUtils.nonGeneric(cNode), "other");
    final Expression other = varX(methodParam);
    boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE;
    BlockStatement methodBody = new BlockStatement();
    if (hasParent) {
        methodBody.addStatement(stmt(callSuperX("cloneOrCopyMembers", args(other))));
    }
    for (FieldNode fieldNode : fieldNodes) {
        String name = fieldNode.getName();
        if (excludes != null && excludes.contains(name)) continue;
        ClassNode fieldType = fieldNode.getType();
        Expression direct = propX(varX("this"), name);
        Expression to = propX(other, name);
        Statement assignDirect = assignS(to, direct);
        Statement assignCloned = assignS(to, castX(fieldType, callCloneDirectX(direct)));
        Statement assignClonedDynamic = assignS(to, castX(fieldType, callCloneDynamicX(direct)));
        if (isCloneableType(fieldType)) {
            methodBody.addStatement(assignCloned);
        } else if (!possiblyCloneable(fieldType)) {
            methodBody.addStatement(assignDirect);
        } else {
            methodBody.addStatement(ifElseS(isInstanceOfX(direct, CLONEABLE_TYPE), assignClonedDynamic, assignDirect));
        }
    }
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "cloneOrCopyMembers", ACC_PROTECTED, ClassHelper.VOID_TYPE, params(methodParam), exceptions, methodBody);
}
 
Example 8
Source File: ClassCompletionVerifierTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testDetectsIncorrectMethodModifiersInInterface() throws Exception {
    // can't check volatile here as it doubles up with bridge
    ClassNode node = new ClassNode("zzz", ACC_ABSTRACT | ACC_INTERFACE, ClassHelper.OBJECT_TYPE);
    node.addMethod(new MethodNode("st", ACC_STRICT, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null));
    node.addMethod(new MethodNode("na", ACC_NATIVE, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null));
    node.addMethod(new MethodNode("sy", ACC_SYNCHRONIZED, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null));
    addDummyConstructor(node);
    verifier.visitClass(node);
    checkErrorCount(3);
    checkErrorMessage(EXPECTED_STRICT_METHOD_ERROR_MESSAGE);
    checkErrorMessage(EXPECTED_NATIVE_METHOD_ERROR_MESSAGE);
    checkErrorMessage(EXPECTED_SYNCHRONIZED_METHOD_ERROR_MESSAGE);
}
 
Example 9
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<ClassNode> getAllUnresolvedSuperClasses(ClassNode actualReceiver) {
    List<ClassNode> superClassNodeList = new LinkedList<>();

    for (ClassNode cn = actualReceiver.getUnresolvedSuperClass(); null != cn && ClassHelper.OBJECT_TYPE != cn; cn = cn.getUnresolvedSuperClass()) {
        superClassNodeList.add(cn);
    }

    return superClassNodeList;
}
 
Example 10
Source File: TraitTypeCheckingExtension.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ClassNode inferTraitMethodReturnType(ClassNode nextTrait, String methodName, ClassNode[] paramTypes) {
    ClassNode result = ClassHelper.OBJECT_TYPE;
    if (nextTrait != null) {
        List<MethodNode> candidates = typeCheckingVisitor.findMethod(nextTrait, methodName, paramTypes);
        if (candidates.size() == 1) {
            result = candidates.get(0).getReturnType();
        }
    }
    return result;
}
 
Example 11
Source File: IndexedPropertyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getComponentTypeForList(ClassNode fType) {
    if (fType.isUsingGenerics() && fType.getGenericsTypes().length == 1) {
        return fType.getGenericsTypes()[0].getType();
    } else {
        return ClassHelper.OBJECT_TYPE;
    }
}
 
Example 12
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static Map<String, ClassNode> addMethodGenerics(MethodNode current, Map<String, ClassNode> oldSpec) {
    Map<String, ClassNode> newSpec = new HashMap<>(oldSpec);
    GenericsType[] gts = current.getGenericsTypes();
    if (gts != null) {
        for (GenericsType gt : gts) {
            String name = gt.getName();
            ClassNode type = gt.getType();
            if (gt.isPlaceholder()) {
                ClassNode redirect;
                if (gt.getUpperBounds() != null) {
                    redirect = gt.getUpperBounds()[0];
                } else if (gt.getLowerBound() != null) {
                    redirect = gt.getLowerBound();
                } else {
                    redirect = ClassHelper.OBJECT_TYPE;
                }
                if (redirect.isGenericsPlaceHolder()) {
                    // "T extends U" or "T super U"
                    type = redirect;
                } else {
                    // "T" or "T extends Thing" or "T super Thing"
                    type = ClassHelper.makeWithoutCaching(name);
                    type.setGenericsPlaceHolder(true);
                    type.setRedirect(redirect);
                }
            }
            newSpec.put(name, type);
        }
    }
    return newSpec;
}
 
Example 13
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void adjustTypesIfStaticMainMethod(MethodNode node) {
    if (node.getName().equals("main") && node.isStatic()) {
        Parameter[] params = node.getParameters();
        if (params.length == 1) {
            Parameter param = params[0];
            if (param.getType() == null || param.getType() == ClassHelper.OBJECT_TYPE) {
                param.setType(ClassHelper.STRING_TYPE.makeArray());
                ClassNode returnType = node.getReturnType();
                if (returnType == ClassHelper.OBJECT_TYPE) {
                    node.setReturnType(ClassHelper.VOID_TYPE);
                }
            }
        }
    }
}
 
Example 14
Source File: PropertyTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testFields() throws Exception {
    ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, ClassHelper.OBJECT_TYPE);
    classNode.addField("x", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, null);
    classNode.addField("y", ACC_PUBLIC, ClassHelper.Integer_TYPE, null);
    classNode.addField("z", ACC_PRIVATE, ClassHelper.STRING_TYPE, null);

    Class fooClass = loadClass(classNode);
    assertTrue("Loaded a new class", fooClass != null);

    assertField(fooClass, "x", Modifier.PUBLIC, ClassHelper.OBJECT_TYPE);
    assertField(fooClass, "y", Modifier.PUBLIC, ClassHelper.Integer_TYPE);
    assertField(fooClass, "z", Modifier.PRIVATE, ClassHelper.STRING_TYPE);
}
 
Example 15
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ClassNode getAttributeType(AnnotationNode node, String attrName) {
    ClassNode classNode = node.getClassNode();
    List methods = classNode.getMethods(attrName);
    // if size is >1, then the method was overwritten or something, we ignore that
    // if it is an error, we have to test it at another place. But size==0 is
    // an error, because it means that no such attribute exists.
    if (methods.isEmpty()) {
        addError("'" + attrName + "'is not part of the annotation " + classNode.getNameWithoutPackage(), node);
        return ClassHelper.OBJECT_TYPE;
    }
    MethodNode method = (MethodNode) methods.get(0);
    return method.getReturnType();
}
 
Example 16
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void evaluateCompareExpression(final MethodCaller compareMethod, final BinaryExpression expression) {
    ClassNode classNode = controller.getClassNode();
    Expression leftExp = expression.getLeftExpression();
    Expression rightExp = expression.getRightExpression();
    ClassNode leftType = controller.getTypeChooser().resolveType(leftExp, classNode);
    ClassNode rightType = controller.getTypeChooser().resolveType(rightExp, classNode);

    boolean done = false;
    if (ClassHelper.isPrimitiveType(leftType) && ClassHelper.isPrimitiveType(rightType)) {
        BinaryExpressionMultiTypeDispatcher helper = new BinaryExpressionMultiTypeDispatcher(controller);
        done = helper.doPrimitiveCompare(leftType, rightType, expression);
    }
    if (!done) {
        AsmClassGenerator acg = controller.getAcg();
        OperandStack operandStack = controller.getOperandStack();

        leftExp.visit(acg);
        operandStack.box();
        rightExp.visit(acg);
        operandStack.box();

        compareMethod.call(controller.getMethodVisitor());
        ClassNode resType = ClassHelper.boolean_TYPE;
        if (compareMethod == findRegexMethod) {
            resType = ClassHelper.OBJECT_TYPE;
        }
        operandStack.replace(resType, 2);
    }
}
 
Example 17
Source File: InvocationWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected boolean writeDirectMethodCall(final MethodNode target, final boolean implicitThis, final Expression receiver, final TupleExpression args) {
    if (target == null) return false;

    String methodName = target.getName();
    CompileStack compileStack = controller.getCompileStack();
    OperandStack operandStack = controller.getOperandStack();
    ClassNode declaringClass = target.getDeclaringClass();
    ClassNode classNode = controller.getClassNode();

    MethodVisitor mv = controller.getMethodVisitor();
    int opcode = INVOKEVIRTUAL;
    if (target.isStatic()) {
        opcode = INVOKESTATIC;
    } else if (declaringClass.isInterface()) {
        opcode = INVOKEINTERFACE;
    } else if (target.isPrivate() || AsmClassGenerator.isSuperExpression(receiver)) {
        opcode = INVOKESPECIAL;
    }

    // handle receiver
    int argumentsToRemove = 0;
    if (opcode != INVOKESTATIC) {
        if (receiver != null) {
            // load receiver if not static invocation
            // todo: fix inner class case
            if (implicitThis
                    && classNode.getOuterClass() != null
                    && !classNode.isDerivedFrom(declaringClass)
                    && !classNode.implementsInterface(declaringClass)) {
                // we are calling an outer class method
                compileStack.pushImplicitThis(false);
                if (controller.isInGeneratedFunction()) {
                    new VariableExpression("thisObject").visit(controller.getAcg());
                } else {
                    Expression expr = new PropertyExpression(new ClassExpression(declaringClass), "this");
                    expr.visit(controller.getAcg());
                }
            } else {
                compileStack.pushImplicitThis(implicitThis);
                receiver.visit(controller.getAcg());
            }
            operandStack.doGroovyCast(declaringClass);
            compileStack.popImplicitThis();
            argumentsToRemove += 1;
        } else {
            mv.visitIntInsn(ALOAD,0);
            operandStack.push(classNode);
            argumentsToRemove += 1;
        }
    }

    int stackSize = operandStack.getStackLength();

    String owner = BytecodeHelper.getClassInternalName(declaringClass);
    ClassNode receiverType = receiver != null ? controller.getTypeChooser().resolveType(receiver, classNode) : declaringClass;
    if (opcode == INVOKEVIRTUAL && ClassHelper.OBJECT_TYPE.equals(declaringClass)) {
        // avoid using a narrowed type if the method is defined on object because it can interfere
        // with delegate type inference in static compilation mode and trigger a ClassCastException
        receiverType = declaringClass;
    }
    if (opcode == INVOKEVIRTUAL) {
        if (!receiverType.equals(declaringClass)
                && !ClassHelper.OBJECT_TYPE.equals(declaringClass)
                && !receiverType.isArray()
                && !receiverType.isInterface()
                && !ClassHelper.isPrimitiveType(receiverType) // e.g int.getClass()
                && receiverType.isDerivedFrom(declaringClass)) {

            owner = BytecodeHelper.getClassInternalName(receiverType);
            ClassNode top = operandStack.getTopOperand();
            if (!receiverType.equals(top)) {
                mv.visitTypeInsn(CHECKCAST, owner);
            }
        } else if (target.isPublic()
                && (!receiverType.equals(declaringClass) && !Modifier.isPublic(declaringClass.getModifiers()))
                && receiverType.isDerivedFrom(declaringClass) && !Objects.equals(receiverType.getPackageName(), classNode.getPackageName())) {
            // GROOVY-6962: package private class, public method
            owner = BytecodeHelper.getClassInternalName(receiverType);
        }
    }

    loadArguments(args.getExpressions(), target.getParameters());

    String desc = BytecodeHelper.getMethodDescriptor(target.getReturnType(), target.getParameters());
    mv.visitMethodInsn(opcode, owner, methodName, desc, declaringClass.isInterface());
    ClassNode ret = target.getReturnType().redirect();
    if (ret == ClassHelper.VOID_TYPE) {
        ret = ClassHelper.OBJECT_TYPE;
        mv.visitInsn(ACONST_NULL);
    }
    argumentsToRemove += (operandStack.getStackLength()-stackSize);
    controller.getOperandStack().remove(argumentsToRemove);
    controller.getOperandStack().push(ret);
    return true;
}
 
Example 18
Source File: UnionTypeClassNode.java    From groovy with Apache License 2.0 4 votes vote down vote up
public UnionTypeClassNode(ClassNode... classNodes) {
    super("<UnionType:" + asArrayDescriptor(classNodes) + ">", 0, ClassHelper.OBJECT_TYPE);
    delegates = classNodes == null ? ClassNode.EMPTY_ARRAY : classNodes;
}
 
Example 19
Source File: ClassCompletionVerifierTest.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void testDetectsAbstractPrivateMethod() throws Exception {
    ClassNode node = new ClassNode("X", ACC_ABSTRACT, ClassHelper.OBJECT_TYPE);
    node.addMethod(new MethodNode("y", ACC_PRIVATE | ACC_ABSTRACT, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null));
    verifier.visitClass(node);
    checkErrorMessage(EXPECTED_ABSTRACT_PRIVATE_METHOD_ERROR_MESSAGE);
}
 
Example 20
Source File: ClosureWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected ClassNode createClosureClass(final ClosureExpression expression, final int modifiers) {
    ClassNode classNode = controller.getClassNode();
    ClassNode outerClass = controller.getOutermostClass();
    String name = genClosureClassName();
    boolean staticMethodOrInStaticClass = controller.isStaticMethod() || classNode.isStaticClass();

    Parameter[] parameters = expression.getParameters();
    if (parameters == null) {
        parameters = Parameter.EMPTY_ARRAY;
    } else if (parameters.length == 0) {
        // let's create a default 'it' parameter
        Parameter it = new Parameter(ClassHelper.OBJECT_TYPE, "it", ConstantExpression.NULL);
        parameters = new Parameter[]{it};
        Variable ref = expression.getVariableScope().getDeclaredVariable("it");
        if (ref!=null) it.setClosureSharedVariable(ref.isClosureSharedVariable());
    }

    Parameter[] localVariableParams = getClosureSharedVariables(expression);
    removeInitialValues(localVariableParams);

    InnerClassNode answer = new InnerClassNode(classNode, name, modifiers, ClassHelper.CLOSURE_TYPE.getPlainNodeReference());
    answer.setEnclosingMethod(controller.getMethodNode());
    answer.setSynthetic(true);
    answer.setUsingGenerics(outerClass.isUsingGenerics());
    answer.setSourcePosition(expression);

    if (staticMethodOrInStaticClass) {
        answer.setStaticClass(true);
    }
    if (controller.isInScriptBody()) {
        answer.setScriptBody(true);
    }
    MethodNode method =
            answer.addMethod("doCall", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, expression.getCode());
    method.setSourcePosition(expression);

    VariableScope varScope = expression.getVariableScope();
    if (varScope == null) {
        throw new RuntimeException(
                "Must have a VariableScope by now! for expression: " + expression + " class: " + name);
    } else {
        method.setVariableScope(varScope.copy());
    }
    if (parameters.length > 1
            || (parameters.length == 1
            && parameters[0].getType() != null
            && parameters[0].getType() != ClassHelper.OBJECT_TYPE
            && !ClassHelper.OBJECT_TYPE.equals(parameters[0].getType().getComponentType())))
    {

        // let's add a typesafe call method
        MethodNode call = answer.addMethod(
                "call",
                ACC_PUBLIC,
                ClassHelper.OBJECT_TYPE,
                parameters,
                ClassNode.EMPTY_ARRAY,
                new ReturnStatement(
                        new MethodCallExpression(
                                VariableExpression.THIS_EXPRESSION,
                                "doCall",
                                new ArgumentListExpression(parameters))));
        call.setSourcePosition(expression);
    }

    // let's make the constructor
    BlockStatement block = createBlockStatementForConstructor(expression, outerClass, classNode);

    // let's assign all the parameter fields from the outer context
    addFieldsAndGettersForLocalVariables(answer, localVariableParams);

    addConstructor(expression, localVariableParams, answer, block);

    correctAccessedVariable(answer,expression);

    return answer;
}