Java Code Examples for org.codehaus.groovy.ast.expr.Expression#getType()

The following examples show how to use org.codehaus.groovy.ast.expr.Expression#getType() . 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: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 6 votes vote down vote up
private List<AnnotationNode> getTargetListFromValue(AnnotationNode collector, AnnotationNode aliasAnnotationUsage, SourceUnit source) {
    Expression memberValue = collector.getMember("value");
    if (memberValue == null) {
        return Collections.emptyList();
    }
    if (!(memberValue instanceof ListExpression)) {
        addError("Annotation collector expected a list of classes, but got a "+memberValue.getClass(), collector, source);
        return Collections.emptyList();
    }
    ListExpression memberListExp = (ListExpression) memberValue;
    List<Expression> memberList = memberListExp.getExpressions();
    if (memberList.isEmpty()) {
        return Collections.emptyList();
    }
    List<AnnotationNode> ret = new ArrayList<>();
    for (Expression e : memberList) {
        AnnotationNode toAdd = new AnnotationNode(e.getType());
        toAdd.setSourcePosition(aliasAnnotationUsage);
        ret.add(toAdd);
    }
    return ret;
}
 
Example 2
Source File: LegacyHashMapPropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Statement createLegacyConstructorStatementMapSpecial(FieldNode fNode) {
    final Expression fieldExpr = varX(fNode);
    final ClassNode fieldType = fieldExpr.getType();
    final Expression initExpr = fNode.getInitialValueExpression();
    final Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        assignInit = assignS(fieldExpr, ConstantExpression.EMPTY_EXPRESSION);
    } else {
        assignInit = assignS(fieldExpr, cloneCollectionExpr(initExpr, fieldType));
    }
    Expression namedArgs = findArg(fNode.getName());
    Expression baseArgs = varX("args");
    Statement assignStmt = ifElseS(
            equalsNullX(namedArgs),
            ifElseS(
                    isTrueX(callX(baseArgs, "containsKey", constX(fNode.getName()))),
                    assignS(fieldExpr, namedArgs),
                    assignS(fieldExpr, cloneCollectionExpr(baseArgs, fieldType))),
            ifElseS(
                    isOneX(callX(baseArgs, "size")),
                    assignS(fieldExpr, cloneCollectionExpr(namedArgs, fieldType)),
                    assignS(fieldExpr, cloneCollectionExpr(baseArgs, fieldType)))
    );
    return ifElseS(equalsNullX(baseArgs), assignInit, assignStmt);
}
 
Example 3
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
public List<ClassNode> getMemberClassList(AnnotationNode anno, String name) {
    List<ClassNode> list = new ArrayList<>();
    Expression expr = anno.getMember(name);
    if (expr == null) {
        return null;
    }
    if (expr instanceof ListExpression) {
        final ListExpression listExpression = (ListExpression) expr;
        if (isUndefinedMarkerList(listExpression)) {
            return null;
        }
        list = getTypeList(listExpression);
    } else if (expr instanceof ClassExpression) {
        ClassNode cn = expr.getType();
        if (isUndefined(cn)) return null;
        if (cn != null) list.add(cn);
    }
    return list;
}
 
Example 4
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Statement createConstructorStatementCollection(FieldNode fNode, Parameter namedArgsMap, boolean shouldNullCheck) {
    final Expression fieldExpr = propX(varX("this"), fNode.getName());
    ClassNode fieldType = fieldExpr.getType();
    Expression param = getParam(fNode, namedArgsMap != null);
    Statement assignStmt = ifElseS(
            isInstanceOfX(param, CLONEABLE_TYPE),
            assignS(fieldExpr, cloneCollectionExpr(cloneArrayOrCloneableExpr(param, fieldType), fieldType)),
            assignS(fieldExpr, cloneCollectionExpr(param, fieldType)));
    assignStmt = ifElseS(
            equalsNullX(param),
            shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr),
            assignStmt);
    Expression initExpr = fNode.getInitialValueExpression();
    final Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
    } else {
        assignInit = assignS(fieldExpr, cloneCollectionExpr(initExpr, fieldType));
    }
    return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
 
Example 5
Source File: TypeCheckingExtension.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Given a method call, first checks that it's a static method call, and if it is, returns the
 * class node for the receiver. For example, with the following code:
 * <code></code>Person.findAll { ... }</code>, it would return the class node for <i>Person</i>.
 * If it's not a static method call, returns null.
 * @param call a method call
 * @return null if it's not a static method call, or the class node for the receiver instead.
 */
public ClassNode extractStaticReceiver(MethodCall call) {
    if (call instanceof StaticMethodCallExpression) {
        return ((StaticMethodCallExpression) call).getOwnerType();
    } else if (call instanceof MethodCallExpression) {
        Expression objectExpr = ((MethodCallExpression) call).getObjectExpression();
        if (objectExpr instanceof ClassExpression && ClassHelper.CLASS_Type.equals(objectExpr.getType())) {
            GenericsType[] genericsTypes = objectExpr.getType().getGenericsTypes();
            if (genericsTypes!=null && genericsTypes.length==1) {
                return genericsTypes[0].getType();
            }
        }
        if (objectExpr instanceof ClassExpression) {
            return objectExpr.getType();
        }
    }
    return null;
}
 
Example 6
Source File: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Integer matchingScore(MethodNode mn, Expression typeOrTargetRef) {
    ClassNode typeOrTargetRefType = typeOrTargetRef.getType();

    int score = 9;
    for (ClassNode cn = mn.getDeclaringClass(); null != cn && !cn.equals(typeOrTargetRefType); cn = cn.getSuperClass()) {
        score--;
    }
    if (score < 0) {
        score = 0;
    }
    score *= 10;

    boolean isClassExpr = isClassExpr(typeOrTargetRef);
    boolean isStaticMethod = mn.isStatic();

    if (isClassExpr && isStaticMethod || !isClassExpr && !isStaticMethod) {
        score += 9;
    }

    if (isExtensionMethod(mn)) {
        score += 100;
    }

    return score;
}
 
Example 7
Source File: PicocliScriptASTTransformation.java    From picocli with Apache License 2.0 6 votes vote down vote up
private void changeBaseScriptTypeFromPackageOrImport(final SourceUnit source, final AnnotatedNode parent, final AnnotationNode node) {
    Expression value = node.getMember("value");
    ClassNode scriptType;
    if (value == null) {
        scriptType = BASE_SCRIPT_TYPE;
    } else {
        if (!(value instanceof ClassExpression)) {
            addError("Annotation " + MY_TYPE_NAME + " member 'value' should be a class literal.", value);
            return;
        }
        scriptType = value.getType();
    }
    List<ClassNode> classes = source.getAST().getClasses();
    for (ClassNode classNode : classes) {
        if (classNode.isScriptBody()) {
            changeBaseScriptType(source, parent, classNode, scriptType, node);
        }
    }
}
 
Example 8
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void loadWrapper(final Expression argument) {
    MethodVisitor mv = controller.getMethodVisitor();
    ClassNode goalClass = argument.getType();
    visitClassExpression(new ClassExpression(goalClass));
    if (goalClass.isDerivedFromGroovyObject()) {
        createGroovyObjectWrapperMethod.call(mv);
    } else {
        createPojoWrapperMethod.call(mv);
    }
    controller.getOperandStack().remove(1);
}
 
Example 9
Source File: ASTTransformer.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
private void changeBaseScriptTypeFromPackageOrImport(final SourceUnit source, final AnnotatedNode parent, final AnnotationNode node) {
    Expression value = node.getMember("value");
    ClassNode scriptType;

    if (value == null) {
        if ( type == Type.MAVEN )
        {
            scriptType = MAVEN_BASE_SCRIPT_TYPE;
        }
        else
        {
            scriptType = GRADLE_BASE_SCRIPT_TYPE;
        }
    } else {
        if (!(value instanceof ClassExpression)) {
            addError( "Annotation " + getType() + " member 'value' should be a class literal.", value);
            return;
        }
        scriptType = value.getType();
    }
    List<ClassNode> classes = source.getAST().getClasses();
    for (ClassNode classNode : classes) {
        if (classNode.isScriptBody()) {
            changeBaseScriptType(parent, classNode, scriptType);
        }
    }
}
 
Example 10
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getConstructorArgumentType(Expression arg, ConstructorNode node) {
    if (!(arg instanceof VariableExpression)) return arg.getType();
    VariableExpression vexp = (VariableExpression) arg;
    String name = vexp.getName();
    for (Parameter param : node.getParameters()) {
        if (param.getName().equals(name)) {
            return param.getType();
        }
    }
    return vexp.getType();
}
 
Example 11
Source File: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private MethodNode findMethodRefMethod(String methodRefName, Parameter[] abstractMethodParameters, Expression typeOrTargetRef) {
    ClassNode typeOrTargetRefType = typeOrTargetRef.getType();
    List<MethodNode> methodNodeList = typeOrTargetRefType.getMethods(methodRefName);
    Set<MethodNode> dgmMethodNodeSet = findDGMMethodsForClassNode(controller.getSourceUnit().getClassLoader(), typeOrTargetRefType, methodRefName);

    List<MethodNode> allMethodNodeList = new LinkedList<>(methodNodeList);
    allMethodNodeList.addAll(dgmMethodNodeSet);

    ClassNode classNode = controller.getClassNode();

    List<MethodNode> candidates = new LinkedList<>();
    for (MethodNode mn : filterMethodsByVisibility(allMethodNodeList, classNode)) {
        Parameter[] parameters = abstractMethodParameters;
        if (isTypeReferingInstanceMethod(typeOrTargetRef, mn)) {
            if (0 == abstractMethodParameters.length) {
                continue;
            }

            parameters = removeFirstParameter(abstractMethodParameters);
        }

        Parameter[] methodParameters;
        if (isExtensionMethod(mn)) {
            methodParameters = removeFirstParameter(((ExtensionMethodNode) mn).getExtensionMethodNode().getParameters());
        } else {
            methodParameters = mn.getParameters();
        }

        if (ParameterUtils.parametersCompatible(parameters, methodParameters)) {
            candidates.add(mn);
        }
    }

    return chooseMethodRefMethodCandidate(typeOrTargetRef, candidates);
}
 
Example 12
Source File: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private String createAbstractMethodDesc(ClassNode functionalInterfaceType, Expression methodRef) {
    List<Parameter> methodReferenceSharedVariableList = new LinkedList<>();

    if (!(isClassExpr(methodRef))) {
        ClassNode methodRefTargetType = methodRef.getType();
        prependParameter(methodReferenceSharedVariableList, METHODREF_EXPR_INSTANCE, methodRefTargetType);
    }

    return BytecodeHelper.getMethodDescriptor(functionalInterfaceType.redirect(), methodReferenceSharedVariableList.toArray(Parameter.EMPTY_ARRAY));
}
 
Example 13
Source File: StatementMetaTypeChooser.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public ClassNode resolveType(final Expression exp, final ClassNode current) {
    ClassNode type = null;
    if (exp instanceof ClassExpression) { type = exp.getType();
        ClassNode classType = ClassHelper.makeWithoutCaching("java.lang.Class");
        classType.setGenericsTypes(new GenericsType[] {new GenericsType(type)});
        classType.setRedirect(ClassHelper.CLASS_Type);
        return classType;
    }

    OptimizingStatementWriter.StatementMeta meta = exp.getNodeMetaData(OptimizingStatementWriter.StatementMeta.class);
    if (meta != null) type = meta.type;
    if (type != null) return type;

    if (exp instanceof VariableExpression) {
        VariableExpression ve = (VariableExpression) exp;
        if (ve.isClosureSharedVariable()) return ve.getType();
        if (ve.isSuperExpression()) return current.getSuperClass();

        type = ve.getOriginType();
    } else if (exp instanceof Variable) {
        Variable v = (Variable) exp;
        type = v.getOriginType();
    } else {
        type = exp.getType();
    }
    return type.redirect();
}
 
Example 14
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean isGroovyObject(final Expression objectExpression) {
    if (isThisExpression(objectExpression)) return true;
    if (objectExpression instanceof ClassExpression) return false;

    ClassNode objectExpressionType = controller.getTypeChooser().resolveType(objectExpression, controller.getClassNode());
    if (objectExpressionType.equals(ClassHelper.OBJECT_TYPE)) objectExpressionType = objectExpression.getType();
    return objectExpressionType.isDerivedFromGroovyObject();
}
 
Example 15
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean isTraitSuperPropertyExpression(Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pexp = (PropertyExpression) exp;
        Expression objectExpression = pexp.getObjectExpression();
        if (objectExpression instanceof ClassExpression) {
            ClassNode type = objectExpression.getType();
            if (Traits.isTrait(type) && "super".equals(pexp.getPropertyAsString())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 16
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<ClassNode> getTypeList(ListExpression listExpression) {
    List<ClassNode> list = new ArrayList<>();
    for (Expression itemExpr : listExpression.getExpressions()) {
        if (itemExpr instanceof ClassExpression) {
            ClassNode cn = itemExpr.getType();
            if (cn != null) list.add(cn);
        }
    }
    return list;
}
 
Example 17
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public ClassNode getMemberClassValue(AnnotationNode node, String name, ClassNode defaultValue) {
    final Expression member = node.getMember(name);
    if (member != null) {
        if (member instanceof ClassExpression) {
            if (!isUndefined(member.getType())) return member.getType();
        } else if (member instanceof VariableExpression) {
            addError("Error expecting to find class value for '" + name + "' but found variable: " + member.getText() + ". Missing import?", node);
            return null;
        } else if (member instanceof ConstantExpression) {
            addError("Error expecting to find class value for '" + name + "' but found constant: " + member.getText() + "!", node);
            return null;
        }
    }
    return defaultValue;
}
 
Example 18
Source File: AbstractInterruptibleASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected static ClassNode getClassAnnotationParameter(AnnotationNode node, String parameterName, ClassNode defaultValue) {
    Expression member = node.getMember(parameterName);
    if (member != null) {
        if (member instanceof ClassExpression) {
            try {
                return member.getType();
            } catch (Exception e) {
                internalError("Expecting class value for " + parameterName + " annotation parameter. Found " + member + "member");
            }
        } else {
            internalError("Expecting class value for " + parameterName + " annotation parameter. Found " + member + "member");
        }
    }
    return defaultValue;
}
 
Example 19
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void visitAttributeOrProperty(final PropertyExpression pexp, final MethodCallerMultiAdapter adapter) {
    ClassNode classNode = controller.getClassNode();
    String propertyName = pexp.getPropertyAsString();
    Expression objectExpression = pexp.getObjectExpression();

    if (objectExpression instanceof ClassExpression && "this".equals(propertyName)) {
        // we have something like A.B.this, and need to make it
        // into this.this$0.this$0, where this.this$0 returns
        // A.B and this.this$0.this$0 return A.
        ClassNode type = objectExpression.getType();
        if (controller.getCompileStack().isInSpecialConstructorCall() && type.equals(classNode.getOuterClass())) {
            // Outer.this in a special constructor call
            ConstructorNode ctor = controller.getConstructorNode();
            Expression receiver = !classNode.isStaticClass() ? new VariableExpression(ctor.getParameters()[0]) : new ClassExpression(type);
            receiver.setSourcePosition(pexp);
            receiver.visit(this);
            return;
        }

        MethodVisitor mv = controller.getMethodVisitor();
        mv.visitVarInsn(ALOAD, 0);
        ClassNode iterType = classNode;
        while (!iterType.equals(type)) {
            String ownerName = BytecodeHelper.getClassInternalName(iterType);
            if (iterType.getOuterClass() == null) break;
            FieldNode thisField = iterType.getField("this$0");
            iterType = iterType.getOuterClass();
            if (thisField == null) {
                // closure within inner class
                while (ClassHelper.isGeneratedFunction(iterType)) {
                    // GROOVY-8881: cater for closures within closures - getThisObject is already outer class of all closures
                    iterType = iterType.getOuterClass();
                }
                mv.visitMethodInsn(INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(ClassHelper.CLOSURE_TYPE), "getThisObject", "()Ljava/lang/Object;", false);
                mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(iterType));
            } else {
                ClassNode thisFieldType = thisField.getType();
                if (ClassHelper.CLOSURE_TYPE.equals(thisFieldType)) {
                    mv.visitFieldInsn(GETFIELD, ownerName, "this$0", BytecodeHelper.getTypeDescription(ClassHelper.CLOSURE_TYPE));
                    mv.visitMethodInsn(INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(ClassHelper.CLOSURE_TYPE), "getThisObject", "()Ljava/lang/Object;", false);
                    mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(iterType));
                } else {
                    String typeName = BytecodeHelper.getTypeDescription(iterType);
                    mv.visitFieldInsn(GETFIELD, ownerName, "this$0", typeName);
                }
            }
        }
        controller.getOperandStack().push(type);
        return;
    }

    if (propertyName != null) {
        // TODO: spread safe should be handled inside
        if (adapter == getProperty && !pexp.isSpreadSafe()) {
            controller.getCallSiteWriter().makeGetPropertySite(objectExpression, propertyName, pexp.isSafe(), pexp.isImplicitThis());
        } else if (adapter == getGroovyObjectProperty && !pexp.isSpreadSafe()) {
            controller.getCallSiteWriter().makeGroovyObjectGetPropertySite(objectExpression, propertyName, pexp.isSafe(), pexp.isImplicitThis());
        } else {
            controller.getCallSiteWriter().fallbackAttributeOrPropertySite(pexp, objectExpression, propertyName, adapter);
        }
    } else {
        controller.getCallSiteWriter().fallbackAttributeOrPropertySite(pexp, objectExpression, null, adapter);
    }
}
 
Example 20
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void printField(PrintWriter out, FieldNode fieldNode, boolean isInterface) {
    if ((fieldNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
    printAnnotations(out, fieldNode);
    if (!isInterface) {
        printModifiers(out, fieldNode.getModifiers());
    }

    ClassNode type = fieldNode.getType();
    printType(out, type);

    out.print(" ");
    out.print(fieldNode.getName());
    if (isInterface || (fieldNode.getModifiers() & Opcodes.ACC_FINAL) != 0) {
        out.print(" = ");
        Expression valueExpr = fieldNode.getInitialValueExpression();
        if (valueExpr instanceof ConstantExpression) {
            valueExpr = Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) valueExpr);
        }
        if (valueExpr instanceof ConstantExpression
                && fieldNode.isStatic() && fieldNode.isFinal()
                && ClassHelper.isStaticConstantInitializerType(valueExpr.getType())
                && valueExpr.getType().equals(fieldNode.getType())) {
            // GROOVY-5150 : Initialize value with a dummy constant so that Java cross compiles correctly
            if (ClassHelper.STRING_TYPE.equals(valueExpr.getType())) {
                out.print(formatString(valueExpr.getText()));
            } else if (ClassHelper.char_TYPE.equals(valueExpr.getType())) {
                out.print("'"+valueExpr.getText()+"'");
            } else {
                ClassNode constantType = valueExpr.getType();
                out.print('(');
                printType(out, type);
                out.print(") ");
                out.print(valueExpr.getText());
                if (ClassHelper.Long_TYPE.equals(ClassHelper.getWrapper(constantType))) out.print('L');
            }
        } else if (ClassHelper.isPrimitiveType(type)) {
            String val = type == ClassHelper.boolean_TYPE ? "false" : "0";
            out.print("new " + ClassHelper.getWrapper(type) + "((" + type + ")" + val + ")");
        } else {
            out.print("null");
        }
    }
    out.println(";");
}