Search in sources :

Example 36 with CtStatement

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

the class StatementTemplate method apply.

public CtStatement apply(CtType<?> targetType) {
    CtClass<?> c = Substitution.getTemplateCtClass(targetType, this);
    // we substitute the first statement of method statement
    CtStatement result = c.getMethod("statement").getBody().getStatements().get(0).clone();
    List<CtStatement> statements = new SubstitutionVisitor(c.getFactory(), targetType, this).substitute(result);
    if (statements.size() > 1) {
        throw new SpoonException("StatementTemplate cannot return more then one statement");
    }
    return statements.isEmpty() ? null : statements.get(0);
}
Also used : SubstitutionVisitor(spoon.support.template.SubstitutionVisitor) CtStatement(spoon.reflect.code.CtStatement) SpoonException(spoon.SpoonException)

Example 37 with CtStatement

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

the class IntercessionTest method testEqualConstructor.

@Test
public void testEqualConstructor() {
    CtClass<?> clazz = factory.Code().createCodeSnippetStatement("" + "class X { public X() {} };").compile();
    CtConstructor<?> foo = (CtConstructor<?>) clazz.getConstructors().toArray()[0];
    CtConstructor<?> fooClone = foo.clone();
    Assert.assertEquals(foo, fooClone);
    CtBlock<?> body = foo.getBody();
    // there is an implicit call to super()
    assertEquals(1, body.getStatements().size());
    assertEquals("super()", body.getStatements().get(0).toString());
    // adding a new statement;
    CtStatement stmt = factory.Core().createCodeSnippetStatement();
    body.insertEnd(stmt);
    assertEquals(2, body.getStatements().size());
    // constructor are not equals anymore
    Assert.assertNotEquals(foo, fooClone);
}
Also used : CtStatement(spoon.reflect.code.CtStatement) CtConstructor(spoon.reflect.declaration.CtConstructor) Test(org.junit.Test)

Example 38 with CtStatement

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

the class IntercessionTest method testResetCollectionInSetters.

@Test
// interesting but too fragile with conventions
@Ignore
public void testResetCollectionInSetters() throws Exception {
    final Launcher launcher = new Launcher();
    launcher.setArgs(new String[] { "--output-type", "nooutput" });
    final Factory factory = launcher.getFactory();
    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");
    launcher.buildModel();
    new IntercessionScanner(factory) {

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

        private boolean takeSetterCollection(CtMethod<?> candidate) {
            final CtTypeReference<?> type = candidate.getParameters().get(0).getType();
            final List<CtTypeReference<?>> actualTypeArguments = type.getActualTypeArguments();
            return COLLECTIONS.contains(type) && actualTypeArguments.size() == 1 && actualTypeArguments.get(0).isSubtypeOf(CTELEMENT_REFERENCE);
        }

        @Override
        protected void process(CtMethod<?> element) {
            if (element.getAnnotation(UnsettableProperty.class) != null) {
                // we don't check the contracts for unsettable setters
                return;
            }
            final CtStatement statement = element.getBody().getStatement(0);
            if (!(statement instanceof CtIf)) {
                fail(log(element, "First statement should be an if to check the parameter of the setter"));
            }
            final CtIf anIf = (CtIf) statement;
            if (!createCheckNull(element.getParameters().get(0)).equals(anIf.getCondition())) {
                fail(log(element, "Condition should test if the parameter is null.\nThe condition was " + anIf.getCondition()));
            }
            if (!(anIf.getThenStatement() instanceof CtBlock)) {
                fail(log(element, "Should have a block in the if condition to have the initialization and the return."));
            }
            if (element.getParameters().get(0).getType().equals(SET_REFERENCE)) {
                if (!hasCallEmptyInv(anIf.getThenStatement(), SET_REFERENCE)) {
                    fail(log(element, "Should initilize the list with CtElementImpl#emptySet()."));
                }
            } else {
                if (!hasCallEmptyInv(anIf.getThenStatement(), LIST_REFERENCE)) {
                    fail(log(element, "Should initilize the list with CtElementImpl#emptyList()."));
                }
            }
        }

        private boolean hasCallEmptyInv(CtBlock thenStatement, CtTypeReference<? extends Collection> collectionReference) {
            if (!(thenStatement.getStatement(0) instanceof CtAssignment)) {
                return false;
            }
            final CtExpression assignment = ((CtAssignment) thenStatement.getStatement(0)).getAssignment();
            if (!(assignment instanceof CtInvocation)) {
                return false;
            }
            final CtInvocation inv = (CtInvocation) assignment;
            if (collectionReference.equals(SET_REFERENCE)) {
                if (!inv.getExecutable().getSimpleName().equals("emptySet")) {
                    return false;
                }
            } else if (collectionReference.equals(LIST_REFERENCE)) {
                if (!inv.getExecutable().getSimpleName().equals("emptyList")) {
                    return false;
                }
            }
            return true;
        }

        /**
         * Creates <code>list == null && list.isEmpty()</code>.
         *
         * @param ctParameter <code>list</code>
         */
        private CtBinaryOperator<Boolean> createCheckNull(CtParameter<?> ctParameter) {
            final CtVariableAccess<?> variableRead = factory.Code().createVariableRead(ctParameter.getReference(), true);
            final CtLiteral nullLiteral = factory.Code().createLiteral(null);
            nullLiteral.setType(factory.Type().nullType());
            final CtBinaryOperator<Boolean> checkNull = factory.Code().createBinaryOperator(variableRead, nullLiteral, BinaryOperatorKind.EQ);
            checkNull.setType(factory.Type().BOOLEAN_PRIMITIVE);
            final CtMethod<Boolean> isEmptyMethod = ctParameter.getType().getTypeDeclaration().getMethod(factory.Type().booleanPrimitiveType(), "isEmpty");
            final CtInvocation<Boolean> isEmpty = factory.Code().createInvocation(variableRead, isEmptyMethod.getReference());
            final CtBinaryOperator<Boolean> condition = factory.Code().createBinaryOperator(checkNull, isEmpty, BinaryOperatorKind.OR);
            return condition.setType(factory.Type().booleanPrimitiveType());
        }

        private String log(CtMethod<?> element, String message) {
            return message + "\nin " + element.getSignature() + "\ndeclared in " + element.getDeclaringType().getQualifiedName();
        }
    }.scan(factory.getModel().getUnnamedModule());
}
Also used : CtVariableAccess(spoon.reflect.code.CtVariableAccess) CtAssignment(spoon.reflect.code.CtAssignment) CtExpression(spoon.reflect.code.CtExpression) CtBinaryOperator(spoon.reflect.code.CtBinaryOperator) ModelUtils.createFactory(spoon.testing.utils.ModelUtils.createFactory) Factory(spoon.reflect.factory.Factory) CtIf(spoon.reflect.code.CtIf) CtInvocation(spoon.reflect.code.CtInvocation) CtBlock(spoon.reflect.code.CtBlock) CtLiteral(spoon.reflect.code.CtLiteral) CtStatement(spoon.reflect.code.CtStatement) CtTypeReference(spoon.reflect.reference.CtTypeReference) Launcher(spoon.Launcher) ArrayList(java.util.ArrayList) List(java.util.List) CtMethod(spoon.reflect.declaration.CtMethod) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 39 with CtStatement

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

the class RemoveTest method testRemoveAllStatements.

@Test
public void testRemoveAllStatements() {
    Factory factory = createFactory();
    CtClass<?> clazz = factory.Code().createCodeSnippetStatement("" + "class X {" + "public void foo() {" + " int x=0;int y=0;" + "}};").compile();
    CtMethod<?> foo = (CtMethod<?>) clazz.getMethods().toArray()[0];
    CtBlock<?> body = foo.getBody();
    assertEquals(2, body.getStatements().size());
    for (CtStatement s : body) {
        body.removeStatement(s);
    }
    assertEquals(0, body.getStatements().size());
}
Also used : CtStatement(spoon.reflect.code.CtStatement) Factory(spoon.reflect.factory.Factory) ModelUtils.createFactory(spoon.testing.utils.ModelUtils.createFactory) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Example 40 with CtStatement

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

the class InsertMethodsTest method testInsertAfter.

@Test
public void testInsertAfter() throws Exception {
    CtMethod<Void> foo = (CtMethod<Void>) assignmentClass.getMethods().toArray()[0];
    CtBlock<?> body = foo.getBody();
    assertEquals(3, body.getStatements().size());
    CtStatement s = body.getStatements().get(2);
    assertEquals("int z = x + y", s.toString());
    // adding a new statement;
    CtCodeSnippetStatement stmt = factory.Core().createCodeSnippetStatement();
    stmt.setValue("System.out.println(x);");
    s.insertAfter(stmt);
    assertEquals(4, body.getStatements().size());
    assertSame(stmt, body.getStatements().get(3));
    assertEquals(body, stmt.getParent());
}
Also used : CtStatement(spoon.reflect.code.CtStatement) CtCodeSnippetStatement(spoon.reflect.code.CtCodeSnippetStatement) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

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