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

The following examples show how to use org.codehaus.groovy.ast.ClassNode#getFields() . 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: CategoryASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static boolean ensureNoInstanceFieldOrProperty(final SourceUnit source, final ClassNode parent) {
    boolean valid = true;
    for (FieldNode fieldNode : parent.getFields()) {
        if (!fieldNode.isStatic() && fieldNode.getLineNumber()>0) {
            // if <0, probably an AST transform or internal code (like generated metaclass field, ...)
            addUnsupportedError(fieldNode,  source);
            valid = false;
        }
    }
    for (PropertyNode propertyNode : parent.getProperties()) {
        if (!propertyNode.isStatic() && propertyNode.getLineNumber()>0) {
            // if <0, probably an AST transform or internal code (like generated metaclass field, ...)
            addUnsupportedError(propertyNode, source);
            valid = false;
        }
    }
    return valid;
}
 
Example 2
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void printFields(PrintWriter out, ClassNode classNode) {
    boolean isInterface = isInterfaceOrTrait(classNode);
    List<FieldNode> fields = classNode.getFields();
    if (fields == null) return;
    List<FieldNode> enumFields = new ArrayList<FieldNode>(fields.size());
    List<FieldNode> normalFields = new ArrayList<FieldNode>(fields.size());
    for (FieldNode field : fields) {
        boolean isSynthetic = (field.getModifiers() & Opcodes.ACC_SYNTHETIC) != 0;
        if (field.isEnum()) {
            enumFields.add(field);
        } else if (!isSynthetic) {
            normalFields.add(field);
        }
    }
    printEnumFields(out, enumFields);
    for (FieldNode normalField : normalFields) {
        printField(out, normalField, isInterface);
    }
}
 
Example 3
Source File: NamedParamsCompletion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void completeNamedParams(
        List<CompletionProposal> proposals,
        int anchor,
        ConstructorCallExpression constructorCall,
        NamedArgumentListExpression namedArguments) {

    ClassNode type = constructorCall.getType();
    String prefix = context.getPrefix();

    for (FieldNode fieldNode : type.getFields()) {
        if (fieldNode.getLineNumber() < 0 || fieldNode.getColumnNumber() < 0) {
            continue;
        }

        String typeName = fieldNode.getType().getNameWithoutPackage();
        String name = fieldNode.getName();

        // If the prefix is empty, complete only missing parameters
        if ("".equals(prefix)) {
            if (isAlreadyPresent(namedArguments, name)) {
                continue;
            }
        // Otherwise check if the field is starting with (and not equal to) the prefix
        } else {
            if (name.equals(prefix) || !name.startsWith(prefix)) {
                continue;
            }
        }

        proposals.add(new CompletionItem.NamedParameter(typeName, name, anchor));
    }
}
 
Example 4
Source File: UnionTypeClassNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public List<FieldNode> getFields() {
    List<FieldNode> nodes = new LinkedList<FieldNode>();
    for (ClassNode delegate : delegates) {
        List<FieldNode> fields = delegate.getFields();
        if (fields != null) nodes.addAll(fields);
    }
    return nodes;
}
 
Example 5
Source File: GeneralUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static List<FieldNode> getInstanceNonPropertyFields(final ClassNode cNode) {
    List<FieldNode> result = new ArrayList<>();
    for (FieldNode fNode : cNode.getFields()) {
        if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) {
            result.add(fNode);
        }
    }
    return result;
}
 
Example 6
Source File: GeneralUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static List<FieldNode> getSuperNonPropertyFields(final ClassNode cNode) {
    List<FieldNode> result;
    if (cNode == ClassHelper.OBJECT_TYPE) {
        result = new ArrayList<>();
    } else {
        result = getSuperNonPropertyFields(cNode.getSuperClass());
    }
    for (FieldNode fNode : cNode.getFields()) {
        if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) {
            result.add(fNode);
        }
    }
    return result;
}
 
Example 7
Source File: BindableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Snoops through the declaring class and all parents looking for methods
 * <code>void addPropertyChangeListener(PropertyChangeListener)</code>,
 * <code>void removePropertyChangeListener(PropertyChangeListener)</code>, and
 * <code>void firePropertyChange(String, Object, Object)</code>. If any are defined all
 * must be defined or a compilation error results.
 *
 * @param declaringClass the class to search
 * @param sourceUnit the source unit, for error reporting. {@code @NotNull}.
 * @return true if property change support should be added
 */
protected boolean needsPropertyChangeSupport(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("addPropertyChangeListener") && method.getParameters().length == 1;
            foundRemove = foundRemove || method.getName().equals("removePropertyChangeListener") && method.getParameters().length == 1;
            foundFire = foundFire || method.getName().equals("firePropertyChange") && method.getParameters().length == 3;
            if (foundAdd && foundRemove && foundFire) {
                return false;
            }
        }
        consideredClass = consideredClass.getSuperClass();
    }
    // check if a super class has @Bindable annotations
    consideredClass = declaringClass.getSuperClass();
    while (consideredClass!=null) {
        if (hasBindableAnnotation(consideredClass)) return false;
        for (FieldNode field : consideredClass.getFields()) {
            if (hasBindableAnnotation(field)) return false;
        }
        consideredClass = consideredClass.getSuperClass();
    }
    if (foundAdd || foundRemove || foundFire) {
        sourceUnit.getErrorCollector().addErrorAndContinue(
            new SimpleMessage("@Bindable cannot be processed on "
                + declaringClass.getName()
                + " because some but not all of addPropertyChangeListener, removePropertyChange, and firePropertyChange were declared in the current or super classes.",
            sourceUnit)
        );
        return false;
    }
    return true;
}
 
Example 8
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 9
Source File: GeneralUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static List<PropertyNode> getAllProperties(final Set<String> names, final ClassNode origType, final ClassNode cNode, final boolean includeProperties,
                                                  final boolean includeFields, final boolean includePseudoGetters, final boolean includePseudoSetters,
                                                  final boolean traverseSuperClasses, final boolean skipReadonly, final boolean reverse, final boolean allNames, final boolean includeStatic) {
    List<PropertyNode> result = new ArrayList<>();
    if (cNode != ClassHelper.OBJECT_TYPE && traverseSuperClasses && !reverse) {
        result.addAll(getAllProperties(names, origType, cNode.getSuperClass(), includeProperties, includeFields, includePseudoGetters, includePseudoSetters, true, skipReadonly));
    }
    if (includeProperties) {
        for (PropertyNode pNode : cNode.getProperties()) {
            if ((!pNode.isStatic() || includeStatic) && !names.contains(pNode.getName())) {
                result.add(pNode);
                names.add(pNode.getName());
            }
        }
        if (includePseudoGetters || includePseudoSetters) {
            BeanUtils.addPseudoProperties(origType, cNode, result, names, includeStatic, includePseudoGetters, includePseudoSetters);
        }
    }
    if (includeFields) {
        for (FieldNode fNode : cNode.getFields()) {
            if ((fNode.isStatic() && !includeStatic) || fNode.isSynthetic() || cNode.getProperty(fNode.getName()) != null || names.contains(fNode.getName())) {
                continue;
            }

            // internal field
            if (fNode.getName().contains("$") && !allNames) {
                continue;
            }

            if (fNode.isPrivate() && !cNode.equals(origType)) {
                continue;
            }
            if (fNode.isFinal() && fNode.getInitialExpression() != null && skipReadonly) {
                continue;
            }
            result.add(new PropertyNode(fNode, fNode.getModifiers(), null, null));
            names.add(fNode.getName());
        }
    }
    if (cNode != ClassHelper.OBJECT_TYPE && traverseSuperClasses && reverse) {
        result.addAll(getAllProperties(names, origType, cNode.getSuperClass(), includeProperties, includeFields, includePseudoGetters, includePseudoSetters, true, skipReadonly));
    }
    return result;
}
 
Example 10
Source File: Verifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void addInitialization(ClassNode node, ConstructorNode constructorNode) {
    Statement firstStatement = constructorNode.getFirstStatement();
    // if some transformation decided to generate constructor then it probably knows who it does
    if (firstStatement instanceof BytecodeSequence)
        return;

    ConstructorCallExpression first = getFirstIfSpecialConstructorCall(firstStatement);

    // in case of this(...) let the other constructor do the init
    if (first != null && (first.isThisCall())) return;

    List<Statement> statements = new ArrayList<Statement>();
    List<Statement> staticStatements = new ArrayList<Statement>();
    final boolean isEnum = node.isEnum();
    List<Statement> initStmtsAfterEnumValuesInit = new ArrayList<Statement>();
    Set<String> explicitStaticPropsInEnum = new HashSet<String>();
    if (isEnum) {
        for (PropertyNode propNode : node.getProperties()) {
            if (!propNode.isSynthetic() && propNode.getField().isStatic()) {
                explicitStaticPropsInEnum.add(propNode.getField().getName());
            }
        }
        for (FieldNode fieldNode : node.getFields()) {
            if (!fieldNode.isSynthetic() && fieldNode.isStatic() && fieldNode.getType() != node) {
                explicitStaticPropsInEnum.add(fieldNode.getName());
            }
        }
    }

    if (!Traits.isTrait(node)) {
        for (FieldNode fn : node.getFields()) {
            addFieldInitialization(statements, staticStatements, fn, isEnum,
                    initStmtsAfterEnumValuesInit, explicitStaticPropsInEnum);
        }
    }

    statements.addAll(node.getObjectInitializerStatements());

    BlockStatement block = getCodeAsBlock(constructorNode);
    List<Statement> otherStatements = block.getStatements();
    if (!otherStatements.isEmpty()) {
        if (first != null) {
            // it is super(..) since this(..) is already covered
            otherStatements.remove(0);
            statements.add(0, firstStatement);
        }
        Statement stmtThis$0 = getImplicitThis$0StmtIfInnerClass(otherStatements);
        if (stmtThis$0 != null) {
            // since there can be field init statements that depend on method/property dispatching
            // that uses this$0, it needs to bubble up before the super call itself (GROOVY-4471)
            statements.add(0, stmtThis$0);
        }
        statements.addAll(otherStatements);
    }
    BlockStatement newBlock = new BlockStatement(statements, block.getVariableScope());
    newBlock.setSourcePosition(block);
    constructorNode.setCode(newBlock);


    if (!staticStatements.isEmpty()) {
        if (isEnum) {
            /*
             * GROOVY-3161: initialize statements for explicitly declared static fields
             * inside an enum should come after enum values are initialized
             */
            staticStatements.removeAll(initStmtsAfterEnumValuesInit);
            node.addStaticInitializerStatements(staticStatements, true);
            if (!initStmtsAfterEnumValuesInit.isEmpty()) {
                node.positionStmtsAfterEnumInitStmts(initStmtsAfterEnumValuesInit);
            }
        } else {
            node.addStaticInitializerStatements(staticStatements, true);
        }
    }
}