Search in sources :

Example 21 with CtBlock

use of spoon.reflect.code.CtBlock 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 22 with CtBlock

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

the class DefaultJavaPrettyPrinter method visitCtIf.

@Override
public void visitCtIf(CtIf ifElement) {
    enterCtStatement(ifElement);
    printer.writeKeyword("if").writeSpace().writeSeparator("(");
    scan(ifElement.getCondition());
    printer.writeSeparator(")");
    elementPrinterHelper.writeIfOrLoopBlock(ifElement.getThenStatement());
    if (ifElement.getElseStatement() != null) {
        List<CtComment> comments = elementPrinterHelper.getComments(ifElement, CommentOffset.INSIDE);
        for (CtComment comment : comments) {
            SourcePosition thenPosition = ifElement.getThenStatement().getPosition() == null ? ((CtBlock) ifElement.getThenStatement()).getStatement(0).getPosition() : ifElement.getThenStatement().getPosition();
            if (comment.getPosition().getSourceStart() > thenPosition.getSourceEnd()) {
                elementPrinterHelper.writeComment(comment);
            }
        }
        printer.writeKeyword("else");
        elementPrinterHelper.writeIfOrLoopBlock(ifElement.getElseStatement());
    }
}
Also used : CtComment(spoon.reflect.code.CtComment) CtBlock(spoon.reflect.code.CtBlock) SourcePosition(spoon.reflect.cu.SourcePosition)

Example 23 with CtBlock

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

the class ExecutableRefTest method getInvocationFromMethod.

private CtAbstractInvocation<?> getInvocationFromMethod(String methodName) throws Exception {
    Factory factory = build(ExecutableRefTestSource.class, MyIntf.class);
    CtClass<ExecutableRefTestSource> clazz = factory.Class().get(ExecutableRefTestSource.class);
    Assert.assertNotNull(clazz);
    List<CtMethod<?>> methods = clazz.getMethodsByName(methodName);
    assertEquals(1, methods.size());
    CtMethod<?> ctMethod = methods.get(0);
    CtBlock<?> ctBody = (CtBlock<?>) ctMethod.getBody();
    Assert.assertNotNull(ctBody);
    List<CtStatement> ctStatements = ctBody.getStatements();
    assertEquals(1, ctStatements.size());
    CtStatement ctStatement = ctStatements.get(0);
    Assert.assertTrue(ctStatement instanceof CtAbstractInvocation<?>);
    return (CtAbstractInvocation<?>) ctStatement;
}
Also used : CtBlock(spoon.reflect.code.CtBlock) CtStatement(spoon.reflect.code.CtStatement) ExecutableRefTestSource(spoon.test.executable.testclasses.ExecutableRefTestSource) CtAbstractInvocation(spoon.reflect.code.CtAbstractInvocation) Factory(spoon.reflect.factory.Factory) CtMethod(spoon.reflect.declaration.CtMethod)

Example 24 with CtBlock

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

the class ReplaceParametrizedTest method testContract.

@Test
public void testContract() throws Throwable {
    List<String> problems = new ArrayList<>();
    // contract: all elements are replaceable wherever they are in the model
    // this test puts them at all possible locations
    CtType<?> toTest = typeToTest.getModelInterface();
    CtElement o = factory.Core().create((Class<? extends CtElement>) toTest.getActualClass());
    for (MetamodelProperty mmField : typeToTest.getRoleToProperty().values()) {
        Class<?> argType = mmField.getItemValueType().getActualClass();
        if (!CtElement.class.isAssignableFrom(argType)) {
            continue;
        }
        CtTypeReference<?> itemType = mmField.getItemValueType();
        // special cases...
        if (itemType.getQualifiedName().equals(CtStatement.class.getName())) {
            // the children of CtLoop wraps CtStatement into an implicit CtBlock. So make a block directly to test plain get/set and not wrapping.
            itemType = factory.createCtTypeReference(CtBlock.class);
        }
        if (o.getClass().getSimpleName().equals("CtAnnotationFieldAccessImpl") && mmField.getRole() == CtRole.VARIABLE) {
            itemType = factory.createCtTypeReference(CtFieldReference.class);
        } else if (CtFieldAccess.class.isAssignableFrom(o.getClass()) && mmField.getRole() == CtRole.VARIABLE) {
            itemType = factory.createCtTypeReference(CtFieldReference.class);
        }
        CtElement argument = (CtElement) createCompatibleObject(itemType);
        assertNotNull(argument);
        // we create a fresh object
        CtElement receiver = ((CtElement) o).clone();
        RoleHandler rh = RoleHandlerHelper.getRoleHandler(o.getClass(), mmField.getRole());
        if (mmField.isUnsettable()) {
            try {
                // we invoke the setter
                invokeSetter(rh, receiver, argument);
            } catch (SpoonException e) {
                // ok this unsettable property has no setter at all
                return;
            }
            // this unsettable property has setter, but it should do nothing
            CtRole argumentsRoleInParent = argument.getRoleInParent();
            if (argumentsRoleInParent == null) {
                // OK - unsettable property set no value
                continue;
            }
            if (argumentsRoleInParent == mmField.getRole()) {
                problems.add("UnsettableProperty " + mmField + " sets the value");
            } else {
                if (mmField.isDerived()) {
                // it is OK, that setting of value into derived unsettable field influences other field
                // Example 1: CtCatchVariable.setType(x) influences result of getMultitype()
                // Example 2: CtEnumValue.setAssignment(x) influences result of getDefaultExpression()
                } else {
                    problems.add("UnsettableProperty " + mmField + " sets the value into different role " + argumentsRoleInParent);
                }
            }
            continue;
        }
        // we invoke the setter
        invokeSetter(rh, receiver, argument);
        // contract: a property setter sets properties that are visitable by a scanner
        CtElement finalArgument = argument;
        class Scanner extends CtScanner {

            boolean found = false;

            @Override
            public void scan(CtRole role, CtElement e) {
                super.scan(role, e);
                if (e == finalArgument) {
                    if (rh.getRole() == role || rh.getRole().getSuperRole() == role) {
                        found = true;
                        return;
                    }
                    // if (rh.getRole()==CtRole.TYPE && role==CtRole.MULTI_TYPE) {
                    // //CtCatchVaraible#type sets CtCatchVaraible#multiType - OK
                    // found = true;
                    // return;
                    // }
                    problems.add("Argument was set into " + rh.getRole() + " but was found in " + role);
                }
            }
        }
        ;
        Scanner s = new Scanner();
        receiver.accept(s);
        assertTrue("Settable field " + mmField.toString() + " should set value.\n" + getReport(problems), s.found);
        // contract: a property getter on the same role can be used to get the value back
        assertSame(argument, invokeGetter(rh, receiver));
        final CtElement argument2 = argument.clone();
        assertNotSame(argument, argument2);
        // we do the replace
        argument.replace(argument2);
        // the new element is indeed now in this AST
        assertTrue(receiver.getClass().getSimpleName() + " failed for " + mmField, receiver.getElements(new Filter<CtElement>() {

            @Override
            public boolean matches(CtElement element) {
                return element == argument2;
            }
        }).size() == 1);
    }
    if (problems.size() > 0) {
        fail(getReport(problems));
    }
}
Also used : CtScanner(spoon.reflect.visitor.CtScanner) SpoonException(spoon.SpoonException) CtElement(spoon.reflect.declaration.CtElement) RoleHandler(spoon.reflect.meta.RoleHandler) ArrayList(java.util.ArrayList) CtFieldReference(spoon.reflect.reference.CtFieldReference) CtBlock(spoon.reflect.code.CtBlock) CtStatement(spoon.reflect.code.CtStatement) Filter(spoon.reflect.visitor.Filter) MetamodelProperty(spoon.test.metamodel.MetamodelProperty) CtRole(spoon.reflect.path.CtRole) CtScanner(spoon.reflect.visitor.CtScanner) Test(org.junit.Test)

Example 25 with CtBlock

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

the class SignatureTest method testLiteralSignature.

@Test
public void testLiteralSignature() {
    Factory factory = new FactoryImpl(new DefaultCoreFactory(), new StandardEnvironment());
    CtStatement sta1 = (factory).Code().createCodeSnippetStatement("System.out.println(\"hello\")").compile();
    CtStatement sta2 = (factory).Code().createCodeSnippetStatement("String hello =\"t1\"; System.out.println(hello)").compile();
    CtStatement sta2bis = ((CtBlock<?>) sta2.getParent()).getStatement(1);
    // equals depends on deep equality
    assertFalse(sta1.equals(sta2bis));
    String parameterWithQuotes = ((CtInvocation<?>) sta1).getArguments().get(0).toString();
    assertEquals("\"hello\"", parameterWithQuotes);
    (factory).Code().createCodeSnippetStatement("Integer.toBinaryString(20)").compile();
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) CtBlock(spoon.reflect.code.CtBlock) DefaultCoreFactory(spoon.support.DefaultCoreFactory) CtStatement(spoon.reflect.code.CtStatement) DefaultCoreFactory(spoon.support.DefaultCoreFactory) Factory(spoon.reflect.factory.Factory) FactoryImpl(spoon.reflect.factory.FactoryImpl) StandardEnvironment(spoon.support.StandardEnvironment) Test(org.junit.Test)

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