Search in sources :

Example 66 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class ReplacementVisitor method replaceElementIfExist.

private void replaceElementIfExist(CtElement candidate, ReplaceListener listener) {
    if (candidate == original) {
        CtElement val = null;
        if (replace.length > 0) {
            if (replace.length > 1) {
                throw new InvalidReplaceException("Cannot replace single value by multiple values in " + listener.getClass().getSimpleName());
            }
            val = replace[0];
        }
        if (val != null) {
            val.setParent(candidate.getParent());
        }
        listener.set(val);
    }
}
Also used : CtElement(spoon.reflect.declaration.CtElement) InvalidReplaceException(spoon.support.visitor.replace.InvalidReplaceException)

Example 67 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class JDTCommentBuilder method insertCommentInAST.

/**
 * Inserts the comment into the AST.
 * @param comment the comment to insert
 */
private void insertCommentInAST(final CtComment comment) {
    CtElement commentParent = findCommentParent(comment);
    if (commentParent == null) {
        File file = spoonUnit.getFile();
        if (file != null && file.getName().equals(DefaultJavaPrettyPrinter.JAVA_PACKAGE_DECLARATION)) {
            spoonUnit.getDeclaredPackage().addComment(comment);
        } else if (file != null && file.getName().equals(DefaultJavaPrettyPrinter.JAVA_MODULE_DECLARATION)) {
            spoonUnit.getDeclaredModule().addComment(comment);
        } else {
            comment.setCommentType(CtComment.CommentType.FILE);
            addCommentToNear(comment, new ArrayList<CtElement>(spoonUnit.getDeclaredTypes()));
        }
        return;
    }
    // visitor that inserts the comment in the element
    CtInheritanceScanner insertionVisitor = new CtInheritanceScanner() {

        private boolean isScanned = false;

        @Override
        public void scan(CtElement e) {
            if (e == null) {
                return;
            }
            // Do not visit the AST, only the first element
            if (!isScanned) {
                isScanned = true;
                if (e.getPosition().getSourceStart() == comment.getPosition().getSourceStart()) {
                    e.addComment(comment);
                    return;
                }
                super.scan(e);
            }
        }

        @Override
        public <R> void visitCtStatementList(CtStatementList e) {
            addCommentToNear(comment, new ArrayList<CtElement>(e.getStatements()));
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addStatement(comment);
            }
        }

        @Override
        public <T> void visitCtMethod(CtMethod<T> e) {
            e.addComment(comment);
        }

        @Override
        public <T> void visitCtConstructor(CtConstructor<T> e) {
            e.addComment(comment);
        }

        @Override
        public <T> void visitCtConditional(CtConditional<T> e) {
            List<CtElement> elements = new ArrayList<>();
            elements.add(e.getElseExpression());
            elements.add(e.getThenExpression());
            elements.add(e.getCondition());
            addCommentToNear(comment, elements);
        }

        @Override
        public <T> void visitCtBinaryOperator(CtBinaryOperator<T> e) {
            List<CtElement> elements = new ArrayList<>();
            elements.add(e.getLeftHandOperand());
            elements.add(e.getRightHandOperand());
            addCommentToNear(comment, elements);
        }

        @Override
        public <T> void visitCtClass(CtClass<T> e) {
            if (comment.getPosition().getLine() <= e.getPosition().getLine()) {
                e.addComment(comment);
                return;
            }
            final List<CtElement> elements = new ArrayList<>();
            for (CtTypeMember typeMember : e.getTypeMembers()) {
                if (typeMember instanceof CtField || typeMember instanceof CtMethod || typeMember instanceof CtConstructor) {
                    elements.add(typeMember);
                }
            }
            addCommentToNear(comment, elements);
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public <T> void visitCtInterface(CtInterface<T> e) {
            final List<CtElement> elements = new ArrayList<>();
            for (CtTypeMember typeMember : e.getTypeMembers()) {
                if (typeMember instanceof CtField || typeMember instanceof CtMethod) {
                    elements.add(typeMember);
                }
            }
            addCommentToNear(comment, elements);
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public <T> void visitCtField(CtField<T> e) {
            e.addComment(comment);
        }

        @Override
        public <E> void visitCtSwitch(CtSwitch<E> e) {
            List<CtCase<? super E>> cases = e.getCases();
            CtCase previous = null;
            for (int i = 0; i < cases.size(); i++) {
                CtCase<? super E> ctCase = cases.get(i);
                if (previous == null) {
                    if (comment.getPosition().getSourceStart() < ctCase.getPosition().getSourceStart() && e.getPosition().getSourceStart() < comment.getPosition().getSourceStart()) {
                        ctCase.addComment(comment);
                        return;
                    }
                } else {
                    if (previous.getPosition().getSourceEnd() < comment.getPosition().getSourceStart() && ctCase.getPosition().getSourceStart() > comment.getPosition().getSourceStart()) {
                        addCommentToNear(comment, new ArrayList<CtElement>(previous.getStatements()));
                        try {
                            comment.getParent();
                        } catch (ParentNotInitializedException ex) {
                            previous.addStatement(comment);
                        }
                        return;
                    }
                }
                previous = ctCase;
            }
            if (previous.getPosition().getSourceEnd() < comment.getPosition().getSourceStart()) {
                addCommentToNear(comment, new ArrayList<CtElement>(previous.getStatements()));
                try {
                    comment.getParent();
                } catch (ParentNotInitializedException ex) {
                    previous.addStatement(comment);
                }
                return;
            }
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public void visitCtIf(CtIf e) {
            if (!(e.getThenStatement() instanceof CtBlock)) {
                if (comment.getPosition().getSourceEnd() <= e.getThenStatement().getPosition().getSourceStart()) {
                    e.getThenStatement().addComment(comment);
                    return;
                }
            }
            if (e.getElseStatement() != null) {
                SourcePosition thenPosition = e.getThenStatement().getPosition() == null ? ((CtBlock) e.getThenStatement()).getStatement(0).getPosition() : e.getThenStatement().getPosition();
                SourcePosition elsePosition = e.getElseStatement().getPosition() == null ? ((CtBlock) e.getElseStatement()).getStatement(0).getPosition() : e.getElseStatement().getPosition();
                if (comment.getPosition().getSourceStart() > thenPosition.getSourceEnd() && comment.getPosition().getSourceEnd() < elsePosition.getSourceStart()) {
                    e.getElseStatement().addComment(comment);
                }
            }
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public void scanCtStatement(CtStatement s) {
            if (!(s instanceof CtStatementList || s instanceof CtSwitch)) {
                s.addComment(comment);
            }
        }

        @Override
        public void visitCtAnonymousExecutable(CtAnonymousExecutable e) {
            e.addComment(comment);
        }

        @Override
        public <T> void visitCtNewArray(CtNewArray<T> e) {
            addCommentToNear(comment, new ArrayList<CtElement>(e.getElements()));
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public <T> void visitCtParameter(CtParameter<T> e) {
            e.addComment(comment);
        }

        @Override
        public void visitCtCatch(CtCatch e) {
            if (comment.getPosition().getLine() <= e.getPosition().getLine()) {
                e.addComment(comment);
                return;
            }
        }

        @Override
        public void visitCtModule(CtModule module) {
            addCommentToNear(comment, new ArrayList<>(module.getModuleDirectives()));
        }
    };
    insertionVisitor.scan(commentParent);
    try {
        comment.getParent();
    } catch (ParentNotInitializedException e) {
        LOGGER.error(comment + " is not added into the AST", e);
    }
}
Also used : CtConditional(spoon.reflect.code.CtConditional) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtSwitch(spoon.reflect.code.CtSwitch) ArrayList(java.util.ArrayList) CtParameter(spoon.reflect.declaration.CtParameter) CtNewArray(spoon.reflect.code.CtNewArray) CtStatement(spoon.reflect.code.CtStatement) CtField(spoon.reflect.declaration.CtField) SourcePosition(spoon.reflect.cu.SourcePosition) CtInheritanceScanner(spoon.reflect.visitor.CtInheritanceScanner) CtStatementList(spoon.reflect.code.CtStatementList) CtInterface(spoon.reflect.declaration.CtInterface) CtBinaryOperator(spoon.reflect.code.CtBinaryOperator) CtElement(spoon.reflect.declaration.CtElement) CtIf(spoon.reflect.code.CtIf) CtConstructor(spoon.reflect.declaration.CtConstructor) CtModule(spoon.reflect.declaration.CtModule) CtClass(spoon.reflect.declaration.CtClass) CtTypeMember(spoon.reflect.declaration.CtTypeMember) CtBlock(spoon.reflect.code.CtBlock) CtCase(spoon.reflect.code.CtCase) CtCatch(spoon.reflect.code.CtCatch) File(java.io.File) CtAnonymousExecutable(spoon.reflect.declaration.CtAnonymousExecutable) CtMethod(spoon.reflect.declaration.CtMethod)

Example 68 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class JDTCommentBuilder method findCommentParent.

/**
 * Find the parent of a comment based on the position
 * @param comment the comment
 * @return the parent of the comment
 */
private CtElement findCommentParent(CtComment comment) {
    class FindCommentParentScanner extends CtScanner {

        public CtElement commentParent;

        private int start;

        private int end;

        FindCommentParentScanner(int start, int end) {
            this.start = start;
            this.end = end;
        }

        private boolean isCommentBetweenElementPosition(CtElement element) {
            return (element.getPosition() != null && element.getPosition().getSourceStart() <= this.start && element.getPosition().getSourceEnd() >= this.end);
        }

        @Override
        public void scan(CtElement element) {
            if (element == null) {
                return;
            }
            if (element.isImplicit()) {
                return;
            }
            CtElement body = getBody(element);
            if (body != null && body.getPosition() == null) {
                body = null;
            }
            boolean betweenElementPosition = this.isCommentBetweenElementPosition(element);
            boolean bodyBetweenElementPosition = (body != null) && this.isCommentBetweenElementPosition(body);
            if (betweenElementPosition || bodyBetweenElementPosition) {
                commentParent = element;
                element.accept(this);
            }
        }
    }
    FindCommentParentScanner findCommentParentScanner = new FindCommentParentScanner(comment.getPosition().getSourceStart(), comment.getPosition().getSourceEnd());
    if (!spoonUnit.getDeclaredTypes().isEmpty()) {
        findCommentParentScanner.scan(spoonUnit.getDeclaredTypes());
    } else if (spoonUnit.getDeclaredModule() != null) {
        findCommentParentScanner.scan(spoonUnit.getDeclaredModule());
    }
    return findCommentParentScanner.commentParent;
}
Also used : CtElement(spoon.reflect.declaration.CtElement) CtScanner(spoon.reflect.visitor.CtScanner)

Example 69 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class JDTCommentBuilder method addCommentToNear.

/**
 * Insert the element to nearer element in the elements collections
 * @param comment the comment to insert
 * @param elements the collection that content the ast elements
 * @return
 */
private CtElement addCommentToNear(final CtComment comment, final Collection<CtElement> elements) {
    CtElement best = null;
    int smallDistance = Integer.MAX_VALUE;
    for (CtElement element : elements) {
        if (element.getPosition() == null) {
            continue;
        }
        if (element.isImplicit()) {
            continue;
        }
        if (element instanceof CtComment) {
            continue;
        }
        final boolean isAfter = element.getPosition().getSourceEnd() < comment.getPosition().getSourceStart();
        int distance = Math.abs(element.getPosition().getSourceStart() - comment.getPosition().getSourceEnd());
        if (isAfter) {
            distance = Math.abs(element.getPosition().getSourceEnd() - comment.getPosition().getSourceStart());
        }
        int elementEndLine = element.getPosition().getEndLine();
        int commentLine = comment.getPosition().getLine();
        if (distance < smallDistance && (!isAfter || elementEndLine == commentLine)) {
            best = element;
            smallDistance = distance;
        }
    }
    // adds the comment to the nearest element
    if (best != null) {
        best.addComment(comment);
    }
    return best;
}
Also used : CtComment(spoon.reflect.code.CtComment) CtElement(spoon.reflect.declaration.CtElement)

Example 70 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class ParentExiter method substituteAnnotation.

private void substituteAnnotation(CtTypedElement ele) {
    if (annotationsMap.containsKey(ele)) {
        List<CtAnnotation> annotations = annotationsMap.get(ele);
        for (CtAnnotation annotation : annotations) {
            // if we are here, we may have find an element for whom it's a better place
            if (this.jdtTreeBuilder.getFactory().getEnvironment().getNoClasspath() && annotation.isParentInitialized()) {
                CtElement parent = annotation.getParent();
                parent.removeAnnotation(annotation);
            }
            if (!ele.getType().getAnnotations().contains(annotation)) {
                ele.getType().addAnnotation(annotation.clone());
            }
        }
        annotationsMap.remove(ele);
    }
}
Also used : CtAnnotation(spoon.reflect.declaration.CtAnnotation) CtElement(spoon.reflect.declaration.CtElement)

Aggregations

CtElement (spoon.reflect.declaration.CtElement)86 Test (org.junit.Test)39 Launcher (spoon.Launcher)23 Factory (spoon.reflect.factory.Factory)18 ArrayList (java.util.ArrayList)17 CtMethod (spoon.reflect.declaration.CtMethod)17 CtType (spoon.reflect.declaration.CtType)15 CtStatement (spoon.reflect.code.CtStatement)14 CtTypeReference (spoon.reflect.reference.CtTypeReference)14 List (java.util.List)12 CtClass (spoon.reflect.declaration.CtClass)12 CtField (spoon.reflect.declaration.CtField)12 CtIf (spoon.reflect.code.CtIf)11 CtInvocation (spoon.reflect.code.CtInvocation)11 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)11 CtLocalVariable (spoon.reflect.code.CtLocalVariable)10 CtExecutableReference (spoon.reflect.reference.CtExecutableReference)9 CtScanner (spoon.reflect.visitor.CtScanner)9 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)9 Collection (java.util.Collection)8