Search in sources :

Example 16 with CtExpression

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);
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtExpression(spoon.reflect.code.CtExpression) Writable(spoon.reflect.visitor.PrintingContext.Writable) CtArrayTypeReference(spoon.reflect.reference.CtArrayTypeReference)

Example 17 with CtExpression

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());
}
Also used : CtAssignment(spoon.reflect.code.CtAssignment) CtStatement(spoon.reflect.code.CtStatement) CtExpression(spoon.reflect.code.CtExpression) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) Test(org.junit.Test)

Example 18 with CtExpression

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);
}
Also used : CtLambda(spoon.reflect.code.CtLambda) CtExpression(spoon.reflect.code.CtExpression) CtAbstractInvocation(spoon.reflect.code.CtAbstractInvocation) CtParameter(spoon.reflect.declaration.CtParameter) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtLocalVariableReference(spoon.reflect.reference.CtLocalVariableReference)

Example 19 with CtExpression

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);
}
Also used : CtLiteral(spoon.reflect.code.CtLiteral) CtExpression(spoon.reflect.code.CtExpression) DefaultCoreFactory(spoon.support.DefaultCoreFactory) Factory(spoon.reflect.factory.Factory) Launcher(spoon.Launcher) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) ReferenceTypeFilter(spoon.reflect.visitor.filter.ReferenceTypeFilter) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 20 with CtExpression

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);
    }
}
Also used : Arrays(java.util.Arrays) Launcher(spoon.Launcher) IsEqual.equalTo(org.hamcrest.core.IsEqual.equalTo) CtRole(spoon.reflect.path.CtRole) ArrayList(java.util.ArrayList) CtType(spoon.reflect.declaration.CtType) CtElement(spoon.reflect.declaration.CtElement) SpoonAPI(spoon.SpoonAPI) CtExpression(spoon.reflect.code.CtExpression) CtNewArray(spoon.reflect.code.CtNewArray) Metamodel(spoon.Metamodel) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) CtQuery(spoon.reflect.visitor.chain.CtQuery) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtField(spoon.reflect.declaration.CtField) CtReference(spoon.reflect.reference.CtReference) MetamodelPropertyField(spoon.reflect.annotations.MetamodelPropertyField) SuperInheritanceHierarchyFunction(spoon.reflect.visitor.filter.SuperInheritanceHierarchyFunction) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Factory(spoon.reflect.factory.Factory) PropertySetter(spoon.reflect.annotations.PropertySetter) Collectors(java.util.stream.Collectors) CtTypeReference(spoon.reflect.reference.CtTypeReference) List(java.util.List) CtAnnotation(spoon.reflect.declaration.CtAnnotation) AnnotationFilter(spoon.reflect.visitor.filter.AnnotationFilter) CtClass(spoon.reflect.declaration.CtClass) ModifierKind(spoon.reflect.declaration.ModifierKind) CtFieldRead(spoon.reflect.code.CtFieldRead) Assert(org.junit.Assert) Collections(java.util.Collections) PropertyGetter(spoon.reflect.annotations.PropertyGetter) CtMethod(spoon.reflect.declaration.CtMethod) ArrayList(java.util.ArrayList) Factory(spoon.reflect.factory.Factory) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtNewArray(spoon.reflect.code.CtNewArray) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtField(spoon.reflect.declaration.CtField) PropertyGetter(spoon.reflect.annotations.PropertyGetter) ArrayList(java.util.ArrayList) List(java.util.List) SpoonAPI(spoon.SpoonAPI) SuperInheritanceHierarchyFunction(spoon.reflect.visitor.filter.SuperInheritanceHierarchyFunction) CtAnnotation(spoon.reflect.declaration.CtAnnotation) CtFieldRead(spoon.reflect.code.CtFieldRead) CtExpression(spoon.reflect.code.CtExpression) PropertySetter(spoon.reflect.annotations.PropertySetter) CtQuery(spoon.reflect.visitor.chain.CtQuery) MetamodelPropertyField(spoon.reflect.annotations.MetamodelPropertyField) CtClass(spoon.reflect.declaration.CtClass) CtType(spoon.reflect.declaration.CtType) Launcher(spoon.Launcher) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Aggregations

CtExpression (spoon.reflect.code.CtExpression)33 Factory (spoon.reflect.factory.Factory)19 Test (org.junit.Test)16 CtTypeReference (spoon.reflect.reference.CtTypeReference)11 CtStatement (spoon.reflect.code.CtStatement)10 CtInvocation (spoon.reflect.code.CtInvocation)6 CtMethod (spoon.reflect.declaration.CtMethod)6 AbstractTest (fr.inria.AbstractTest)5 ArrayList (java.util.ArrayList)5 List (java.util.List)5 CtAssignment (spoon.reflect.code.CtAssignment)5 CtLiteral (spoon.reflect.code.CtLiteral)5 CtNewArray (spoon.reflect.code.CtNewArray)5 Launcher (spoon.Launcher)4 CtConstructorCall (spoon.reflect.code.CtConstructorCall)4 CtLocalVariable (spoon.reflect.code.CtLocalVariable)4 CtClass (spoon.reflect.declaration.CtClass)4 CtElement (spoon.reflect.declaration.CtElement)4 CtExecutableReference (spoon.reflect.reference.CtExecutableReference)4 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)4