Search in sources :

Example 11 with CtCatch

use of spoon.reflect.code.CtCatch 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 CtCatch

use of spoon.reflect.code.CtCatch in project spoon by INRIA.

the class JDTTreeBuilder method visit.

@Override
public boolean visit(SingleTypeReference singleTypeReference, BlockScope scope) {
    if (skipTypeInAnnotation) {
        return true;
    }
    if (context.stack.peekFirst().node instanceof UnionTypeReference) {
        if (singleTypeReference.resolvedType == null) {
            CtTypeReference typeReference = factory.Type().createReference(singleTypeReference.toString());
            CtReference ref = references.getDeclaringReferenceFromImports(singleTypeReference.getLastToken());
            references.setPackageOrDeclaringType(typeReference, ref);
            context.enter(typeReference, singleTypeReference);
        } else {
            context.enter(references.<Throwable>getTypeReference(singleTypeReference.resolvedType), singleTypeReference);
        }
        return true;
    } else if (context.stack.peekFirst().element instanceof CtCatch) {
        context.enter(helper.createCatchVariable(singleTypeReference), singleTypeReference);
        return true;
    }
    context.enter(factory.Code().createTypeAccessWithoutCloningReference(references.buildTypeReference(singleTypeReference, scope)), singleTypeReference);
    return true;
}
Also used : CtReference(spoon.reflect.reference.CtReference) CtTypeReference(spoon.reflect.reference.CtTypeReference) UnionTypeReference(org.eclipse.jdt.internal.compiler.ast.UnionTypeReference) CtCatch(spoon.reflect.code.CtCatch)

Example 13 with CtCatch

use of spoon.reflect.code.CtCatch in project spoon by INRIA.

the class TryCatchTest method testCatchWithUnknownExceptions.

@Test
public void testCatchWithUnknownExceptions() {
    // contract: unknown exception type in multicatch should not cause IndexOutOfBoundsException
    String inputResource = "./src/test/resources/spoon/test/noclasspath/exceptions/Foo.java";
    Launcher launcher = new Launcher();
    launcher.addInputResource(inputResource);
    launcher.getEnvironment().setNoClasspath(true);
    CtModel model = launcher.buildModel();
    List<CtCatch> catches = model.getElements(new TypeFilter<CtCatch>(CtCatch.class));
    // catch with single UnknownException
    assertNotNull(catches.get(0).getParameter().getType());
    // multicatch with UnknownException
    assertNull(catches.get(1).getParameter().getType());
    // multicatch with UnknownException
    assertNull(catches.get(2).getParameter().getType());
}
Also used : Launcher(spoon.Launcher) CtCatch(spoon.reflect.code.CtCatch) CtModel(spoon.reflect.CtModel) Test(org.junit.Test)

Example 14 with CtCatch

use of spoon.reflect.code.CtCatch in project spoon by INRIA.

the class TryCatchTest method testCatchWithExplicitFinalVariable.

@Test
public void testCatchWithExplicitFinalVariable() throws IOException {
    // contract: explicit final modifier are possible in catch variables and should be kept when pretty-printing
    String inputResource = "./src/test/java/spoon/test/trycatch/testclasses/Bar.java";
    Launcher launcher = new Launcher();
    launcher.addInputResource(inputResource);
    launcher.getEnvironment().setComplianceLevel(5);
    launcher.buildModel();
    CtTry tryStmt = launcher.getModel().getElements(new TypeFilter<>(CtTry.class)).get(0);
    List<CtCatch> catchers = tryStmt.getCatchers();
    assertEquals(1, catchers.size());
    CtCatchVariable<?> catchVariable = catchers.get(0).getParameter();
    assertTrue(catchVariable.hasModifier(ModifierKind.FINAL));
    Set<CtExtendedModifier> extendedModifierSet = catchVariable.getExtendedModifiers();
    assertEquals(1, extendedModifierSet.size());
    assertEquals(new CtExtendedModifier(ModifierKind.FINAL, false), extendedModifierSet.iterator().next());
    launcher = new Launcher();
    launcher.addInputResource(inputResource);
    launcher.setSourceOutputDirectory("./target/spoon-trycatch");
    launcher.getEnvironment().setShouldCompile(true);
    launcher.getEnvironment().setComplianceLevel(5);
    launcher.run();
    File f = new File("target/spoon-trycatch/spoon/test/trycatch/testclasses/Bar.java");
    String content = StringUtils.join(Files.readAllLines(f.toPath()), "\n");
    assertTrue(content.contains("catch (final java.lang.Exception e)"));
}
Also used : Launcher(spoon.Launcher) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtCatch(spoon.reflect.code.CtCatch) CtTry(spoon.reflect.code.CtTry) CtExtendedModifier(spoon.support.reflect.CtExtendedModifier) File(java.io.File) Test(org.junit.Test)

Example 15 with CtCatch

use of spoon.reflect.code.CtCatch in project spoon by INRIA.

the class TryCatchTest method testExceptionJava7.

@Test
public void testExceptionJava7() {
    Factory factory = createFactory();
    CtClass<?> clazz = factory.Code().createCodeSnippetStatement("" + "class X {" + "public void foo() {" + " try{}catch(RuntimeException | Error e){System.exit(0);}" + "}" + "};").compile();
    CtTry tryStmt = (CtTry) clazz.getElements(new TypeFilter<>(CtTry.class)).get(0);
    List<CtCatch> catchers = tryStmt.getCatchers();
    assertEquals(1, catchers.size());
    assertEquals(Throwable.class, catchers.get(0).getParameter().getType().getActualClass());
    assertEquals(2, catchers.get(0).getParameter().getMultiTypes().size());
    assertEquals(RuntimeException.class, catchers.get(0).getParameter().getMultiTypes().get(0).getActualClass());
    assertEquals(Error.class, catchers.get(0).getParameter().getMultiTypes().get(1).getActualClass());
    // the code of the catch block is duplicated
    assertEquals("java.lang.System.exit(0)", catchers.get(0).getBody().getStatement(0).toString());
}
Also used : ModelUtils.createFactory(spoon.testing.utils.ModelUtils.createFactory) Factory(spoon.reflect.factory.Factory) CtCatch(spoon.reflect.code.CtCatch) CtTry(spoon.reflect.code.CtTry) Test(org.junit.Test)

Aggregations

CtCatch (spoon.reflect.code.CtCatch)17 Test (org.junit.Test)7 Launcher (spoon.Launcher)4 CtTry (spoon.reflect.code.CtTry)4 Factory (spoon.reflect.factory.Factory)4 File (java.io.File)3 CtCatchVariable (spoon.reflect.code.CtCatchVariable)3 CtStatementList (spoon.reflect.code.CtStatementList)3 CtClass (spoon.reflect.declaration.CtClass)3 CtElement (spoon.reflect.declaration.CtElement)3 CtField (spoon.reflect.declaration.CtField)3 CtTypeReference (spoon.reflect.reference.CtTypeReference)3 ModelUtils.createFactory (spoon.testing.utils.ModelUtils.createFactory)3 ArrayList (java.util.ArrayList)2 CtStatement (spoon.reflect.code.CtStatement)2 CtExecutable (spoon.reflect.declaration.CtExecutable)2 CtMethod (spoon.reflect.declaration.CtMethod)2 CtPackage (spoon.reflect.declaration.CtPackage)2 CtType (spoon.reflect.declaration.CtType)2 UnionTypeReference (org.eclipse.jdt.internal.compiler.ast.UnionTypeReference)1