Search in sources :

Example 6 with CtVariable

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

the class AccessibleVariablesFinder method getVariable.

private List<CtVariable> getVariable(final CtElement parent) {
    final List<CtVariable> variables = new ArrayList<>();
    if (parent == null) {
        return variables;
    }
    class VariableScanner extends CtInheritanceScanner {

        @Override
        public void visitCtStatementList(CtStatementList e) {
            for (int i = 0; i < e.getStatements().size(); i++) {
                CtStatement ctStatement = e.getStatements().get(i);
                if (ctStatement.getPosition() == null) {
                }
                if (ctStatement.getPosition() != null && ctStatement.getPosition().getSourceStart() > expression.getPosition().getSourceEnd()) {
                    break;
                }
                if (ctStatement instanceof CtVariable) {
                    variables.add((CtVariable) ctStatement);
                }
            }
            super.visitCtStatementList(e);
        }

        @Override
        public <T> void scanCtType(CtType<T> type) {
            List<CtField<?>> fields = type.getFields();
            for (int i = 0; i < fields.size(); i++) {
                CtField<?> ctField = fields.get(i);
                if (ctField.hasModifier(ModifierKind.PUBLIC) || ctField.hasModifier(ModifierKind.PROTECTED)) {
                    variables.add(ctField);
                } else if (ctField.hasModifier(ModifierKind.PRIVATE)) {
                    if (expression.hasParent(type)) {
                        variables.add(ctField);
                    }
                } else if (expression.getParent(CtPackage.class).equals(type.getParent(CtPackage.class))) {
                    // default visibility
                    variables.add(ctField);
                }
            }
            CtTypeReference<?> superclass = type.getSuperclass();
            if (superclass != null) {
                variables.addAll(getVariable(superclass.getTypeDeclaration()));
            }
            Set<CtTypeReference<?>> superInterfaces = type.getSuperInterfaces();
            for (Iterator<CtTypeReference<?>> iterator = superInterfaces.iterator(); iterator.hasNext(); ) {
                CtTypeReference<?> typeReference = iterator.next();
                variables.addAll(getVariable(typeReference.getTypeDeclaration()));
            }
            super.scanCtType(type);
        }

        @Override
        public void visitCtTryWithResource(CtTryWithResource e) {
            variables.addAll(e.getResources());
            super.visitCtTryWithResource(e);
        }

        @Override
        public void scanCtExecutable(CtExecutable e) {
            variables.addAll(e.getParameters());
            super.scanCtExecutable(e);
        }

        @Override
        public void visitCtFor(CtFor e) {
            for (CtStatement ctStatement : e.getForInit()) {
                this.scan(ctStatement);
            }
            super.visitCtFor(e);
        }

        @Override
        public void visitCtForEach(CtForEach e) {
            variables.add(e.getVariable());
            super.visitCtForEach(e);
        }

        @Override
        public void visitCtMethod(CtMethod e) {
            this.scan(e.getBody());
            super.visitCtMethod(e);
        }

        @Override
        public void visitCtLocalVariable(CtLocalVariable e) {
            variables.add(e);
            super.visitCtLocalVariable(e);
        }

        @Override
        public void visitCtCatch(CtCatch e) {
            variables.add(e.getParameter());
            super.visitCtCatch(e);
        }
    }
    new VariableScanner().scan(parent);
    return variables;
}
Also used : ArrayList(java.util.ArrayList) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtExecutable(spoon.reflect.declaration.CtExecutable) CtForEach(spoon.reflect.code.CtForEach) CtType(spoon.reflect.declaration.CtType) CtStatement(spoon.reflect.code.CtStatement) CtField(spoon.reflect.declaration.CtField) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtVariable(spoon.reflect.declaration.CtVariable) CtStatementList(spoon.reflect.code.CtStatementList) CtPackage(spoon.reflect.declaration.CtPackage) CtTryWithResource(spoon.reflect.code.CtTryWithResource) CtCatch(spoon.reflect.code.CtCatch) CtFor(spoon.reflect.code.CtFor) CtMethod(spoon.reflect.declaration.CtMethod)

Example 7 with CtVariable

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

the class GenericsTest method testisGeneric.

@Test
public void testisGeneric() throws Exception {
    Factory factory = build(new File("src/test/java/spoon/test/generics/testclasses"));
    /*
		// this code has been used to generate the list of assertEquals below,
		// and then each assertEquals was verified

		Set<String> s = new HashSet<>();
		factory.getModel().getElements(new TypeFilter<CtTypeReference>(CtTypeReference.class) {
			@Override
			public boolean matches(CtTypeReference element) {
				return super.matches(element) && element.getParent() instanceof CtVariable;
			}
		}).forEach(x -> {
				String simpleName = ((CtVariable) x.getParent()).getSimpleName();
				if (!s.contains(simpleName)) {
					System.out.println("\t\t// "+x.toString());
					System.out.println("\t\tCtTypeReference<?> "+simpleName+"Ref = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, \"" + simpleName+ "\")).first(CtVariable.class).getType();");
					System.out.println("\t\tassertEquals("+x.isGeneric() + ", " + simpleName + "Ref.isGeneric());");
					System.out.println();
				}
				s.add(simpleName);
		});
		 */
    // T
    CtTypeReference<?> var1Ref = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "var1")).first(CtVariable.class).getType();
    assertEquals(true, var1Ref.isGenerics());
    // spoon.test.generics.testclasses.rxjava.Subscriber<? super T>
    CtTypeReference<?> sRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "s")).first(CtVariable.class).getType();
    assertEquals(true, sRef.isGenerics());
    // spoon.test.generics.testclasses.rxjava.Try<java.util.Optional<java.lang.Object>>
    CtTypeReference<?> notificationRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "notification")).first(CtVariable.class).getType();
    assertEquals(false, notificationRef.isGenerics());
    // java.util.function.Function<? super spoon.test.generics.testclasses.rxjava.Observable<spoon.test.generics.testclasses.rxjava.Try<java.util.Optional<java.lang.Object>>>, ? extends spoon.test.generics.testclasses.rxjava.Publisher<?>>
    CtTypeReference<?> managerRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "manager")).first(CtVariable.class).getType();
    assertEquals(false, managerRef.isGenerics());
    // spoon.test.generics.testclasses.rxjava.BehaviorSubject<spoon.test.generics.testclasses.rxjava.Try<java.util.Optional<java.lang.Object>>>
    CtTypeReference<?> subjectRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "subject")).first(CtVariable.class).getType();
    assertEquals(false, subjectRef.isGenerics());
    // spoon.test.generics.testclasses.rxjava.PublisherRedo.RedoSubscriber<T>
    CtTypeReference<?> parentRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "parent")).first(CtVariable.class).getType();
    assertEquals(true, parentRef.isGenerics());
    // spoon.test.generics.testclasses.rxjava.Publisher<?>
    CtTypeReference<?> actionRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "action")).first(CtVariable.class).getType();
    assertEquals(false, actionRef.isGenerics());
    // spoon.test.generics.testclasses.rxjava.ToNotificationSubscriber
    CtTypeReference<?> trucRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "truc")).first(CtVariable.class).getType();
    assertEquals(false, trucRef.isGenerics());
    // java.util.function.Consumer<? super spoon.test.generics.testclasses.rxjava.Try<java.util.Optional<java.lang.Object>>>
    CtTypeReference<?> consumerRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "consumer")).first(CtVariable.class).getType();
    assertEquals(false, consumerRef.isGenerics());
    // S
    CtTypeReference<?> sectionRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "section")).first(CtVariable.class).getType();
    assertEquals(true, sectionRef.isGenerics());
    // X
    CtTypeReference<?> paramARef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "paramA")).first(CtVariable.class).getType();
    assertEquals(true, paramARef.isGenerics());
    // spoon.test.generics.testclasses.Tacos
    CtTypeReference<?> paramBRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "paramB")).first(CtVariable.class).getType();
    assertEquals(false, paramBRef.isGenerics());
    // C
    CtTypeReference<?> paramCRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "paramC")).first(CtVariable.class).getType();
    assertEquals(true, paramCRef.isGenerics());
    // R
    CtTypeReference<?> cookRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "cook")).first(CtVariable.class).getType();
    assertEquals(true, cookRef.isGenerics());
    // spoon.test.generics.testclasses.CelebrationLunch<java.lang.Integer, java.lang.Long, java.lang.Double>
    CtTypeReference<?> clRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "cl")).first(CtVariable.class).getType();
    assertEquals(false, clRef.isGenerics());
    // spoon.test.generics.testclasses.CelebrationLunch<java.lang.Integer, java.lang.Long, java.lang.Double>.WeddingLunch<spoon.test.generics.testclasses.Mole>
    CtTypeReference<?> disgustRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "disgust")).first(CtVariable.class).getType();
    assertEquals(false, disgustRef.isGenerics());
    // L
    CtTypeReference<?> paramRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "param")).first(CtVariable.class).getType();
    assertEquals(true, paramRef.isGenerics());
    // spoon.reflect.declaration.CtType<? extends spoon.reflect.declaration.CtNamedElement>
    CtTypeReference<?> targetTypeRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "targetType")).first(CtVariable.class).getType();
    assertEquals(false, targetTypeRef.isGenerics());
    // spoon.reflect.declaration.CtType<?>
    CtTypeReference<?> somethingRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "something")).first(CtVariable.class).getType();
    assertEquals(false, somethingRef.isGenerics());
    // int
    CtTypeReference<?> iRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "i")).first(CtVariable.class).getType();
    assertEquals(false, iRef.isGenerics());
    // T
    CtTypeReference<?> biduleRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "bidule")).first(CtVariable.class).getType();
    assertEquals(true, biduleRef.isGenerics());
    // Cook<java.lang.String>
    CtTypeReference<?> aClassRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "aClass")).first(CtVariable.class).getType();
    assertEquals(false, aClassRef.isGenerics());
    // java.util.List<java.util.List<M>>
    CtTypeReference<?> list2mRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "list2m")).first(CtVariable.class).getType();
    assertEquals(true, list2mRef.isGenerics());
    // spoon.test.generics.testclasses.Panini.Subscriber<? extends java.lang.Long>
    CtTypeReference<?> tRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "t")).first(CtVariable.class).getType();
    assertEquals(false, tRef.isGenerics());
    // spoon.test.generics.testclasses.Spaghetti<B>.Tester
    CtTypeReference<?> testerRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "tester")).first(CtVariable.class).getType();
    assertEquals(false, testerRef.isGenerics());
    // spoon.test.generics.testclasses.Spaghetti<B>.Tester
    CtTypeReference<?> tester1Ref = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "tester1")).first(CtVariable.class).getType();
    assertEquals(false, tester1Ref.isGenerics());
    // spoon.test.generics.testclasses.Spaghetti<B>.That<java.lang.String, java.lang.String>
    CtTypeReference<?> fieldRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "field")).first(CtVariable.class).getType();
    assertEquals(false, fieldRef.isGenerics());
    // spoon.test.generics.testclasses.Spaghetti<java.lang.String>.That<java.lang.String, java.lang.String>
    CtTypeReference<?> field1Ref = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "field1")).first(CtVariable.class).getType();
    assertEquals(false, field1Ref.isGenerics());
    // spoon.test.generics.testclasses.Spaghetti<java.lang.Number>.That<java.lang.String, java.lang.String>
    CtTypeReference<?> field2Ref = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "field2")).first(CtVariable.class).getType();
    assertEquals(false, field2Ref.isGenerics());
    // spoon.test.generics.testclasses.Tacos<K, java.lang.String>.Burritos<K, V>
    CtTypeReference<?> burritosRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "burritos")).first(CtVariable.class).getType();
    // now that the order of type members is correct
    // this burritos is indeed "IBurritos<?, ?> burritos = new Burritos<>()" with no generics
    assertEquals(false, burritosRef.isGenerics());
    // int
    CtTypeReference<?> nbTacosRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "nbTacos")).first(CtVariable.class).getType();
    assertEquals(false, nbTacosRef.isGenerics());
    // java.util.List<java.lang.String>
    CtTypeReference<?> lRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "l")).first(CtVariable.class).getType();
    assertEquals(false, lRef.isGenerics());
    // java.util.List
    CtTypeReference<?> l2Ref = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "l2")).first(CtVariable.class).getType();
    assertEquals(false, l2Ref.isGenerics());
    // java.util.List<?>
    CtTypeReference<?> l3Ref = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "l3")).first(CtVariable.class).getType();
    assertEquals(false, l3Ref.isGenerics());
    // T
    CtTypeReference<?> anObjectRef = factory.getModel().filterChildren(new NamedElementFilter(CtVariable.class, "anObject")).first(CtVariable.class).getType();
    assertEquals(true, anObjectRef.isGenerics());
}
Also used : CtVariable(spoon.reflect.declaration.CtVariable) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) ModelUtils.createFactory(spoon.testing.utils.ModelUtils.createFactory) Factory(spoon.reflect.factory.Factory) File(java.io.File) MainTest(spoon.test.main.MainTest) Test(org.junit.Test)

Example 8 with CtVariable

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

the class FilterTest method classCastExceptionIsNotThrown.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void classCastExceptionIsNotThrown() throws Exception {
    Factory factory = build("spoon.test.testclasses", "SampleClass").getFactory();
    NamedElementFilter<CtVariable> nameFilterA = new NamedElementFilter<>(CtVariable.class, "j");
    NamedElementFilter<CtVariable> nameFilterB = new NamedElementFilter<>(CtVariable.class, "k");
    CompositeFilter compositeFilter = new CompositeFilter(FilteringOperator.INTERSECTION, nameFilterA, nameFilterB);
    List filteredWithCompositeFilter = Query.getElements(factory, compositeFilter);
    assertTrue(filteredWithCompositeFilter.isEmpty());
}
Also used : CompositeFilter(spoon.reflect.visitor.filter.CompositeFilter) CtVariable(spoon.reflect.declaration.CtVariable) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) Factory(spoon.reflect.factory.Factory) List(java.util.List) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 9 with CtVariable

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

the class ReplaceTest method testReplaceStatement.

@Test
public void testReplaceStatement() {
    CtMethod<?> sample = factory.Package().get("spoon.test.replace.testclasses").getType("Foo").getMethod("foo");
    Assert.assertTrue(sample.getBody().getStatement(0) instanceof CtVariable);
    CtStatement replacement = factory.Core().createInvocation();
    sample.getBody().getStatement(0).replace(replacement);
    Assert.assertTrue(sample.getBody().getStatement(0) instanceof CtInvocation);
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) CtStatement(spoon.reflect.code.CtStatement) CtVariable(spoon.reflect.declaration.CtVariable) Test(org.junit.Test)

Example 10 with CtVariable

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

the class VariableReferencesTest method testCheckModelConsistency.

@Test
public void testCheckModelConsistency() throws Exception {
    // 2) check that each of them is using different identification value
    class Context {

        Map<Integer, CtElement> unique = new HashMap<>();

        int maxKey = 0;

        void checkKey(int key, CtElement ele) {
            CtElement ambiquous = unique.put(key, ele);
            if (ambiquous != null) {
                fail("Two variables [" + ambiquous.toString() + " in " + getParentMethodName(ambiquous) + "," + ele.toString() + " in " + getParentMethodName(ele) + "] has same value");
            }
            maxKey = Math.max(maxKey, key);
        }
    }
    Context context = new Context();
    modelClass.filterChildren((CtElement e) -> {
        if (e instanceof CtVariable) {
            CtVariable<?> var = (CtVariable<?>) e;
            if (isTestFieldName(var.getSimpleName()) == false) {
                return false;
            }
            // check only these variables whose name is isTestFieldName(name)==true
            Integer val = getLiteralValue(var);
            // System.out.println("key = "+val+" - "+var.toString());
            context.checkKey(val, var);
        }
        return false;
    }).list();
    // System.out.println("Next available key is: "+(context.maxKey+1));
    assertTrue(context.unique.size() > 0);
    assertEquals("Only these keys were found: " + context.unique.keySet(), context.maxKey, context.unique.size());
    assertEquals("AllLocalVars#maxValue must be equal to maximum value number ", (int) getLiteralValue((CtVariable) modelClass.filterChildren(new NamedElementFilter<>(CtVariable.class, "maxValue")).first()), context.maxKey);
}
Also used : CtElement(spoon.reflect.declaration.CtElement) CtVariable(spoon.reflect.declaration.CtVariable) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) HashMap(java.util.HashMap) Map(java.util.Map) VariableReferencesModelTest(spoon.test.query_function.testclasses.VariableReferencesModelTest) Test(org.junit.Test)

Aggregations

CtVariable (spoon.reflect.declaration.CtVariable)11 Test (org.junit.Test)7 Factory (spoon.reflect.factory.Factory)4 CtLocalVariable (spoon.reflect.code.CtLocalVariable)3 CtStatement (spoon.reflect.code.CtStatement)3 CtClass (spoon.reflect.declaration.CtClass)3 CtElement (spoon.reflect.declaration.CtElement)3 CtField (spoon.reflect.declaration.CtField)3 CtPackage (spoon.reflect.declaration.CtPackage)3 CtType (spoon.reflect.declaration.CtType)3 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)3 ArrayList (java.util.ArrayList)2 Launcher (spoon.Launcher)2 CtCatch (spoon.reflect.code.CtCatch)2 CtStatementList (spoon.reflect.code.CtStatementList)2 CtExecutable (spoon.reflect.declaration.CtExecutable)2 CtMethod (spoon.reflect.declaration.CtMethod)2 CtVariableReference (spoon.reflect.reference.CtVariableReference)2 PotentialVariableDeclarationFunction (spoon.reflect.visitor.filter.PotentialVariableDeclarationFunction)2 VariableReferencesModelTest (spoon.test.query_function.testclasses.VariableReferencesModelTest)2