Search in sources :

Example 41 with CtStatement

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

the class ParentTest method testParentSetInSetter.

@Test
// too fragile because of conventions
@Ignore
public void testParentSetInSetter() throws Exception {
    // contract: Check that all setters protect their parameter.
    final Launcher launcher = new Launcher();
    final Factory factory = launcher.getFactory();
    launcher.setArgs(new String[] { "--output-type", "nooutput" });
    launcher.getEnvironment().setNoClasspath(true);
    // interfaces.
    launcher.addInputResource("./src/main/java/spoon/reflect/code");
    launcher.addInputResource("./src/main/java/spoon/reflect/declaration");
    launcher.addInputResource("./src/main/java/spoon/reflect/reference");
    // implementations.
    launcher.addInputResource("./src/main/java/spoon/support/reflect/code");
    launcher.addInputResource("./src/main/java/spoon/support/reflect/declaration");
    launcher.addInputResource("./src/main/java/spoon/support/reflect/reference");
    // Utils.
    launcher.addInputResource("./src/test/java/spoon/reflect/ast/");
    launcher.buildModel();
    // Asserts.
    new IntercessionScanner(launcher.getFactory()) {

        @Override
        protected boolean isToBeProcessed(CtMethod<?> candidate) {
            return (// 
            candidate.getSimpleName().startsWith("set") || // 
            candidate.getSimpleName().startsWith("add")) && // 
            candidate.hasModifier(ModifierKind.PUBLIC) && // 
            takeSetterForCtElement(candidate) && // 
            avoidInterfaces(candidate) && avoidThrowUnsupportedOperationException(candidate);
        }

        @Override
        public void process(CtMethod<?> element) {
            if (element.getAnnotation(UnsettableProperty.class) != null) {
                // we don't check the contracts for unsettable setters
                return;
            }
            if (element.getSimpleName().startsWith("add")) {
                checkAddStrategy(element);
            } else {
                checkSetStrategy(element);
            }
        }

        private void checkAddStrategy(CtMethod<?> element) {
            final CtStatement statement = element.getBody().getStatement(0);
            if (!(statement instanceof CtIf)) {
                fail("First statement should be an if to check the parameter of the setter." + element.getSignature() + " declared in " + element.getDeclaringType().getQualifiedName());
            }
            if (!createCheckNull(element.getParameters().get(0)).equals(((CtIf) statement).getCondition())) {
                fail("Condition should test if the parameter is null. The condition was " + ((CtIf) statement).getCondition() + "in " + element.getSignature() + " declared in " + element.getDeclaringType().getQualifiedName());
            }
        }

        private void checkSetStrategy(CtMethod<?> element) {
            final CtTypeReference<?> type = element.getParameters().get(0).getType();
            if (!COLLECTIONS.contains(type) && !(type instanceof CtArrayTypeReference)) {
                CtInvocation<?> setParent = searchSetParent(element.getBody());
                if (setParent == null) {
                    return;
                }
                try {
                    if (setParent.getParent(CtIf.class) == null) {
                        fail("Missing condition in " + element.getSignature() + " declared in the class " + element.getDeclaringType().getQualifiedName());
                    }
                } catch (ParentNotInitializedException e) {
                    fail("Missing parent condition in " + element.getSignature() + " declared in the class " + element.getDeclaringType().getQualifiedName());
                }
            }
        }

        /**
         * Creates <code>parameter == null</code>.
         *
         * @param ctParameter <code>parameter</code>
         */
        private CtBinaryOperator<Boolean> createCheckNull(CtParameter<?> ctParameter) {
            final CtLiteral nullLiteral = factory.Code().createLiteral(null);
            nullLiteral.setType(factory.Type().NULL_TYPE.clone());
            final CtBinaryOperator<Boolean> operator = // 
            factory.Code().createBinaryOperator(// 
            factory.Code().createVariableRead(ctParameter.getReference(), true), nullLiteral, BinaryOperatorKind.EQ);
            operator.setType(factory.Type().BOOLEAN_PRIMITIVE);
            return operator;
        }

        private CtInvocation<?> searchSetParent(CtBlock<?> body) {
            final List<CtInvocation<?>> ctInvocations = body.getElements(new TypeFilter<CtInvocation<?>>(CtInvocation.class) {

                @Override
                public boolean matches(CtInvocation<?> element) {
                    return "setParent".equals(element.getExecutable().getSimpleName()) && super.matches(element);
                }
            });
            return ctInvocations.size() > 0 ? ctInvocations.get(0) : null;
        }
    }.scan(launcher.getModel().getRootPackage());
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtBinaryOperator(spoon.reflect.code.CtBinaryOperator) Factory(spoon.reflect.factory.Factory) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) ReferenceTypeFilter(spoon.reflect.visitor.filter.ReferenceTypeFilter) CtIf(spoon.reflect.code.CtIf) CtInvocation(spoon.reflect.code.CtInvocation) CtLiteral(spoon.reflect.code.CtLiteral) CtStatement(spoon.reflect.code.CtStatement) CtTypeReference(spoon.reflect.reference.CtTypeReference) Launcher(spoon.Launcher) CtStatementList(spoon.reflect.code.CtStatementList) List(java.util.List) CtArrayTypeReference(spoon.reflect.reference.CtArrayTypeReference) IntercessionScanner(spoon.test.intercession.IntercessionScanner) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 42 with CtStatement

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

the class TypeReferenceTest method testIgnoreEnclosingClassInActualTypes.

@Test
public void testIgnoreEnclosingClassInActualTypes() throws Exception {
    final CtType<Panini> aPanini = buildClass(Panini.class);
    final CtStatement ctReturn = aPanini.getMethod("entryIterator").getBody().getStatement(0);
    assertTrue(ctReturn instanceof CtReturn);
    final CtExpression ctConstructorCall = ((CtReturn) ctReturn).getReturnedExpression();
    assertTrue(ctConstructorCall instanceof CtConstructorCall);
    assertEquals("spoon.test.reference.testclasses.Panini<K, V>.Itr<java.util.Map.Entry<K, V>>", ctConstructorCall.getType().toString());
}
Also used : CtStatement(spoon.reflect.code.CtStatement) CtReturn(spoon.reflect.code.CtReturn) CtExpression(spoon.reflect.code.CtExpression) CtConstructorCall(spoon.reflect.code.CtConstructorCall) Panini(spoon.test.reference.testclasses.Panini) Test(org.junit.Test)

Example 43 with CtStatement

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

the class PositionTest method getPositionOfImplicitBlock.

@Test
public void getPositionOfImplicitBlock() {
    // contract: position of implicit block in if (cond) [implicit block] else [implicit block] should be the source position of implicit block content.
    Launcher launcher = new Launcher();
    launcher.addInputResource("./src/test/java/spoon/test/position/testclasses/ImplicitBlock.java");
    launcher.buildModel();
    CtIf ifElement = launcher.getModel().getElements(new TypeFilter<CtIf>(CtIf.class)).get(0);
    CtStatement thenStatement = ifElement.getThenStatement();
    assertTrue(thenStatement instanceof CtBlock);
    CtBlock thenBlock = (CtBlock) thenStatement;
    SourcePosition positionThen = thenBlock.getPosition();
    CtStatement returnStatement = thenBlock.getStatement(0);
    assertEquals(returnStatement.getPosition(), positionThen);
    assertEquals("ImplicitBlock.java", positionThen.getFile().getName());
    assertEquals(7, positionThen.getLine());
    CtStatement elseStatement = ifElement.getElseStatement();
    assertTrue(elseStatement instanceof CtBlock);
    CtBlock elseBlock = (CtBlock) elseStatement;
    SourcePosition positionElse = elseBlock.getPosition();
    CtStatement otherReturnStatement = elseBlock.getStatement(0);
    assertEquals(otherReturnStatement.getPosition(), positionElse);
    assertEquals("ImplicitBlock.java", positionThen.getFile().getName());
    assertEquals(8, positionElse.getLine());
    assertNotEquals(returnStatement, otherReturnStatement);
}
Also used : CtBlock(spoon.reflect.code.CtBlock) CtStatement(spoon.reflect.code.CtStatement) DeclarationSourcePosition(spoon.reflect.cu.position.DeclarationSourcePosition) BodyHolderSourcePosition(spoon.reflect.cu.position.BodyHolderSourcePosition) SourcePosition(spoon.reflect.cu.SourcePosition) Launcher(spoon.Launcher) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtIf(spoon.reflect.code.CtIf) Test(org.junit.Test)

Example 44 with CtStatement

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

the class DefaultPrettyPrinterTest method testTernaryParenthesesOnLocalVariable.

@Test
public void testTernaryParenthesesOnLocalVariable() {
    // Spooning the code snippet
    Launcher launcher = new Launcher();
    CtCodeSnippetStatement snippet = launcher.getFactory().Code().createCodeSnippetStatement("final int foo = (new Object() instanceof Object ? new Object().equals(null) : new Object().equals(new Object())) ? 0 : new Object().hashCode();");
    CtStatement compile = snippet.compile();
    // Pretty-printing the Spooned code snippet and compiling the resulting code.
    snippet = launcher.getFactory().Code().createCodeSnippetStatement(compile.toString());
    assertEquals(compile, snippet.compile());
}
Also used : CtStatement(spoon.reflect.code.CtStatement) Launcher(spoon.Launcher) CtCodeSnippetStatement(spoon.reflect.code.CtCodeSnippetStatement) Test(org.junit.Test)

Example 45 with CtStatement

use of spoon.reflect.code.CtStatement in project dspot by STAMP-project.

the class AssertionRemover method removeAssertion.

/**
 * Replaces an invocation with its arguments.
 *
 * @param invocation Invocation
 */
public void removeAssertion(CtInvocation<?> invocation) {
    final Factory factory = invocation.getFactory();
    invocation.getArguments().forEach(argument -> {
        CtExpression clone = ((CtExpression) argument).clone();
        if (clone instanceof CtUnaryOperator) {
            clone = ((CtUnaryOperator) clone).getOperand();
        }
        if (clone instanceof CtStatement) {
            clone.getTypeCasts().clear();
            invocation.insertBefore((CtStatement) clone);
        } else if (!(clone instanceof CtLiteral || clone instanceof CtVariableRead)) {
            CtTypeReference<?> typeOfParameter = clone.getType();
            if (clone.getType().equals(factory.Type().NULL_TYPE)) {
                typeOfParameter = factory.Type().createReference(Object.class);
            }
            final CtLocalVariable localVariable = factory.createLocalVariable(typeOfParameter, typeOfParameter.getSimpleName() + "_" + counter[0]++, clone);
            invocation.insertBefore(localVariable);
        }
    });
    CtElement currentParent = invocation;
    while (!(currentParent.getParent() instanceof CtStatementList)) {
        currentParent = currentParent.getParent();
    }
    ((CtStatementList) currentParent.getParent()).removeStatement((CtStatement) currentParent);
}
Also used : CtLiteral(spoon.reflect.code.CtLiteral) CtExpression(spoon.reflect.code.CtExpression) CtStatement(spoon.reflect.code.CtStatement) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtElement(spoon.reflect.declaration.CtElement) Factory(spoon.reflect.factory.Factory) CtUnaryOperator(spoon.reflect.code.CtUnaryOperator) CtStatementList(spoon.reflect.code.CtStatementList) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtVariableRead(spoon.reflect.code.CtVariableRead)

Aggregations

CtStatement (spoon.reflect.code.CtStatement)84 Test (org.junit.Test)55 Factory (spoon.reflect.factory.Factory)35 CtMethod (spoon.reflect.declaration.CtMethod)23 Launcher (spoon.Launcher)20 CtBlock (spoon.reflect.code.CtBlock)17 CtIf (spoon.reflect.code.CtIf)11 CtExpression (spoon.reflect.code.CtExpression)10 ArrayList (java.util.ArrayList)9 CtElement (spoon.reflect.declaration.CtElement)9 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)9 CtInvocation (spoon.reflect.code.CtInvocation)8 CtTypeReference (spoon.reflect.reference.CtTypeReference)7 CtCase (spoon.reflect.code.CtCase)6 CtStatementList (spoon.reflect.code.CtStatementList)6 STATEMENT (spoon.reflect.path.CtRole.STATEMENT)6 FileSystemFile (spoon.support.compiler.FileSystemFile)6 Adobada (spoon.test.delete.testclasses.Adobada)6 CtCodeSnippetStatement (spoon.reflect.code.CtCodeSnippetStatement)5 CtLocalVariable (spoon.reflect.code.CtLocalVariable)5