Search in sources :

Example 1 with CtReturn

use of spoon.reflect.code.CtReturn 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 2 with CtReturn

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

the class CommentTest method testBlockComment.

@Test
public void testBlockComment() {
    Factory f = getSpoonFactory();
    CtClass<?> type = (CtClass<?>) f.Type().get(BlockComment.class);
    String strType = type.toString();
    List<CtComment> comments = type.getElements(new TypeFilter<CtComment>(CtComment.class));
    // verify that the number of comment present in the AST is correct
    assertEquals(51, comments.size());
    // verify that all comments present in the AST is printed
    for (CtComment comment : comments) {
        if (comment.getCommentType() == CtComment.CommentType.FILE) {
            // the header of the file is not printed with the toString
            continue;
        }
        assertNotNull(comment.getParent());
        assertTrue(comment.toString() + ":" + comment.getParent() + " is not printed", strType.contains(comment.toString()));
    }
    assertEquals(4, type.getComments().size());
    assertEquals(createFakeBlockComment(f, "comment class"), type.getComments().get(1));
    CtField<?> field = type.getField("field");
    assertEquals(2, field.getComments().size());
    assertEquals(createFakeBlockComment(f, "Comment Field"), field.getComments().get(0));
    assertEquals("/* Comment Field */" + newLine + "/* comment in field */" + newLine + "private int field = 10;", field.toString());
    CtAnonymousExecutable ctAnonymousExecutable = type.getAnonymousExecutables().get(0);
    assertEquals(1, ctAnonymousExecutable.getComments().size());
    assertEquals(createFakeBlockComment(f, "comment static block"), ctAnonymousExecutable.getComments().get(0));
    assertEquals(createFakeBlockComment(f, "comment inside static"), ctAnonymousExecutable.getBody().getStatement(0));
    assertEquals("/* comment static block */" + newLine + "static {" + newLine + "    /* comment inside static */" + newLine + "}", ctAnonymousExecutable.toString());
    CtConstructor constructor = type.getConstructor();
    assertEquals(1, constructor.getComments().size());
    assertEquals(createFakeBlockComment(f, "comment constructor"), constructor.getComments().get(0));
    // index 0 is the implicit super call
    assertEquals(createFakeBlockComment(f, "Comment in constructor"), constructor.getBody().getStatement(1));
    assertEquals("/* comment constructor */" + newLine + "public BlockComment() {" + newLine + "    /* Comment in constructor */" + newLine + "}", constructor.toString());
    CtMethod<Object> m = type.getMethod("m");
    assertEquals(1, m.getComments().size());
    assertEquals(createFakeBlockComment(f, "comment method"), m.getComments().get(0));
    assertEquals(createFakeBlockComment(f, "comment empty method block"), m.getBody().getStatement(0));
    assertEquals("/* comment method */" + newLine + "public void m() {" + newLine + "    /* comment empty method block */" + newLine + "}", m.toString());
    CtMethod<Object> m1 = type.getMethod("m1");
    CtSwitch ctSwitch = m1.getBody().getStatement(0);
    assertEquals(createFakeBlockComment(f, "comment switch"), ctSwitch.getComments().get(0));
    assertEquals("/* comment switch */" + newLine + "switch (1) {" + newLine + "    /* before first case */" + newLine + "    case 0 :" + newLine + "        /* comment case 0: empty case */" + newLine + "    case 1 :" + newLine + "        /* comment case 1 */" + newLine + "        int i = 0;" + newLine + "    default :" + newLine + "        /* comment default */" + newLine + "}", ctSwitch.toString());
    CtFor ctFor = m1.getBody().getStatement(1);
    assertEquals(createFakeBlockComment(f, "comment for"), ctFor.getComments().get(0));
    assertEquals("/* comment for */" + newLine + "for (int i = 0; i < 10; i++) {" + newLine + "    /* comment for block */" + newLine + "}", ctFor.toString());
    CtIf ctIf = m1.getBody().getStatement(2);
    assertEquals(createFakeBlockComment(f, "comment if"), ctIf.getComments().get(0));
    assertEquals("/* comment if */" + newLine + "if ((1 % 2) == 0) {" + newLine + "    /* comment unary operator */" + newLine + "    (field)++;" + newLine + "}", ctIf.toString());
    CtConstructorCall ctConstructorCall = m1.getBody().getStatement(3);
    assertEquals(createFakeBlockComment(f, "comment constructor call"), ctConstructorCall.getComments().get(0));
    assertEquals("/* comment constructor call */" + newLine + "new spoon.test.comment.testclasses.BlockComment()", ctConstructorCall.toString());
    CtInvocation ctInvocation = m1.getBody().getStatement(4);
    assertEquals(createFakeBlockComment(f, "comment invocation"), ctInvocation.getComments().get(0));
    assertEquals("/* comment invocation */" + newLine + "this.m()", ctInvocation.toString());
    CtLocalVariable ctLocalVariable = m1.getBody().getStatement(5);
    assertEquals(createFakeBlockComment(f, "comment local variable"), ctLocalVariable.getComments().get(0));
    assertEquals("/* comment local variable */" + newLine + "int i = 0", ctLocalVariable.toString());
    CtLocalVariable ctLocalVariable2 = m1.getBody().getStatement(6);
    assertEquals(createFakeBlockComment(f, "comment multi assignments"), ctLocalVariable2.getComments().get(0));
    assertEquals("/* comment multi assignments */" + newLine + "int j = 2", ctLocalVariable2.toString());
    CtDo ctDo = m1.getBody().getStatement(7);
    assertEquals(createFakeBlockComment(f, "comment dowhile"), ctDo.getComments().get(0));
    assertEquals("/* comment dowhile */" + newLine + "do {" + newLine + "    /* comment in do while */" + newLine + "    i++;" + newLine + "    /* comment end do while */" + newLine + "} while (i < 10 )", ctDo.toString());
    CtTry ctTry = m1.getBody().getStatement(8);
    assertEquals(createFakeBlockComment(f, "comment try"), ctTry.getComments().get(0));
    assertEquals("/* comment try */" + newLine + "try {" + newLine + "    /* comment in try */" + newLine + "    i++;" + newLine + "} catch (java.lang.Exception e) {" + newLine + "    /* comment in catch */" + newLine + "}", ctTry.toString());
    CtSynchronized ctSynchronized = m1.getBody().getStatement(9);
    assertEquals(createFakeBlockComment(f, "comment synchronized"), ctSynchronized.getComments().get(0));
    assertEquals("/* comment synchronized */" + newLine + "synchronized(this) {" + newLine + "    /* comment in synchronized */" + newLine + "}", ctSynchronized.toString());
    CtReturn ctReturn = m1.getBody().getStatement(10);
    assertEquals(createFakeBlockComment(f, "comment return"), ctReturn.getComments().get(0));
    assertEquals("/* comment return */" + newLine + "return", ctReturn.toString());
    CtMethod m2 = type.getMethodsByName("m2").get(0);
    assertEquals(6, m2.getComments().size());
    CtParameter ctParameter = (CtParameter) m2.getParameters().get(0);
    assertEquals(4, ctParameter.getComments().size());
    assertEquals("/* comment before type */" + newLine + "/* comment after parameter */" + newLine + "/* comment before throws */" + newLine + "/* comment before exception 1 */" + newLine + "/* comment before exception 2 */" + newLine + "/* comment before block */" + newLine + "public void m2(/* comment before name */" + newLine + "/* comment before parameters */" + newLine + "/* comment before type parameter */" + newLine + "/* comment before name parameter */" + newLine + "int i) throws java.lang.Error, java.lang.Exception {" + newLine + "}", m2.toString());
}
Also used : CtComment(spoon.reflect.code.CtComment) CtSwitch(spoon.reflect.code.CtSwitch) DefaultCoreFactory(spoon.support.DefaultCoreFactory) Factory(spoon.reflect.factory.Factory) CtParameter(spoon.reflect.declaration.CtParameter) CtTry(spoon.reflect.code.CtTry) CtSynchronized(spoon.reflect.code.CtSynchronized) CtInvocation(spoon.reflect.code.CtInvocation) CtReturn(spoon.reflect.code.CtReturn) CtDo(spoon.reflect.code.CtDo) CtFor(spoon.reflect.code.CtFor) BlockComment(spoon.test.comment.testclasses.BlockComment) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtIf(spoon.reflect.code.CtIf) CtConstructor(spoon.reflect.declaration.CtConstructor) CtClass(spoon.reflect.declaration.CtClass) CtConstructorCall(spoon.reflect.code.CtConstructorCall) CtAnonymousExecutable(spoon.reflect.declaration.CtAnonymousExecutable) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Example 3 with CtReturn

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

the class CUFilterTest method testSingleExcludeWithFilter.

@Test
public void testSingleExcludeWithFilter() {
    final Launcher launcher = new Launcher();
    launcher.getEnvironment().setNoClasspath(true);
    launcher.addInputResource("./src/test/resources/noclasspath/same-package");
    launcher.getModelBuilder().addCompilationUnitFilter(new CompilationUnitFilter() {

        @Override
        public boolean exclude(final String path) {
            return path.endsWith("B.java");
        }
    });
    launcher.buildModel();
    final CtModel model = launcher.getModel();
    assertEquals(1, model.getAllTypes().size());
    // make sure `B` is not available in `model.getAllTypes`
    assertEquals("A", model.getAllTypes().iterator().next().getSimpleName());
    // make sure declaration of `B` is known in `model`
    final CtReturn ctReturn = model.getAllTypes().iterator().next().getMethod("createB").getBody().getStatement(0);
    final CtConstructorCall ctConstructorCall = (CtConstructorCall) ctReturn.getReturnedExpression();
    assertEquals("spoon.test.same.B", ctConstructorCall.getType().getQualifiedName());
}
Also used : CompilationUnitFilter(spoon.support.compiler.jdt.CompilationUnitFilter) CtReturn(spoon.reflect.code.CtReturn) CtConstructorCall(spoon.reflect.code.CtConstructorCall) Launcher(spoon.Launcher) CtModel(spoon.reflect.CtModel) Test(org.junit.Test)

Example 4 with CtReturn

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

the class GenericsTest method testCannotAdaptTypeOfNonTypeScope.

@Test
public void testCannotAdaptTypeOfNonTypeScope() throws Exception {
    // contract: ClassTypingContext doesn't fail on type parameters, which are defined out of the scope of ClassTypingContext
    CtType<?> ctClass = ModelUtils.buildClass(OuterTypeParameter.class);
    // the method defines type parameter, which is used in super of local class
    CtReturn<?> retStmt = (CtReturn<?>) ctClass.getMethodsByName("method").get(0).getBody().getStatements().get(0);
    CtNewClass<?> newClassExpr = (CtNewClass<?>) retStmt.getReturnedExpression();
    CtType<?> declaringType = newClassExpr.getAnonymousClass();
    CtMethod<?> m1 = declaringType.getMethodsByName("iterator").get(0);
    ClassTypingContext c = new ClassTypingContext(declaringType);
    // the adaptation of such type parameter keeps that parameter as it is.
    assertFalse(c.isOverriding(m1, declaringType.getSuperclass().getTypeDeclaration().getMethodsByName("add").get(0)));
    assertTrue(c.isOverriding(m1, declaringType.getSuperclass().getTypeDeclaration().getMethodsByName("iterator").get(0)));
}
Also used : ClassTypingContext(spoon.support.visitor.ClassTypingContext) CtReturn(spoon.reflect.code.CtReturn) CtNewClass(spoon.reflect.code.CtNewClass) MainTest(spoon.test.main.MainTest) Test(org.junit.Test)

Example 5 with CtReturn

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

the class VisitorPartialEvaluator method visitCtInvocation.

public <T> void visitCtInvocation(CtInvocation<T> invocation) {
    CtInvocation<T> i = invocation.getFactory().Core().createInvocation();
    i.setExecutable(invocation.getExecutable());
    i.setTypeCasts(invocation.getTypeCasts());
    boolean constant = true;
    i.setTarget(evaluate(invocation.getTarget()));
    if ((i.getTarget() != null) && !(i.getTarget() instanceof CtLiteral)) {
        constant = false;
    }
    for (CtExpression<?> e : invocation.getArguments()) {
        CtExpression<?> re = evaluate(e);
        if (!(re instanceof CtLiteral)) {
            constant = false;
        }
        i.addArgument(re);
    }
    // do not partially evaluate super(...)
    if (i.getExecutable().getSimpleName().equals(CtExecutableReference.CONSTRUCTOR_NAME)) {
        setResult(i);
        return;
    }
    if (constant) {
        CtExecutable<?> executable = invocation.getExecutable().getDeclaration();
        CtType<?> aType = invocation.getParent(CtType.class);
        CtTypeReference<?> execDeclaringType = invocation.getExecutable().getDeclaringType();
        // (including to superclasses)
        if (executable != null && aType != null && invocation.getType() != null && execDeclaringType != null && execDeclaringType.isSubtypeOf(aType.getReference())) {
            CtBlock<?> b = evaluate(executable.getBody());
            flowEnded = false;
            CtStatement last = b.getStatements().get(b.getStatements().size() - 1);
            if ((last != null) && (last instanceof CtReturn)) {
                if (((CtReturn<?>) last).getReturnedExpression() instanceof CtLiteral) {
                    setResult(((CtReturn<?>) last).getReturnedExpression());
                    return;
                }
            }
        } else {
            // try to completely evaluate
            T r = null;
            try {
                // System.err.println("invocking "+i);
                r = RtHelper.invoke(i);
                if (isLiteralType(r)) {
                    CtLiteral<T> l = invocation.getFactory().Core().createLiteral();
                    l.setValue(r);
                    setResult(l);
                    return;
                }
            } catch (Exception e) {
            }
        }
    }
    setResult(i);
}
Also used : CtLiteral(spoon.reflect.code.CtLiteral) CtStatement(spoon.reflect.code.CtStatement) CtReturn(spoon.reflect.code.CtReturn)

Aggregations

CtReturn (spoon.reflect.code.CtReturn)12 Test (org.junit.Test)9 Launcher (spoon.Launcher)5 CtConstructorCall (spoon.reflect.code.CtConstructorCall)5 CtClass (spoon.reflect.declaration.CtClass)5 Factory (spoon.reflect.factory.Factory)5 CtMethod (spoon.reflect.declaration.CtMethod)4 CtInvocation (spoon.reflect.code.CtInvocation)3 CtStatement (spoon.reflect.code.CtStatement)3 CtModel (spoon.reflect.CtModel)2 CtBinaryOperator (spoon.reflect.code.CtBinaryOperator)2 CtBlock (spoon.reflect.code.CtBlock)2 CtComment (spoon.reflect.code.CtComment)2 CtDo (spoon.reflect.code.CtDo)2 CtExpression (spoon.reflect.code.CtExpression)2 CtFor (spoon.reflect.code.CtFor)2 CtIf (spoon.reflect.code.CtIf)2 CtLiteral (spoon.reflect.code.CtLiteral)2 CtLocalVariable (spoon.reflect.code.CtLocalVariable)2 CtSwitch (spoon.reflect.code.CtSwitch)2