Java Code Examples for org.codehaus.groovy.ast.ClassNode#equals()
The following examples show how to use
org.codehaus.groovy.ast.ClassNode#equals() .
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 |
private static int getMaximumInterfaceDistance(final ClassNode c, final ClassNode interfaceClass) { // -1 means a mismatch if (c == null) return -1; // 0 means a direct match if (c.equals(interfaceClass)) return 0; ClassNode[] interfaces = c.getInterfaces(); int max = -1; for (ClassNode anInterface : interfaces) { int sub = getMaximumInterfaceDistance(anInterface, interfaceClass); // we need to keep the -1 to track the mismatch, a +1 // by any means could let it look like a direct match // we want to add one, because there is an interface between // the interface we search for and the interface we are in. if (sub != -1) { sub += 1; } // we are interested in the longest path only max = Math.max(max, sub); } // we do not add one for super classes, only for interfaces int superClassMax = getMaximumInterfaceDistance(c.getSuperClass(), interfaceClass); return Math.max(max, superClassMax); }
Example 2
Source File: Methods.java From netbeans with Apache License 2.0 | 6 votes |
public static boolean isSameMethod(MethodNode methodNode1, MethodNode methodNode2) { if (methodNode1.getName().equals(methodNode2.getName())) { Parameter[] params1 = methodNode1.getParameters(); Parameter[] params2 = methodNode2.getParameters(); if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { ClassNode type1 = params1[i].getType(); ClassNode type2 = params2[i].getType(); if (!type1.equals(type2)) { return false; } } return true; } } return false; }
Example 3
Source File: WideningCategories.java From groovy with Apache License 2.0 | 6 votes |
private static void addMostSpecificInterface(ClassNode interfaceNode, List<ClassNode> nodes) { if (nodes.isEmpty()) nodes.add(interfaceNode); for (int i = 0, nodesSize = nodes.size(); i < nodesSize; i++) { final ClassNode node = nodes.get(i); if (node.equals(interfaceNode)||node.implementsInterface(interfaceNode)) { // a more specific interface exists in the list, keep it return; } if (interfaceNode.implementsInterface(node)) { // the interface being added is more specific than the one in the list, replace it nodes.set(i, interfaceNode); return; } } // if we reach this point, this means the interface is new nodes.add(interfaceNode); }
Example 4
Source File: GroovyASTUtils.java From groovy-language-server with Apache License 2.0 | 5 votes |
private static ClassNode tryToResolveOriginalClassNode(ClassNode node, boolean strict, ASTNodeVisitor ast) { for (ClassNode originalNode : ast.getClassNodes()) { if (originalNode.equals(node)) { return originalNode; } } if (strict) { return null; } return node; }
Example 5
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 6
Source File: GenericsUtils.java From groovy with Apache License 2.0 | 5 votes |
public static void extractSuperClassGenerics(ClassNode type, ClassNode target, Map<String, ClassNode> spec) { // TODO: this method is very similar to StaticTypesCheckingSupport#extractGenericsConnections, // but operates on ClassNodes instead of GenericsType if (target == null || type == target) return; if (type.isArray() && target.isArray()) { extractSuperClassGenerics(type.getComponentType(), target.getComponentType(), spec); } else if (type.isArray() && JAVA_LANG_OBJECT.equals(target.getName())) { // Object is superclass of arrays but no generics involved } else if (target.isGenericsPlaceHolder() || type.equals(target) || !implementsInterfaceOrIsSubclassOf(type, target)) { // structural match route if (target.isGenericsPlaceHolder()) { spec.put(target.getGenericsTypes()[0].getName(), type); } else { extractSuperClassGenerics(type.getGenericsTypes(), target.getGenericsTypes(), spec); } } else { // have first to find matching super class or interface ClassNode superClass = getSuperClass(type, target); if (superClass != null) { ClassNode corrected = getCorrectedClassNode(type, superClass, false); extractSuperClassGenerics(corrected, target, spec); } else { // if we reach here, we have an unhandled case throw new GroovyBugError("The type " + type + " seems not to normally extend " + target + ". Sorry, I cannot handle this."); } } }
Example 7
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 5 votes |
public static boolean implementsInterfaceOrIsSubclassOf(final ClassNode type, final ClassNode superOrInterface) { boolean result = (type.equals(superOrInterface) || type.isDerivedFrom(superOrInterface) || type.implementsInterface(superOrInterface) || type == UNKNOWN_PARAMETER_TYPE); if (result) { return true; } if (superOrInterface instanceof WideningCategories.LowestUpperBoundClassNode) { WideningCategories.LowestUpperBoundClassNode cn = (WideningCategories.LowestUpperBoundClassNode) superOrInterface; result = implementsInterfaceOrIsSubclassOf(type, cn.getSuperClass()); if (result) { for (ClassNode interfaceNode : cn.getInterfaces()) { result = type.implementsInterface(interfaceNode); if (!result) break; } } if (result) return true; } else if (superOrInterface instanceof UnionTypeClassNode) { UnionTypeClassNode union = (UnionTypeClassNode) superOrInterface; for (ClassNode delegate : union.getDelegates()) { if (implementsInterfaceOrIsSubclassOf(type, delegate)) return true; } } if (type.isArray() && superOrInterface.isArray()) { return implementsInterfaceOrIsSubclassOf(type.getComponentType(), superOrInterface.getComponentType()); } if (GROOVY_OBJECT_TYPE.equals(superOrInterface) && !type.isInterface() && isBeingCompiled(type)) { return true; } return false; }
Example 8
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 9
Source File: Verifier.java From groovy with Apache License 2.0 | 5 votes |
private boolean isAssignable(ClassNode node, ClassNode testNode) { if (node.isArray() && testNode.isArray()) { return isArrayAssignable(node.getComponentType(), testNode.getComponentType()); } if (testNode.isInterface()) { if (node.equals(testNode) || node.implementsInterface(testNode)) return true; } return node.isDerivedFrom(testNode); }
Example 10
Source File: AsmClassGenerator.java From groovy with Apache License 2.0 | 5 votes |
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 11
Source File: ResolveVisitor.java From groovy with Apache License 2.0 | 5 votes |
private boolean directlyImplementsTrait(final ClassNode trait) { ClassNode[] interfaces = currentClass.getInterfaces(); if (interfaces == null) { return currentClass.getSuperClass().equals(trait); } for (ClassNode node : interfaces) { if (node.equals(trait)) { return true; } } return currentClass.getSuperClass().equals(trait); }
Example 12
Source File: FindAllSubtypes.java From netbeans with Apache License 2.0 | 5 votes |
@Override public void visitClass(final ClassNode node) { if (node.isDerivedFrom(findingParent) && !node.equals(findingParent)) { usages.add(node); } super.visitClass(node); }
Example 13
Source File: CompletionProvider.java From groovy-language-server with Apache License 2.0 | 5 votes |
private void populateItemsFromClassNode(ClassNode classNode, Position position, List<CompletionItem> items) { ASTNode parentNode = ast.getParent(classNode); if (!(parentNode instanceof ClassNode)) { return; } ClassNode parentClassNode = (ClassNode) parentNode; Range classRange = GroovyLanguageServerUtils.astNodeToRange(classNode); String className = getMemberName(classNode.getUnresolvedName(), classRange, position); if (classNode.equals(parentClassNode.getUnresolvedSuperClass())) { populateTypes(classNode, className, new HashSet<>(), true, false, false, items); } else if (Arrays.asList(parentClassNode.getUnresolvedInterfaces()).contains(classNode)) { populateTypes(classNode, className, new HashSet<>(), false, true, false, items); } }
Example 14
Source File: AsmClassGenerator.java From groovy with Apache License 2.0 | 4 votes |
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 15
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 4 votes |
/** * Filter methods according to visibility * * @param methodNodeList method nodes to filter * @param enclosingClassNode the enclosing class * @return filtered method nodes * @since 3.0.0 */ public static List<MethodNode> filterMethodsByVisibility(final List<MethodNode> methodNodeList, final ClassNode enclosingClassNode) { if (!asBoolean(methodNodeList)) { return StaticTypeCheckingVisitor.EMPTY_METHODNODE_LIST; } List<MethodNode> result = new LinkedList<>(); boolean isEnclosingInnerClass = enclosingClassNode instanceof InnerClassNode; List<ClassNode> outerClasses = enclosingClassNode.getOuterClasses(); outer: for (MethodNode methodNode : methodNodeList) { if (methodNode instanceof ExtensionMethodNode) { result.add(methodNode); continue; } ClassNode declaringClass = methodNode.getDeclaringClass(); if (isEnclosingInnerClass) { for (ClassNode outerClass : outerClasses) { if (outerClass.isDerivedFrom(declaringClass)) { if (outerClass.equals(declaringClass)) { result.add(methodNode); continue outer; } else { if (methodNode.isPublic() || methodNode.isProtected()) { result.add(methodNode); continue outer; } } } } } if (declaringClass instanceof InnerClassNode) { if (declaringClass.getOuterClasses().contains(enclosingClassNode)) { result.add(methodNode); continue; } } if (methodNode.isPrivate() && !enclosingClassNode.equals(declaringClass)) { continue; } if (methodNode.isProtected() && !enclosingClassNode.isDerivedFrom(declaringClass) && !samePackageName(enclosingClassNode, declaringClass)) { continue; } if (methodNode.isPackageScope() && !samePackageName(enclosingClassNode, declaringClass)) { continue; } result.add(methodNode); } return result; }
Example 16
Source File: MethodInference.java From netbeans with Apache License 2.0 | 4 votes |
private static MethodNode tryFindPossibleMethod(ClassNode callerType, String methodName, List<ClassNode> paramTypes, boolean isStatic) { int count = paramTypes.size(); MethodNode res = null; ClassNode node = callerType; do { for (MethodNode method : node.getMethods(methodName)) { if (isStatic && !method.isStatic()) { continue; } if (method.getParameters().length == count) { boolean match = true; for (int i = 0; i != count; ++i) { if (!paramTypes.get(i).isDerivedFrom(method.getParameters()[i].getType())) { match = false; break; } } if (match) { if (res == null) { res = method; } else { if (res.getParameters().length != count) { return null; } if (node.equals(callerType)) { return null; } match = true; for (int i = 0; i != count; ++i) { if (!res.getParameters()[i].getType().equals(method.getParameters()[i].getType())) { match = false; break; } } if (!match) { return null; } } } } } node = node.getSuperClass(); } while (node != null); return res; }
Example 17
Source File: BeanUtils.java From groovy with Apache License 2.0 | 4 votes |
public static void addPseudoProperties(ClassNode origType, ClassNode cNode, List<PropertyNode> result, Set<String> names, boolean includeStatic, boolean includePseudoGetters, boolean includePseudoSetters) { if (!includePseudoGetters && !includePseudoSetters) return; List<MethodNode> methods = cNode.getAllDeclaredMethods(); for (MethodNode mNode : methods) { if (!includeStatic && mNode.isStatic()) continue; if (hasAnnotation(mNode, INTERNAL_TYPE)) continue; String name = mNode.getName(); if ((name.length() <= 3 && !name.startsWith(IS_PREFIX)) || name.equals("getClass") || name.equals("getMetaClass") || name.equals("getDeclaringClass")) { // Optimization: skip invalid propertyNames continue; } if (mNode.getDeclaringClass() != origType && mNode.isPrivate()) { // skip private super methods continue; } int paramCount = mNode.getParameters().length; ClassNode paramType = mNode.getReturnType(); String propName = null; Statement getter = null; Statement setter = null; if (paramCount == 0) { if (includePseudoGetters && name.startsWith(GET_PREFIX)) { // Simple getter propName = decapitalize(name.substring(3)); getter = mNode.getCode(); } else if (includePseudoGetters && name.startsWith(IS_PREFIX) && paramType.equals(ClassHelper.boolean_TYPE)) { // boolean getter propName = decapitalize(name.substring(2)); getter = mNode.getCode(); } } else if (paramCount == 1) { if (includePseudoSetters && name.startsWith(SET_PREFIX)) { // Simple setter propName = decapitalize(name.substring(3)); setter = mNode.getCode(); paramType = mNode.getParameters()[0].getType(); } } if (propName != null) { addIfMissing(cNode, result, names, mNode, paramType, propName, getter, setter); } } }
Example 18
Source File: GenericsUtils.java From groovy with Apache License 2.0 | 4 votes |
/** * 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: GeneralUtils.java From groovy with Apache License 2.0 | 3 votes |
/** * This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property * being accessed is defined inside the classnode provided as a parameter, then a getter call is generated * instead of a field access. * @param annotatedNode the class node where the property node is accessed from * @param pNode the property being accessed * @return a method call expression or a property expression */ public static Expression getterThisX(final ClassNode annotatedNode, final PropertyNode pNode) { ClassNode owner = pNode.getDeclaringClass(); if (annotatedNode.equals(owner)) { return callThisX(getterName(annotatedNode, pNode)); } return propX(varX("this"), pNode.getName()); }
Example 20
Source File: TypeCheckingExtension.java From groovy with Apache License 2.0 | 2 votes |
/** * Given a method call, checks if it's a static method call and if it is, tells if the receiver matches * the one supplied as an argument. * @param call a method call * @param receiver a class node * @return true if the method call is a static method call on the receiver */ public boolean isStaticMethodCallOnClass(MethodCall call, ClassNode receiver) { ClassNode staticReceiver = extractStaticReceiver(call); return staticReceiver!=null && staticReceiver.equals(receiver); }