Java Code Examples for org.codehaus.groovy.ast.ClassNode#isDerivedFrom()
The following examples show how to use
org.codehaus.groovy.ast.ClassNode#isDerivedFrom() .
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: InvocationWriter.java From groovy with Apache License 2.0 | 6 votes |
/** * Converts sourceType to a non primitive by using Groovy casting. * sourceType might be a primitive * This might be done using SBA#castToType */ public void castToNonPrimitiveIfNecessary(final ClassNode sourceType, final ClassNode targetType) { OperandStack os = controller.getOperandStack(); ClassNode boxedType = os.box(); if (WideningCategories.implementsInterfaceOrSubclassOf(boxedType, targetType)) return; MethodVisitor mv = controller.getMethodVisitor(); if (ClassHelper.CLASS_Type.equals(targetType)) { castToClassMethod.call(mv); } else if (ClassHelper.STRING_TYPE.equals(targetType)) { castToStringMethod.call(mv); } else if (targetType.isDerivedFrom(ClassHelper.Enum_Type)) { (new ClassExpression(targetType)).visit(controller.getAcg()); os.remove(1); castToEnumMethod.call(mv); BytecodeHelper.doCast(mv, targetType); } else { (new ClassExpression(targetType)).visit(controller.getAcg()); os.remove(1); castToTypeMethod.call(mv); } }
Example 2
Source File: JavaStubGenerator.java From groovy with Apache License 2.0 | 6 votes |
private static boolean noExceptionToAvoid(ConstructorNode fromStub, ConstructorNode fromSuper) { ClassNode[] superExceptions = fromSuper.getExceptions(); if (superExceptions==null || superExceptions.length==0) return true; ClassNode[] stubExceptions = fromStub.getExceptions(); if (stubExceptions==null || stubExceptions.length==0) return false; // if all remaining exceptions are used in the stub we are good outer: for (ClassNode superExc : superExceptions) { for (ClassNode stub : stubExceptions) { if (stub.isDerivedFrom(superExc)) continue outer; } // not found return false; } return true; }
Example 3
Source File: ImmutablePropertyHandler.java From groovy with Apache License 2.0 | 6 votes |
protected Statement createConstructorStatement(AbstractASTTransformation xform, ClassNode cNode, PropertyNode pNode, Parameter namedArgsMap) { final List<String> knownImmutableClasses = ImmutablePropertyUtils.getKnownImmutableClasses(xform, cNode); final List<String> knownImmutables = ImmutablePropertyUtils.getKnownImmutables(xform, cNode); FieldNode fNode = pNode.getField(); final ClassNode fType = fNode.getType(); Statement statement; boolean shouldNullCheck = NullCheckASTTransformation.hasIncludeGenerated(cNode); if (ImmutablePropertyUtils.isKnownImmutableType(fType, knownImmutableClasses) || isKnownImmutable(pNode.getName(), knownImmutables)) { statement = createConstructorStatementDefault(fNode, namedArgsMap, shouldNullCheck); } else if (fType.isArray() || implementsCloneable(fType)) { statement = createConstructorStatementArrayOrCloneable(fNode, namedArgsMap, shouldNullCheck); } else if (derivesFromDate(fType)) { statement = createConstructorStatementDate(fNode, namedArgsMap, shouldNullCheck); } else if (isOrImplements(fType, COLLECTION_TYPE) || fType.isDerivedFrom(COLLECTION_TYPE) || isOrImplements(fType, MAP_TYPE) || fType.isDerivedFrom(MAP_TYPE)) { statement = createConstructorStatementCollection(fNode, namedArgsMap, shouldNullCheck); } else if (fType.isResolved()) { xform.addError(ImmutablePropertyUtils.createErrorMessage(cNode.getName(), fNode.getName(), fType.getName(), "compiling"), fNode); statement = EmptyStatement.INSTANCE; } else { statement = createConstructorStatementGuarded(fNode, namedArgsMap, knownImmutables, knownImmutableClasses, shouldNullCheck); } return statement; }
Example 4
Source File: ClassCompletionVerifier.java From groovy with Apache License 2.0 | 6 votes |
private void checkClassExtendsAllSelfTypes(ClassNode node) { int modifiers = node.getModifiers(); if (!isInterface(modifiers)) { for (ClassNode anInterface : GeneralUtils.getInterfacesAndSuperInterfaces(node)) { if (Traits.isTrait(anInterface)) { LinkedHashSet<ClassNode> selfTypes = new LinkedHashSet<ClassNode>(); for (ClassNode type : Traits.collectSelfTypes(anInterface, selfTypes, true, false)) { if (type.isInterface() && !node.implementsInterface(type)) { addError(getDescription(node) + " implements " + getDescription(anInterface) + " but does not implement self type " + getDescription(type), anInterface); } else if (!type.isInterface() && !node.isDerivedFrom(type)) { addError(getDescription(node) + " implements " + getDescription(anInterface) + " but does not extend self type " + getDescription(type), anInterface); } } } } } }
Example 5
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 6
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 7
Source File: Verifier.java From groovy with Apache License 2.0 | 5 votes |
protected void addPropertyMethod(MethodNode method) { classNode.addMethod(method); markAsGenerated(classNode, method); // GROOVY-4415 / GROOVY-4645: check that there's no abstract method which corresponds to this one String methodName = method.getName(); Parameter[] parameters = method.getParameters(); ClassNode methodReturnType = method.getReturnType(); for (MethodNode node : classNode.getAbstractMethods()) { if (!node.getDeclaringClass().equals(classNode)) continue; if (node.getName().equals(methodName) && node.getParameters().length == parameters.length) { if (parameters.length == 1) { // setter ClassNode abstractMethodParameterType = node.getParameters()[0].getType(); ClassNode methodParameterType = parameters[0].getType(); if (!methodParameterType.isDerivedFrom(abstractMethodParameterType) && !methodParameterType.implementsInterface(abstractMethodParameterType)) { continue; } } ClassNode nodeReturnType = node.getReturnType(); if (!methodReturnType.isDerivedFrom(nodeReturnType) && !methodReturnType.implementsInterface(nodeReturnType)) { continue; } // matching method, remove abstract status and use the same body node.setModifiers(node.getModifiers() ^ ACC_ABSTRACT); node.setCode(method.getCode()); } } }
Example 8
Source File: WideningCategories.java From groovy with Apache License 2.0 | 5 votes |
/** * Determines if the source class implements an interface or subclasses the target type. * This method takes the {@link org.codehaus.groovy.ast.tools.WideningCategories.LowestUpperBoundClassNode lowest * upper bound class node} type into account, allowing to remove unnecessary casts. * @param source the type of interest * @param targetType the target type of interest */ public static boolean implementsInterfaceOrSubclassOf(final ClassNode source, final ClassNode targetType) { if (source.isDerivedFrom(targetType) || source.implementsInterface(targetType)) return true; if (targetType instanceof WideningCategories.LowestUpperBoundClassNode) { WideningCategories.LowestUpperBoundClassNode lub = (WideningCategories.LowestUpperBoundClassNode) targetType; if (implementsInterfaceOrSubclassOf(source, lub.getSuperClass())) return true; for (ClassNode classNode : lub.getInterfaces()) { if (source.implementsInterface(classNode)) return true; } } return false; }
Example 9
Source File: UnionTypeClassNode.java From groovy with Apache License 2.0 | 5 votes |
@Override public boolean isDerivedFrom(final ClassNode type) { for (ClassNode delegate : delegates) { if (delegate.isDerivedFrom(type)) return true; } return false; }
Example 10
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 11
Source File: GeneratorContext.java From groovy with Apache License 2.0 | 5 votes |
private String getNextInnerName(ClassNode owner, ClassNode enclosingClass, MethodNode enclosingMethod, String classifier) { String methodName = ""; if (enclosingMethod != null) { methodName = enclosingMethod.getName(); if (enclosingClass.isDerivedFrom(ClassHelper.CLOSURE_TYPE)) { methodName = ""; } else { methodName = "_" + encodeAsValidClassName(methodName); } } return methodName + "_" + classifier + closureClassIdx++; }
Example 12
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 5 votes |
/** * 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 13
Source File: CompilationUnit.java From groovy with Apache License 2.0 | 5 votes |
protected ClassVisitor createClassVisitor() { CompilerConfiguration config = getConfiguration(); int computeMaxStackAndFrames = ClassWriter.COMPUTE_MAXS; if (CompilerConfiguration.isPostJDK7(config.getTargetBytecode()) || config.isIndyEnabled()) { computeMaxStackAndFrames += ClassWriter.COMPUTE_FRAMES; } return new ClassWriter(computeMaxStackAndFrames) { private ClassNode getClassNode(String name) { // try classes under compilation CompileUnit cu = getAST(); ClassNode cn = cu.getClass(name); if (cn != null) return cn; // try inner classes cn = cu.getGeneratedInnerClass(name); if (cn != null) return cn; ClassNodeResolver.LookupResult lookupResult = getClassNodeResolver().resolveName(name, CompilationUnit.this); return lookupResult == null ? null : lookupResult.getClassNode(); } private ClassNode getCommonSuperClassNode(ClassNode c, ClassNode d) { // adapted from ClassWriter code if (c.isDerivedFrom(d)) return d; if (d.isDerivedFrom(c)) return c; if (c.isInterface() || d.isInterface()) return ClassHelper.OBJECT_TYPE; do { c = c.getSuperClass(); } while (c != null && !d.isDerivedFrom(c)); if (c == null) return ClassHelper.OBJECT_TYPE; return c; } @Override protected String getCommonSuperClass(String arg1, String arg2) { ClassNode a = getClassNode(arg1.replace('/', '.')); ClassNode b = getClassNode(arg2.replace('/', '.')); return getCommonSuperClassNode(a,b).getName().replace('.','/'); } }; }
Example 14
Source File: ExpressionUtils.java From groovy with Apache License 2.0 | 5 votes |
/** * Determine if a type is derived from Number (or array thereof). * * @param targetType the candidate type * @param recurse true if we can have multi-dimension arrays; should be false for annotation member types * @return true if the type equals the targetType or array thereof */ public static boolean isNumberOrArrayOfNumber(final ClassNode targetType, final boolean recurse) { if (targetType == null) return false; return targetType.isDerivedFrom(ClassHelper.Number_TYPE) || (targetType.isArray() && recurse ? isNumberOrArrayOfNumber(targetType.getComponentType(), recurse) : targetType.isArray() && targetType.getComponentType().isDerivedFrom(ClassHelper.Number_TYPE)); }
Example 15
Source File: GroovyASTUtils.java From groovy-language-server with Apache License 2.0 | 5 votes |
private static int calculateArgumentsScore(Parameter[] parameters, ArgumentListExpression arguments, int argIndex) { int score = 0; int paramCount = parameters.length; int expressionsCount = arguments.getExpressions().size(); int argsCount = expressionsCount; if (argIndex >= argsCount) { argsCount = argIndex + 1; } int minCount = Math.min(paramCount, argsCount); if (minCount == 0 && paramCount == argsCount) { score++; } for (int i = 0; i < minCount; i++) { ClassNode argType = (i < expressionsCount) ? arguments.getExpression(i).getType() : null; ClassNode paramType = (i < paramCount) ? parameters[i].getType() : null; if (argType != null && paramType != null) { if (argType.equals(paramType)) { // equal types are preferred score += 1000; } else if (argType.isDerivedFrom(paramType)) { // subtypes are nice, but less important score += 100; } else { // if a type doesn't match at all, it's not worth much score++; } } else if (paramType != null) { //extra parameters are like a type not matching score++; } } return score; }
Example 16
Source File: InvocationWriter.java From groovy with Apache License 2.0 | 4 votes |
protected boolean writeDirectMethodCall(final MethodNode target, final boolean implicitThis, final Expression receiver, final TupleExpression args) { if (target == null) return false; String methodName = target.getName(); CompileStack compileStack = controller.getCompileStack(); OperandStack operandStack = controller.getOperandStack(); ClassNode declaringClass = target.getDeclaringClass(); ClassNode classNode = controller.getClassNode(); MethodVisitor mv = controller.getMethodVisitor(); int opcode = INVOKEVIRTUAL; if (target.isStatic()) { opcode = INVOKESTATIC; } else if (declaringClass.isInterface()) { opcode = INVOKEINTERFACE; } else if (target.isPrivate() || AsmClassGenerator.isSuperExpression(receiver)) { opcode = INVOKESPECIAL; } // handle receiver int argumentsToRemove = 0; if (opcode != INVOKESTATIC) { if (receiver != null) { // load receiver if not static invocation // todo: fix inner class case if (implicitThis && classNode.getOuterClass() != null && !classNode.isDerivedFrom(declaringClass) && !classNode.implementsInterface(declaringClass)) { // we are calling an outer class method compileStack.pushImplicitThis(false); if (controller.isInGeneratedFunction()) { new VariableExpression("thisObject").visit(controller.getAcg()); } else { Expression expr = new PropertyExpression(new ClassExpression(declaringClass), "this"); expr.visit(controller.getAcg()); } } else { compileStack.pushImplicitThis(implicitThis); receiver.visit(controller.getAcg()); } operandStack.doGroovyCast(declaringClass); compileStack.popImplicitThis(); argumentsToRemove += 1; } else { mv.visitIntInsn(ALOAD,0); operandStack.push(classNode); argumentsToRemove += 1; } } int stackSize = operandStack.getStackLength(); String owner = BytecodeHelper.getClassInternalName(declaringClass); ClassNode receiverType = receiver != null ? controller.getTypeChooser().resolveType(receiver, classNode) : declaringClass; if (opcode == INVOKEVIRTUAL && ClassHelper.OBJECT_TYPE.equals(declaringClass)) { // avoid using a narrowed type if the method is defined on object because it can interfere // with delegate type inference in static compilation mode and trigger a ClassCastException receiverType = declaringClass; } if (opcode == INVOKEVIRTUAL) { if (!receiverType.equals(declaringClass) && !ClassHelper.OBJECT_TYPE.equals(declaringClass) && !receiverType.isArray() && !receiverType.isInterface() && !ClassHelper.isPrimitiveType(receiverType) // e.g int.getClass() && receiverType.isDerivedFrom(declaringClass)) { owner = BytecodeHelper.getClassInternalName(receiverType); ClassNode top = operandStack.getTopOperand(); if (!receiverType.equals(top)) { mv.visitTypeInsn(CHECKCAST, owner); } } else if (target.isPublic() && (!receiverType.equals(declaringClass) && !Modifier.isPublic(declaringClass.getModifiers())) && receiverType.isDerivedFrom(declaringClass) && !Objects.equals(receiverType.getPackageName(), classNode.getPackageName())) { // GROOVY-6962: package private class, public method owner = BytecodeHelper.getClassInternalName(receiverType); } } loadArguments(args.getExpressions(), target.getParameters()); String desc = BytecodeHelper.getMethodDescriptor(target.getReturnType(), target.getParameters()); mv.visitMethodInsn(opcode, owner, methodName, desc, declaringClass.isInterface()); ClassNode ret = target.getReturnType().redirect(); if (ret == ClassHelper.VOID_TYPE) { ret = ClassHelper.OBJECT_TYPE; mv.visitInsn(ACONST_NULL); } argumentsToRemove += (operandStack.getStackLength()-stackSize); controller.getOperandStack().remove(argumentsToRemove); controller.getOperandStack().push(ret); return true; }
Example 17
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 18
Source File: WideningCategories.java From groovy with Apache License 2.0 | 4 votes |
public static boolean isNumberCategory(ClassNode type) { return isBigDecCategory(type) || type.isDerivedFrom(Number_TYPE); }
Example 19
Source File: AnnotationVisitor.java From groovy with Apache License 2.0 | 4 votes |
protected void visitExpression(String attrName, Expression attrExp, ClassNode attrType) { if (attrType.isArray()) { // check needed as @Test(attr = {"elem"}) passes through the parser if (attrExp instanceof ListExpression) { ListExpression le = (ListExpression) attrExp; visitListExpression(attrName, le, attrType.getComponentType()); } else if (attrExp instanceof ClosureExpression) { addError("Annotation list attributes must use Groovy notation [el1, el2]", attrExp); } else { // treat like a singleton list as per Java ListExpression listExp = new ListExpression(); listExp.addExpression(attrExp); if (annotation != null) { annotation.setMember(attrName, listExp); } visitExpression(attrName, listExp, attrType); } } else if (ClassHelper.isPrimitiveType(attrType)) { visitConstantExpression(attrName, getConstantExpression(attrExp, attrType), ClassHelper.getWrapper(attrType)); } else if (ClassHelper.STRING_TYPE.equals(attrType)) { visitConstantExpression(attrName, getConstantExpression(attrExp, attrType), ClassHelper.STRING_TYPE); } else if (ClassHelper.CLASS_Type.equals(attrType)) { if (!(attrExp instanceof ClassExpression || attrExp instanceof ClosureExpression)) { addError("Only classes and closures can be used for attribute '" + attrName + "'", attrExp); } } else if (attrType.isDerivedFrom(ClassHelper.Enum_Type)) { if (attrExp instanceof PropertyExpression) { visitEnumExpression(attrName, (PropertyExpression) attrExp, attrType); } else { addError("Expected enum value for attribute " + attrName, attrExp); } } else if (isValidAnnotationClass(attrType)) { if (attrExp instanceof AnnotationConstantExpression) { visitAnnotationExpression(attrName, (AnnotationConstantExpression) attrExp, attrType); } else { addError("Expected annotation of type '" + attrType.getName() + "' for attribute " + attrName, attrExp); } } else { addError("Unexpected type " + attrType.getName(), attrExp); } }
Example 20
Source File: ImmutablePropertyUtils.java From groovy with Apache License 2.0 | 4 votes |
public static boolean derivesFromDate(ClassNode fieldType) { return fieldType.isDerivedFrom(DATE_TYPE); }