Java Code Examples for org.codehaus.groovy.ast.ClassNode#isUsingGenerics()
The following examples show how to use
org.codehaus.groovy.ast.ClassNode#isUsingGenerics() .
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: ClassCompletionVerifier.java From groovy with Apache License 2.0 | 6 votes |
private void checkGenericsUsage(ASTNode ref, ClassNode node) { if (node.isArray()) { checkGenericsUsage(ref, node.getComponentType()); } else if (!node.isRedirectNode() && node.isUsingGenerics()) { addError( "A transform used a generics containing ClassNode "+ node + " " + "for "+getRefDescriptor(ref) + "directly. You are not supposed to do this. " + "Please create a new ClassNode referring to the old ClassNode " + "and use the new ClassNode instead of the old one. Otherwise " + "the compiler will create wrong descriptors and a potential " + "NullPointerException in TypeResolver in the OpenJDK. If this is " + "not your own doing, please report this bug to the writer of the " + "transform.", ref); } }
Example 2
Source File: TypeCheckingExtension.java From groovy with Apache License 2.0 | 6 votes |
public ClassNode parameterizedType(ClassNode baseType, ClassNode... genericsTypeArguments) { ClassNode result = baseType.getPlainNodeReference(); if (result.isUsingGenerics()) { GenericsType[] gts = new GenericsType[genericsTypeArguments.length]; int expectedLength = result.getGenericsTypes().length; if (expectedLength!=genericsTypeArguments.length) { throw new GroovyBugError("Expected number of generic type arguments for "+baseType.toString(false)+" is "+expectedLength + " but you gave "+genericsTypeArguments.length); } for (int i = 0; i < gts.length; i++) { gts[i] = new GenericsType(genericsTypeArguments[i]); } result.setGenericsTypes(gts); } return result; }
Example 3
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 6 votes |
protected static boolean typeCheckMethodsWithGenerics(final ClassNode receiver, final ClassNode[] argumentTypes, final MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), argumentTypes, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[argumentTypes.length + 1]; dgmArgs[0] = receiver; System.arraycopy(argumentTypes, 0, dgmArgs, 1, argumentTypes.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, argumentTypes, candidateMethod, false); } }
Example 4
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 6 votes |
static ClassNode applyGenericsContext(final Map<GenericsTypeName, GenericsType> spec, final ClassNode bound) { if (bound == null) return null; if (bound.isArray()) { return applyGenericsContext(spec, bound.getComponentType()).makeArray(); } if (!bound.isUsingGenerics()) return bound; ClassNode newBound = bound.getPlainNodeReference(); newBound.setGenericsTypes(applyGenericsContext(spec, bound.getGenericsTypes())); if (bound.isGenericsPlaceHolder()) { GenericsType[] gt = newBound.getGenericsTypes(); boolean hasBounds = hasNonTrivialBounds(gt[0]); if (hasBounds || !gt[0].isPlaceholder()) return getCombinedBoundType(gt[0]); String placeHolderName = newBound.getGenericsTypes()[0].getName(); if (!placeHolderName.equals(newBound.getUnresolvedName())) { // we should produce a clean placeholder ClassNode here ClassNode clean = make(placeHolderName); clean.setGenericsTypes(newBound.getGenericsTypes()); clean.setRedirect(newBound); newBound = clean; } newBound.setGenericsPlaceHolder(true); } return newBound; }
Example 5
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 5 votes |
/** * @param node the node to be tested * @return true if the node is using generics types and one of those types is a string */ public static boolean isParameterizedWithString(final ClassNode node) { if (node.isArray()) return isParameterizedWithString(node.getComponentType()); if (node.isUsingGenerics()) { GenericsType[] genericsTypes = node.getGenericsTypes(); if (genericsTypes != null) { for (GenericsType genericsType : genericsTypes) { if (STRING_TYPE.equals(genericsType.getType())) return true; } } } return node.getSuperClass() != null && isParameterizedWithString(node.getUnresolvedSuperClass()); }
Example 6
Source File: GenericsUtils.java From groovy with Apache License 2.0 | 5 votes |
private static void extractSuperClassGenerics(ClassNode[] usage, ClassNode[] declaration, Map<String, ClassNode> spec) { if (usage == null || declaration == null || declaration.length == 0) return; // both have generics for (int i = 0; i < usage.length; i++) { ClassNode ui = usage[i]; ClassNode di = declaration[i]; if (di.isGenericsPlaceHolder()) { spec.put(di.getGenericsTypes()[0].getName(), di); } else if (di.isUsingGenerics()) { extractSuperClassGenerics(ui.getGenericsTypes(), di.getGenericsTypes(), spec); } } }
Example 7
Source File: GenericsUtils.java From groovy with Apache License 2.0 | 5 votes |
public static ClassNode nonGeneric(ClassNode type) { if (type.isUsingGenerics()) { final ClassNode nonGen = ClassHelper.makeWithoutCaching(type.getName()); nonGen.setRedirect(type); nonGen.setGenericsTypes(null); nonGen.setUsingGenerics(false); return nonGen; } if (type.isArray() && type.getComponentType().isUsingGenerics()) { return type.getComponentType().getPlainNodeReference().makeArray(); } return type; }
Example 8
Source File: WideningCategories.java From groovy with Apache License 2.0 | 5 votes |
/** * 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 9
Source File: WideningCategories.java From groovy with Apache License 2.0 | 5 votes |
private static ClassNode findGenericsTypeHolderForClass(ClassNode source, ClassNode type) { if (isPrimitiveType(source)) source = getWrapper(source); if (source.equals(type)) return source; if (type.isInterface()) { for (ClassNode interfaceNode : source.getAllInterfaces()) { if (interfaceNode.equals(type)) { ClassNode parameterizedInterface = GenericsUtils.parameterizeType(source, interfaceNode); return parameterizedInterface; } } } ClassNode superClass = source.getUnresolvedSuperClass(); // copy generic type information if available if (superClass!=null && superClass.isUsingGenerics()) { Map<GenericsTypeName, GenericsType> genericsTypeMap = GenericsUtils.extractPlaceholders(source); GenericsType[] genericsTypes = superClass.getGenericsTypes(); if (genericsTypes!=null) { GenericsType[] copyTypes = new GenericsType[genericsTypes.length]; for (int i = 0; i < genericsTypes.length; i++) { GenericsType genericsType = genericsTypes[i]; GenericsTypeName gtn = new GenericsTypeName(genericsType.getName()); if (genericsType.isPlaceholder() && genericsTypeMap.containsKey(gtn)) { copyTypes[i] = genericsTypeMap.get(gtn); } else { copyTypes[i] = genericsType; } } superClass = superClass.getPlainNodeReference(); superClass.setGenericsTypes(copyTypes); } } if (superClass!=null) return findGenericsTypeHolderForClass(superClass, type); return null; }
Example 10
Source File: WideningCategories.java From groovy with Apache License 2.0 | 5 votes |
/** * Given a lowest upper bound computed without generic type information but which requires to be parameterized * and the two implementing classnodes which are parameterized with potentially two different types, returns * a parameterized lowest upper bound. * * For example, if LUB is Set<T> and a is Set<String> and b is Set<StringBuffer>, this * will return a LUB which parameterized type matches Set<? extends CharSequence> * @param lub the type to be parameterized * @param a parameterized type a * @param b parameterized type b * @param fallback if we detect a recursive call, use this LUB as the parameterized type instead of computing a value * @return the class node representing the parameterized lowest upper bound */ private static ClassNode parameterizeLowestUpperBound(final ClassNode lub, final ClassNode a, final ClassNode b, final ClassNode fallback) { if (!lub.isUsingGenerics()) return lub; // a common super type exists, all we have to do is to parameterize // it according to the types provided by the two class nodes ClassNode holderForA = findGenericsTypeHolderForClass(a, lub); ClassNode holderForB = findGenericsTypeHolderForClass(b, lub); // let's compare their generics type GenericsType[] agt = holderForA == null ? null : holderForA.getGenericsTypes(); GenericsType[] bgt = holderForB == null ? null : holderForB.getGenericsTypes(); if (agt==null || bgt==null || agt.length!=bgt.length) { return lub; } GenericsType[] lubgt = new GenericsType[agt.length]; for (int i = 0; i < agt.length; i++) { ClassNode t1 = agt[i].getType(); ClassNode t2 = bgt[i].getType(); ClassNode basicType; if (areEqualWithGenerics(t1, a) && areEqualWithGenerics(t2,b)) { // we are facing a self referencing type ! basicType = fallback; } else { basicType = lowestUpperBound(t1, t2); } if (t1.equals(t2)) { lubgt[i] = new GenericsType(basicType); } else { lubgt[i] = GenericsUtils.buildWildcardType(basicType); } } ClassNode plain = lub.getPlainNodeReference(); plain.setGenericsTypes(lubgt); return plain; }
Example 11
Source File: WideningCategories.java From groovy with Apache License 2.0 | 5 votes |
/** * Given two class nodes, returns the first common supertype, or the class itself * if there are equal. For example, Double and Float would return Number, while * Set and String would return Object. * * This method is not guaranteed to return a class node which corresponds to a * real type. For example, if two types have more than one interface in common * and are not in the same hierarchy branch, then the returned type will be a * virtual type implementing all those interfaces. * * Calls to this method are supposed to be made with resolved generics. This means * that you can have wildcards, but no placeholder. * * @param a first class node * @param b second class node * @return first common supertype */ public static ClassNode lowestUpperBound(ClassNode a, ClassNode b) { ClassNode lub = lowestUpperBound(a, b, null, null); if (lub==null || !lub.isUsingGenerics()) return lub; // types may be parameterized. If so, we must ensure that generic type arguments // are made compatible if (lub instanceof LowestUpperBoundClassNode) { // no parent super class representing both types could be found // or both class nodes implement common interfaces which may have // been parameterized differently. // We must create a classnode for which the "superclass" is potentially parameterized // plus the interfaces ClassNode superClass = lub.getSuperClass(); ClassNode psc = superClass.isUsingGenerics()?parameterizeLowestUpperBound(superClass, a, b, lub):superClass; ClassNode[] interfaces = lub.getInterfaces(); ClassNode[] pinterfaces = new ClassNode[interfaces.length]; for (int i = 0, interfacesLength = interfaces.length; i < interfacesLength; i++) { final ClassNode icn = interfaces[i]; if (icn.isUsingGenerics()) { pinterfaces[i] = parameterizeLowestUpperBound(icn, a, b, lub); } else { pinterfaces[i] = icn; } } return new LowestUpperBoundClassNode(((LowestUpperBoundClassNode)lub).name, psc, pinterfaces); } else { return parameterizeLowestUpperBound(lub, a, b, lub); } }
Example 12
Source File: BytecodeHelper.java From groovy with Apache License 2.0 | 5 votes |
private static boolean usesGenericsInClassSignature(ClassNode node) { if (!node.isUsingGenerics()) return false; if (hasGenerics(node)) return true; ClassNode sclass = node.getUnresolvedSuperClass(false); if (sclass.isUsingGenerics()) return true; ClassNode[] interfaces = node.getInterfaces(); if (interfaces != null) { for (ClassNode anInterface : interfaces) { if (anInterface.isUsingGenerics()) return true; } } return false; }
Example 13
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 5 votes |
/** * @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 14
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 5 votes |
private static void extractGenericsConnections(final Map<GenericsTypeName, GenericsType> connections, final ClassNode[] usage, final ClassNode[] declaration) { if (usage == null || declaration == null || declaration.length == 0) return; // both have generics for (int i = 0, n = usage.length; i < n; i += 1) { ClassNode ui = usage[i]; ClassNode di = declaration[i]; if (di.isGenericsPlaceHolder()) { GenericsType gt = new GenericsType(di); gt.setPlaceholder(di.isGenericsPlaceHolder()); connections.put(new GenericsTypeName(di.getGenericsTypes()[0].getName()), gt); } else if (di.isUsingGenerics()) { extractGenericsConnections(connections, ui.getGenericsTypes(), di.getGenericsTypes()); } } }
Example 15
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 5 votes |
/** * Checks that the parameterized generics of an argument are compatible with the generics of the parameter. * * @param parameterType the parameter type of a method * @param argumentType the type of the argument passed to the method */ protected static boolean typeCheckMethodArgumentWithGenerics(final ClassNode parameterType, final ClassNode argumentType, final boolean lastArg) { if (UNKNOWN_PARAMETER_TYPE == argumentType) { // called with null return !isPrimitiveType(parameterType); } if (!isAssignableTo(argumentType, parameterType) && !lastArg) { // incompatible assignment return false; } if (!isAssignableTo(argumentType, parameterType) && lastArg) { if (parameterType.isArray()) { if (!isAssignableTo(argumentType, parameterType.getComponentType())) { return false; } } else { return false; } } if (parameterType.isUsingGenerics() && argumentType.isUsingGenerics()) { GenericsType gt = GenericsUtils.buildWildcardType(parameterType); if (!gt.isCompatibleWith(argumentType)) { boolean samCoercion = isSAMType(parameterType) && argumentType.equals(CLOSURE_TYPE); if (!samCoercion) return false; } } else if (parameterType.isArray() && argumentType.isArray()) { // verify component type return typeCheckMethodArgumentWithGenerics(parameterType.getComponentType(), argumentType.getComponentType(), lastArg); } else if (lastArg && parameterType.isArray()) { // verify component type, but if we reach that point, the only possibility is that the argument is // the last one of the call, so we're in the cast of a vargs call // (otherwise, we face a type checker bug) return typeCheckMethodArgumentWithGenerics(parameterType.getComponentType(), argumentType, lastArg); } return true; }
Example 16
Source File: IndexedPropertyASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private static ClassNode getComponentTypeForList(ClassNode fType) { if (fType.isUsingGenerics() && fType.getGenericsTypes().length == 1) { return fType.getGenericsTypes()[0].getType(); } else { return ClassHelper.OBJECT_TYPE; } }
Example 17
Source File: JavaStubGenerator.java From groovy with Apache License 2.0 | 4 votes |
private void printMethods(PrintWriter out, ClassNode classNode, boolean isEnum) { if (!isEnum) printConstructors(out, classNode); @SuppressWarnings("unchecked") List<MethodNode> methods = (List) propertyMethods.clone(); methods.addAll(classNode.getMethods()); for (MethodNode method : methods) { if (isEnum && method.isSynthetic()) { // skip values() method and valueOf(String) String name = method.getName(); Parameter[] params = method.getParameters(); if (name.equals("values") && params.length == 0) continue; if (name.equals("valueOf") && params.length == 1 && params[0].getType().equals(ClassHelper.STRING_TYPE)) { continue; } } printMethod(out, classNode, method); } // print the methods from traits for (ClassNode trait : findTraits(classNode)) { Map<String, ClassNode> generics = trait.isUsingGenerics() ? createGenericsSpec(trait) : null; List<MethodNode> traitMethods = trait.getMethods(); for (MethodNode traitOrigMethod : traitMethods) { // GROOVY-9606: replace method return type and parameter type placeholder with resolved type from trait generics MethodNode traitMethod = correctToGenericsSpec(generics, traitOrigMethod); MethodNode existingMethod = classNode.getMethod(traitMethod.getName(), traitMethod.getParameters()); if (existingMethod != null) continue; for (MethodNode propertyMethod : propertyMethods) { if (propertyMethod.getName().equals(traitMethod.getName())) { boolean sameParams = sameParameterTypes(propertyMethod, traitMethod); if (sameParams) { existingMethod = propertyMethod; break; } } } if (existingMethod != null) continue; boolean isCandidate = isCandidateTraitMethod(trait, traitMethod); if (!isCandidate) continue; printMethod(out, classNode, traitMethod); } } }
Example 18
Source File: CompleteElementHandler.java From netbeans with Apache License 2.0 | 4 votes |
private Map<MethodSignature, CompletionItem> getMethodsInner( ClassNode source, ClassNode node, String prefix, int anchor, int level, Set<AccessLevel> access, boolean nameOnly) { boolean leaf = (level == 0); Set<AccessLevel> modifiedAccess = AccessLevel.update(access, source, node); Map<MethodSignature, CompletionItem> result = new TreeMap<>(new Comparator<MethodSignature>() { @Override public int compare(MethodSignature method1, MethodSignature method2) { // Different method name --> just compare as normal Strings if (!method1.getName().equals(method2.getName())) { return method1.getName().compareTo(method2.getName()); } // Method with lower 'parameter count' should be always first if (method1.getParameters().length < method2.getParameters().length) { return -1; } if (method1.getParameters().length > method2.getParameters().length) { return 1; } // Same number of parameters --> compare param by param as normal Strings for (int i = 0; i < method1.getParameters().length; i++) { String param1 = method1.getParameters()[i]; String param2 = method2.getParameters()[i]; int comparedValue = param1.compareTo(param2); if (comparedValue != 0) { return comparedValue; } } // This should happened only if there are two absolutely identical methods return 0; } }); ClassDefinition definition = loadDefinition(node); ClassNode typeNode = definition.getNode(); String typeName = typeNode.getName(); // In cases like 1.^ we have current type name "int" but indexer won't find anything for such a primitive if ("int".equals(typeName)) { // NOI18N typeName = "java.lang.Integer"; // NOI18N } context.setTypeName(typeName); GroovyElementsProvider groovyProvider = new GroovyElementsProvider(); fillSuggestions(groovyProvider.getMethods(context), result); // we can't go groovy and java - helper methods would be visible if (result.isEmpty()) { String[] typeParameters = new String[(typeNode.isUsingGenerics() && typeNode.getGenericsTypes() != null) ? typeNode.getGenericsTypes().length : 0]; for (int i = 0; i < typeParameters.length; i++) { GenericsType genType = typeNode.getGenericsTypes()[i]; if (genType.getUpperBounds() != null) { typeParameters[i] = Utilities.translateClassLoaderTypeName(genType.getUpperBounds()[0].getName()); } else { typeParameters[i] = Utilities.translateClassLoaderTypeName(genType.getName()); } } fillSuggestions(JavaElementHandler.forCompilationInfo(info) .getMethods(typeName, prefix, anchor, typeParameters, leaf, modifiedAccess, nameOnly), result); } CompletionProviderHandler providerHandler = new CompletionProviderHandler(); fillSuggestions(providerHandler.getMethods(context), result); fillSuggestions(providerHandler.getStaticMethods(context), result); if (typeNode.getSuperClass() != null) { fillSuggestions(getMethodsInner(source, typeNode.getSuperClass(), prefix, anchor, level + 1, modifiedAccess, nameOnly), result); } else if (leaf) { fillSuggestions(JavaElementHandler.forCompilationInfo(info).getMethods("java.lang.Object", prefix, anchor, new String[]{}, false, modifiedAccess, nameOnly), result); // NOI18N } for (ClassNode inter : typeNode.getInterfaces()) { fillSuggestions(getMethodsInner(source, inter, prefix, anchor, level + 1, modifiedAccess, nameOnly), result); } fillSuggestions(TransformationHandler.getMethods(index, typeNode, prefix, anchor), result); return result; }
Example 19
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 3 votes |
/** * Returns true if the class node represents a the class node for the Class class * and if the parametrized type is a neither a placeholder or a wildcard. For example, * the class node Class<Foo> where Foo is a class would return true, but the class * node for Class<?> would return false. * * @param classNode a class node to be tested * @return true if it is the class node for Class and its generic type is a real class */ public static boolean isClassClassNodeWrappingConcreteType(final ClassNode classNode) { GenericsType[] genericsTypes = classNode.getGenericsTypes(); return CLASS_Type.equals(classNode) && classNode.isUsingGenerics() && genericsTypes != null && !genericsTypes[0].isPlaceholder() && !genericsTypes[0].isWildcard(); }
Example 20
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 3 votes |
/** * 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); }