Java Code Examples for org.codehaus.groovy.ast.FieldNode#getName()

The following examples show how to use org.codehaus.groovy.ast.FieldNode#getName() . 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: GeneralUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static Statement createConstructorStatementDefault(final FieldNode fNode) {
    final String name = fNode.getName();
    final ClassNode fType = fNode.getType();
    final Expression fieldExpr = propX(varX("this"), name);
    Expression initExpr = fNode.getInitialValueExpression();
    Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        if (ClassHelper.isPrimitiveType(fType)) {
            assignInit = EmptyStatement.INSTANCE;
        } else {
            assignInit = assignS(fieldExpr, ConstantExpression.EMPTY_EXPRESSION);
        }
    } else {
        assignInit = assignS(fieldExpr, initExpr);
    }
    fNode.setInitialValueExpression(null);
    Expression value = findArg(name);
    return ifElseS(equalsNullX(value), assignInit, assignS(fieldExpr, castX(fType, value)));
}
 
Example 2
Source File: VetoableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void addListenerToProperty(SourceUnit source, AnnotationNode node, AnnotatedNode parent) {
    ClassNode declaringClass = parent.getDeclaringClass();
    FieldNode field = ((FieldNode) parent);
    String fieldName = field.getName();
    for (PropertyNode propertyNode : declaringClass.getProperties()) {
        boolean bindable = BindableASTTransformation.hasBindableAnnotation(parent)
                || BindableASTTransformation.hasBindableAnnotation(parent.getDeclaringClass());

        if (propertyNode.getName().equals(fieldName)) {
            if (field.isStatic()) {
                //noinspection ThrowableInstanceNeverThrown
                source.getErrorCollector().addErrorAndContinue("@groovy.beans.Vetoable cannot annotate a static property.", node, source);
            } else {
                createListenerSetter(source, bindable, declaringClass, propertyNode);
            }
            return;
        }
    }
    //noinspection ThrowableInstanceNeverThrown
    source.getErrorCollector().addErrorAndContinue("@groovy.beans.Vetoable must be on a property, not a field.  Try removing the private, protected, or public modifier.", node, source);
}
 
Example 3
Source File: BindableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void addListenerToProperty(SourceUnit source, AnnotationNode node, ClassNode declaringClass, FieldNode field) {
    String fieldName = field.getName();
    for (PropertyNode propertyNode : declaringClass.getProperties()) {
        if (propertyNode.getName().equals(fieldName)) {
            if (field.isStatic()) {
                //noinspection ThrowableInstanceNeverThrown
                source.getErrorCollector().addErrorAndContinue("@groovy.beans.Bindable cannot annotate a static property.", node, source);
            } else {
                if (needsPropertyChangeSupport(declaringClass, source)) {
                    addPropertyChangeSupport(declaringClass);
                }
                createListenerSetter(declaringClass, propertyNode);
            }
            return;
        }
    }
    //noinspection ThrowableInstanceNeverThrown
    source.getErrorCollector().addErrorAndContinue("@groovy.beans.Bindable must be on a property, not a field.  Try removing the private, protected, or public modifier.", node, source);
}
 
Example 4
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static String getRefDescriptor(ASTNode ref) {
    if (ref instanceof FieldNode) {
        FieldNode f = (FieldNode) ref;
        return "the field "+f.getName()+" ";
    } else if (ref instanceof PropertyNode) {
        PropertyNode p = (PropertyNode) ref;
        return "the property "+p.getName()+" ";
    } else if (ref instanceof ConstructorNode) {
        return "the constructor "+ref.getText()+" ";
    } else if (ref instanceof MethodNode) {
        return "the method "+ref.getText()+" ";
    } else if (ref instanceof ClassNode) {
        return "the super class "+ref+" ";
    }
    return "<unknown with class "+ref.getClass()+"> ";
}
 
Example 5
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
static void visitField(ErrorCollecting xform, AnnotationNode node, FieldNode fieldNode) {
    final Expression soft = node.getMember("soft");
    final Expression init = getInitExpr(xform, fieldNode);

    String backingFieldName = "$" + fieldNode.getName();
    fieldNode.rename(backingFieldName);
    fieldNode.setModifiers(ACC_PRIVATE | ACC_SYNTHETIC | (fieldNode.getModifiers() & (~(ACC_PUBLIC | ACC_PROTECTED))));
    PropertyNode pNode = fieldNode.getDeclaringClass().getProperty(backingFieldName);
    if (pNode != null) {
        fieldNode.getDeclaringClass().getProperties().remove(pNode);
    }

    if (soft instanceof ConstantExpression && ((ConstantExpression) soft).getValue().equals(true)) {
        createSoft(fieldNode, init);
    } else {
        create(fieldNode, init);
        // @Lazy not meaningful with primitive so convert to wrapper if needed
        if (ClassHelper.isPrimitiveType(fieldNode.getType())) {
            fieldNode.setType(ClassHelper.getWrapper(fieldNode.getType()));
        }
    }
}
 
Example 6
Source File: GroovydocVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitField(FieldNode node) {
    String name = node.getName();
    SimpleGroovyFieldDoc fieldDoc = new SimpleGroovyFieldDoc(name, currentClassDoc);
    fieldDoc.setType(new SimpleGroovyType(makeType(node.getType())));
    processModifiers(fieldDoc, node, node.getModifiers());
    processAnnotations(fieldDoc, node);
    fieldDoc.setRawCommentText(getDocContent(node.getGroovydoc()));
    currentClassDoc.add(fieldDoc);
    super.visitField(node);
}
 
Example 7
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 8
Source File: ImmutableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void ensureNotPublic(AbstractASTTransformation xform, String cNode, FieldNode fNode) {
    String fName = fNode.getName();
    // TODO: do we need to lock down things like: $ownClass
    if (fNode.isPublic() && !fName.contains("$") && !(fNode.isStatic() && fNode.isFinal())) {
        xform.addError("Public field '" + fName + "' not allowed for " + MY_TYPE_NAME + " class '" + cNode + "'.", fNode);
    }
}
 
Example 9
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitField(FieldNode visitedField) {
    final String visitedName = visitedField.getName();

    if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
        addFieldOccurrences(visitedField, (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset));
    } else {
        if (leaf instanceof FieldNode) {
            if (visitedName.equals(((FieldNode) leaf).getName())) {
                occurrences.add(visitedField);
            }
        } else if (leaf instanceof PropertyNode) {
            if (visitedName.equals(((PropertyNode) leaf).getField().getName())) {
                occurrences.add(visitedField);
            }
        } else if (leaf instanceof Variable) {
            if (visitedName.equals(((Variable) leaf).getName())) {
                occurrences.add(visitedField);
            }
        } else if (leaf instanceof ConstantExpression && leafParent instanceof PropertyExpression) {
            PropertyExpression property = (PropertyExpression) leafParent;
            if (visitedName.equals(property.getPropertyAsString())) {
                occurrences.add(visitedField);
            }
        }
    }
    super.visitField(visitedField);
}
 
Example 10
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Statement checkFinalArgNotOverridden(ClassNode cNode, FieldNode fNode) {
    final String name = fNode.getName();
    Expression value = findArg(name);
    return ifS(
            notX(equalsNullX(value)),
            throwS(ctorX(READONLYEXCEPTION_TYPE,
                    args(constX(name), constX(cNode.getName()))
            )));
}
 
Example 11
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Parameter[] getParams(List<FieldNode> fields, ClassNode cNode) {
    Parameter[] parameters = new Parameter[fields.size()];
    for (int i = 0; i < parameters.length; i++) {
        FieldNode fNode = fields.get(i);
        Map<String,ClassNode> genericsSpec = createGenericsSpec(fNode.getDeclaringClass());
        extractSuperClassGenerics(fNode.getType(), cNode, genericsSpec);
        ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, fNode.getType());
        parameters[i] = new Parameter(correctedType, fNode.getName());
    }
    return parameters;
}
 
Example 12
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void initializeFields(List<FieldNode> fields, BlockStatement body, boolean useSetters) {
    for (FieldNode field : fields) {
        String name = field.getName();
        body.addStatement(
                stmt(useSetters && !field.isFinal()
                                ? callThisX(GeneralUtils.getSetterName(name), varX(param(field.getType(), name)))
                                : assignX(propX(varX("this"), field.getName()), varX(param(field.getType(), name)))
                )
        );
    }
}
 
Example 13
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 14
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 15
Source File: FindVariableUsages.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void addField(FieldNode field) {
    final String fieldName = field.getName();
    final String fieldOwner = field.getOwner().getName();

    addIfEqual(field, fieldOwner, fieldName);
}
 
Example 16
Source File: ASTField.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public ASTField(FieldNode node, String in, boolean isProperty) {
    super(node, in, node.getName());
    this.isProperty = isProperty;
    this.fieldType = node.getType().getNameWithoutPackage();
}
 
Example 17
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static String getDescription(FieldNode node) {
    return "field '" + node.getName() + "'";
}
 
Example 18
Source File: SimpleStrategy.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void build(BuilderASTTransformation transform, AnnotatedNode annotatedNode, AnnotationNode anno) {
    if (!(annotatedNode instanceof ClassNode)) {
        transform.addError("Error during " + BuilderASTTransformation.MY_TYPE_NAME + " processing: building for " +
                annotatedNode.getClass().getSimpleName() + " not supported by " + getClass().getSimpleName(), annotatedNode);
        return;
    }
    ClassNode buildee = (ClassNode) annotatedNode;
    if (unsupportedAttribute(transform, anno, "builderClassName")) return;
    if (unsupportedAttribute(transform, anno, "buildMethodName")) return;
    if (unsupportedAttribute(transform, anno, "builderMethodName")) return;
    if (unsupportedAttribute(transform, anno, "forClass")) return;
    if (unsupportedAttribute(transform, anno, "includeSuperProperties")) return;
    if (unsupportedAttribute(transform, anno, "allProperties")) return;
    if (unsupportedAttribute(transform, anno, "force")) return;
    boolean useSetters = transform.memberHasValue(anno, "useSetters", true);
    boolean allNames = transform.memberHasValue(anno, "allNames", true);

    List<String> excludes = new ArrayList<String>();
    List<String> includes = new ArrayList<String>();
    includes.add(Undefined.STRING);
    if (!getIncludeExclude(transform, anno, buildee, excludes, includes)) return;
    if (includes.size() == 1 && Undefined.isUndefined(includes.get(0))) includes = null;
    String prefix = getMemberStringValue(anno, "prefix", "set");
    List<FieldNode> fields = getFields(transform, anno, buildee);
    if (includes != null) {
        for (String name : includes) {
            checkKnownField(transform, anno, name, fields);
        }
    }
    for (FieldNode field : fields) {
        String fieldName = field.getName();
        if (!AbstractASTTransformation.shouldSkipUndefinedAware(fieldName, excludes, includes, allNames)) {
            String methodName = getSetterName(prefix, fieldName);
            Parameter parameter = param(field.getType(), fieldName);
            addGeneratedMethod(buildee, methodName, Opcodes.ACC_PUBLIC, newClass(buildee), params(parameter), NO_EXCEPTIONS, block(
                    stmt(useSetters && !field.isFinal()
                            ? callThisX(getSetterName("set", fieldName), varX(parameter))
                            : assignX(fieldX(field), varX(parameter))
                    ),
                    returnS(varX("this")))
            );
        }
    }
}
 
Example 19
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static FieldNode createFieldCopy(ClassNode buildee, FieldNode fNode) {
    Map<String,ClassNode> genericsSpec = createGenericsSpec(fNode.getDeclaringClass());
    extractSuperClassGenerics(fNode.getType(), buildee, genericsSpec);
    ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, fNode.getType());
    return new FieldNode(fNode.getName(), fNode.getModifiers(), correctedType, buildee, DEFAULT_INITIAL_VALUE);
}
 
Example 20
Source File: StructureAnalyzer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private AnalysisResult scan(GroovyParserResult result) {
    AnalysisResult analysisResult = new AnalysisResult();

    ASTNode root = ASTUtils.getRoot(result);

    if (root == null) {
        return analysisResult;
    }

    structure = new ArrayList<>();
    fields = new HashMap<>();
    methods = new ArrayList<>();
    properties = new HashMap<>();

    AstPath path = new AstPath();
    path.descend(root);
    // TODO: I should pass in a "default" context here to stash methods etc. outside of modules and classes
    scan(result, root, path, null, null, null);
    path.ascend();

    // Process fields
    Map<String, FieldNode> names = new HashMap<>();

    for (ASTClass clz : fields.keySet()) {
        Set<FieldNode> assignments = fields.get(clz);

        // Find unique variables
        if (assignments != null) {
            for (FieldNode assignment : assignments) {
                names.put(assignment.getName(), assignment);
            }

            // Add unique fields
            for (FieldNode field : names.values()) {
                // Make sure I don't already have an entry for this field as an
                // attr_accessor or writer
                String fieldName = field.getName();

                boolean found = false;

                Set<PropertyNode> nodes = properties.get(clz);
                if (nodes != null) {
                    for (PropertyNode node : nodes) {
                        if (fieldName.equals(node.getName())) {
                            found = true;
                            break;
                        }
                    }
                }

                boolean isProperty = false;
                if (found) {
                    isProperty = true;
                }
                clz.addChild(new ASTField(field, clz.getFqn(), isProperty));
            }

            names.clear();
        }
    }

    analysisResult.setElements(structure);

    return analysisResult;
}