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

The following examples show how to use org.codehaus.groovy.ast.ClassNode#isResolved() . 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: 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 2
Source File: ExtendedVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void visitOverride(AnnotatedNode node, AnnotationNode visited) {
    ClassNode annotationType = visited.getClassNode();
    if (annotationType.isResolved() && annotationType.getName().equals("java.lang.Override")) {
        if (node instanceof MethodNode && !Boolean.TRUE.equals(node.getNodeMetaData(Verifier.DEFAULT_PARAMETER_GENERATED))) {
            boolean override = false;
            MethodNode origMethod = (MethodNode) node;
            ClassNode cNode = origMethod.getDeclaringClass();
            if (origMethod.hasDefaultValue()) {
                List<MethodNode> variants = cNode.getDeclaredMethods(origMethod.getName());
                for (MethodNode m : variants) {
                    if (m.getAnnotations().contains(visited) && isOverrideMethod(m)) {
                        override = true;
                        break;
                    }
                }
            } else {
                override = isOverrideMethod(origMethod);
            }

            if (!override) {
                addError("Method '" + origMethod.getName() + "' from class '" + cNode.getName() + "' does not override " +
                        "method from its superclass or interfaces but is annotated with @Override.", visited);
            }
        }
    }
}
 
Example 3
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
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: FindMethodUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Find and add method usage if the given type contains method corresponding
 * with the given method call. In other words we are looking for the method
 * declaration in the given type and the method we are looking for is based
 * on given method call. Might return null if the type can't be interfered
 * properly and thus we are not able to find correct method - this is typical
 * for dynamic types.
 *
 * @param type where we are looking for the specific method
 * @param methodCall method call for which we want to find method in given
 * type or null if the type is dynamic
 */
private static MethodNode findMethod(ClassNode type, MethodCallExpression methodCall) {
    String findingMethod = methodCall.getMethodAsString();
    Expression arguments = methodCall.getArguments();
    
    if (!type.isResolved()) {
        type = type.redirect();
    }

    MethodNode method = type.tryFindPossibleMethod(findingMethod, arguments);
    if (method != null) {
        return method;
    }
    return findMostAccurateMethod(methodCall, type.getMethods(findingMethod));
}
 
Example 5
Source File: StaticImportVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression findStaticField(ClassNode staticImportType, String fieldName) {
    if (staticImportType.isPrimaryClassNode() || staticImportType.isResolved()) {
        FieldNode field = getField(staticImportType, fieldName);
        if (field != null && field.isStatic())
            return newStaticPropertyX(staticImportType, fieldName);
    }
    return null;
}
 
Example 6
Source File: StaticImportVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression findStaticMethod(ClassNode staticImportType, String methodName, Expression args) {
    if (staticImportType.isPrimaryClassNode() || staticImportType.isResolved()) {
        if (staticImportType.hasPossibleStaticMethod(methodName, args)) {
            return newStaticMethodCallX(staticImportType, methodName, args);
        }
    }
    return null;
}
 
Example 7
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 8
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitAnnotations(final AnnotatedNode node) {
    List<AnnotationNode> annotations = node.getAnnotations();
    if (annotations.isEmpty()) return;
    Map<String, AnnotationNode> tmpAnnotations = new HashMap<>();
    for (AnnotationNode an : annotations) {
        // skip built-in properties
        if (an.isBuiltIn()) continue;
        ClassNode annType = an.getClassNode();
        resolveOrFail(annType, " for annotation", an);
        for (Map.Entry<String, Expression> member : an.getMembers().entrySet()) {
            Expression newValue = transform(member.getValue());
            Expression adjusted = transformInlineConstants(newValue);
            member.setValue(adjusted);
            checkAnnotationMemberValue(adjusted);
        }
        if (annType.isResolved()) {
            Class<?> annTypeClass = annType.getTypeClass();
            Retention retAnn = annTypeClass.getAnnotation(Retention.class);
            if (retAnn != null && !retAnn.value().equals(RetentionPolicy.SOURCE) && !isRepeatable(annTypeClass)) {
                // remember non-source/non-repeatable annos (auto collecting of Repeatable annotations is handled elsewhere)
                AnnotationNode anyPrevAnnNode = tmpAnnotations.put(annTypeClass.getName(), an);
                if (anyPrevAnnNode != null) {
                    addError("Cannot specify duplicate annotation on the same member : " + annType.getName(), an);
                }
            }
        }
    }
}
 
Example 9
Source File: ClassNodeResolver.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Search for classes using ASM decompiler
 */
private LookupResult findDecompiled(String name, CompilationUnit compilationUnit, GroovyClassLoader loader) {
    ClassNode node = ClassHelper.make(name);
    if (node.isResolved()) {
        return new LookupResult(null, node);
    }

    DecompiledClassNode asmClass = null;
    String fileName = name.replace('.', '/') + ".class";
    URL resource = loader.getResource(fileName);
    if (resource != null) {
        try {
            asmClass = new DecompiledClassNode(AsmDecompiler.parseClass(resource), new AsmReferenceResolver(this, compilationUnit));
            if (!asmClass.getName().equals(name)) {
                // this may happen under Windows because getResource is case insensitive under that OS!
                asmClass = null;
            }
        } catch (IOException e) {
            // fall through and attempt other search strategies
        }
    }

    if (asmClass != null) {
        if (isFromAnotherClassLoader(loader, fileName)) {
            return tryAsScript(name, compilationUnit, asmClass);
        }

        return new LookupResult(null, asmClass);
    }
    return null;
}
 
Example 10
Source File: ASTTransformationCollectorCodeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Annotation getTransformClassAnnotation(final ClassNode annotationType) {
    if (!annotationType.isResolved()) return null;

    for (Annotation a : annotationType.getTypeClass().getAnnotations()) {
        // clients are free to choose any GroovyClassLoader for resolving a
        // ClassNode such as annotationType; we have to compare by name and
        // cannot cast the return value to our GroovyASTTransformationClass
        if (a.annotationType().getName().equals(GroovyASTTransformationClass.class.getName())) {
            return a;
        }
    }

    return null;
}
 
Example 11
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected Expression transformVariableExpression(final VariableExpression ve) {
    visitAnnotations(ve);
    Variable v = ve.getAccessedVariable();

    if(!(v instanceof DynamicVariable) && !checkingVariableTypeInDeclaration) {
        /*
         *  GROOVY-4009: when a normal variable is simply being used, there is no need to try to
         *  resolve its type. Variable type resolve should proceed only if the variable is being declared.
         */
        return ve;
    }
    if (v instanceof DynamicVariable) {
        String name = ve.getName();
        ClassNode t = ClassHelper.make(name);
        // asking isResolved here allows to check if a primitive
        // type name like "int" was used to make t. In such a case
        // we have nothing left to do.
        boolean isClass = t.isResolved();
        if (!isClass) {
            // It was no primitive type, so next we see if the name,
            // which is a vanilla name, starts with a lower case letter.
            // In that case we change it to a LowerCaseClass to let the
            // compiler skip the resolving at several places in this class.
            if (Character.isLowerCase(name.charAt(0))) {
                t = new LowerCaseClass(name);
            }
            isClass = resolve(t);
        }
        if (isClass) {
            // the name is a type so remove it from the scoping
            // as it is only a classvariable, it is only in
            // referencedClassVariables, but must be removed
            // for each parentscope too
            for (VariableScope scope = currentScope; scope != null && !scope.isRoot(); scope = scope.getParent()) {
                if (scope.removeReferencedClassVariable(ve.getName()) == null) break;
            }
            return new ClassExpression(t);
        }
    }
    resolveOrFail(ve.getType(), ve);
    ClassNode origin = ve.getOriginType();
    if (origin != ve.getType()) resolveOrFail(origin, ve);
    return ve;
}
 
Example 12
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void checkNoStaticMethodWithSameSignatureAsNonStatic(final ClassNode node) {
    ClassNode parent = node.getSuperClass();
    Map<String, MethodNode> result;
    // start with methods from the parent if any
    if (parent != null) {
        result = parent.getDeclaredMethodsMap();
    } else {
        result = new HashMap<String, MethodNode>();
    }
    // add in unimplemented abstract methods from the interfaces
    ClassNodeUtils.addDeclaredMethodsFromInterfaces(node, result);
    for (MethodNode methodNode : node.getMethods()) {
        MethodNode mn = result.get(methodNode.getTypeDescriptor());
        if (mn != null && (mn.isStatic() ^ methodNode.isStatic()) && !methodNode.isStaticConstructor()) {
            if (!mn.isAbstract()) continue;
            ClassNode declaringClass = mn.getDeclaringClass();
            ClassNode cn = declaringClass.getOuterClass();
            if (cn == null && declaringClass.isResolved()) {
                // in case of a precompiled class, the outerclass is unknown
                Class typeClass = declaringClass.getTypeClass();
                typeClass = typeClass.getEnclosingClass();
                if (typeClass != null) {
                    cn = ClassHelper.make(typeClass);
                }
            }
            if (!Traits.isTrait(cn)) {
                ASTNode errorNode = methodNode;
                String name = mn.getName();
                if (errorNode.getLineNumber() == -1) {
                    // try to get a better error message location based on the property
                    for (PropertyNode propertyNode : node.getProperties()) {
                        if (name.startsWith("set") || name.startsWith("get") || name.startsWith("is")) {
                            String propName = Verifier.capitalize(propertyNode.getField().getName());
                            String shortName = name.substring(name.startsWith("is") ? 2 : 3);
                            if (propName.equals(shortName)) {
                                errorNode = propertyNode;
                                break;
                            }
                        }
                    }
                }
                addError("The " + getDescription(methodNode) + " is already defined in " + getDescription(node) +
                        ". You cannot have both a static and an instance method with the same signature", errorNode);
            }
        }
        result.put(methodNode.getTypeDescriptor(), methodNode);
    }
}