Search in sources :

Example 16 with CtInvocation

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

the class ReplaceScanner method updateSetter.

private void updateSetter(Factory factory, CtMethod<?> setListener, CtTypeReference getterType, CtField<?> field, CtMethod setter) {
    setListener.getParameters().get(0).setType(getterType);
    CtInvocation ctInvocation = // 
    factory.Code().createInvocation(// 
    factory.Code().createVariableRead(field.getReference(), false), // 
    setter.getReference(), // 
    factory.Code().createVariableRead(setListener.getParameters().get(0).getReference(), false));
    CtBlock ctBlock = factory.Code().createCtBlock(ctInvocation);
    setListener.setBody(ctBlock);
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) CtBlock(spoon.reflect.code.CtBlock)

Example 17 with CtInvocation

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

the class TemplateMatcher method getMethods.

/**
 * Searches for all invocations of {@link TemplateParameter#S()} in "root", a CtClass model of {@link Template}
 *
 * @param root CtClass model of {@link Template}
 */
private List<CtInvocation<?>> getMethods(CtClass<? extends Template<?>> root) {
    CtExecutableReference<?> methodRef = root.getFactory().Executable().createReference(root.getFactory().Type().createReference(TemplateParameter.class), root.getFactory().Type().createTypeParameterReference("T"), "S");
    List<CtInvocation<?>> meths = Query.getElements(root, new InvocationFilter(methodRef));
    return meths;
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) InvocationFilter(spoon.reflect.visitor.filter.InvocationFilter)

Example 18 with CtInvocation

use of spoon.reflect.code.CtInvocation 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 19 with CtInvocation

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

the class InvocationTest method testTypeOfStaticInvocation.

@Test
public void testTypeOfStaticInvocation() throws Exception {
    SpoonAPI launcher = new Launcher();
    launcher.run(new String[] { "-i", "./src/test/java/spoon/test/invocations/testclasses/", "-o", "./target/spooned/" });
    Factory factory = launcher.getFactory();
    CtClass<?> aClass = factory.Class().get(Foo.class);
    final List<CtInvocation<?>> elements = aClass.getElements(new AbstractFilter<CtInvocation<?>>(CtInvocation.class) {

        @Override
        public boolean matches(CtInvocation<?> element) {
            return element.getTarget() != null;
        }
    });
    assertEquals(2, elements.size());
    assertTrue(elements.get(0).getTarget() instanceof CtTypeAccess);
    assertTrue(elements.get(1).getTarget() instanceof CtTypeAccess);
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) CtTypeAccess(spoon.reflect.code.CtTypeAccess) SpoonAPI(spoon.SpoonAPI) Test(org.junit.Test)

Example 20 with CtInvocation

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

the class MethodReferenceTest method testGetGenericMethodFromReference.

@Test
public void testGetGenericMethodFromReference() throws Exception {
    CtType<?> classCloud = ModelUtils.buildClass(Cloud.class);
    CtMethod<?> ctMethod = classCloud.getMethodsByName("method").get(0);
    CtExecutableReference<?> execRef = ctMethod.getReference();
    Method method = execRef.getActualMethod();
    assertNotNull(method);
    assertEquals("method", method.getName());
    CtClass<?> classSun = classCloud.getFactory().Class().get("spoon.test.methodreference.testclasses.Sun");
    // CtExecutableReference<?> execRef2 = classSun.filterChildren(new TypeFilter<>(CtExecutableReference.class)).select(new NameFilter<>("method")).first();
    CtExecutableReference<?> execRef2 = classSun.filterChildren(new TypeFilter<>(CtInvocation.class)).select(((CtInvocation i) -> i.getExecutable().getSimpleName().equals("method"))).map((CtInvocation i) -> i.getExecutable()).first();
    assertNotNull(execRef2);
    Method method2 = execRef2.getActualMethod();
    assertNotNull(method2);
    assertEquals("method", method2.getName());
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) Method(java.lang.reflect.Method) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Aggregations

CtInvocation (spoon.reflect.code.CtInvocation)64 Test (org.junit.Test)49 Factory (spoon.reflect.factory.Factory)30 Launcher (spoon.Launcher)27 CtMethod (spoon.reflect.declaration.CtMethod)25 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)25 CtClass (spoon.reflect.declaration.CtClass)18 CtTypeReference (spoon.reflect.reference.CtTypeReference)11 List (java.util.List)9 CtExecutableReference (spoon.reflect.reference.CtExecutableReference)9 ReferenceTypeFilter (spoon.reflect.visitor.filter.ReferenceTypeFilter)9 CtStatement (spoon.reflect.code.CtStatement)8 CtBlock (spoon.reflect.code.CtBlock)7 CtElement (spoon.reflect.declaration.CtElement)7 CtIf (spoon.reflect.code.CtIf)6 CtLiteral (spoon.reflect.code.CtLiteral)6 AbstractTest (fr.inria.AbstractTest)5 InputProgram (fr.inria.diversify.utils.sosiefier.InputProgram)5 ArrayList (java.util.ArrayList)5 Arrays (java.util.Arrays)5