Search in sources :

Example 56 with CtStatement

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

the class ReplaceTest method testReplaceBlock.

@Test
public void testReplaceBlock() throws Exception {
    CtClass<?> foo = factory.Package().get("spoon.test.replace.testclasses").getType("Foo");
    CtMethod<?> m = foo.getElements(new NamedElementFilter<>(CtMethod.class, "foo")).get(0);
    assertEquals("foo", m.getSimpleName());
    final CtStatement parent = m.getBody().getStatements().get(2);
    CtAssignment<?, ?> assignment = (CtAssignment<?, ?>) parent;
    CtExpression<Integer> s1 = (CtExpression<Integer>) assignment.getAssignment();
    CtExpression<Integer> s2 = factory.Code().createLiteral(3);
    assertEquals("z = x + 1", assignment.toString());
    assertEquals("x + 1", s1.toString());
    // do
    s1.replace(s2);
    assertSame(s2, assignment.getAssignment());
    assertEquals("z = 3", assignment.toString());
    assertEquals(parent, s2.getParent());
    // undo
    s2.replace(s1);
    assertSame(s1, assignment.getAssignment());
    assertEquals("z = x + 1", assignment.toString());
    assertEquals(parent, s1.getParent());
}
Also used : CtAssignment(spoon.reflect.code.CtAssignment) CtStatement(spoon.reflect.code.CtStatement) CtExpression(spoon.reflect.code.CtExpression) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) Test(org.junit.Test)

Example 57 with CtStatement

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

the class VariableReferencesTest method testPotentialVariableAccessFromStaticMethod.

@Test
public void testPotentialVariableAccessFromStaticMethod() throws Exception {
    Factory factory = ModelUtils.build(VariableReferencesFromStaticMethod.class);
    CtClass<?> clazz = factory.Class().get(VariableReferencesFromStaticMethod.class);
    CtMethod staticMethod = clazz.getMethodsByName("staticMethod").get(0);
    CtStatement stmt = staticMethod.getBody().getStatements().get(1);
    assertEquals("org.junit.Assert.assertTrue((field == 2))", stmt.toString());
    CtLocalVariableReference varRef = stmt.filterChildren(new TypeFilter<>(CtLocalVariableReference.class)).first();
    List<CtVariable> vars = varRef.map(new PotentialVariableDeclarationFunction()).list();
    assertEquals("Found unexpected variable declaration.", 1, vars.size());
}
Also used : CtStatement(spoon.reflect.code.CtStatement) CtLocalVariableReference(spoon.reflect.reference.CtLocalVariableReference) CtVariable(spoon.reflect.declaration.CtVariable) PotentialVariableDeclarationFunction(spoon.reflect.visitor.filter.PotentialVariableDeclarationFunction) Factory(spoon.reflect.factory.Factory) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtMethod(spoon.reflect.declaration.CtMethod) VariableReferencesModelTest(spoon.test.query_function.testclasses.VariableReferencesModelTest) Test(org.junit.Test)

Example 58 with CtStatement

use of spoon.reflect.code.CtStatement 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)

Example 59 with CtStatement

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

the class SignatureTest method testMethodInvocationSignatureStaticFieldsVariables.

@Test
public void testMethodInvocationSignatureStaticFieldsVariables() {
    Factory factory = new FactoryImpl(new DefaultCoreFactory(), new StandardEnvironment());
    CtStatement sta1 = (factory).Code().createCodeSnippetStatement("Integer.toBinaryString(Integer.MAX_VALUE)").compile();
    CtStatement sta2 = (factory).Code().createCodeSnippetStatement("Integer.toBinaryString(Integer.MIN_VALUE)").compile();
    String signature1 = ((CtInvocation) sta1).getExecutable().getSignature();
    String signature2 = ((CtInvocation) sta2).getExecutable().getSignature();
    assertEquals(signature1, signature2);
    assertFalse(sta1.equals(sta2));
    CtStatement stb1 = (factory).Code().createCodeSnippetStatement("Integer.toBinaryString(20)").compile();
    CtStatement stb2 = (factory).Code().createCodeSnippetStatement("Integer.toBinaryString(30)").compile();
    String signature1b = ((CtInvocation) sta1).getExecutable().getSignature();
    String signature2b = ((CtInvocation) sta2).getExecutable().getSignature();
    assertEquals(signature1b, signature2b);
    assertFalse(stb1.equals(stb2));
    CtStatement stc1 = (factory).Code().createCodeSnippetStatement("String.format(\"format1\",\"f2\" )").compile();
    CtStatement stc2 = (factory).Code().createCodeSnippetStatement("String.format(\"format2\",\"f2\" )").compile();
    String signaturestc1 = ((CtInvocation) sta1).getExecutable().getSignature();
    String signaturestc2 = ((CtInvocation) sta2).getExecutable().getSignature();
    assertEquals(signaturestc1, signaturestc2);
    assertFalse(stc1.equals(stc2));
}
Also used : 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)

Example 60 with CtStatement

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

the class APITest method testSetterInNodes.

@Test
public void testSetterInNodes() throws Exception {
    // that the new value is != null to avoid NPE when we set the parent.
    class SetterMethodWithoutCollectionsFilter extends TypeFilter<CtMethod<?>> {

        private final List<CtTypeReference<?>> collections = new ArrayList<>(4);

        public SetterMethodWithoutCollectionsFilter(Factory factory) {
            super(CtMethod.class);
            for (Class<?> aCollectionClass : Arrays.asList(Collection.class, List.class, Map.class, Set.class)) {
                collections.add(factory.Type().createReference(aCollectionClass));
            }
        }

        @Override
        public boolean matches(CtMethod<?> element) {
            boolean isSetter = isSetterMethod(element);
            boolean isNotSubType = !isSubTypeOfCollection(element);
            // setter with unsettableProperty should not respect the contract, as well as derived properties
            boolean doesNotHaveUnsettableAnnotation = doesNotHaveUnsettableAnnotation(element);
            boolean isNotSetterForADerivedProperty = isNotSetterForADerivedProperty(element);
            boolean superMatch = super.matches(element);
            return isSetter && doesNotHaveUnsettableAnnotation && isNotSetterForADerivedProperty && isNotSubType && superMatch;
        }

        private boolean isNotSetterForADerivedProperty(CtMethod<?> method) {
            String methodName = method.getSimpleName();
            String getterName = methodName.replace("set", "get");
            if (getterName.equals(methodName)) {
                return false;
            }
            CtType<?> zeClass = (CtType) method.getParent();
            List<CtMethod<?>> getterMethods = zeClass.getMethodsByName(getterName);
            if (getterMethods.size() != 1) {
                return false;
            }
            CtMethod<?> getterMethod = getterMethods.get(0);
            return (getterMethod.getAnnotation(DerivedProperty.class) == null);
        }

        private boolean doesNotHaveUnsettableAnnotation(CtMethod<?> element) {
            return (element.getAnnotation(UnsettableProperty.class) == null);
        }

        private boolean isSubTypeOfCollection(CtMethod<?> element) {
            final List<CtParameter<?>> parameters = element.getParameters();
            if (parameters.size() != 1) {
                return false;
            }
            final CtTypeReference<?> type = parameters.get(0).getType();
            for (CtTypeReference<?> aCollectionRef : collections) {
                if (type.isSubtypeOf(aCollectionRef) || type.equals(aCollectionRef)) {
                    return true;
                }
            }
            return false;
        }

        private boolean isSetterMethod(CtMethod<?> element) {
            final List<CtParameter<?>> parameters = element.getParameters();
            if (parameters.size() != 1) {
                return false;
            }
            final CtTypeReference<?> typeParameter = parameters.get(0).getType();
            final CtTypeReference<CtElement> ctElementRef = element.getFactory().Type().createReference(CtElement.class);
            // isSubtypeOf will return true in case of equality
            boolean isSubtypeof = typeParameter.isSubtypeOf(ctElementRef);
            if (!isSubtypeof) {
                return false;
            }
            return element.getSimpleName().startsWith("set") && element.getDeclaringType().getSimpleName().startsWith("Ct") && element.getBody() != null;
        }
    }
    class CheckNotNullToSetParentMatcher extends CtElementImpl {

        public TemplateParameter<CtVariableAccess<?>> _parameter_access_;

        public void matcher() {
            if (_parameter_access_.S() != null) {
                _parameter_access_.S().setParent(this);
            }
        }

        @Override
        @Local
        public void accept(CtVisitor visitor) {
        }
    }
    final Launcher launcher = new Launcher();
    launcher.setArgs(new String[] { "--output-type", "nooutput" });
    launcher.getEnvironment().setNoClasspath(true);
    // 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.addInputResource("./src/test/java/" + this.getClass().getCanonicalName().replace(".", "/") + ".java");
    // Needed for #isSubTypeOf method.
    launcher.addInputResource("./src/main/java/spoon/reflect/");
    launcher.buildModel();
    // Template matcher.
    CtClass<CheckNotNullToSetParentMatcher> matcherCtClass = launcher.getFactory().Class().get(CheckNotNullToSetParentMatcher.class);
    CtIf templateRoot = matcherCtClass.getMethod("matcher").getBody().getStatement(0);
    final List<CtMethod<?>> setters = Query.getElements(launcher.getFactory(), new SetterMethodWithoutCollectionsFilter(launcher.getFactory()));
    assertTrue("Number of setters found null", setters.size() > 0);
    for (CtStatement statement : setters.stream().map((Function<CtMethod<?>, CtStatement>) ctMethod -> ctMethod.getBody().getStatement(0)).collect(Collectors.toList())) {
        // First statement should be a condition to protect the setter of the parent.
        assertTrue("Check the method " + statement.getParent(CtMethod.class).getSignature() + " in the declaring class " + statement.getParent(CtType.class).getQualifiedName(), statement instanceof CtIf);
        CtIf ifCondition = (CtIf) statement;
        TemplateMatcher matcher = new TemplateMatcher(templateRoot);
        assertEquals("Check the number of if in method " + statement.getParent(CtMethod.class).getSignature() + " in the declaring class " + statement.getParent(CtType.class).getQualifiedName(), 1, matcher.find(ifCondition).size());
    }
}
Also used : Factory(spoon.reflect.factory.Factory) CtParameter(spoon.reflect.declaration.CtParameter) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) Function(java.util.function.Function) CtStatement(spoon.reflect.code.CtStatement) List(java.util.List) ArrayList(java.util.ArrayList) CtVisitor(spoon.reflect.visitor.CtVisitor) CtElement(spoon.reflect.declaration.CtElement) CtIf(spoon.reflect.code.CtIf) TemplateParameter(spoon.template.TemplateParameter) CtElementImpl(spoon.support.reflect.declaration.CtElementImpl) CtType(spoon.reflect.declaration.CtType) TemplateMatcher(spoon.template.TemplateMatcher) Launcher(spoon.Launcher) 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