Search in sources :

Example 11 with CtParameter

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

the class CtRenameLocalVariableRefactoring method detectNameConflicts.

@Override
protected void detectNameConflicts() {
    /*
		 * There can be these conflicts
		 * 1) target variable would shadow before declared variable (parameter, localVariable, catchVariable)
		 * --------------------------------------------------------------------------------------------------
		 */
    PotentialVariableDeclarationFunction potentialDeclarationFnc = new PotentialVariableDeclarationFunction(newName);
    CtVariable<?> var = getTarget().map(potentialDeclarationFnc).first();
    if (var != null) {
        if (var instanceof CtField) {
        /*
				 * we have found a field of same name.
				 * It is not problem, because variables can hide field declaration.
				 * Do nothing - OK
				 */
        } else if (potentialDeclarationFnc.isTypeOnTheWay()) {
            /*
				 * There is a local class declaration between future variable reference and variable declaration `var`.
				 * The found variable declaration `var` can be hidden by target variable with newName
				 * as long as there is no reference to `var` in visibility scope of the target variable.
				 * So search for such `var` reference now
				 */
            CtVariableReference<?> shadowedVar = target.map(new SiblingsFunction().includingSelf(true).mode(Mode.NEXT)).map(new VariableReferenceFunction(var)).first();
            if (shadowedVar != null) {
                // found variable reference, which would be shadowed by variable after rename.
                createNameConflictIssue(var, shadowedVar);
            } else {
            /*
					 * there is no local variable reference, which would be shadowed by variable after rename.
					 * OK
					 */
            }
        } else {
            /*
				 * the found variable is in conflict with target variable with newName
				 */
            createNameConflictIssue(var);
        }
    }
    /*
		 * 2) target variable is shadowed by later declared variable
		 * ---------------------------------------------------------
		 */
    final QueryDriver queryDriver = new QueryDriver();
    getTarget().map(new LocalVariableScopeFunction(queryDriver)).select(new Filter<CtElement>() {

        /**
         * return true for all CtVariables, which are in conflict
         */
        @Override
        public boolean matches(CtElement element) {
            if (element instanceof CtType<?>) {
                CtType<?> localClass = (CtType<?>) element;
                // TODO use faster hasField, implemented using map(new AllFieldsFunction()).select(new NameFilter(newName)).first()!=null
                Collection<CtFieldReference<?>> fields = localClass.getAllFields();
                for (CtFieldReference<?> fieldRef : fields) {
                    if (newName.equals(fieldRef.getSimpleName())) {
                        /*
							 * we have found a local class field, which will shadow input local variable if it's reference is in visibility scope of that field.
							 * Search for target variable reference in visibility scope of this field.
							 * If found than we cannot rename target variable to newName, because that reference would be shadowed
							 */
                        queryDriver.ignoreChildrenOf(element);
                        CtLocalVariableReference<?> shadowedVar = element.map(new LocalVariableReferenceFunction(target)).first();
                        if (shadowedVar != null) {
                            createNameConflictIssue(fieldRef.getFieldDeclaration(), shadowedVar);
                            return true;
                        }
                        return false;
                    }
                }
                return false;
            }
            if (element instanceof CtVariable<?>) {
                CtVariable<?> variable = (CtVariable<?>) element;
                if (newName.equals(variable.getSimpleName()) == false) {
                    // the variable with different name. Ignore it
                    return false;
                }
                // we have found a variable with new name
                if (variable instanceof CtField) {
                    throw new SpoonException("This should not happen. The children of local class which contains a field with new name should be skipped!");
                }
                if (variable instanceof CtCatchVariable || variable instanceof CtLocalVariable || variable instanceof CtParameter) {
                    /*
						 * we have found a catch variable or local variable or parameter with new name.
						 */
                    if (queryDriver.isInContextOfLocalClass()) {
                        /*
							 * We are in context of local class.
							 * This variable would shadow input local variable after rename
							 * so we cannot rename if there exist a local variable reference in variable visibility scope.
							 */
                        queryDriver.ignoreChildrenOf(variable.getParent());
                        CtQueryable searchScope;
                        if (variable instanceof CtLocalVariable) {
                            searchScope = variable.map(new SiblingsFunction().includingSelf(true).mode(Mode.NEXT));
                        } else {
                            searchScope = variable.getParent();
                        }
                        CtLocalVariableReference<?> shadowedVar = searchScope.map(new LocalVariableReferenceFunction(target)).first();
                        if (shadowedVar != null) {
                            // found local variable reference, which would be shadowed by variable after rename.
                            createNameConflictIssue(variable, shadowedVar);
                            return true;
                        }
                        // there is no local variable reference, which would be shadowed by variable after rename.
                        return false;
                    } else {
                        /*
							 * We are not in context of local class.
							 * So this variable is in conflict. Return it
							 */
                        createNameConflictIssue(variable);
                        return true;
                    }
                } else {
                    // Any new variable type???
                    throw new SpoonException("Unexpected variable " + variable.getClass().getName());
                }
            }
            return false;
        }
    }).first();
}
Also used : CtVariableReference(spoon.reflect.reference.CtVariableReference) SiblingsFunction(spoon.reflect.visitor.filter.SiblingsFunction) SpoonException(spoon.SpoonException) CtElement(spoon.reflect.declaration.CtElement) VariableReferenceFunction(spoon.reflect.visitor.filter.VariableReferenceFunction) LocalVariableReferenceFunction(spoon.reflect.visitor.filter.LocalVariableReferenceFunction) CtFieldReference(spoon.reflect.reference.CtFieldReference) CtParameter(spoon.reflect.declaration.CtParameter) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtType(spoon.reflect.declaration.CtType) Filter(spoon.reflect.visitor.Filter) CtField(spoon.reflect.declaration.CtField) CtQueryable(spoon.reflect.visitor.chain.CtQueryable) CtVariable(spoon.reflect.declaration.CtVariable) PotentialVariableDeclarationFunction(spoon.reflect.visitor.filter.PotentialVariableDeclarationFunction) CtCatchVariable(spoon.reflect.code.CtCatchVariable) LocalVariableScopeFunction(spoon.reflect.visitor.filter.LocalVariableScopeFunction) LocalVariableReferenceFunction(spoon.reflect.visitor.filter.LocalVariableReferenceFunction)

Example 12 with CtParameter

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

the class GenericsTest method testGetDeclarationOfTypeParameterReference.

@Test
public void testGetDeclarationOfTypeParameterReference() {
    Launcher launcher = new Launcher();
    launcher.addInputResource("./src/test/java/spoon/test/generics/testclasses/ExtendedPaella.java");
    launcher.addInputResource("./src/test/java/spoon/test/generics/testclasses/Paella.java");
    launcher.buildModel();
    Factory factory = launcher.getFactory();
    CtClass extendedPaella = factory.getModel().getElements(new NamedElementFilter<>(CtClass.class, "ExtendedPaella")).get(0);
    List<CtTypeParameter> typeParameterList = extendedPaella.getFormalCtTypeParameters();
    assertEquals(1, typeParameterList.size());
    CtMethod totoMethod = factory.getModel().getElements(new NamedElementFilter<>(CtMethod.class, "toto")).get(0);
    CtTypeReference returnTypeToto = totoMethod.getType();
    CtTypeReference paramToto = ((CtParameter) totoMethod.getParameters().get(0)).getType();
    CtType declaration = returnTypeToto.getDeclaration();
    assertSame(typeParameterList.get(0), declaration);
    assertSame(typeParameterList.get(0), paramToto.getDeclaration());
    CtMethod machinMethod = factory.getModel().getElements(new NamedElementFilter<>(CtMethod.class, "machin")).get(0);
    CtTypeReference returnTypeMachin = machinMethod.getType();
    List<CtTypeParameter> formalCtTypeParameters = machinMethod.getFormalCtTypeParameters();
    assertEquals(1, formalCtTypeParameters.size());
    CtType declarationMachin = returnTypeMachin.getDeclaration();
    assertNotSame(typeParameterList.get(0), declarationMachin);
    assertSame(formalCtTypeParameters.get(0), declarationMachin);
    CtClass innerPaella = factory.getModel().getElements(new NamedElementFilter<>(CtClass.class, "InnerPaella")).get(0);
    List<CtTypeParameter> innerTypeParametersList = innerPaella.getFormalCtTypeParameters();
    assertEquals(typeParameterList.get(0), innerTypeParametersList.get(0).getSuperclass().getDeclaration());
    CtMethod innerMachinMethod = factory.getModel().getElements(new NamedElementFilter<>(CtMethod.class, "innerMachin")).get(0);
    CtTypeReference returnTypeInnerMachin = innerMachinMethod.getType();
    CtTypeReference paramInnerMachinType = ((CtParameter) innerMachinMethod.getParameters().get(0)).getType();
    List<CtTypeParameter> innerMachinFormalCtType = innerMachinMethod.getFormalCtTypeParameters();
    assertSame(typeParameterList.get(0), returnTypeInnerMachin.getDeclaration());
    assertSame(innerMachinFormalCtType.get(0), paramInnerMachinType.getDeclaration());
    CtMethod innerTotoMethod = factory.getModel().getElements(new NamedElementFilter<>(CtMethod.class, "innerToto")).get(0);
    CtTypeReference returnInnerToto = innerTotoMethod.getType();
    CtTypeReference paramInnerToto = ((CtParameter) innerTotoMethod.getParameters().get(0)).getType();
    List<CtTypeParameter> innerTotoFormatCtType = innerTotoMethod.getFormalCtTypeParameters();
    assertSame(innerTotoFormatCtType.get(0), paramInnerToto.getDeclaration());
    assertSame(innerTypeParametersList.get(0), returnInnerToto.getDeclaration());
}
Also used : LikeCtClass(spoon.test.generics.testclasses2.LikeCtClass) CtClass(spoon.reflect.declaration.CtClass) CtTypeParameter(spoon.reflect.declaration.CtTypeParameter) CtType(spoon.reflect.declaration.CtType) CtTypeReference(spoon.reflect.reference.CtTypeReference) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) Launcher(spoon.Launcher) ModelUtils.createFactory(spoon.testing.utils.ModelUtils.createFactory) Factory(spoon.reflect.factory.Factory) CtParameter(spoon.reflect.declaration.CtParameter) CtMethod(spoon.reflect.declaration.CtMethod) MainTest(spoon.test.main.MainTest) Test(org.junit.Test)

Example 13 with CtParameter

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

the class DeleteTest method testDeleteParameterOfMethod.

@Test
public void testDeleteParameterOfMethod() throws Exception {
    final Factory factory = build(Adobada.class);
    final CtClass<Adobada> adobada = factory.Class().get(Adobada.class);
    final CtMethod method = adobada.getMethod("m4", factory.Type().INTEGER_PRIMITIVE, factory.Type().FLOAT_PRIMITIVE, factory.Type().STRING);
    final CtParameter param = (CtParameter) method.getParameters().get(1);
    assertEquals(3, method.getParameters().size());
    param.delete();
    assertEquals(2, method.getParameters().size());
    assertFalse(method.getParameters().contains(param));
}
Also used : Factory(spoon.reflect.factory.Factory) CtParameter(spoon.reflect.declaration.CtParameter) Adobada(spoon.test.delete.testclasses.Adobada) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Example 14 with CtParameter

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

the class ConstructorFactoryTest method testCreate.

@Test
public void testCreate() throws Exception {
    CtClass<?> type = build("spoon.test.testclasses", "SampleClass");
    Factory factory = type.getFactory();
    ConstructorFactory ctorf = factory.Constructor();
    CoreFactory coref = factory.Core();
    Set<ModifierKind> mods = new HashSet<ModifierKind>();
    mods.add(ModifierKind.PUBLIC);
    List<CtParameter<?>> params = new ArrayList<CtParameter<?>>();
    CtParameter<?> param = coref.createParameter();
    CtTypeReference<?> tref = factory.Type().createReference(String.class);
    param.setType((CtTypeReference) tref);
    param.setSimpleName("str");
    params.add(param);
    Set<CtTypeReference<? extends Throwable>> thrownTypes = new HashSet<CtTypeReference<? extends Throwable>>();
    ctorf.create(type, mods, params, thrownTypes);
    CtConstructor<?> c = type.getConstructor(tref);
    Assert.assertEquals(1, c.getParameters().size());
    Assert.assertEquals("str", c.getParameters().get(0).getSimpleName());
}
Also used : ModifierKind(spoon.reflect.declaration.ModifierKind) ArrayList(java.util.ArrayList) CoreFactory(spoon.reflect.factory.CoreFactory) ConstructorFactory(spoon.reflect.factory.ConstructorFactory) ClassFactory(spoon.reflect.factory.ClassFactory) Factory(spoon.reflect.factory.Factory) DefaultCoreFactory(spoon.support.DefaultCoreFactory) CtParameter(spoon.reflect.declaration.CtParameter) CoreFactory(spoon.reflect.factory.CoreFactory) DefaultCoreFactory(spoon.support.DefaultCoreFactory) CtTypeReference(spoon.reflect.reference.CtTypeReference) ConstructorFactory(spoon.reflect.factory.ConstructorFactory) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 15 with CtParameter

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

the class VariableAccessTest method testDeclaringTypeOfALambdaReferencedByParameterReference.

@Test
public void testDeclaringTypeOfALambdaReferencedByParameterReference() {
    final spoon.Launcher launcher = new spoon.Launcher();
    launcher.addInputResource("src/test/resources/noclasspath/Foo3.java");
    launcher.getEnvironment().setNoClasspath(true);
    launcher.getEnvironment().setComplianceLevel(8);
    launcher.buildModel();
    launcher.getModel().getElements(new TypeFilter<CtExecutable<?>>(CtExecutable.class) {

        @Override
        public boolean matches(CtExecutable<?> exec) {
            final List<CtParameterReference<?>> guiParams = exec.getParameters().stream().map(CtParameter::getReference).collect(Collectors.toList());
            if (guiParams.size() != 1) {
                return false;
            }
            final CtParameterReference<?> param = guiParams.get(0);
            exec.getBody().getElements(new TypeFilter<CtParameterReference<?>>(CtParameterReference.class) {

                @Override
                public boolean matches(CtParameterReference<?> p) {
                    assertEquals(p.getSimpleName(), param.getSimpleName());
                    return super.matches(p);
                }
            });
            return super.matches(exec);
        }
    });
}
Also used : Launcher(spoon.Launcher) CtParameterReference(spoon.reflect.reference.CtParameterReference) Launcher(spoon.Launcher) List(java.util.List) CtParameter(spoon.reflect.declaration.CtParameter) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtExecutable(spoon.reflect.declaration.CtExecutable) Test(org.junit.Test)

Aggregations

CtParameter (spoon.reflect.declaration.CtParameter)32 Test (org.junit.Test)18 CtMethod (spoon.reflect.declaration.CtMethod)13 Factory (spoon.reflect.factory.Factory)12 CtTypeReference (spoon.reflect.reference.CtTypeReference)10 ArrayList (java.util.ArrayList)8 Launcher (spoon.Launcher)8 CtElement (spoon.reflect.declaration.CtElement)7 List (java.util.List)6 CtIf (spoon.reflect.code.CtIf)6 CtLocalVariable (spoon.reflect.code.CtLocalVariable)6 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)6 CtConstructor (spoon.reflect.declaration.CtConstructor)5 CtField (spoon.reflect.declaration.CtField)5 CtInvocation (spoon.reflect.code.CtInvocation)4 CtClass (spoon.reflect.declaration.CtClass)4 CtType (spoon.reflect.declaration.CtType)4 SpoonException (spoon.SpoonException)3 CtComment (spoon.reflect.code.CtComment)3 CtConstructorCall (spoon.reflect.code.CtConstructorCall)3