Search in sources :

Example 11 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class FilterTest method testInvalidQueryStepFailurePolicyIgnore.

@Test
public void testInvalidQueryStepFailurePolicyIgnore() throws Exception {
    // contract: with QueryFailurePolicy.IGNORE, no exception is thrown
    // and only valid elements are kept for the next step
    final Launcher launcher = new Launcher();
    launcher.setArgs(new String[] { "--output-type", "nooutput", "--level", "info" });
    launcher.addInputResource("./src/test/java/spoon/test/filters/testclasses");
    launcher.run();
    class Context {

        int count = 0;
    }
    Context context = new Context();
    launcher.getFactory().Package().getRootPackage().filterChildren((CtElement c) -> {
        return true;
    }).name("step1").map((CtMethod<?> m) -> m).name("invalidStep2").map((o) -> o).name("step3").failurePolicy(QueryFailurePolicy.IGNORE).forEach((CtElement c) -> {
        assertTrue(c instanceof CtMethod);
        context.count++;
    });
    assertTrue(context.count > 0);
}
Also used : Arrays(java.util.Arrays) Launcher(spoon.Launcher) CtSwitch(spoon.reflect.code.CtSwitch) CtInterface(spoon.reflect.declaration.CtInterface) CtConsumableFunction(spoon.reflect.visitor.chain.CtConsumableFunction) Tostada(spoon.test.filters.testclasses.Tostada) CtNamedElement(spoon.reflect.declaration.CtNamedElement) CtQueryImpl(spoon.reflect.visitor.chain.CtQueryImpl) CtType(spoon.reflect.declaration.CtType) QueryFailurePolicy(spoon.reflect.visitor.chain.QueryFailurePolicy) CtElement(spoon.reflect.declaration.CtElement) ReturnOrThrowFilter(spoon.reflect.visitor.filter.ReturnOrThrowFilter) FieldAccessFilterTacos(spoon.test.filters.testclasses.FieldAccessFilterTacos) OverridingMethodFilter(spoon.reflect.visitor.filter.OverridingMethodFilter) DeepRepresentationComparator(spoon.support.comparator.DeepRepresentationComparator) Assert.fail(org.junit.Assert.fail) CtMethodImpl(spoon.support.reflect.declaration.CtMethodImpl) CtExecutable(spoon.reflect.declaration.CtExecutable) Query(spoon.reflect.visitor.Query) CompositeFilter(spoon.reflect.visitor.filter.CompositeFilter) CtQuery(spoon.reflect.visitor.chain.CtQuery) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtScannerFunction(spoon.reflect.visitor.filter.CtScannerFunction) ModelUtils.build(spoon.testing.utils.ModelUtils.build) CtField(spoon.reflect.declaration.CtField) Predicate(java.util.function.Predicate) Collection(java.util.Collection) QualifiedNameComparator(spoon.support.comparator.QualifiedNameComparator) Antojito(spoon.test.filters.testclasses.Antojito) ModelUtils(spoon.testing.utils.ModelUtils) Collectors(java.util.stream.Collectors) CtModule(spoon.reflect.declaration.CtModule) Constants(spoon.test.imports.testclasses.internal4.Constants) CtFieldAccess(spoon.reflect.code.CtFieldAccess) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) LineFilter(spoon.reflect.visitor.filter.LineFilter) List(java.util.List) AnnotationFilter(spoon.reflect.visitor.filter.AnnotationFilter) Assert.assertFalse(org.junit.Assert.assertFalse) CtMethod(spoon.reflect.declaration.CtMethod) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtIf(spoon.reflect.code.CtIf) ITostada(spoon.test.filters.testclasses.ITostada) SubInheritanceHierarchyResolver(spoon.support.visitor.SubInheritanceHierarchyResolver) CtPackage(spoon.reflect.declaration.CtPackage) TreeSet(java.util.TreeSet) CtStatement(spoon.reflect.code.CtStatement) AbstractTostada(spoon.test.filters.testclasses.AbstractTostada) ArrayList(java.util.ArrayList) Assert.assertSame(org.junit.Assert.assertSame) CtExecutableReference(spoon.reflect.reference.CtExecutableReference) SubTostada(spoon.test.filters.testclasses.SubTostada) CtExpression(spoon.reflect.code.CtExpression) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) CtNewClass(spoon.reflect.code.CtNewClass) Filter(spoon.reflect.visitor.Filter) FieldAccessFilter(spoon.reflect.visitor.filter.FieldAccessFilter) ScanningMode(spoon.reflect.visitor.chain.ScanningMode) InvocationFilter(spoon.reflect.visitor.filter.InvocationFilter) Before(org.junit.Before) CtLoop(spoon.reflect.code.CtLoop) CtScannerListener(spoon.reflect.visitor.chain.CtScannerListener) Iterator(java.util.Iterator) CtInvocation(spoon.reflect.code.CtInvocation) Assert.assertNotNull(org.junit.Assert.assertNotNull) OverriddenMethodFilter(spoon.reflect.visitor.filter.OverriddenMethodFilter) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Factory(spoon.reflect.factory.Factory) CtVariable(spoon.reflect.declaration.CtVariable) OverriddenMethodQuery(spoon.reflect.visitor.filter.OverriddenMethodQuery) Tacos(spoon.test.filters.testclasses.Tacos) AbstractFilter(spoon.reflect.visitor.filter.AbstractFilter) FilteringOperator(spoon.reflect.visitor.filter.FilteringOperator) CtTypeReference(spoon.reflect.reference.CtTypeReference) Assert.assertNull(org.junit.Assert.assertNull) ParentFunction(spoon.reflect.visitor.filter.ParentFunction) CtCFlowBreak(spoon.reflect.code.CtCFlowBreak) CtConsumer(spoon.reflect.visitor.chain.CtConsumer) CtClass(spoon.reflect.declaration.CtClass) ModifierKind(spoon.reflect.declaration.ModifierKind) CtFieldReference(spoon.reflect.reference.CtFieldReference) RegexFilter(spoon.reflect.visitor.filter.RegexFilter) Comparator(java.util.Comparator) Assert.assertEquals(org.junit.Assert.assertEquals) CtFunction(spoon.reflect.visitor.chain.CtFunction) CtElement(spoon.reflect.declaration.CtElement) Launcher(spoon.Launcher) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Example 12 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class FilterTest method testFilterQueryStep.

@Test
public void testFilterQueryStep() throws Exception {
    final Launcher launcher = new Launcher();
    launcher.setArgs(new String[] { "--output-type", "nooutput", "--level", "info" });
    launcher.addInputResource("./src/test/java/spoon/test/filters/testclasses");
    launcher.run();
    // Contract: the filter(Filter) can be used to detect if input of query step should pass to next query step.
    List<CtElement> realList = launcher.getFactory().Package().getRootPackage().filterChildren(e -> {
        return true;
    }).select(new TypeFilter<>(CtClass.class)).list();
    List<CtElement> expectedList = launcher.getFactory().Package().getRootPackage().filterChildren(new TypeFilter<>(CtClass.class)).list();
    assertArrayEquals(expectedList.toArray(), realList.toArray());
    assertTrue(expectedList.size() > 0);
}
Also used : CtElement(spoon.reflect.declaration.CtElement) Launcher(spoon.Launcher) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) Test(org.junit.Test)

Example 13 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class TemplateTest method testTemplateMatcherWithWholePackage.

@Test
public void testTemplateMatcherWithWholePackage() throws Exception {
    Launcher spoon = new Launcher();
    spoon.addInputResource("./src/test/java/spoon/test/template/testclasses/ContextHelper.java");
    spoon.addInputResource("./src/test/java/spoon/test/template/testclasses/BServiceImpl.java");
    spoon.addTemplateResource(new FileSystemFile("./src/test/java/spoon/test/template/testclasses/SecurityCheckerTemplate.java"));
    spoon.buildModel();
    Factory factory = spoon.getFactory();
    CtClass<?> templateKlass = factory.Class().get(SecurityCheckerTemplate.class);
    CtMethod templateMethod = (CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher1")).get(0);
    CtIf templateRoot = (CtIf) templateMethod.getBody().getStatement(0);
    TemplateMatcher matcher = new TemplateMatcher(templateRoot);
    List<CtElement> matches = matcher.find(factory.getModel().getRootPackage());
    assertEquals(1, matches.size());
    CtElement match = matches.get(0);
    assertTrue("Match is not a if", match instanceof CtIf);
    CtElement matchParent = match.getParent();
    assertTrue("Match parent is not a block", matchParent instanceof CtBlock);
    CtElement matchParentParent = matchParent.getParent();
    assertTrue("Match grand parent is not a method", matchParentParent instanceof CtMethod);
    CtMethod methodHello = (CtMethod) matchParentParent;
    assertEquals("Match grand parent is not a method called hello", "hello", methodHello.getSimpleName());
    CtElement methodParent = methodHello.getParent();
    assertTrue("Parent of the method is not a class", methodParent instanceof CtClass);
    CtClass bservice = (CtClass) methodParent;
    assertEquals("Parent of the method is not a class called BServiceImpl", "BServiceImpl", bservice.getSimpleName());
}
Also used : CtClass(spoon.reflect.declaration.CtClass) CtBlock(spoon.reflect.code.CtBlock) CtElement(spoon.reflect.declaration.CtElement) TemplateMatcher(spoon.template.TemplateMatcher) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) FileSystemFile(spoon.support.compiler.FileSystemFile) CtMethod(spoon.reflect.declaration.CtMethod) CtIf(spoon.reflect.code.CtIf) Test(org.junit.Test)

Example 14 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class TemplateTest method testTemplateInheritance.

@Test
public void testTemplateInheritance() throws Exception {
    Launcher spoon = new Launcher();
    Factory factory = spoon.getFactory();
    spoon.getEnvironment().setCommentEnabled(true);
    spoon.createCompiler(factory, SpoonResourceHelper.resources("./src/test/java/spoon/test/template/testclasses/inheritance/SubClass.java", "./src/test/java/spoon/test/template/testclasses/inheritance/SuperClass.java"), SpoonResourceHelper.resources("./src/test/java/spoon/test/template/testclasses/inheritance/SubTemplate.java", "./src/test/java/spoon/test/template/testclasses/inheritance/SuperTemplate.java")).build();
    // Collects type members which should contain generated by comment
    final Map<CtElement, String> elementToGeneratedByMember = new IdentityHashMap<>();
    CtClass<?> superc = factory.Class().get(SuperClass.class);
    new SuperTemplate().addGeneratedBy(true).apply(superc);
    CtMethod<?> addedMethod = superc.getElements(new NamedElementFilter<>(CtMethod.class, "toBeOverriden")).get(0);
    assertEquals("toBeOverriden", addedMethod.getSimpleName());
    elementToGeneratedByMember.put(addedMethod, "#toBeOverriden");
    CtClass<?> subc = factory.Class().get(SubClass.class);
    SubTemplate template = new SubTemplate();
    template.addGeneratedBy(true);
    template.params = new ArrayList<>();
    CtParameter<Integer> parameter = factory.Core().createParameter();
    parameter.setSimpleName("x");
    parameter.setType(factory.Type().createReference(int.class));
    template.params.add(parameter);
    // templating the invocation
    template.invocation = factory.Code().createInvocation(null, addedMethod.getReference());
    // templating the foreach
    template.intValues = new CtExpression[2];
    template.intValues[0] = factory.Code().createLiteral(0);
    template.intValues[1] = factory.Code().createLiteral(1);
    // we apply the extension template to subc
    template.apply(subc);
    CtMethod<?> addedMethod2 = subc.getElements(new NamedElementFilter<>(CtMethod.class, "toBeOverriden")).get(0);
    assertEquals("toBeOverriden", addedMethod2.getSimpleName());
    assertEquals("super.toBeOverriden()", addedMethod2.getBody().getStatements().get(0).toString());
    elementToGeneratedByMember.put(addedMethod2, "#toBeOverriden");
    // contract; method parameter templates are handled
    CtMethod<?> methodWithTemplatedParameters = subc.getElements(new NamedElementFilter<>(CtMethod.class, "methodWithTemplatedParameters")).get(0);
    assertEquals("methodWithTemplatedParameters", methodWithTemplatedParameters.getSimpleName());
    assertEquals("x", methodWithTemplatedParameters.getParameters().get(0).getSimpleName());
    assertEquals("int x", methodWithTemplatedParameters.getParameters().get(0).toString());
    elementToGeneratedByMember.put(methodWithTemplatedParameters, "#methodWithTemplatedParameters");
    // contract: nested types of the templates are copied
    assertEquals(1, subc.getNestedTypes().size());
    elementToGeneratedByMember.put(subc.getNestedTypes().iterator().next(), "$InnerClass");
    // contract: methods are renamed
    assertEquals(1, subc.getMethodsByName("newVarName").size());
    CtMethod<?> varMethod = subc.getMethodsByName("newVarName").get(0);
    elementToGeneratedByMember.put(varMethod, "#var");
    // contract: parameters are replaced in comments too. The Class parameter value is converted to String
    assertEquals("newVarName", varMethod.getComments().get(0).getContent().split("[\\n\\r]+")[0]);
    assertEquals("{@link LinkedList}", varMethod.getComments().get(1).getContent());
    assertEquals("{@link SuperClass#toBeOverriden()}", varMethod.getComments().get(2).getContent());
    // contract: variable are renamed
    assertEquals("java.util.List newVarName = null", methodWithTemplatedParameters.getBody().getStatement(0).toString());
    // contract: types are replaced by other types
    assertEquals("java.util.LinkedList l = null", methodWithTemplatedParameters.getBody().getStatement(1).toString());
    // contract: casts are replaced by substitution types
    assertEquals("java.util.List o = ((java.util.LinkedList) (new java.util.LinkedList()))", methodWithTemplatedParameters.getBody().getStatement(2).toString());
    // contract: invocations are replaced by actual invocations
    assertEquals("toBeOverriden()", methodWithTemplatedParameters.getBody().getStatement(3).toString());
    // contract: foreach in block is inlined into that wrapping block
    CtBlock templatedForEach = methodWithTemplatedParameters.getBody().getStatement(4);
    assertEquals("java.lang.System.out.println(0)", templatedForEach.getStatement(0).toString());
    assertEquals("java.lang.System.out.println(1)", templatedForEach.getStatement(1).toString());
    // contract: foreach with single body block are inlined without extra block
    assertEquals("java.lang.System.out.println(0)", methodWithTemplatedParameters.getBody().getStatement(5).toString());
    assertEquals("java.lang.System.out.println(1)", methodWithTemplatedParameters.getBody().getStatement(6).toString());
    // contract: foreach with double body block are inlined with one extra block for each inlined statement
    assertEquals("java.lang.System.out.println(0)", ((CtBlock) methodWithTemplatedParameters.getBody().getStatement(7)).getStatement(0).toString());
    assertEquals("java.lang.System.out.println(1)", ((CtBlock) methodWithTemplatedParameters.getBody().getStatement(8)).getStatement(0).toString());
    // contract: foreach with statement are inlined without extra (implicit) block
    assertFalse(methodWithTemplatedParameters.getBody().getStatement(9) instanceof CtBlock);
    assertEquals("java.lang.System.out.println(0)", methodWithTemplatedParameters.getBody().getStatement(9).toString());
    assertFalse(methodWithTemplatedParameters.getBody().getStatement(10) instanceof CtBlock);
    assertEquals("java.lang.System.out.println(1)", methodWithTemplatedParameters.getBody().getStatement(10).toString());
    // contract: for each whose expression is not a template parameter is not inlined
    assertTrue(methodWithTemplatedParameters.getBody().getStatement(11) instanceof CtForEach);
    // contract: local variable write are replaced by local variable write with modified local variable name
    assertEquals("newVarName = o", methodWithTemplatedParameters.getBody().getStatement(12).toString());
    // contract: local variable read are replaced by local variable read with modified local variable name
    assertEquals("l = ((java.util.LinkedList) (newVarName))", methodWithTemplatedParameters.getBody().getStatement(13).toString());
    // contract; field access is handled same like local variable access
    CtMethod<?> methodWithFieldAccess = subc.getElements(new NamedElementFilter<>(CtMethod.class, "methodWithFieldAccess")).get(0);
    elementToGeneratedByMember.put(methodWithFieldAccess, "#methodWithFieldAccess");
    elementToGeneratedByMember.put(subc.getField("newVarName"), "#var");
    // contract: field write are replaced by field write with modified field name
    assertEquals("newVarName = o", methodWithFieldAccess.getBody().getStatement(2).toString());
    // contract: field read are replaced by field read with modified field name
    assertEquals("l = ((java.util.LinkedList) (newVarName))", methodWithFieldAccess.getBody().getStatement(3).toString());
    class Context {

        int nrTypeMembers = 0;

        int nrOthers = 0;
    }
    final Context ctx = new Context();
    // contract: each CtTypeMember has `Generated by ` with appropriate template class name, member name and line number
    superc.filterChildren(null).forEach((CtElement e) -> {
        if (e instanceof CtTypeMember) {
            ctx.nrTypeMembers++;
            assertCommentHasGeneratedBy(e, SuperTemplate.class.getName(), elementToGeneratedByMember);
        } else {
            ctx.nrOthers++;
            assertTrue(e.getDocComment() == null || e.getDocComment().indexOf("Generated by") == -1);
        }
    });
    assertTrue(ctx.nrTypeMembers > 0);
    assertTrue(ctx.nrOthers > 0);
    ctx.nrTypeMembers = 0;
    ctx.nrOthers = 0;
    subc.filterChildren(null).forEach((CtElement e) -> {
        if (e instanceof CtTypeMember) {
            ctx.nrTypeMembers++;
            assertCommentHasGeneratedBy(e, SubTemplate.class.getName(), elementToGeneratedByMember);
        } else {
            ctx.nrOthers++;
            assertTrue(e.getDocComment() == null || e.getDocComment().indexOf("Generated by") == -1);
        }
    });
    assertTrue(ctx.nrTypeMembers > 0);
    assertTrue(ctx.nrOthers > 0);
}
Also used : SubTemplate(spoon.test.template.testclasses.inheritance.SubTemplate) CtElement(spoon.reflect.declaration.CtElement) IdentityHashMap(java.util.IdentityHashMap) Factory(spoon.reflect.factory.Factory) CtForEach(spoon.reflect.code.CtForEach) CtBlock(spoon.reflect.code.CtBlock) CtTypeMember(spoon.reflect.declaration.CtTypeMember) SuperTemplate(spoon.test.template.testclasses.inheritance.SuperTemplate) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) Launcher(spoon.Launcher) Test(org.junit.Test)

Example 15 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class DefaultJavaPrettyPrinter method isInitializeStaticFinalField.

/**
 * Check if the target expression is a static final field initialized in a static anonymous block.
 */
private <T> boolean isInitializeStaticFinalField(CtExpression<T> targetExp) {
    final CtElement parent;
    final CtAnonymousExecutable anonymousParent;
    try {
        parent = targetExp.getParent();
        anonymousParent = targetExp.getParent(CtAnonymousExecutable.class);
    } catch (ParentNotInitializedException e) {
        return false;
    }
    if (parent instanceof CtFieldWrite && targetExp.equals(((CtFieldWrite) parent).getTarget()) && anonymousParent != null && ((CtFieldWrite) parent).getVariable() != null && ((CtFieldWrite) parent).getVariable().getModifiers().contains(ModifierKind.STATIC) && ((CtFieldWrite) parent).getVariable().getModifiers().contains(ModifierKind.FINAL)) {
        return true;
    }
    return false;
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtElement(spoon.reflect.declaration.CtElement) CtFieldWrite(spoon.reflect.code.CtFieldWrite) CtAnonymousExecutable(spoon.reflect.declaration.CtAnonymousExecutable)

Aggregations

CtElement (spoon.reflect.declaration.CtElement)86 Test (org.junit.Test)39 Launcher (spoon.Launcher)23 Factory (spoon.reflect.factory.Factory)18 ArrayList (java.util.ArrayList)17 CtMethod (spoon.reflect.declaration.CtMethod)17 CtType (spoon.reflect.declaration.CtType)15 CtStatement (spoon.reflect.code.CtStatement)14 CtTypeReference (spoon.reflect.reference.CtTypeReference)14 List (java.util.List)12 CtClass (spoon.reflect.declaration.CtClass)12 CtField (spoon.reflect.declaration.CtField)12 CtIf (spoon.reflect.code.CtIf)11 CtInvocation (spoon.reflect.code.CtInvocation)11 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)11 CtLocalVariable (spoon.reflect.code.CtLocalVariable)10 CtExecutableReference (spoon.reflect.reference.CtExecutableReference)9 CtScanner (spoon.reflect.visitor.CtScanner)9 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)9 Collection (java.util.Collection)8