Search in sources :

Example 21 with CtInvocation

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

the class ParentTest method testParentOfCtVariableReference.

@Test
public void testParentOfCtVariableReference() throws Exception {
    // contract: parent of a variable reference is the element which call getVariable().
    final Factory factory = build(Tacos.class);
    final CtType<Tacos> aTacos = factory.Type().get(Tacos.class);
    final CtInvocation inv = aTacos.getMethodsByName("m3").get(0).getElements(new TypeFilter<>(CtInvocation.class)).get(0);
    final CtVariableRead<?> variableRead = (CtVariableRead<?>) inv.getArguments().get(0);
    final CtParameterReference<?> aParameterReference = (CtParameterReference<?>) variableRead.getVariable();
    assertNotNull(aParameterReference.getParent());
    assertEquals(variableRead, aParameterReference.getParent());
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) CtParameterReference(spoon.reflect.reference.CtParameterReference) Tacos(spoon.test.replace.testclasses.Tacos) Factory(spoon.reflect.factory.Factory) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) ReferenceTypeFilter(spoon.reflect.visitor.filter.ReferenceTypeFilter) CtVariableRead(spoon.reflect.code.CtVariableRead) Test(org.junit.Test)

Example 22 with CtInvocation

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

the class ParentTest method testParentSetInSetter.

@Test
// too fragile because of conventions
@Ignore
public void testParentSetInSetter() throws Exception {
    // contract: Check that all setters protect their parameter.
    final Launcher launcher = new Launcher();
    final Factory factory = launcher.getFactory();
    launcher.setArgs(new String[] { "--output-type", "nooutput" });
    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");
    // Utils.
    launcher.addInputResource("./src/test/java/spoon/reflect/ast/");
    launcher.buildModel();
    // Asserts.
    new IntercessionScanner(launcher.getFactory()) {

        @Override
        protected boolean isToBeProcessed(CtMethod<?> candidate) {
            return (// 
            candidate.getSimpleName().startsWith("set") || // 
            candidate.getSimpleName().startsWith("add")) && // 
            candidate.hasModifier(ModifierKind.PUBLIC) && // 
            takeSetterForCtElement(candidate) && // 
            avoidInterfaces(candidate) && avoidThrowUnsupportedOperationException(candidate);
        }

        @Override
        public void process(CtMethod<?> element) {
            if (element.getAnnotation(UnsettableProperty.class) != null) {
                // we don't check the contracts for unsettable setters
                return;
            }
            if (element.getSimpleName().startsWith("add")) {
                checkAddStrategy(element);
            } else {
                checkSetStrategy(element);
            }
        }

        private void checkAddStrategy(CtMethod<?> element) {
            final CtStatement statement = element.getBody().getStatement(0);
            if (!(statement instanceof CtIf)) {
                fail("First statement should be an if to check the parameter of the setter." + element.getSignature() + " declared in " + element.getDeclaringType().getQualifiedName());
            }
            if (!createCheckNull(element.getParameters().get(0)).equals(((CtIf) statement).getCondition())) {
                fail("Condition should test if the parameter is null. The condition was " + ((CtIf) statement).getCondition() + "in " + element.getSignature() + " declared in " + element.getDeclaringType().getQualifiedName());
            }
        }

        private void checkSetStrategy(CtMethod<?> element) {
            final CtTypeReference<?> type = element.getParameters().get(0).getType();
            if (!COLLECTIONS.contains(type) && !(type instanceof CtArrayTypeReference)) {
                CtInvocation<?> setParent = searchSetParent(element.getBody());
                if (setParent == null) {
                    return;
                }
                try {
                    if (setParent.getParent(CtIf.class) == null) {
                        fail("Missing condition in " + element.getSignature() + " declared in the class " + element.getDeclaringType().getQualifiedName());
                    }
                } catch (ParentNotInitializedException e) {
                    fail("Missing parent condition in " + element.getSignature() + " declared in the class " + element.getDeclaringType().getQualifiedName());
                }
            }
        }

        /**
         * Creates <code>parameter == null</code>.
         *
         * @param ctParameter <code>parameter</code>
         */
        private CtBinaryOperator<Boolean> createCheckNull(CtParameter<?> ctParameter) {
            final CtLiteral nullLiteral = factory.Code().createLiteral(null);
            nullLiteral.setType(factory.Type().NULL_TYPE.clone());
            final CtBinaryOperator<Boolean> operator = // 
            factory.Code().createBinaryOperator(// 
            factory.Code().createVariableRead(ctParameter.getReference(), true), nullLiteral, BinaryOperatorKind.EQ);
            operator.setType(factory.Type().BOOLEAN_PRIMITIVE);
            return operator;
        }

        private CtInvocation<?> searchSetParent(CtBlock<?> body) {
            final List<CtInvocation<?>> ctInvocations = body.getElements(new TypeFilter<CtInvocation<?>>(CtInvocation.class) {

                @Override
                public boolean matches(CtInvocation<?> element) {
                    return "setParent".equals(element.getExecutable().getSimpleName()) && super.matches(element);
                }
            });
            return ctInvocations.size() > 0 ? ctInvocations.get(0) : null;
        }
    }.scan(launcher.getModel().getRootPackage());
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtBinaryOperator(spoon.reflect.code.CtBinaryOperator) Factory(spoon.reflect.factory.Factory) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) ReferenceTypeFilter(spoon.reflect.visitor.filter.ReferenceTypeFilter) CtIf(spoon.reflect.code.CtIf) CtInvocation(spoon.reflect.code.CtInvocation) CtLiteral(spoon.reflect.code.CtLiteral) CtStatement(spoon.reflect.code.CtStatement) CtTypeReference(spoon.reflect.reference.CtTypeReference) Launcher(spoon.Launcher) CtStatementList(spoon.reflect.code.CtStatementList) List(java.util.List) CtArrayTypeReference(spoon.reflect.reference.CtArrayTypeReference) IntercessionScanner(spoon.test.intercession.IntercessionScanner) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 23 with CtInvocation

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

the class TypeReferenceTest method testInvocationWithFieldAccessInNoClasspath.

@Test
public void testInvocationWithFieldAccessInNoClasspath() throws Exception {
    // contract: In no classpath mode, if we have field accesses in an invocation, we should build field access and not type access.
    final Launcher launcher = new Launcher();
    launcher.addInputResource("./src/test/resources/noclasspath/Demo4.java");
    launcher.setSourceOutputDirectory("./target/class-declaration");
    launcher.getEnvironment().setNoClasspath(true);
    launcher.run();
    final CtClass<Object> demo4 = launcher.getFactory().Class().get("Demo4");
    final CtMethod<?> doSomething = demo4.getMethodsByName("doSomething").get(0);
    final CtInvocation topInvocation = doSomething.getElements(new TypeFilter<>(CtInvocation.class)).get(0);
    assertNotNull(topInvocation.getTarget());
    assertTrue(topInvocation.getTarget() instanceof CtInvocation);
    assertNotNull(((CtInvocation) topInvocation.getTarget()).getTarget());
    assertTrue(((CtInvocation) topInvocation.getTarget()).getTarget() instanceof CtFieldRead);
    assertEquals(1, topInvocation.getArguments().size());
    assertTrue(topInvocation.getArguments().get(0) instanceof CtFieldRead);
    assertEquals("a.foo().bar(b)", topInvocation.toString());
    // Class concerned by this bug.
    canBeBuilt("./src/test/resources/noclasspath/TestBot.java", 8, true);
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) CtFieldRead(spoon.reflect.code.CtFieldRead) Launcher(spoon.Launcher) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) ReferenceTypeFilter(spoon.reflect.visitor.filter.ReferenceTypeFilter) Test(org.junit.Test)

Example 24 with CtInvocation

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

the class RefactoringTest method testThisInConstructorAfterATransformation.

@Test
public void testThisInConstructorAfterATransformation() throws Exception {
    final Launcher launcher = new Launcher();
    launcher.setArgs(new String[] { "-i", "src/test/java/spoon/test/refactoring/testclasses", "-o", "target/spooned/refactoring", "-p", ThisTransformationProcessor.class.getName() });
    launcher.run();
    final CtClass<?> aClassX = (CtClass<?>) launcher.getFactory().Type().get("spoon.test.refactoring.testclasses.AClassX");
    final CtInvocation<?> thisInvocation = aClassX.getElements(new AbstractFilter<CtInvocation<?>>(CtInvocation.class) {

        @Override
        public boolean matches(CtInvocation<?> element) {
            return element.getExecutable().isConstructor();
        }
    }).get(0);
    assertEquals("this(\"\")", thisInvocation.toString());
}
Also used : CtClass(spoon.reflect.declaration.CtClass) CtInvocation(spoon.reflect.code.CtInvocation) AbstractFilter(spoon.reflect.visitor.filter.AbstractFilter) Launcher(spoon.Launcher) Test(org.junit.Test)

Example 25 with CtInvocation

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

the class DefaultPrettyPrinterTest method printerCanPrintInvocationWithoutException.

@Test
public void printerCanPrintInvocationWithoutException() throws Exception {
    String packageName = "spoon.test.subclass.prettyprinter";
    String className = "DefaultPrettyPrinterExample";
    String qualifiedName = packageName + "." + className;
    SpoonModelBuilder comp = new Launcher().createCompiler();
    List<SpoonResource> fileToBeSpooned = SpoonResourceHelper.resources("./src/test/resources/printer-test/" + qualifiedName.replace('.', '/') + ".java");
    assertEquals(1, fileToBeSpooned.size());
    comp.addInputSources(fileToBeSpooned);
    List<SpoonResource> classpath = SpoonResourceHelper.resources("./src/test/resources/printer-test/DefaultPrettyPrinterDependency.jar");
    assertEquals(1, classpath.size());
    comp.setSourceClasspath(classpath.get(0).getPath());
    comp.build();
    Factory factory = comp.getFactory();
    CtType<?> theClass = factory.Type().get(qualifiedName);
    List<CtInvocation<?>> elements = Query.getElements(theClass, new TypeFilter<CtInvocation<?>>(CtInvocation.class));
    assertEquals(3, elements.size());
    CtInvocation<?> mathAbsInvocation = elements.get(1);
    assertEquals("java.lang.Math.abs(message.length())", mathAbsInvocation.toString());
}
Also used : SpoonModelBuilder(spoon.SpoonModelBuilder) CtInvocation(spoon.reflect.code.CtInvocation) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) SpoonResource(spoon.compiler.SpoonResource) 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