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

The following examples show how to use org.codehaus.groovy.ast.ClassNode#getSuperClass() . 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: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) {
    ClassNode type = node.getDeclaringClass();
    ClassNode superType = type.getSuperClass();

    boolean hadPrivateConstructor = false;
    for (ConstructorNode c : superType.getDeclaredConstructors()) {
        // Only look at things we can actually call
        if (c.isPublic() || c.isProtected()) {
            return c.getParameters();
        }
    }

    // fall back for parameterless constructor
    if (superType.isPrimaryClassNode()) {
        return Parameter.EMPTY_ARRAY;
    }

    return null;
}
 
Example 2
Source File: EnumCompletionVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Add map and no-arg constructor or mirror those of the superclass (i.e. base enum).
 */
private static void addImplicitConstructors(ClassNode enumClass, boolean aic) {
    if (aic) {
        ClassNode sn = enumClass.getSuperClass();
        List<ConstructorNode> sctors = new ArrayList<ConstructorNode>(sn.getDeclaredConstructors());
        if (sctors.isEmpty()) {
            addMapConstructors(enumClass);
        } else {
            for (ConstructorNode constructorNode : sctors) {
                ConstructorNode init = new ConstructorNode(ACC_PUBLIC, constructorNode.getParameters(), ClassNode.EMPTY_ARRAY, new BlockStatement());
                enumClass.addConstructor(init);
            }
        }
    } else {
        addMapConstructors(enumClass);
    }
}
 
Example 3
Source File: ImmutableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
static boolean isSpecialNamedArgCase(List<PropertyNode> list, boolean checkSize) {
    if (checkSize && list.size() != 1) return false;
    if (list.size() == 0) return false;
    ClassNode firstParamType = list.get(0).getField().getType();
    if (firstParamType.equals(ClassHelper.MAP_TYPE)) {
        return true;
    }
    ClassNode candidate = HMAP_TYPE;
    while (candidate != null) {
        if (candidate.equals(firstParamType)) {
            return true;
        }
        candidate = candidate.getSuperClass();
    }
    return false;
}
 
Example 4
Source File: StatementMetaTypeChooser.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public ClassNode resolveType(final Expression exp, final ClassNode current) {
    ClassNode type = null;
    if (exp instanceof ClassExpression) { type = exp.getType();
        ClassNode classType = ClassHelper.makeWithoutCaching("java.lang.Class");
        classType.setGenericsTypes(new GenericsType[] {new GenericsType(type)});
        classType.setRedirect(ClassHelper.CLASS_Type);
        return classType;
    }

    OptimizingStatementWriter.StatementMeta meta = exp.getNodeMetaData(OptimizingStatementWriter.StatementMeta.class);
    if (meta != null) type = meta.type;
    if (type != null) return type;

    if (exp instanceof VariableExpression) {
        VariableExpression ve = (VariableExpression) exp;
        if (ve.isClosureSharedVariable()) return ve.getType();
        if (ve.isSuperExpression()) return current.getSuperClass();

        type = ve.getOriginType();
    } else if (exp instanceof Variable) {
        Variable v = (Variable) exp;
        type = v.getOriginType();
    } else {
        type = exp.getType();
    }
    return type.redirect();
}
 
Example 5
Source File: GroovyNodeToStringUtils.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public static String classToString(ClassNode classNode, ASTNodeVisitor ast) {
	StringBuilder builder = new StringBuilder();
	String packageName = classNode.getPackageName();
	if (packageName != null && packageName.length() > 0) {
		builder.append("package ");
		builder.append(packageName);
		builder.append("\n");
	}
	if (!classNode.isSyntheticPublic()) {
		builder.append("public ");
	}
	if (classNode.isAbstract()) {
		builder.append("abstract ");
	}
	if (classNode.isInterface()) {
		builder.append("interface ");
	} else if (classNode.isEnum()) {
		builder.append("enum ");
	} else {
		builder.append("class ");
	}
	builder.append(classNode.getNameWithoutPackage());

	ClassNode superClass = null;
	try {
		superClass = classNode.getSuperClass();
	} catch (NoClassDefFoundError e) {
		//this is fine, we'll just treat it as null
	}
	if (superClass != null && !superClass.getName().equals(JAVA_OBJECT)) {
		builder.append(" extends ");
		builder.append(superClass.getNameWithoutPackage());
	}
	return builder.toString();
}
 
Example 6
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 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 7
Source File: ClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean classNodeUsesReferences(final ClassNode classNode) {
    boolean ret = classNode.getSuperClass() == ClassHelper.CLOSURE_TYPE;
    if (ret) return ret;
    if (classNode instanceof InnerClassNode) {
        InnerClassNode inner = (InnerClassNode) classNode;
        return inner.isAnonymous();
    }
    return false;
}
 
Example 8
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void visitSpecialConstructorCall(final ConstructorCallExpression call) {
    if (controller.getClosureWriter().addGeneratedClosureConstructorCall(call)) return;
    ClassNode callNode = controller.getClassNode();
    if (call.isSuperCall()) callNode = callNode.getSuperClass();
    List<ConstructorNode> constructors = sortConstructors(call, callNode);
    if (!makeDirectConstructorCall(constructors, call, callNode)) {
        makeMOPBasedConstructorCall(constructors, call, callNode);
    }
}
 
Example 9
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addSimpleCloneHelperMethod(ClassNode cNode, List<FieldNode> fieldNodes, List<String> excludes) {
    Parameter methodParam = new Parameter(GenericsUtils.nonGeneric(cNode), "other");
    final Expression other = varX(methodParam);
    boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE;
    BlockStatement methodBody = new BlockStatement();
    if (hasParent) {
        methodBody.addStatement(stmt(callSuperX("cloneOrCopyMembers", args(other))));
    }
    for (FieldNode fieldNode : fieldNodes) {
        String name = fieldNode.getName();
        if (excludes != null && excludes.contains(name)) continue;
        ClassNode fieldType = fieldNode.getType();
        Expression direct = propX(varX("this"), name);
        Expression to = propX(other, name);
        Statement assignDirect = assignS(to, direct);
        Statement assignCloned = assignS(to, castX(fieldType, callCloneDirectX(direct)));
        Statement assignClonedDynamic = assignS(to, castX(fieldType, callCloneDynamicX(direct)));
        if (isCloneableType(fieldType)) {
            methodBody.addStatement(assignCloned);
        } else if (!possiblyCloneable(fieldType)) {
            methodBody.addStatement(assignDirect);
        } else {
            methodBody.addStatement(ifElseS(isInstanceOfX(direct, CLONEABLE_TYPE), assignClonedDynamic, assignDirect));
        }
    }
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "cloneOrCopyMembers", ACC_PROTECTED, ClassHelper.VOID_TYPE, params(methodParam), exceptions, methodBody);
}
 
Example 10
Source File: CompilationUnit.java    From groovy with Apache License 2.0 5 votes vote down vote up
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 11
Source File: VetoableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Snoops through the declaring class and all parents looking for a field
 * of type VetoableChangeSupport.  Remembers the field and returns false
 * if found otherwise returns true to indicate that such support should
 * be added.
 *
 * @param declaringClass the class to search
 * @return true if vetoable change support should be added
 */
protected boolean needsVetoableChangeSupport(ClassNode declaringClass, SourceUnit sourceUnit) {
    boolean foundAdd = false, foundRemove = false, foundFire = false;
    ClassNode consideredClass = declaringClass;
    while (consideredClass!= null) {
        for (MethodNode method : consideredClass.getMethods()) {
            // just check length, MOP will match it up
            foundAdd = foundAdd || method.getName().equals("addVetoableChangeListener") && method.getParameters().length == 1;
            foundRemove = foundRemove || method.getName().equals("removeVetoableChangeListener") && method.getParameters().length == 1;
            foundFire = foundFire || method.getName().equals("fireVetoableChange") && method.getParameters().length == 3;
            if (foundAdd && foundRemove && foundFire) {
                return false;
            }
        }
        consideredClass = consideredClass.getSuperClass();
    }
    // check if a super class has @Vetoable annotations
    consideredClass = declaringClass.getSuperClass();
    while (consideredClass!=null) {
        if (hasVetoableAnnotation(consideredClass)) return false;
        for (FieldNode field : consideredClass.getFields()) {
            if (hasVetoableAnnotation(field)) return false;
        }
        consideredClass = consideredClass.getSuperClass();
    }
    if (foundAdd || foundRemove || foundFire) {
        sourceUnit.getErrorCollector().addErrorAndContinue(
            new SimpleMessage("@Vetoable cannot be processed on "
                + declaringClass.getName()
                + " because some but not all of addVetoableChangeListener, removeVetoableChange, and fireVetoableChange were declared in the current or super classes.",
            sourceUnit)
        );
        return false;
    }
    return true;
}
 
Example 12
Source File: GeneralUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static List<PropertyNode> getAllProperties(final ClassNode type) {
    ClassNode node = type;
    List<PropertyNode> result = new ArrayList<>();
    while (node != null) {
        result.addAll(node.getProperties());
        node = node.getSuperClass();
    }
    return result;
}
 
Example 13
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Adds methods from interfaces and parent interfaces. Existing entries in the methods map take precedence.
 * Methods from interfaces visited early take precedence over later ones.
 *
 * @param cNode The ClassNode
 * @param methodsMap A map of existing methods to alter
 */
public static void addDeclaredMethodsFromAllInterfaces(ClassNode cNode, Map<String, MethodNode> methodsMap) {
    List<?> cnInterfaces = Arrays.asList(cNode.getInterfaces());
    ClassNode parent = cNode.getSuperClass();
    while (parent != null && !parent.equals(ClassHelper.OBJECT_TYPE)) {
        ClassNode[] interfaces = parent.getInterfaces();
        for (ClassNode iface : interfaces) {
            if (!cnInterfaces.contains(iface)) {
                methodsMap.putAll(iface.getDeclaredMethodsMap());
            }
        }
        parent = parent.getSuperClass();
    }
}
 
Example 14
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static FieldNode getDeclaredFieldOfCurrentClassOrAccessibleFieldOfSuper(final ClassNode accessingNode, final ClassNode current, final String name, final boolean skipCurrent) {
    if (!skipCurrent) {
        FieldNode currentClassField = current.getDeclaredField(name);
        if (isValidFieldNodeForByteCodeAccess(currentClassField, accessingNode)) return currentClassField;
    }
    for (ClassNode node = current.getSuperClass(); node != null; node = node.getSuperClass()) {
        FieldNode fn = node.getDeclaredField(name);
        if (isValidFieldNodeForByteCodeAccess(fn, accessingNode)) return fn;
    }
    return null;
}
 
Example 15
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void checkTraitAllowed(final ClassNode bottomTrait, final SourceUnit unit) {
    ClassNode superClass = bottomTrait.getSuperClass();
    if (superClass==null || ClassHelper.OBJECT_TYPE.equals(superClass)) return;
    if (!Traits.isTrait(superClass)) {
        unit.addError(new SyntaxException("A trait can only inherit from another trait", superClass.getLineNumber(), superClass.getColumnNumber()));
    }
}
 
Example 16
Source File: GeneralUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static List<MethodNode> getAllMethods(final ClassNode type) {
    ClassNode node = type;
    List<MethodNode> result = new ArrayList<>();
    while (node != null) {
        result.addAll(node.getMethods());
        node = node.getSuperClass();
    }
    return result;
}
 
Example 17
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);
    }
}
 
Example 18
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static void createCloneCopyConstructor(ClassNode cNode, List<FieldNode> list, List<String> excludes) {
    if (cNode.getDeclaredConstructors().isEmpty()) {
        // add no-arg constructor
        BlockStatement noArgBody = new BlockStatement();
        noArgBody.addStatement(EmptyStatement.INSTANCE);
        addGeneratedConstructor(cNode, ACC_PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, noArgBody);
    }
    boolean hasThisCons = false;
    for (ConstructorNode consNode : cNode.getDeclaredConstructors()) {
        Parameter[] parameters = consNode.getParameters();
        if (parameters.length == 1 && parameters[0].getType().equals(cNode)) {
            hasThisCons = true;
        }
    }
    if (!hasThisCons) {
        BlockStatement initBody = new BlockStatement();
        Parameter initParam = param(GenericsUtils.nonGeneric(cNode), "other");
        final Expression other = varX(initParam);
        boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE;
        if (hasParent) {
            initBody.addStatement(stmt(ctorX(ClassNode.SUPER, other)));
        }
        for (FieldNode fieldNode : list) {
            String name = fieldNode.getName();
            if (excludes != null && excludes.contains(name)) continue;
            ClassNode fieldType = fieldNode.getType();
            Expression direct = propX(other, name);
            Expression to = propX(varX("this"), name);
            Statement assignDirect = assignS(to, direct);
            Statement assignCloned = assignS(to, castX(fieldType, callCloneDirectX(direct)));
            Statement assignClonedDynamic = assignS(to, castX(fieldType, callCloneDynamicX(direct)));
            if (isCloneableType(fieldType)) {
                initBody.addStatement(assignCloned);
            } else if (!possiblyCloneable(fieldType)) {
                initBody.addStatement(assignDirect);
            } else {
                initBody.addStatement(ifElseS(isInstanceOfX(direct, CLONEABLE_TYPE), assignClonedDynamic, assignDirect));
            }
        }
        addGeneratedConstructor(cNode, ACC_PROTECTED, params(initParam), ClassNode.EMPTY_ARRAY, initBody);
    }
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, block(stmt(ctorX(cNode, args(varX("this"))))));
}
 
Example 19
Source File: CompleteElementHandler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
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 20
Source File: TraitASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void checkExtendsClause(final ClassNode cNode) {
    ClassNode superClass = cNode.getSuperClass();
    if (superClass.isInterface() && !Traits.isTrait(superClass)) {
        addError("Trait cannot extend an interface. Use 'implements' instead", cNode);
    }
}