Java Code Examples for org.codehaus.groovy.ast.ClassNode#getComponentType()

The following examples show how to use org.codehaus.groovy.ast.ClassNode#getComponentType() . 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: ClassNodeUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Formats a type name into a human readable version. For arrays, appends "[]" to the formatted
 * type name of the component. For unit class nodes, uses the class node name.
 *
 * @param cNode the type to format
 * @return a human readable version of the type name (java.lang.String[] for example)
 */
public static String formatTypeName(ClassNode cNode) {
    if (cNode.isArray()) {
        ClassNode it = cNode;
        int dim = 0;
        while (it.isArray()) {
            dim++;
            it = it.getComponentType();
        }
        StringBuilder sb = new StringBuilder(it.getName().length() + 2 * dim);
        sb.append(it.getName());
        for (int i = 0; i < dim; i++) {
            sb.append("[]");
        }
        return sb.toString();
    }
    return cNode.getName();
}
 
Example 2
Source File: InstanceOfVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    if (expression.getOperation().isA(Types.INSTANCEOF_OPERATOR) &&
            expression.getRightExpression() instanceof ClassExpression) {
        ClassNode referenceType = expression.getRightExpression().getType();

        if (ClassHelper.isPrimitiveType(referenceType)) {
            addTypeError(expression.getRightExpression(), "primitive type " + referenceType.getName());
        } else {
            while (referenceType.isArray()) {
                referenceType = referenceType.getComponentType();
            }

            if (referenceType.isGenericsPlaceHolder()) {
                addTypeError(expression.getRightExpression(), "type parameter " + referenceType.getUnresolvedName() +
                    ". Use its erasure " + referenceType.getNameWithoutPackage() + " instead since further generic type information will be erased at runtime");
            } else if (referenceType.getGenericsTypes() != null) {
                // TODO: Cannot perform instanceof check against parameterized type Class<Type>. Use the form Class<?> instead since further eneric type information will be erased at runtime
            }
        }
    }
    super.visitBinaryExpression(expression);
}
 
Example 3
Source File: GroovydocVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private String makeType(ClassNode node) {
    final ClassNode cn = node.isArray() ? node.getComponentType() : node;
    return cn.getName().replace('.', '/').replace('$', '.')
        + genericTypesAsString(cn.getGenericsTypes())
        + (node.isArray() ? "[]" : "")
        ;
}
 
Example 4
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected boolean resolve(final ClassNode type, final boolean testModuleImports, final boolean testDefaultImports, final boolean testStaticInnerClasses) {
    resolveGenericsTypes(type.getGenericsTypes());
    if (type.isResolved() || type.isPrimaryClassNode()) return true;
    if (type.isArray()) {
        ClassNode element = type.getComponentType();
        boolean resolved = resolve(element, testModuleImports, testDefaultImports, testStaticInnerClasses);
        if (resolved) {
            ClassNode cn = element.makeArray();
            type.setRedirect(cn);
        }
        return resolved;
    }

    // test if vanilla name is current class name
    if (currentClass == type) return true;

    String typeName = type.getName();

    GenericsType genericsType = genericParameterNames.get(new GenericsTypeName(typeName));
    if (genericsType != null) {
        type.setRedirect(genericsType.getType());
        type.setGenericsTypes(new GenericsType[]{genericsType});
        type.setGenericsPlaceHolder(true);
        return true;
    }

    if (currentClass.getNameWithoutPackage().equals(typeName)) {
        type.setRedirect(currentClass);
        return true;
    }

    return  (!type.hasPackageName() && resolveNestedClass(type)) ||
            resolveFromModule(type, testModuleImports) ||
            resolveFromCompileUnit(type) ||
            (testDefaultImports && !type.hasPackageName() && resolveFromDefaultImports(type)) ||
            resolveToOuter(type) ||
            (testStaticInnerClasses && type.hasPackageName() && resolveFromStaticInnerClasses(type));
}
 
Example 5
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the last argument matches the vararg type.
 *
 * @return -1 if no match, 0 if the last argument is exactly the vararg type and 1 if of an assignable type
 */
static int lastArgMatchesVarg(final Parameter[] parameters, final ClassNode... argumentTypes) {
    if (!isVargs(parameters)) return -1;
    // case length ==0 handled already
    // we have now two cases,
    // the argument is wrapped in the vargs array or
    // the argument is an array that can be used for the vargs part directly
    // we test only the wrapping part, since the non wrapping is done already
    ClassNode lastParamType = parameters[parameters.length - 1].getType();
    ClassNode ptype = lastParamType.getComponentType();
    ClassNode arg = argumentTypes[argumentTypes.length - 1];
    if (isNumberType(ptype) && isNumberType(arg) && !ptype.equals(arg)) return -1;
    return isAssignableTo(arg, ptype) ? min(getDistance(arg, lastParamType), getDistance(arg, ptype)) : -1;
}
 
Example 6
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Given a parameter, builds a new parameter for which the known generics placeholders are resolved.
 *
 * @param genericFromReceiver      resolved generics from the receiver of the message
 * @param placeholdersFromContext  resolved generics from the method context
 * @param methodParameter          the method parameter for which we want to resolve generic types
 * @param paramType                the (unresolved) type of the method parameter
 * @return a new parameter with the same name and type as the original one, but with resolved generic types
 */
private static Parameter buildParameter(final Map<GenericsTypeName, GenericsType> genericFromReceiver, final Map<GenericsTypeName, GenericsType> placeholdersFromContext, final Parameter methodParameter, final ClassNode paramType) {
    if (genericFromReceiver.isEmpty() && (placeholdersFromContext == null || placeholdersFromContext.isEmpty())) {
        return methodParameter;
    }
    if (paramType.isArray()) {
        ClassNode componentType = paramType.getComponentType();
        Parameter subMethodParameter = new Parameter(componentType, methodParameter.getName());
        Parameter component = buildParameter(genericFromReceiver, placeholdersFromContext, subMethodParameter, componentType);
        return new Parameter(component.getType().makeArray(), component.getName());
    }
    ClassNode resolved = resolveClassNodeGenerics(genericFromReceiver, placeholdersFromContext, paramType);

    return new Parameter(resolved, methodParameter.getName());
}
 
Example 7
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean inferenceCheck(final Set<GenericsTypeName> fixedGenericsPlaceHolders, final Map<GenericsTypeName, GenericsType> resolvedMethodGenerics, ClassNode type, ClassNode wrappedArgument, final boolean lastArg) {
    Map<GenericsTypeName, GenericsType> connections = new HashMap<>();
    if (isPrimitiveType(wrappedArgument)) wrappedArgument = getWrapper(wrappedArgument);

    if (lastArg &&
            type.isArray() && type.getComponentType().isGenericsPlaceHolder() &&
            !wrappedArgument.isArray() && wrappedArgument.isGenericsPlaceHolder()) {
        // GROOVY-8090: handle generics varargs, e.g. "U x = ...; Arrays.asList(x)"
        // we should connect the type of vararg(e.g. T is the type of T...) to the argument type
        type = type.getComponentType();
    }
    // the context we compare with in the end is the one of the callsite
    // so far we specified the context of the method declaration only
    // thus for each argument, we try to find the connected generics first
    extractGenericsConnections(connections, wrappedArgument, type);
    // each found connection must comply with already found connections
    boolean failure = !compatibleConnections(connections, resolvedMethodGenerics, fixedGenericsPlaceHolders);
    // and then apply the found information to refine the method level
    // information. This way the method level information slowly turns
    // into information for the callsite
    applyGenericsConnections(connections, resolvedMethodGenerics);
    // since it is possible that the callsite uses some generics as well,
    // we may have to add additional elements here
    addMissingEntries(connections, resolvedMethodGenerics);
    // to finally see if the parameter and the argument fit together,
    // we use the provided information to transform the parameter
    // into something that can exist in the callsite context
    type = applyGenericsContext(resolvedMethodGenerics, type);
    // there of course transformed parameter type and argument must fit
    failure = failure || !typeCheckMethodArgumentWithGenerics(type, wrappedArgument, lastArg);
    return failure;
}
 
Example 8
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static String getStaticFieldName(final ClassNode type) {
    ClassNode componentType = type;
    StringBuilder prefix = new StringBuilder();
    for (; componentType.isArray(); componentType = componentType.getComponentType()) {
        prefix.append("$");
    }
    if (prefix.length() != 0) prefix.insert(0, "array");
    String name = prefix + "$class$" + makeFieldClassName(componentType);
    return name;
}
 
Example 9
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void loadArguments(final List<Expression> argumentList, final Parameter[] para) {
    if (para.length == 0) return;
    ClassNode lastParaType = para[para.length - 1].getOriginType();
    AsmClassGenerator acg = controller.getAcg();
    OperandStack operandStack = controller.getOperandStack();
    if (lastParaType.isArray() && (argumentList.size() > para.length
            || argumentList.size() == para.length - 1 || !lastIsArray(argumentList, para.length - 1))) {
        int stackLen = operandStack.getStackLength() + argumentList.size();
        MethodVisitor mv = controller.getMethodVisitor();
        controller.setMethodVisitor(mv);
        // varg call
        // first parameters as usual
        for (int i = 0, n = para.length - 1; i < n; i += 1) {
            argumentList.get(i).visit(acg);
            operandStack.doGroovyCast(para[i].getType());
        }
        // last parameters wrapped in an array
        List<Expression> lastParams = new LinkedList<>();
        for (int i = para.length - 1, n = argumentList.size(); i < n; i += 1) {
            lastParams.add(argumentList.get(i));
        }
        ArrayExpression array = new ArrayExpression(
                lastParaType.getComponentType(),
                lastParams
        );
        array.visit(acg);
        // adjust stack length
        while (operandStack.getStackLength() < stackLen) {
            operandStack.push(ClassHelper.OBJECT_TYPE);
        }
        if (argumentList.size() == para.length - 1) {
            operandStack.remove(1);
        }
    } else {
        for (int i = 0, n = argumentList.size(); i < n; i += 1) {
            argumentList.get(i).visit(acg);
            operandStack.doGroovyCast(para[i].getType());
        }
    }
}
 
Example 10
Source File: BinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void assignToArray(final Expression orig, final Expression receiver, final Expression index, final Expression rhsValueLoader, final boolean safe) {
    ClassNode current = controller.getClassNode();
    ClassNode arrayType = controller.getTypeChooser().resolveType(receiver, current);
    ClassNode arrayComponentType = arrayType.getComponentType();
    int operationType = getOperandType(arrayComponentType);
    BinaryExpressionWriter bew = binExpWriter[operationType];
    AsmClassGenerator acg = controller.getAcg();

    if (bew.arraySet(true) && arrayType.isArray() && !safe) {
        OperandStack operandStack   =   controller.getOperandStack();

        // load the array
        receiver.visit(acg);
        operandStack.doGroovyCast(arrayType);

        // load index
        index.visit(acg);
        operandStack.doGroovyCast(int_TYPE);

        // load rhs
        rhsValueLoader.visit(acg);
        operandStack.doGroovyCast(arrayComponentType);

        // store value in array
        bew.arraySet(false);

        // load return value && correct operand stack stack
        operandStack.remove(3);
        rhsValueLoader.visit(acg);
    } else {
        super.assignToArray(orig, receiver, index, rhsValueLoader, safe);
    }
}
 
Example 11
Source File: ElementUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Returns type for the given ASTNode. For example if FieldNode is passed
 * as a parameter, it returns type of the given field etc. If the Method call
 * is passed as a parameter, the method tried to interfere proper type and return it
 *
 * @param node where we want to know declared type
 * @return type of the given node
 * @throws IllegalStateException if an implementation is missing for the given ASTNode type
 */
public static ClassNode getType(ASTNode node) {
    if (node instanceof FakeASTNode) {
        node = ((FakeASTNode) node).getOriginalNode();
    }

    if (node instanceof ClassNode) {
        ClassNode clazz = ((ClassNode) node);
        if (clazz.getComponentType() != null) {
            return clazz.getComponentType();
        } else {
            return clazz;
        }
    } else if (node instanceof AnnotationNode) {
        return ((AnnotationNode) node).getClassNode();
    } else if (node instanceof FieldNode) {
        return ((FieldNode) node).getType();
    } else if (node instanceof PropertyNode) {
        return ((PropertyNode) node).getType();
    } else if (node instanceof MethodNode) {
        return ((MethodNode) node).getReturnType();
    } else if (node instanceof Parameter) {
       return ((Parameter) node).getType();
    } else if (node instanceof ForStatement) {
        return ((ForStatement) node).getVariableType();
    } else if (node instanceof CatchStatement) {
        return ((CatchStatement) node).getVariable().getOriginType();
    } else if (node instanceof ImportNode) {
        return ((ImportNode) node).getType();
    } else if (node instanceof ClassExpression) {
        return ((ClassExpression) node).getType();
    } else if (node instanceof VariableExpression) {
        return ((VariableExpression) node).getType();
    } else if (node instanceof DeclarationExpression) {
        DeclarationExpression declaration = ((DeclarationExpression) node);
        if (declaration.isMultipleAssignmentDeclaration()) {
            return declaration.getTupleExpression().getType();
        } else {
            return declaration.getVariableExpression().getType();
        }
    } else if (node instanceof ConstructorCallExpression) {
        return ((ConstructorCallExpression) node).getType();
    } else if (node instanceof ArrayExpression) {
        return ((ArrayExpression) node).getElementType();
    }
    throw new IllegalStateException("Not implemented yet - GroovyRefactoringElement.getType() needs to be improve!"); // NOI18N
}
 
Example 12
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitBinaryExpression(final BinaryExpression expression) {
    if (expression.getNodeMetaData(StatementMeta.class) != null) return;
    super.visitBinaryExpression(expression);

    ClassNode leftType = typeChooser.resolveType(expression.getLeftExpression(), node);
    ClassNode rightType = typeChooser.resolveType(expression.getRightExpression(), node);
    ClassNode resultType = null;
    int operation = expression.getOperation().getType();

    if (operation == Types.LEFT_SQUARE_BRACKET && leftType.isArray()) {
        opt.chainShouldOptimize(true);
        resultType = leftType.getComponentType();
    } else {
        switch (operation) {
            case Types.COMPARE_EQUAL:
            case Types.COMPARE_LESS_THAN:
            case Types.COMPARE_LESS_THAN_EQUAL:
            case Types.COMPARE_GREATER_THAN:
            case Types.COMPARE_GREATER_THAN_EQUAL:
            case Types.COMPARE_NOT_EQUAL:
                if (isIntCategory(leftType) && isIntCategory(rightType)) {
                    opt.chainShouldOptimize(true);
                } else if (isLongCategory(leftType) && isLongCategory(rightType)) {
                    opt.chainShouldOptimize(true);
                } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) {
                    opt.chainShouldOptimize(true);
                } else {
                    opt.chainCanOptimize(true);
                }
                resultType = boolean_TYPE;
                break;
            case Types.LOGICAL_AND:
            case Types.LOGICAL_AND_EQUAL:
            case Types.LOGICAL_OR:
            case Types.LOGICAL_OR_EQUAL:
                if (boolean_TYPE.equals(leftType) && boolean_TYPE.equals(rightType)) {
                    opt.chainShouldOptimize(true);
                } else {
                    opt.chainCanOptimize(true);
                }
                expression.setType(boolean_TYPE);
                resultType = boolean_TYPE;
                break;
            case Types.DIVIDE:
            case Types.DIVIDE_EQUAL:
                if (isLongCategory(leftType) && isLongCategory(rightType)) {
                    resultType = BigDecimal_TYPE;
                    opt.chainShouldOptimize(true);
                } else if (isBigDecCategory(leftType) && isBigDecCategory(rightType)) {
                    // no optimization for BigDecimal yet
                    //resultType = BigDecimal_TYPE;
                } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) {
                    resultType = double_TYPE;
                    opt.chainShouldOptimize(true);
                }
                break;
            case Types.POWER:
            case Types.POWER_EQUAL:
                // TODO: implement
                break;
            case Types.ASSIGN:
                resultType = optimizeDivWithIntOrLongTarget(expression.getRightExpression(), leftType);
                opt.chainCanOptimize(true);
                break;
            default:
                if (isIntCategory(leftType) && isIntCategory(rightType)) {
                    resultType = int_TYPE;
                    opt.chainShouldOptimize(true);
                } else if (isLongCategory(leftType) && isLongCategory(rightType)) {
                    resultType = long_TYPE;
                    opt.chainShouldOptimize(true);
                } else if (isBigDecCategory(leftType) && isBigDecCategory(rightType)) {
                    // no optimization for BigDecimal yet
                    //resultType = BigDecimal_TYPE;
                } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) {
                    resultType = double_TYPE;
                    opt.chainShouldOptimize(true);
                }
        }
    }

    if (resultType != null) {
        addMeta(expression).type = resultType;
        opt.chainInvolvedType(resultType);
        opt.chainInvolvedType(rightType);
        opt.chainInvolvedType(leftType);
    }
}
 
Example 13
Source File: StaticInvocationWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
protected void loadArguments(final List<Expression> argumentList, final Parameter[] para) {
    if (para.length == 0) return;
    ClassNode lastParaType = para[para.length - 1].getOriginType();
    AsmClassGenerator acg = controller.getAcg();
    TypeChooser typeChooser = controller.getTypeChooser();
    OperandStack operandStack = controller.getOperandStack();
    int argumentListSize = argumentList.size();
    ClassNode lastArgType = argumentListSize > 0 ?
            typeChooser.resolveType(argumentList.get(argumentListSize -1), controller.getClassNode()) : null;
    if (lastParaType.isArray()
            && ((argumentListSize > para.length)
            || ((argumentListSize == (para.length - 1)) && !lastParaType.equals(lastArgType))
            || ((argumentListSize == para.length && lastArgType!=null && !lastArgType.isArray())
                && (StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(lastArgType,lastParaType.getComponentType())))
                    || ClassHelper.GSTRING_TYPE.equals(lastArgType) && ClassHelper.STRING_TYPE.equals(lastParaType.getComponentType()))
            ) {
        int stackLen = operandStack.getStackLength() + argumentListSize;
        MethodVisitor mv = controller.getMethodVisitor();
        controller.setMethodVisitor(mv);
        // varg call
        // first parameters as usual
        for (int i = 0; i < para.length - 1; i += 1) {
            visitArgument(argumentList.get(i), para[i].getType());
        }
        // last parameters wrapped in an array
        List<Expression> lastParams = new ArrayList<>();
        for (int i = para.length - 1; i < argumentListSize; i += 1) {
            lastParams.add(argumentList.get(i));
        }
        ArrayExpression array = new ArrayExpression(lastParaType.getComponentType(), lastParams);
        array.visit(acg);
        // adjust stack length
        while (operandStack.getStackLength() < stackLen) {
            operandStack.push(ClassHelper.OBJECT_TYPE);
        }
        if (argumentListSize == para.length - 1) {
            operandStack.remove(1);
        }
    } else if (argumentListSize == para.length) {
        for (int i = 0; i < argumentListSize; i++) {
            visitArgument(argumentList.get(i), para[i].getType());
        }
    } else {
        // method call with default arguments
        ClassNode classNode = controller.getClassNode();
        Expression[] arguments = new Expression[para.length];
        for (int i = 0, j = 0, n = para.length; i < n; i += 1) {
            Parameter curParam = para[i];
            ClassNode curParamType = curParam.getType();
            Expression curArg = j < argumentListSize ? argumentList.get(j) : null;
            Expression initialExpression = curParam.getNodeMetaData(StaticTypesMarker.INITIAL_EXPRESSION);
            if (initialExpression == null && curParam.hasInitialExpression())
                initialExpression = curParam.getInitialExpression();
            if (initialExpression == null && curParam.getNodeMetaData(Verifier.INITIAL_EXPRESSION) != null) {
                initialExpression = curParam.getNodeMetaData(Verifier.INITIAL_EXPRESSION);
            }
            ClassNode curArgType = curArg == null ? null : typeChooser.resolveType(curArg, classNode);

            if (initialExpression != null && !compatibleArgumentType(curArgType, curParamType)) {
                // use default expression
                arguments[i] = initialExpression;
            } else {
                arguments[i] = curArg;
                j += 1;
            }
        }
        for (int i = 0, n = arguments.length; i < n; i += 1) {
            visitArgument(arguments[i], para[i].getType());
        }
    }
}