Search in sources :

Example 1 with CtBlock

use of spoon.reflect.code.CtBlock in project Ex2Amplifier by STAMP-project.

the class MainGenerator method generateMainMethodFromTestMethod.

public static CtMethod<?> generateMainMethodFromTestMethod(CtMethod<?> testMethod, CtType<?> testClass) {
    final Factory factory = testMethod.getFactory();
    final CtBlock<?> blockMain = new AssertionRemover().removeAssertion(testMethod).getBody().clone();
    final List<CtLiteral<?>> originalLiterals = blockMain.getElements(Ex2Amplifier.CT_LITERAL_TYPE_FILTER);
    final int[] count = new int[] { 1 };
    final List<CtLocalVariable<?>> localVariables = originalLiterals.stream().map(literal -> factory.createLocalVariable(Utils.getRealTypeOfLiteral(literal), "lit" + count[0]++, factory.createCodeSnippetExpression(createMakeRead(factory, literal)))).collect(Collectors.toList());
    final CtMethod<?> mainMethod = initMainMethod(factory);
    Collections.reverse(localVariables);
    localVariables.forEach(blockMain::insertBegin);
    Collections.reverse(localVariables);
    final Iterator<CtLocalVariable<?>> iterator = localVariables.iterator();
    blockMain.getElements(Ex2Amplifier.CT_LITERAL_TYPE_FILTER).forEach(literal -> literal.replace(factory.createVariableRead(iterator.next().getReference(), false)));
    if (!testMethod.getThrownTypes().isEmpty()) {
        final CtTry largeTryCatchBlock = createLargeTryCatchBlock(testMethod.getThrownTypes(), factory);
        largeTryCatchBlock.setBody(blockMain);
        mainMethod.setBody(largeTryCatchBlock);
    } else {
        mainMethod.setBody(blockMain);
    }
    removeNonStaticElement(mainMethod, testClass);
    return mainMethod;
}
Also used : Ex2Amplifier(eu.stamp.project.ex2amplifier.amplifier.Ex2Amplifier) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtCatch(spoon.reflect.code.CtCatch) CtCatchVariable(spoon.reflect.code.CtCatchVariable) CtThrow(spoon.reflect.code.CtThrow) Function(java.util.function.Function) CtStatement(spoon.reflect.code.CtStatement) AssertionRemover(fr.inria.diversify.dspot.assertGenerator.AssertionRemover) CtType(spoon.reflect.declaration.CtType) CtThisAccess(spoon.reflect.code.CtThisAccess) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) Iterator(java.util.Iterator) Utils(eu.stamp.project.ex2amplifier.Utils) CtTargetedExpression(spoon.reflect.code.CtTargetedExpression) Set(java.util.Set) Factory(spoon.reflect.factory.Factory) Collectors(java.util.stream.Collectors) CtTypeReference(spoon.reflect.reference.CtTypeReference) List(java.util.List) ModifierKind(spoon.reflect.declaration.ModifierKind) Optional(java.util.Optional) CtBlock(spoon.reflect.code.CtBlock) CtTry(spoon.reflect.code.CtTry) CtParameter(spoon.reflect.declaration.CtParameter) CtLiteral(spoon.reflect.code.CtLiteral) Collections(java.util.Collections) CtMethod(spoon.reflect.declaration.CtMethod) Factory(spoon.reflect.factory.Factory) CtTry(spoon.reflect.code.CtTry) CtLocalVariable(spoon.reflect.code.CtLocalVariable) AssertionRemover(fr.inria.diversify.dspot.assertGenerator.AssertionRemover) CtLiteral(spoon.reflect.code.CtLiteral)

Example 2 with CtBlock

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

the class SnippetCompilationHelper method createWrapperContent.

private static String createWrapperContent(final CtElement element, final Factory f, final CtTypeReference returnType) {
    CtClass<?> w = f.Class().create(WRAPPER_CLASS_NAME);
    CtBlock body = f.Core().createBlock();
    if (element instanceof CtStatement) {
        body.addStatement((CtStatement) element);
    } else if (element instanceof CtExpression) {
        CtReturn ret = f.Core().createReturn();
        ret.setReturnedExpression((CtExpression) element);
        body.addStatement(ret);
    }
    Set<ModifierKind> modifiers = EnumSet.of(ModifierKind.STATIC);
    Set<CtTypeReference<? extends Throwable>> thrownTypes = new HashSet<>();
    thrownTypes.add(f.Class().<Throwable>get(Throwable.class).getReference());
    f.Method().create(w, modifiers, returnType, WRAPPER_METHOD_NAME, CtElementImpl.<CtParameter<?>>emptyList(), thrownTypes, body);
    String contents = w.toString();
    // Clean up (delete wrapper from factory) after it is printed. The DefaultJavaPrettyPrinter needs w in model to be able to print it correctly
    w.getPackage().removeType(w);
    return contents;
}
Also used : CtBlock(spoon.reflect.code.CtBlock) CtStatement(spoon.reflect.code.CtStatement) CtExpression(spoon.reflect.code.CtExpression) CtReturn(spoon.reflect.code.CtReturn) CtTypeReference(spoon.reflect.reference.CtTypeReference) ModifierKind(spoon.reflect.declaration.ModifierKind) HashSet(java.util.HashSet)

Example 3 with CtBlock

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

the class CompilationTest method testNewInstance.

@Test
public void testNewInstance() throws Exception {
    // contract: a ctclass can be instantiated, and each modification results in a new valid object
    Factory factory = new Launcher().getFactory();
    CtClass<Ifoo> c = factory.Code().createCodeSnippetStatement("class X implements spoon.test.compilation.Ifoo { public int foo() {int i=0; return i;} }").compile();
    // required otherwise java.lang.IllegalAccessException at runtime when instantiating
    c.addModifier(ModifierKind.PUBLIC);
    CtBlock body = c.getElements(new TypeFilter<>(CtBlock.class)).get(1);
    Ifoo o = c.newInstance();
    assertEquals(0, o.foo());
    for (int i = 1; i <= 10; i++) {
        body.getStatement(0).replace(factory.Code().createCodeSnippetStatement("int i = " + i + ";"));
        o = c.newInstance();
        // each time this is a new class
        // each time the behavior has changed!
        assertEquals(i, o.foo());
    }
}
Also used : CtBlock(spoon.reflect.code.CtBlock) CoreFactory(spoon.reflect.factory.CoreFactory) Factory(spoon.reflect.factory.Factory) CodeFactory(spoon.reflect.factory.CodeFactory) Launcher(spoon.Launcher) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) Test(org.junit.Test)

Example 4 with CtBlock

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

the class ConditionalTest method testNoBlockInConditionAndLoop.

@Test
public void testNoBlockInConditionAndLoop() throws Exception {
    String newLine = System.getProperty("line.separator");
    final CtType<Foo> aFoo = ModelUtils.buildClass(Foo.class);
    CtMethod<Object> method = aFoo.getMethod("m3");
    final List<CtIf> conditions = method.getElements(new TypeFilter<CtIf>(CtIf.class));
    for (int i = 0; i < conditions.size(); i++) {
        CtIf ctIf = conditions.get(i);
        // replace the block to a statement
        CtStatement then = ((CtBlock) ctIf.getThenStatement()).getStatement(0);
        ctIf.setThenStatement(then);
        if (ctIf.getElseStatement() != null) {
            CtStatement elseStatement = ((CtBlock) ctIf.getElseStatement()).getStatement(0);
            ctIf.setElseStatement(elseStatement);
        }
    }
    assertEquals("if (true)" + newLine + "    java.lang.System.out.println();" + newLine + "else if (true)" + newLine + "    java.lang.System.out.println();" + newLine + "else" + newLine + "    java.lang.System.out.println();" + newLine, method.getBody().getStatement(0).toString());
}
Also used : CtBlock(spoon.reflect.code.CtBlock) CtStatement(spoon.reflect.code.CtStatement) Foo(spoon.test.condition.testclasses.Foo) CtIf(spoon.reflect.code.CtIf) Test(org.junit.Test)

Example 5 with CtBlock

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

the class CtBodyHolderTest method checkCtBody.

private void checkCtBody(CtBodyHolder p_bodyHolder, String p_constant, int off) {
    CtStatement body = p_bodyHolder.getBody();
    assertTrue(body instanceof CtBlock<?>);
    CtBlock<?> block = (CtBlock) body;
    assertEquals(1 + off, block.getStatements().size());
    assertTrue(block.getStatement(off) instanceof CtAssignment);
    CtAssignment assignment = block.getStatement(off);
    assertEquals(p_constant, ((CtLiteral<String>) assignment.getAssignment().partiallyEvaluate()).getValue());
    Factory f = body.getFactory();
    CtStatement newStat = new CWBStatementTemplate("xx").apply(body.getParent(CtType.class));
    try {
        newStat.getParent();
        fail();
    } catch (ParentNotInitializedException e) {
    // expected exception
    }
    // try to set statement and get CtBlock
    p_bodyHolder.setBody(newStat);
    CtBlock newBlock = (CtBlock) p_bodyHolder.getBody();
    assertSame(p_bodyHolder, newBlock.getParent());
    assertSame(newBlock, newStat.getParent());
    // try to set CtBlock and get the same CtBlock
    CtStatement newStat2 = newStat.clone();
    try {
        newStat2.getParent();
        fail();
    } catch (ParentNotInitializedException e) {
    // expected exception
    }
    CtBlock newBlock2 = f.Code().createCtBlock(newStat2);
    assertSame(newBlock2, newStat2.getParent());
    try {
        newBlock2.getParent();
        fail();
    } catch (ParentNotInitializedException e) {
    // expected exception
    }
    p_bodyHolder.setBody(newBlock2);
    assertSame(newBlock2, p_bodyHolder.getBody());
    assertSame(p_bodyHolder, newBlock2.getParent());
    assertSame(newBlock2, newStat2.getParent());
}
Also used : CtAssignment(spoon.reflect.code.CtAssignment) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtBlock(spoon.reflect.code.CtBlock) CtType(spoon.reflect.declaration.CtType) CtStatement(spoon.reflect.code.CtStatement) Factory(spoon.reflect.factory.Factory) CWBStatementTemplate(spoon.test.ctBodyHolder.testclasses.CWBStatementTemplate)

Aggregations

CtBlock (spoon.reflect.code.CtBlock)37 Test (org.junit.Test)24 CtStatement (spoon.reflect.code.CtStatement)17 CtIf (spoon.reflect.code.CtIf)15 Factory (spoon.reflect.factory.Factory)15 Launcher (spoon.Launcher)13 CtMethod (spoon.reflect.declaration.CtMethod)10 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)9 CtElement (spoon.reflect.declaration.CtElement)7 CtInvocation (spoon.reflect.code.CtInvocation)5 CtTypeReference (spoon.reflect.reference.CtTypeReference)5 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)5 ArrayList (java.util.ArrayList)4 CtCodeSnippetStatement (spoon.reflect.code.CtCodeSnippetStatement)4 CtClass (spoon.reflect.declaration.CtClass)4 File (java.io.File)3 List (java.util.List)3 CtAssignment (spoon.reflect.code.CtAssignment)3 CtBinaryOperator (spoon.reflect.code.CtBinaryOperator)3 SourcePosition (spoon.reflect.cu.SourcePosition)3