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

The following examples show how to use org.codehaus.groovy.ast.ClassNode#getGenericsTypes() . 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: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static boolean missesGenericsTypes(final ClassNode cn) {
    if (cn.isArray()) return missesGenericsTypes(cn.getComponentType());
    GenericsType[] cnTypes = cn.getGenericsTypes();
    GenericsType[] rnTypes = cn.redirect().getGenericsTypes();
    if (rnTypes != null && cnTypes == null) return true;
    if (cnTypes != null) {
        for (GenericsType genericsType : cnTypes) {
            if (genericsType.isPlaceholder()) return true;
            if (genericsType.isWildcard()) {
                ClassNode lowerBound = genericsType.getLowerBound();
                ClassNode[] upperBounds = genericsType.getUpperBounds();
                if (lowerBound != null) {
                    if (lowerBound.isGenericsPlaceHolder() || missesGenericsTypes(lowerBound)) return true;
                } else if (upperBounds != null) {
                    if (upperBounds[0].isGenericsPlaceHolder() || missesGenericsTypes(upperBounds[0])) return true;
                }
            }
        }
    }
    return false;
}
 
Example 2
Source File: GenericsUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Map<GenericsType, GenericsType> makePlaceholderAndParameterizedTypeMap(ClassNode declaringClass) {
    if (null == declaringClass) {
        return Collections.emptyMap();
    }

    Map<GenericsType, GenericsType> result = new LinkedHashMap<>();

    ClassNode redirectDeclaringClass = declaringClass.redirect();
    GenericsType[] declaringGenericsTypes = declaringClass.getGenericsTypes();
    GenericsType[] redirectDeclaringGenericsTypes = redirectDeclaringClass.getGenericsTypes();

    if (null != declaringGenericsTypes && null != redirectDeclaringGenericsTypes) {
        for (int i = 0, n = declaringGenericsTypes.length; i < n; i++) {
            result.put(redirectDeclaringGenericsTypes[i], declaringGenericsTypes[i]);
        }
    }

    return result;
}
 
Example 3
Source File: GenericsUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static ClassNode[] parseClassNodesFromString(final String option, final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final MethodNode mn, final ASTNode usage) {
    try {
        ModuleNode moduleNode = ParserPlugin.buildAST("Dummy<" + option + "> dummy;", compilationUnit.getConfiguration(), compilationUnit.getClassLoader(), null);
        DeclarationExpression dummyDeclaration = (DeclarationExpression) ((ExpressionStatement) moduleNode.getStatementBlock().getStatements().get(0)).getExpression();

        // the returned node is DummyNode<Param1, Param2, Param3, ...)
        ClassNode dummyNode = dummyDeclaration.getLeftExpression().getType();
        GenericsType[] dummyNodeGenericsTypes = dummyNode.getGenericsTypes();
        if (dummyNodeGenericsTypes == null) {
            return null;
        }
        ClassNode[] signature = new ClassNode[dummyNodeGenericsTypes.length];
        for (int i = 0, n = dummyNodeGenericsTypes.length; i < n; i += 1) {
            final GenericsType genericsType = dummyNodeGenericsTypes[i];
            signature[i] = resolveClassNode(sourceUnit, compilationUnit, mn, usage, genericsType.getType());
        }
        return signature;
    } catch (Exception | LinkageError e) {
        sourceUnit.addError(new IncorrectTypeHintException(mn, e, usage.getLineNumber(), usage.getColumnNumber()));
    }
    return null;
}
 
Example 4
Source File: ImmutablePropertyUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static boolean isKnownImmutableType(ClassNode fieldType, List<String> knownImmutableClasses) {
    if (builtinOrDeemedType(fieldType, knownImmutableClasses))
        return true;
    if (!fieldType.isResolved())
        return false;
    if ("java.util.Optional".equals(fieldType.getName()) && fieldType.getGenericsTypes() != null && fieldType.getGenericsTypes().length == 1) {
        GenericsType optionalType = fieldType.getGenericsTypes()[0];
        if (optionalType.isResolved() && !optionalType.isPlaceholder() && !optionalType.isWildcard()) {
            ClassNode valueType = optionalType.getType();
            if (builtinOrDeemedType(valueType, knownImmutableClasses)) return true;
            if (valueType.isEnum()) return true;
        }
    }
    return fieldType.isEnum() ||
            ClassHelper.isPrimitiveType(fieldType) ||
            hasImmutableAnnotation(fieldType);
}
 
Example 5
Source File: BytecodeHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static String getGenericsMethodSignature(MethodNode node) {
    GenericsType[] generics = node.getGenericsTypes();
    Parameter[] param = node.getParameters();
    ClassNode returnType = node.getReturnType();

    if (generics == null && !hasGenerics(param) && !hasGenerics(returnType)) return null;

    StringBuilder ret = new StringBuilder(100);
    getGenericsTypeSpec(ret, generics);

    GenericsType[] paramTypes = new GenericsType[param.length];
    for (int i = 0; i < param.length; i++) {
        ClassNode pType = param[i].getType();
        if (pType.getGenericsTypes() == null || !pType.isGenericsPlaceHolder()) {
            paramTypes[i] = new GenericsType(pType);
        } else {
            paramTypes[i] = pType.getGenericsTypes()[0];
        }
    }
    addSubTypes(ret, paramTypes, "(", ")");
    addSubTypes(ret, new GenericsType[]{new GenericsType(returnType)}, "", "");
    return ret.toString();
}
 
Example 6
Source File: ClosureSignatureHint.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * A helper method which will extract the n-th generic type from a class node.
 * @param type the class node from which to pick a generic type
 * @param gtIndex the index of the generic type to extract
 * @return the n-th generic type, or {@link org.codehaus.groovy.ast.ClassHelper#OBJECT_TYPE} if it doesn't exist.
 */
public static ClassNode pickGenericType(ClassNode type, int gtIndex) {
    final GenericsType[] genericsTypes = type.getGenericsTypes();
    if (genericsTypes==null || genericsTypes.length<gtIndex) {
        return ClassHelper.OBJECT_TYPE;
    }
    return genericsTypes[gtIndex].getType();
}
 
Example 7
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean checkPlaceHolders(ClassNode parameterizedType, Predicate<GenericsType> p) {
    if (null == parameterizedType) return false;

    GenericsType[] genericsTypes = parameterizedType.getGenericsTypes();

    if (null == genericsTypes) return false;

    for (GenericsType genericsType : genericsTypes) {
        if (p.test(genericsType)) {
            return true;
        }
    }

    return false;
}
 
Example 8
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * @param node the node to be tested
 * @return true if the node is using generics types and one of those types is a gstring or string/gstring lub
 */
public static boolean isParameterizedWithGStringOrGStringString(final ClassNode node) {
    if (node.isArray()) return isParameterizedWithGStringOrGStringString(node.getComponentType());
    if (node.isUsingGenerics()) {
        GenericsType[] genericsTypes = node.getGenericsTypes();
        if (genericsTypes != null) {
            for (GenericsType genericsType : genericsTypes) {
                if (isGStringOrGStringStringLUB(genericsType.getType())) return true;
            }
        }
    }
    return node.getSuperClass() != null && isParameterizedWithGStringOrGStringString(node.getUnresolvedSuperClass());
}
 
Example 9
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 10
Source File: FindTypeUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isCaretOnGenericType(ClassNode classNode, BaseDocument doc, int cursorOffset) {
    GenericsType[] genericsTypes = classNode.getGenericsTypes();
    if (genericsTypes != null && genericsTypes.length > 0) {
        for (GenericsType genericsType : genericsTypes) {
            if (getGenericTypeRange(genericsType, doc, cursorOffset) != OffsetRange.NONE) {
                return true;
            }
        }
    }
    return false;
}
 
Example 11
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if a class node is assignable to another. This is used for example in
 * assignment checks where you want to verify that the assignment is valid.
 *
 * @return true if the class node is assignable to the other class node, false otherwise
 */
static boolean isAssignableTo(ClassNode type, ClassNode toBeAssignedTo) {
    if (type == toBeAssignedTo || type == UNKNOWN_PARAMETER_TYPE) return true;
    if (isPrimitiveType(type)) type = getWrapper(type);
    if (isPrimitiveType(toBeAssignedTo)) toBeAssignedTo = getWrapper(toBeAssignedTo);
    if (NUMBER_TYPES.containsKey(type.redirect()) && NUMBER_TYPES.containsKey(toBeAssignedTo.redirect())) {
        return NUMBER_TYPES.get(type.redirect()) <= NUMBER_TYPES.get(toBeAssignedTo.redirect());
    }
    if (type.isArray() && toBeAssignedTo.isArray()) {
        return isAssignableTo(type.getComponentType(), toBeAssignedTo.getComponentType());
    }
    if (type.isDerivedFrom(GSTRING_TYPE) && STRING_TYPE.equals(toBeAssignedTo)) {
        return true;
    }
    if (STRING_TYPE.equals(type) && toBeAssignedTo.isDerivedFrom(GSTRING_TYPE)) {
        return true;
    }
    if (implementsInterfaceOrIsSubclassOf(type, toBeAssignedTo)) {
        if (toBeAssignedTo.getGenericsTypes() != null) {
            // perform additional check on generics
            // ? extends toBeAssignedTo
            GenericsType gt = GenericsUtils.buildWildcardType(toBeAssignedTo);
            return gt.isCompatibleWith(type);
        }
        return true;
    }
    // SAM check
    if (type.isDerivedFrom(CLOSURE_TYPE) && isSAMType(toBeAssignedTo)) {
        return true;
    }

    return false;
}
 
Example 12
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static FieldNode tryGetFieldNode(final ClassNode weavedType, final String fieldName) {
    FieldNode fn = weavedType.getDeclaredField(fieldName);
    if (fn == null && ClassHelper.CLASS_Type.equals(weavedType)) {
        GenericsType[] genericsTypes = weavedType.getGenericsTypes();
        if (genericsTypes != null && genericsTypes.length == 1) {
            // for static properties
            fn = genericsTypes[0].getType().getDeclaredField(fieldName);
        }
    }
    return fn;
}
 
Example 13
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static Map<String, ClassNode> createGenericsSpec(ClassNode current, Map<String, ClassNode> oldSpec) {
    Map<String, ClassNode> ret = new HashMap<String, ClassNode>(oldSpec);
    // ret contains the type specs, what we now need is the type spec for the
    // current class. To get that we first apply the type parameters to the
    // current class and then use the type names of the current class to reset
    // the map. Example:
    //   class A<V,W,X>{}
    //   class B<T extends Number> extends A<T,Long,String> {}
    // first we have:    T->Number
    // we apply it to A<T,Long,String> -> A<Number,Long,String>
    // resulting in:     V->Number,W->Long,X->String

    GenericsType[] sgts = current.getGenericsTypes();
    if (sgts != null) {
        ClassNode[] spec = new ClassNode[sgts.length];
        for (int i = 0; i < spec.length; i++) {
            spec[i] = correctToGenericsSpec(ret, sgts[i]);
        }
        GenericsType[] newGts = current.redirect().getGenericsTypes();
        if (newGts == null) return ret;
        ret.clear();
        for (int i = 0; i < spec.length; i++) {
            ret.put(newGts[i].getName(), spec[i]);
        }
    }
    return ret;
}
 
Example 14
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean equalIncludingGenerics(final ClassNode orig, final ClassNode copy) {
    if (orig == copy) return true;
    if (orig.isGenericsPlaceHolder() != copy.isGenericsPlaceHolder()) return false;
    if (!orig.equals(copy)) return false;
    GenericsType[] gt1 = orig.getGenericsTypes();
    GenericsType[] gt2 = orig.getGenericsTypes();
    if ((gt1 == null) ^ (gt2 == null)) return false;
    if (gt1 != gt2) {
        if (gt1.length != gt2.length) return false;
        for (int i = 0, n = gt1.length; i < n; i += 1) {
            if (!equalIncludingGenerics(gt1[i], gt2[i])) return false;
        }
    }
    return true;
}
 
Example 15
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static ClassNode correctToGenericsSpec(Map<String, ClassNode> genericsSpec, ClassNode type) {
    if (type.isArray()) {
        return correctToGenericsSpec(genericsSpec, type.getComponentType()).makeArray();
    }
    if (type.isGenericsPlaceHolder() && type.getGenericsTypes() != null) {
        String name = type.getGenericsTypes()[0].getName();
        type = genericsSpec.get(name);
        if (type != null && type.isGenericsPlaceHolder()
                && !name.equals(type.getUnresolvedName())) {
            return correctToGenericsSpec(genericsSpec, type);
        }
    }
    if (type == null) type = ClassHelper.OBJECT_TYPE;
    return type;
}
 
Example 16
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
static Map<GenericsTypeName, GenericsType> applyGenericsContextToParameterClass(final Map<GenericsTypeName, GenericsType> spec, final ClassNode parameterUsage) {
    GenericsType[] gts = parameterUsage.getGenericsTypes();
    if (gts == null) return Collections.emptyMap();

    GenericsType[] newGTs = applyGenericsContext(spec, gts);
    ClassNode newTarget = parameterUsage.redirect().getPlainNodeReference();
    newTarget.setGenericsTypes(newGTs);
    return GenericsUtils.extractPlaceholders(newTarget);
}
 
Example 17
Source File: WideningCategories.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Compares two class nodes, but including their generics types.
 * @param a
 * @param b
 * @return true if the class nodes are equal, false otherwise
 */
private static boolean areEqualWithGenerics(ClassNode a, ClassNode b) {
    if (a==null) return b==null;
    if (!a.equals(b)) return false;
    if (a.isUsingGenerics() && !b.isUsingGenerics()) return false;
    GenericsType[] gta = a.getGenericsTypes();
    GenericsType[] gtb = b.getGenericsTypes();
    if (gta==null && gtb!=null) return false;
    if (gtb==null && gta!=null) return false;
    if (gta!=null && gtb!=null) {
        if (gta.length!=gtb.length) return false;
        for (int i = 0; i < gta.length; i++) {
            GenericsType ga = gta[i];
            GenericsType gb = gtb[i];
            boolean result = ga.isPlaceholder()==gb.isPlaceholder() && ga.isWildcard()==gb.isWildcard();
            result = result && ga.isResolved() && gb.isResolved();
            result = result && ga.getName().equals(gb.getName());
            result = result && areEqualWithGenerics(ga.getType(), gb.getType());
            result = result && areEqualWithGenerics(ga.getLowerBound(), gb.getLowerBound());
            if (result) {
                ClassNode[] upA = ga.getUpperBounds();
                if (upA!=null) {
                    ClassNode[] upB = gb.getUpperBounds();
                    if (upB==null || upB.length!=upA.length) return false;
                    for (int j = 0; j < upA.length; j++) {
                        if (!areEqualWithGenerics(upA[j],upB[j])) return false;
                    }
                }
            }
            if (!result) return false;
        }
    }
    return true;
}
 
Example 18
Source File: GenericsUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Get the parameterized type by searching the whole class hierarchy according to generics class and actual receiver.
 * {@link #findParameterizedTypeFromCache(ClassNode, ClassNode, boolean)} is strongly recommended for better performance.
 *
 * @param genericsClass the generics class
 * @param actualType the actual type
 * @param tryToFindExactType whether to try to find exact type
 * @return the parameterized type
 */
public static ClassNode findParameterizedType(ClassNode genericsClass, ClassNode actualType, boolean tryToFindExactType) {
    ClassNode parameterizedType = null;

    if (null == genericsClass.getGenericsTypes()) {
        return parameterizedType;
    }

    GenericsType[] declaringGenericsTypes = genericsClass.getGenericsTypes();

    List<ClassNode> classNodeList = new LinkedList<>(getAllSuperClassesAndInterfaces(actualType));
    classNodeList.add(0, actualType);

    LinkedList<ClassNode> parameterizedTypeCandidateList = new LinkedList<>();

    for (ClassNode cn : classNodeList) {
        if (cn == genericsClass) {
            continue;
        }

        if (tryToFindExactType && null != cn.getGenericsTypes() && hasNonPlaceHolders(cn)) {
            parameterizedTypeCandidateList.add(cn);
        }

        if (!(genericsClass.equals(cn.redirect()))) {
            continue;
        }

        if (isGenericsTypeArraysLengthEqual(declaringGenericsTypes, cn.getGenericsTypes())) {
            parameterizedType = cn;
            break;
        }
    }

    if (null == parameterizedType) {
        if (!parameterizedTypeCandidateList.isEmpty()) {
            parameterizedType = parameterizedTypeCandidateList.getLast();
        }
    }

    return parameterizedType;
}
 
Example 19
Source File: SignatureCodecVersion1.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void doEncode(final ClassNode node, DataOutputStream dos) throws IOException {
    dos.writeUTF(node.getClass().getSimpleName());
    if (node instanceof UnionTypeClassNode) {
        UnionTypeClassNode union = (UnionTypeClassNode) node;
        ClassNode[] delegates = union.getDelegates();
        dos.writeInt(delegates.length);
        for (ClassNode delegate : delegates) {
            doEncode(delegate, dos);
        }
        return;
    } else if (node instanceof WideningCategories.LowestUpperBoundClassNode) {
        WideningCategories.LowestUpperBoundClassNode lub = (WideningCategories.LowestUpperBoundClassNode) node;
        dos.writeUTF(lub.getLubName());
        doEncode(lub.getUnresolvedSuperClass(), dos);
        ClassNode[] interfaces = lub.getInterfaces();
        if (interfaces == null) {
            dos.writeInt(-1);
        } else {
            dos.writeInt(interfaces.length);
            for (ClassNode anInterface : interfaces) {
                doEncode(anInterface, dos);
            }
        }
        return;
    }
    if (node.isArray()) {
        dos.writeBoolean(true);
        doEncode(node.getComponentType(), dos);
    } else {
        dos.writeBoolean(false);
        dos.writeUTF(BytecodeHelper.getTypeDescription(node));
        dos.writeBoolean(node.isUsingGenerics());
        GenericsType[] genericsTypes = node.getGenericsTypes();
        if (genericsTypes == null) {
            dos.writeInt(-1);
        } else {
            dos.writeInt(genericsTypes.length);
            for (GenericsType type : genericsTypes) {
                dos.writeBoolean(type.isPlaceholder());
                dos.writeBoolean(type.isWildcard());
                doEncode(type.getType(), dos);
                ClassNode lb = type.getLowerBound();
                if (lb == null) {
                    dos.writeBoolean(false);
                } else {
                    dos.writeBoolean(true);
                    doEncode(lb, dos);
                }
                ClassNode[] upperBounds = type.getUpperBounds();
                if (upperBounds == null) {
                    dos.writeInt(-1);
                } else {
                    dos.writeInt(upperBounds.length);
                    for (ClassNode bound : upperBounds) {
                        doEncode(bound, dos);
                    }
                }
            }
        }
    }
}
 
Example 20
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 3 votes vote down vote up
/**
 * Returns true if a class node makes use of generic types. If the class node represents an
 * array type, then checks if the component type is using generics.
 *
 * @param cn a class node for which to check if it is using generics
 * @return true if the type (or component type) is using generics
 */
public static boolean isUsingGenericsOrIsArrayUsingGenerics(final ClassNode cn) {
    if (cn.isArray()) {
        return isUsingGenericsOrIsArrayUsingGenerics(cn.getComponentType());
    }
    return (cn.isUsingGenerics() && cn.getGenericsTypes() != null);
}