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);
}
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);
}
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());
}
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);
}
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;
}
Aggregations