Search in sources :

Example 11 with SourcePosition

use of spoon.reflect.cu.SourcePosition 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 12 with SourcePosition

use of spoon.reflect.cu.SourcePosition in project spoon by INRIA.

the class SubstitutionVisitor method getGeneratedByComment.

private static String getGeneratedByComment(CtElement ele) {
    SourcePosition pos = ele.getPosition();
    if (pos != null) {
        CompilationUnit cu = pos.getCompilationUnit();
        if (cu != null) {
            CtType<?> mainType = cu.getMainType();
            if (mainType != null) {
                StringBuilder result = new StringBuilder();
                result.append("Generated by ");
                result.append(mainType.getQualifiedName());
                appendInnerTypedElements(result, mainType, ele);
                result.append('(');
                result.append(mainType.getSimpleName());
                result.append(".java:");
                result.append(pos.getLine());
                result.append(')');
                return result.toString();
            }
        }
    }
    return null;
}
Also used : CompilationUnit(spoon.reflect.cu.CompilationUnit) SourcePosition(spoon.reflect.cu.SourcePosition)

Example 13 with SourcePosition

use of spoon.reflect.cu.SourcePosition in project spoon by INRIA.

the class PositionTest method testSourcePosition.

@Test
public void testSourcePosition() throws Exception {
    SourcePosition s = new spoon.Launcher().getFactory().Core().createClass().getPosition();
    assertEquals(-1, s.getSourceStart());
    assertEquals(-1, s.getSourceEnd());
    assertEquals(-1, s.getColumn());
    assertEquals(-1, s.getLine());
    assertEquals("(unknown file)", s.toString());
    // no NPE
    assertTrue(s.hashCode() > 0);
}
Also used : DeclarationSourcePosition(spoon.reflect.cu.position.DeclarationSourcePosition) BodyHolderSourcePosition(spoon.reflect.cu.position.BodyHolderSourcePosition) SourcePosition(spoon.reflect.cu.SourcePosition) Launcher(spoon.Launcher) Test(org.junit.Test)

Example 14 with SourcePosition

use of spoon.reflect.cu.SourcePosition in project spoon by INRIA.

the class PositionTest method testPositionInterface.

@Test
public void testPositionInterface() throws Exception {
    final Factory build = build(new File("src/test/java/spoon/test/position/testclasses/"));
    final CtType<FooInterface> foo = build.Type().get(FooInterface.class);
    String classContent = getClassContent(foo);
    BodyHolderSourcePosition position = (BodyHolderSourcePosition) foo.getPosition();
    assertEquals(7, position.getLine());
    assertEquals(9, position.getEndLine());
    assertEquals(96, position.getSourceStart());
    assertEquals(169, position.getSourceEnd());
    assertEquals("@Deprecated\n" + "@InnerAnnot(value=\"machin\")\n" + "public interface FooInterface {\n" + "\n" + "}", contentAtPosition(classContent, position));
    assertEquals("{\n\n}", contentAtPosition(classContent, position.getBodyStart(), position.getBodyEnd()));
    assertEquals("FooInterface", contentAtPosition(classContent, position.getNameStart(), position.getNameEnd()));
    assertEquals("public", contentAtPosition(classContent, position.getModifierSourceStart(), position.getModifierSourceEnd()));
    {
        SourcePosition annPosition = foo.getAnnotations().get(0).getPosition();
        assertEquals("@Deprecated", contentAtPosition(classContent, annPosition.getSourceStart(), annPosition.getSourceEnd()));
    }
    {
        SourcePosition annPosition = foo.getAnnotations().get(1).getPosition();
        assertEquals("@InnerAnnot(value=\"machin\")", contentAtPosition(classContent, annPosition.getSourceStart(), annPosition.getSourceEnd()));
    }
}
Also used : BodyHolderSourcePosition(spoon.reflect.cu.position.BodyHolderSourcePosition) DeclarationSourcePosition(spoon.reflect.cu.position.DeclarationSourcePosition) BodyHolderSourcePosition(spoon.reflect.cu.position.BodyHolderSourcePosition) SourcePosition(spoon.reflect.cu.SourcePosition) Factory(spoon.reflect.factory.Factory) File(java.io.File) FooInterface(spoon.test.position.testclasses.FooInterface) Test(org.junit.Test)

Example 15 with SourcePosition

use of spoon.reflect.cu.SourcePosition in project spoon by INRIA.

the class PositionTest method testPositionField.

@Test
public void testPositionField() throws Exception {
    final Factory build = build(FooField.class);
    final CtType<FooField> foo = build.Type().get(FooField.class);
    String classContent = getClassContent(foo);
    DeclarationSourcePosition position1 = (DeclarationSourcePosition) foo.getField("field1").getPosition();
    assertEquals(5, position1.getLine());
    assertEquals(5, position1.getEndLine());
    assertEquals(68, position1.getSourceStart());
    assertEquals(95, position1.getSourceEnd());
    assertEquals("public final int field1 = 0;", contentAtPosition(classContent, position1));
    assertEquals("field1", contentAtPosition(classContent, position1.getNameStart(), position1.getNameEnd()));
    assertEquals("public final", contentAtPosition(classContent, position1.getModifierSourceStart(), position1.getModifierSourceEnd()));
    DeclarationSourcePosition position2 = (DeclarationSourcePosition) foo.getField("field2").getPosition();
    assertEquals(7, position2.getLine());
    assertEquals(8, position2.getEndLine());
    assertEquals(99, position2.getSourceStart());
    assertEquals(116, position2.getSourceEnd());
    assertEquals("int field2 =\n" + "\t\t\t0;", contentAtPosition(classContent, position2));
    assertEquals("field2", contentAtPosition(classContent, position2.getNameStart(), position2.getNameEnd()));
    assertEquals("", contentAtPosition(classContent, position2.getModifierSourceStart(), position2.getModifierSourceEnd()));
    CtAssignment m = foo.getMethod("m").getBody().getStatement(0);
    CtFieldAccess assigned = (CtFieldAccess) m.getAssigned();
    SourcePosition position3 = assigned.getPosition();
    assertEquals(13, position3.getLine());
    assertEquals(13, position3.getEndLine());
    assertEquals(168, position3.getSourceStart());
    assertEquals(184, position3.getSourceEnd());
    assertEquals("FooField.f.field2", contentAtPosition(classContent, position3));
    CtFieldAccess target = (CtFieldAccess) assigned.getTarget();
    SourcePosition position4 = target.getPosition();
    assertEquals(13, position4.getLine());
    assertEquals(13, position4.getEndLine());
    assertEquals(168, position4.getSourceStart());
    assertEquals(177, position4.getSourceEnd());
    assertEquals("FooField.f", contentAtPosition(classContent, position4));
    CtExpression typeAccess = target.getTarget();
    SourcePosition position5 = typeAccess.getPosition();
    assertEquals(13, position5.getLine());
    assertEquals(13, position5.getEndLine());
    assertEquals(168, position5.getSourceStart());
    assertEquals(175, position5.getSourceEnd());
    assertEquals("FooField", contentAtPosition(classContent, position5));
}
Also used : CtFieldAccess(spoon.reflect.code.CtFieldAccess) CtAssignment(spoon.reflect.code.CtAssignment) CtExpression(spoon.reflect.code.CtExpression) DeclarationSourcePosition(spoon.reflect.cu.position.DeclarationSourcePosition) BodyHolderSourcePosition(spoon.reflect.cu.position.BodyHolderSourcePosition) SourcePosition(spoon.reflect.cu.SourcePosition) Factory(spoon.reflect.factory.Factory) FooField(spoon.test.position.testclasses.FooField) DeclarationSourcePosition(spoon.reflect.cu.position.DeclarationSourcePosition) Test(org.junit.Test)

Aggregations

SourcePosition (spoon.reflect.cu.SourcePosition)16 Test (org.junit.Test)8 BodyHolderSourcePosition (spoon.reflect.cu.position.BodyHolderSourcePosition)6 DeclarationSourcePosition (spoon.reflect.cu.position.DeclarationSourcePosition)6 Factory (spoon.reflect.factory.Factory)5 CtBlock (spoon.reflect.code.CtBlock)4 File (java.io.File)3 Launcher (spoon.Launcher)3 CtIf (spoon.reflect.code.CtIf)3 CtMethod (spoon.reflect.declaration.CtMethod)3 CtComment (spoon.reflect.code.CtComment)2 CtExpression (spoon.reflect.code.CtExpression)2 CtStatement (spoon.reflect.code.CtStatement)2 CompilationUnit (spoon.reflect.cu.CompilationUnit)2 NoSourcePosition (spoon.reflect.cu.position.NoSourcePosition)2 CtClass (spoon.reflect.declaration.CtClass)2 ParentNotInitializedException (spoon.reflect.declaration.ParentNotInitializedException)2 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)2 ArrayList (java.util.ArrayList)1 StringLiteralConcatenation (org.eclipse.jdt.internal.compiler.ast.StringLiteralConcatenation)1