Example usage for org.eclipse.jdt.internal.compiler.ast FieldDeclaration traverse

List of usage examples for org.eclipse.jdt.internal.compiler.ast FieldDeclaration traverse

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.ast FieldDeclaration traverse.

Prototype

public void traverse(ASTVisitor visitor, MethodScope scope) 

Source Link

Usage

From source file:ch.uzh.ifi.seal.changedistiller.ast.java.WhenDeclarationsAreConverted.java

License:Apache License

private void convertField(String name) {
    createRootNode(JavaEntityType.FIELD_DECLARATION, name);
    FieldDeclaration field = CompilationUtils.findField(fCompilation.getCompilationUnit(), name);
    field.traverse(getDeclarationconverter(), (MethodScope) null);
}

From source file:ch.uzh.ifi.seal.changedistiller.ast.java.WhenSourceCodeChangesAreClassified.java

License:Apache License

private Node convertFieldDeclaration(String fieldName, String sourceCode) {
    JavaCompilation compilation = CompilationUtils.compileSource(sourceCode);
    FieldDeclaration field = CompilationUtils.findField(compilation.getCompilationUnit(), fieldName);
    Node root = new Node(JavaEntityType.FIELD, fieldName);
    root.setEntity(new SourceCodeEntity(fieldName, JavaEntityType.FIELD,
            new SourceRange(field.declarationSourceStart, field.declarationSourceEnd)));
    sDeclarationConverter.initialize(root, compilation.getScanner());
    field.traverse(sDeclarationConverter, (MethodScope) null);
    return root;/* www .j a  v  a  2 s .  c o  m*/
}

From source file:ch.uzh.ifi.seal.changedistiller.distilling.WhenChangesAreExtracted.java

License:Apache License

public Node convertFieldDeclaration(String fieldName, JavaCompilation compilation) {
    FieldDeclaration field = CompilationUtils.findField(compilation.getCompilationUnit(), fieldName);
    Node root = new Node(JavaEntityType.FIELD, fieldName);
    root.setEntity(new SourceCodeEntity(fieldName, JavaEntityType.FIELD,
            new SourceRange(field.declarationSourceStart, field.declarationSourceEnd)));
    sDeclarationConverter.initialize(root, compilation.getScanner());
    field.traverse(sDeclarationConverter, (MethodScope) null);
    return root;//w ww  .ja v  a  2 s . com
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Visit the given field declaration and report the nodes that match exactly the
 * search pattern (i.e. the ones in the matching nodes set)
 *///from w  ww  .  ja v a  2 s. c  o  m
protected void reportMatching(FieldDeclaration field, FieldDeclaration[] otherFields, TypeDeclaration type,
        IJavaElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet)
        throws CoreException {
    IJavaElement enclosingElement = null;
    if (accuracy > -1) {
        enclosingElement = createHandle(field, type, parent);
        if (encloses(enclosingElement)) {
            int offset = field.sourceStart;
            SearchMatch match = newDeclarationMatch(enclosingElement, field.binding, accuracy, offset,
                    field.sourceEnd - offset + 1);
            if (field.initialization instanceof AllocationExpression) {
                reportAccurateEnumConstructorReference(match, field,
                        (AllocationExpression) field.initialization);
            } else {
                report(match);
            }
        }
    }

    // handle the nodes for the local type first
    if ((field.bits & ASTNode.HasLocalType) != 0) {
        if (enclosingElement == null) {
            enclosingElement = createHandle(field, type, parent);
        }
        // Traverse field declaration(s) to report matches both in local types declaration
        // and in local variables declaration
        int fieldEnd = field.endPart2Position == 0 ? field.declarationSourceEnd : field.endPart2Position;
        ASTNode[] nodes = typeInHierarchy ? nodeSet.matchingNodes(field.sourceStart, fieldEnd) : null;
        boolean report = (this.matchContainer & PatternLocator.FIELD_CONTAINER) != 0
                && encloses(enclosingElement);
        MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement,
                report ? nodes : null, nodeSet, this);
        try {
            field.traverse(declarationVisitor, (MethodScope) null);
        } catch (WrappedCoreException e) {
            throw e.coreException;
        }
        // Report all nodes and remove them
        if (nodes != null) {
            int length = nodes.length;
            for (int i = 0; i < length; i++) {
                ASTNode node = nodes[i];
                Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
                if (report && level != null) {
                    if (node instanceof TypeDeclaration) {
                        // use field declaration to report match (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88174)
                        AllocationExpression allocation = ((TypeDeclaration) node).allocation;
                        if (allocation != null && allocation.enumConstant != null) {
                            node = field;
                        }
                    }
                    this.patternLocator.matchReportReference(node, enclosingElement,
                            declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i),
                            field.binding, level.intValue(), this);
                }
            }
        }
    }

    // report annotations
    IJavaElement[] otherElements = null;
    if (field.annotations != null) {
        if (enclosingElement == null) {
            enclosingElement = createHandle(field, type, parent);
        }
        if (otherFields != null) {
            otherElements = createHandles(otherFields, type, parent);
        }
        reportMatching(field.annotations, enclosingElement, otherElements, field.binding, nodeSet, true, true);
    }

    if (typeInHierarchy) {
        // Look at field declaration
        if (field.endPart1Position != 0) { // not necessary if field is an initializer
            ASTNode[] nodes = nodeSet.matchingNodes(field.declarationSourceStart, field.endPart1Position);
            if (nodes != null) {
                if ((this.matchContainer & PatternLocator.FIELD_CONTAINER) == 0) {
                    for (int i = 0, l = nodes.length; i < l; i++)
                        nodeSet.matchingNodes.removeKey(nodes[i]);
                } else {
                    if (enclosingElement == null)
                        enclosingElement = createHandle(field, type, parent);
                    if (encloses(enclosingElement)) {
                        for (int i = 0, l = nodes.length; i < l; i++) {
                            ASTNode node = nodes[i];
                            Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
                            if (otherFields != null && otherElements == null) {
                                otherElements = createHandles(otherFields, type, parent);
                            }
                            this.patternLocator.matchReportReference(node, enclosingElement, null,
                                    otherElements, field.binding, level.intValue(), this);
                        }
                    }
                }
            }
        }

        // Look in initializer
        int fieldEnd = field.endPart2Position == 0 ? field.declarationSourceEnd : field.endPart2Position;
        ASTNode[] nodes = nodeSet.matchingNodes(field.sourceStart, fieldEnd);
        if (nodes != null) {
            if ((this.matchContainer & PatternLocator.FIELD_CONTAINER) == 0) {
                for (int i = 0, l = nodes.length; i < l; i++) {
                    nodeSet.matchingNodes.removeKey(nodes[i]);
                }
            } else {
                if (enclosingElement == null) {
                    enclosingElement = createHandle(field, type, parent);
                }
                if (encloses(enclosingElement)) {
                    MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement,
                            nodes, nodeSet, this);
                    field.traverse(declarationVisitor, (MethodScope) null);
                    int length = nodes.length;
                    for (int i = 0; i < length; i++) {
                        ASTNode node = nodes[i];
                        Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
                        if (level != null) { // ensure that the reference has not been already reported while visiting
                            if (node instanceof TypeDeclaration) {
                                // use field declaration to report match (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88174)
                                AllocationExpression allocation = ((TypeDeclaration) node).allocation;
                                if (allocation != null && allocation.enumConstant != null) {
                                    node = field;
                                }
                            }
                            this.patternLocator.matchReportReference(node, enclosingElement,
                                    declarationVisitor.getLocalElement(i),
                                    declarationVisitor.getOtherElements(i), field.binding, level.intValue(),
                                    this);
                        }
                    }
                    return;
                }
            }
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocatorParser.java

License:Open Source License

/**
 * Parses the member bodies in the given type.
 * @param type TypeDeclaration/*  w  w w. j ava 2 s . c om*/
 * @param unit CompilationUnitDeclaration
 */
protected void parseBodies(TypeDeclaration type, CompilationUnitDeclaration unit) {
    FieldDeclaration[] fields = type.fields;
    if (fields != null) {
        for (int i = 0; i < fields.length; i++) {
            FieldDeclaration field = fields[i];
            if (field instanceof Initializer)
                this.parse((Initializer) field, type, unit);
            field.traverse(this.localDeclarationVisitor, null);
        }
    }

    AbstractMethodDeclaration[] methods = type.methods;
    if (methods != null) {
        for (int i = 0; i < methods.length; i++) {
            AbstractMethodDeclaration method = methods[i];
            if (method.sourceStart >= type.bodyStart) { // if not synthetic
                if (method instanceof MethodDeclaration) {
                    MethodDeclaration methodDeclaration = (MethodDeclaration) method;
                    this.parse(methodDeclaration, unit);
                    methodDeclaration.traverse(this.localDeclarationVisitor, (ClassScope) null);
                } else if (method instanceof ConstructorDeclaration) {
                    ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) method;
                    this.parse(constructorDeclaration, unit, false);
                    constructorDeclaration.traverse(this.localDeclarationVisitor, (ClassScope) null);
                }
            } else if (method.isDefaultConstructor()) {
                method.parseStatements(this, unit);
            }
        }
    }

    TypeDeclaration[] memberTypes = type.memberTypes;
    if (memberTypes != null) {
        for (int i = 0; i < memberTypes.length; i++) {
            TypeDeclaration memberType = memberTypes[i];
            this.parseBodies(memberType, unit);
            memberType.traverse(this.localDeclarationVisitor, (ClassScope) null);
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.util.ASTNodeFinder.java

License:Open Source License

public TypeDeclaration findType(IType typeHandle) {
    IJavaElement parent = typeHandle.getParent();
    final char[] typeName = typeHandle.getElementName().toCharArray();
    final int occurenceCount = ((SourceType) typeHandle).occurrenceCount;
    final boolean findAnonymous = typeName.length == 0;
    class Visitor extends ASTVisitor {
        TypeDeclaration result;//from   w  w w.  j a v a2s.c o  m
        int count = 0;

        public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) {
            if (this.result != null)
                return false;
            if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
                if (findAnonymous && ++this.count == occurenceCount) {
                    this.result = typeDeclaration;
                }
            } else {
                if (!findAnonymous && CharOperation.equals(typeName, typeDeclaration.name)) {
                    this.result = typeDeclaration;
                }
            }
            return false; // visit only one level
        }
    }
    switch (parent.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
        TypeDeclaration[] types = this.unit.types;
        if (types != null) {
            for (int i = 0, length = types.length; i < length; i++) {
                TypeDeclaration type = types[i];
                if (CharOperation.equals(typeName, type.name)) {
                    return type;
                }
            }
        }
        break;
    case IJavaElement.TYPE:
        TypeDeclaration parentDecl = findType((IType) parent);
        if (parentDecl == null)
            return null;
        types = parentDecl.memberTypes;
        if (types != null) {
            for (int i = 0, length = types.length; i < length; i++) {
                TypeDeclaration type = types[i];
                if (CharOperation.equals(typeName, type.name)) {
                    return type;
                }
            }
        }
        break;
    case IJavaElement.FIELD:
        FieldDeclaration fieldDecl = findField((IField) parent);
        if (fieldDecl == null)
            return null;
        Visitor visitor = new Visitor();
        fieldDecl.traverse(visitor, null);
        return visitor.result;
    case IJavaElement.INITIALIZER:
        Initializer initializer = findInitializer((IInitializer) parent);
        if (initializer == null)
            return null;
        visitor = new Visitor();
        initializer.traverse(visitor, null);
        return visitor.result;
    case IJavaElement.METHOD:
        AbstractMethodDeclaration methodDecl = findMethod((IMethod) parent);
        if (methodDecl == null)
            return null;
        visitor = new Visitor();
        methodDecl.traverse(visitor, (ClassScope) null);
        return visitor.result;
    }
    return null;
}

From source file:lombok.eclipse.handlers.HandleBuilder.java

License:Open Source License

public void generateBuilderFields(EclipseNode builderType, List<BuilderFieldData> builderFields,
        ASTNode source) {//from  w  ww.ja  va2 s  .  c  om
    List<EclipseNode> existing = new ArrayList<EclipseNode>();
    for (EclipseNode child : builderType.down()) {
        if (child.getKind() == Kind.FIELD)
            existing.add(child);
    }

    top: for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            bfd.createdFields
                    .addAll(bfd.singularData.getSingularizer().generateFields(bfd.singularData, builderType));
        } else {
            for (EclipseNode exists : existing) {
                char[] n = ((FieldDeclaration) exists.get()).name;
                if (Arrays.equals(n, bfd.name)) {
                    bfd.createdFields.add(exists);
                    continue top;
                }
            }

            FieldDeclaration fd = new FieldDeclaration(bfd.name, 0, 0);
            fd.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
            fd.modifiers = ClassFileConstants.AccPrivate;
            fd.type = copyType(bfd.type);
            fd.traverse(new SetGeneratedByVisitor(source), (MethodScope) null);
            bfd.createdFields.add(injectFieldAndMarkGenerated(builderType, fd));
        }
    }
}

From source file:lombok.eclipse.handlers.HandleFieldNameConstants.java

License:Open Source License

private void createInnerTypeFieldNameConstants(EclipseNode typeNode, EclipseNode errorNode, ASTNode source,
        AccessLevel level, List<EclipseNode> fields, boolean asEnum, String innerTypeName) {
    if (fields.isEmpty())
        return;//from   w  w w.  j av a 2s.  c  om

    ASTVisitor generatedByVisitor = new SetGeneratedByVisitor(source);
    TypeDeclaration parent = (TypeDeclaration) typeNode.get();
    EclipseNode fieldsType = findInnerClass(typeNode, innerTypeName);
    boolean genConstr = false, genClinit = false;
    char[] name = innerTypeName.toCharArray();
    TypeDeclaration generatedInnerType = null;
    if (fieldsType == null) {
        generatedInnerType = new TypeDeclaration(parent.compilationResult);
        generatedInnerType.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
        generatedInnerType.modifiers = toEclipseModifier(level) | (asEnum ? ClassFileConstants.AccEnum
                : (ClassFileConstants.AccStatic | ClassFileConstants.AccFinal));
        generatedInnerType.name = name;
        fieldsType = injectType(typeNode, generatedInnerType);
        genConstr = true;
        genClinit = asEnum;
        generatedInnerType.traverse(generatedByVisitor, ((TypeDeclaration) typeNode.get()).scope);
    } else {
        TypeDeclaration builderTypeDeclaration = (TypeDeclaration) fieldsType.get();
        if (asEnum && (builderTypeDeclaration.modifiers & ClassFileConstants.AccEnum) == 0) {
            errorNode.addError("Existing " + innerTypeName + " must be declared as an 'enum'.");
            return;
        }
        if (!asEnum && (builderTypeDeclaration.modifiers & ClassFileConstants.AccStatic) == 0) {
            errorNode.addError("Existing " + innerTypeName + " must be declared as a 'static class'.");
            return;
        }
        genConstr = constructorExists(fieldsType) == MemberExistsResult.NOT_EXISTS;
    }

    if (genConstr) {
        ConstructorDeclaration constructor = new ConstructorDeclaration(parent.compilationResult);
        constructor.selector = name;
        constructor.modifiers = ClassFileConstants.AccPrivate;
        ExplicitConstructorCall superCall = new ExplicitConstructorCall(0);
        superCall.sourceStart = source.sourceStart;
        superCall.sourceEnd = source.sourceEnd;
        superCall.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
        constructor.constructorCall = superCall;
        if (!asEnum)
            constructor.statements = new Statement[0];
        injectMethod(fieldsType, constructor);
    }

    if (genClinit) {
        Clinit cli = new Clinit(parent.compilationResult);
        injectMethod(fieldsType, cli);
        cli.traverse(generatedByVisitor, ((TypeDeclaration) fieldsType.get()).scope);
    }

    for (EclipseNode fieldNode : fields) {
        FieldDeclaration field = (FieldDeclaration) fieldNode.get();
        char[] fName = field.name;
        if (fieldExists(new String(fName), fieldsType) != MemberExistsResult.NOT_EXISTS)
            continue;
        int pS = source.sourceStart, pE = source.sourceEnd;
        long p = (long) pS << 32 | pE;
        FieldDeclaration constantField = new FieldDeclaration(fName, pS, pE);
        constantField.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
        if (asEnum) {
            AllocationExpression ac = new AllocationExpression();
            ac.enumConstant = constantField;
            ac.sourceStart = source.sourceStart;
            ac.sourceEnd = source.sourceEnd;
            constantField.initialization = ac;
            constantField.modifiers = 0;
        } else {
            constantField.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING,
                    new long[] { p, p, p });
            constantField.initialization = new StringLiteral(field.name, pS, pE, 0);
            constantField.modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccStatic
                    | ClassFileConstants.AccFinal;
        }
        injectField(fieldsType, constantField);
        constantField.traverse(generatedByVisitor, ((TypeDeclaration) fieldsType.get()).initializerScope);
    }
}

From source file:lombok.eclipse.handlers.HandleLog.java

License:Open Source License

public static void processAnnotation(LoggingFramework framework,
        AnnotationValues<? extends java.lang.annotation.Annotation> annotation, Annotation source,
        EclipseNode annotationNode, String loggerTopic) {
    EclipseNode owner = annotationNode.up();

    switch (owner.getKind()) {
    case TYPE://from   www .java  2  s. c om
        String logFieldName = annotationNode.getAst().readConfiguration(ConfigurationKeys.LOG_ANY_FIELD_NAME);
        if (logFieldName == null)
            logFieldName = "log";

        boolean useStatic = !Boolean.FALSE
                .equals(annotationNode.getAst().readConfiguration(ConfigurationKeys.LOG_ANY_FIELD_IS_STATIC));

        TypeDeclaration typeDecl = null;
        if (owner.get() instanceof TypeDeclaration)
            typeDecl = (TypeDeclaration) owner.get();
        int modifiers = typeDecl == null ? 0 : typeDecl.modifiers;

        boolean notAClass = (modifiers
                & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation)) != 0;

        if (typeDecl == null || notAClass) {
            annotationNode.addError(framework.getAnnotationAsString() + " is legal only on classes and enums.");
            return;
        }

        if (fieldExists(logFieldName, owner) != MemberExistsResult.NOT_EXISTS) {
            annotationNode.addWarning("Field '" + logFieldName + "' already exists.");
            return;
        }

        ClassLiteralAccess loggingType = selfType(owner, source);

        FieldDeclaration fieldDeclaration = createField(framework, source, loggingType, logFieldName, useStatic,
                loggerTopic);
        fieldDeclaration.traverse(new SetGeneratedByVisitor(source), typeDecl.staticInitializerScope);
        // TODO temporary workaround for issue 217. http://code.google.com/p/projectlombok/issues/detail?id=217
        // injectFieldSuppressWarnings(owner, fieldDeclaration);
        injectField(owner, fieldDeclaration);
        owner.rebuild();
        break;
    default:
        break;
    }
}

From source file:lombok.eclipse.handlers.HandleSuperBuilder.java

License:Open Source License

private void generateBuilderFields(EclipseNode builderType, List<BuilderFieldData> builderFields,
        ASTNode source) {//w  w  w . ja  va 2  s .  co m
    List<EclipseNode> existing = new ArrayList<EclipseNode>();
    for (EclipseNode child : builderType.down()) {
        if (child.getKind() == Kind.FIELD)
            existing.add(child);
    }

    for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            bfd.createdFields
                    .addAll(bfd.singularData.getSingularizer().generateFields(bfd.singularData, builderType));
        } else {
            EclipseNode field = null, setFlag = null;
            for (EclipseNode exists : existing) {
                char[] n = ((FieldDeclaration) exists.get()).name;
                if (Arrays.equals(n, bfd.name))
                    field = exists;
                if (bfd.nameOfSetFlag != null && Arrays.equals(n, bfd.nameOfSetFlag))
                    setFlag = exists;
            }

            if (field == null) {
                FieldDeclaration fd = new FieldDeclaration(bfd.name, 0, 0);
                fd.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
                fd.modifiers = ClassFileConstants.AccPrivate;
                fd.type = copyType(bfd.type);
                fd.traverse(new SetGeneratedByVisitor(source), (MethodScope) null);
                field = injectFieldAndMarkGenerated(builderType, fd);
            }
            if (setFlag == null && bfd.nameOfSetFlag != null) {
                FieldDeclaration fd = new FieldDeclaration(bfd.nameOfSetFlag, 0, 0);
                fd.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
                fd.modifiers = ClassFileConstants.AccPrivate;
                fd.type = TypeReference.baseTypeReference(TypeIds.T_boolean, 0);
                fd.traverse(new SetGeneratedByVisitor(source), (MethodScope) null);
                injectFieldAndMarkGenerated(builderType, fd);
            }
            bfd.createdFields.add(field);
        }
    }
}