use of spoon.reflect.code.CtExpression in project spoon by INRIA.
the class DefaultJavaPrettyPrinter method visitCtNewArray.
@Override
@SuppressWarnings("rawtypes")
public <T> void visitCtNewArray(CtNewArray<T> newArray) {
enterCtExpression(newArray);
boolean isNotInAnnotation;
try {
isNotInAnnotation = (newArray.getParent(CtAnnotationType.class) == null) && (newArray.getParent(CtAnnotation.class) == null);
} catch (ParentNotInitializedException e) {
isNotInAnnotation = true;
}
if (isNotInAnnotation) {
CtTypeReference<?> ref = newArray.getType();
if (ref != null) {
printer.writeKeyword("new").writeSpace();
}
try (Writable _context = context.modify().skipArray(true)) {
scan(ref);
}
for (int i = 0; ref instanceof CtArrayTypeReference; i++) {
printer.writeSeparator("[");
if (newArray.getDimensionExpressions().size() > i) {
CtExpression<Integer> e = newArray.getDimensionExpressions().get(i);
scan(e);
}
printer.writeSeparator("]");
ref = ((CtArrayTypeReference) ref).getComponentType();
}
}
if (newArray.getDimensionExpressions().size() == 0) {
try (ListPrinter lp = elementPrinterHelper.createListPrinter(false, "{", true, false, ",", true, true, "}")) {
for (CtExpression e : newArray.getElements()) {
lp.printSeparatorIfAppropriate();
scan(e);
}
elementPrinterHelper.writeComment(newArray, CommentOffset.INSIDE);
}
}
elementPrinterHelper.writeComment(newArray, CommentOffset.AFTER);
exitCtExpression(newArray);
}
use of spoon.reflect.code.CtExpression 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());
}
use of spoon.reflect.code.CtExpression in project spoon by INRIA.
the class VariableReferencesTest method getLiteralValue.
private Integer getLiteralValue(CtVariable<?> var) {
CtExpression<?> exp = var.getDefaultExpression();
if (exp != null) {
try {
return getLiteralValue(exp);
} catch (ClassCastException e) {
}
}
if (var instanceof CtParameter) {
CtParameter param = (CtParameter) var;
CtExecutable<?> l_exec = param.getParent(CtExecutable.class);
int l_argIdx = l_exec.getParameters().indexOf(param);
assertTrue(l_argIdx >= 0);
if (l_exec instanceof CtLambda) {
CtLambda<?> lambda = (CtLambda<?>) l_exec;
CtLocalVariable<?> lamVar = (CtLocalVariable) lambda.getParent();
CtLocalVariableReference<?> lamVarRef = lamVar.getParent().filterChildren((CtLocalVariableReference ref) -> ref.getSimpleName().equals(lamVar.getSimpleName())).first();
CtAbstractInvocation inv = lamVarRef.getParent(CtAbstractInvocation.class);
return getLiteralValue((CtExpression<?>) inv.getArguments().get(l_argIdx));
} else {
CtExecutableReference<?> l_execRef = l_exec.getReference();
List<CtAbstractInvocation<?>> list = l_exec.getFactory().Package().getRootPackage().filterChildren((CtAbstractInvocation inv) -> {
// return inv.getExecutable().equals(l_execRef);
return inv.getExecutable().getExecutableDeclaration() == l_exec;
}).list();
CtAbstractInvocation inv = list.get(0);
Integer firstValue = getLiteralValue((CtExpression<?>) inv.getArguments().get(l_argIdx));
// check that all found method invocations are using same key
list.forEach(inv2 -> {
assertEquals(firstValue, getLiteralValue((CtExpression<?>) inv2.getArguments().get(l_argIdx)));
});
return firstValue;
}
}
return getCommentValue(var);
}
use of spoon.reflect.code.CtExpression in project spoon by INRIA.
the class SignatureTest method testNullSignature.
@Test
public void testNullSignature() throws Exception {
// bug found by Thomas Vincent et Mathieu Schepens (students at the
// University of Lille) on Nov 4 2014
// in their analysis, they put CtExpressions in a Map
// if one expression has an empty signature, an exception is thrown
// the solution is to improve the signature of null literals
Factory factory = new Launcher().createFactory();
CtClass<?> clazz = factory.Code().createCodeSnippetStatement("" + "class X {" + "public Object foo() {" + " return null;" + "}};").compile();
CtReturn<?> returnEl = clazz.getElements(new TypeFilter<>(CtReturn.class)).get(0);
CtExpression<?> lit = returnEl.getReturnedExpression();
assertTrue(lit instanceof CtLiteral);
assertEquals("null", lit.toString());
// since the signature is null, CtElement.equals throws an exception and
// should not
CtLiteral<?> lit2 = ((CtLiteral<?>) lit).clone();
HashSet<CtExpression<?>> s = new HashSet<CtExpression<?>>();
s.add(lit);
s.add(lit2);
}
use of spoon.reflect.code.CtExpression in project spoon by INRIA.
the class MetamodelTest method testRoleOnField.
@Test
public void testRoleOnField() {
// contract: all non-final fields must be annotated with {@link spoon.reflect.annotations.MetamodelPropertyField}
SpoonAPI implementations = new Launcher();
implementations.addInputResource("src/main/java/spoon/support/reflect");
implementations.buildModel();
Factory factory = implementations.getFactory();
CtTypeReference metamodelPropertyField = factory.Type().get(MetamodelPropertyField.class).getReference();
final List<String> result = new ArrayList();
List<CtField> fieldWithoutAnnotation = (List<CtField>) implementations.getModel().getElements(new TypeFilter<CtField>(CtField.class) {
@Override
public boolean matches(CtField candidate) {
if (candidate.hasModifier(ModifierKind.FINAL) || candidate.hasModifier(ModifierKind.STATIC) || candidate.hasModifier(ModifierKind.TRANSIENT)) {
return false;
}
if (// not a role
"parent".equals(candidate.getSimpleName()) || "metadata".equals(candidate.getSimpleName()) || // cache field
"valueOfMethod".equals(candidate.getSimpleName())) {
return false;
}
CtClass parent = candidate.getParent(CtClass.class);
return parent != null && (parent.isSubtypeOf(candidate.getFactory().createCtTypeReference(CtReference.class)) || parent.isSubtypeOf(candidate.getFactory().createCtTypeReference(CtElement.class)));
}
}).stream().map(x -> {
result.add(x.toString());
return x;
}).filter(f -> f.getAnnotation(metamodelPropertyField) == null).collect(Collectors.toList());
assertTrue(result.contains("@spoon.reflect.annotations.MetamodelPropertyField(role = spoon.reflect.path.CtRole.IS_SHADOW)\nboolean isShadow;"));
assertTrue(result.contains("@spoon.reflect.annotations.MetamodelPropertyField(role = spoon.reflect.path.CtRole.TYPE)\nspoon.reflect.reference.CtTypeReference<T> type;"));
assertTrue(result.size() > 100);
Assert.assertEquals(Collections.emptyList(), fieldWithoutAnnotation);
final CtTypeReference propertySetter = factory.Type().get(PropertySetter.class).getReference();
final CtTypeReference propertyGetter = factory.Type().get(PropertyGetter.class).getReference();
List<CtField> fields = factory.getModel().getElements(new AnnotationFilter<CtField>(MetamodelPropertyField.class));
for (CtField field : fields) {
CtClass parent = field.getParent(CtClass.class);
CtExpression roleExpression = field.getAnnotation(metamodelPropertyField).getValue("role");
List<String> roles = new ArrayList<>();
if (roleExpression instanceof CtFieldRead) {
roles.add(((CtFieldRead) roleExpression).getVariable().getSimpleName());
} else if (roleExpression instanceof CtNewArray) {
List<CtFieldRead> elements = ((CtNewArray) roleExpression).getElements();
for (int i = 0; i < elements.size(); i++) {
CtFieldRead ctFieldRead = elements.get(i);
roles.add(ctFieldRead.getVariable().getSimpleName());
}
}
CtQuery superQuery = parent.map(new SuperInheritanceHierarchyFunction());
List<CtMethod> methods = superQuery.map((CtType type) -> type.getMethodsAnnotatedWith(propertyGetter, propertySetter)).list();
boolean setterFound = false;
boolean getterFound = false;
for (CtMethod method : methods) {
CtAnnotation getterAnnotation = method.getAnnotation(propertyGetter);
CtAnnotation setterAnnotation = method.getAnnotation(propertySetter);
if (getterAnnotation != null) {
getterFound |= roles.contains(((CtFieldRead) getterAnnotation.getValue("role")).getVariable().getSimpleName());
}
if (setterAnnotation != null) {
setterFound |= roles.contains(((CtFieldRead) setterAnnotation.getValue("role")).getVariable().getSimpleName());
}
}
assertTrue(roles + " must have a getter in " + parent.getQualifiedName(), getterFound);
assertTrue(roles + " must have a setter in " + parent.getQualifiedName(), setterFound);
}
}
Aggregations