Search in sources :

Example 21 with CtExecutable

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

the class ExecutableReferenceGenericTest method testOneReferenceWithGenericMethodOutOfTheClass.

@Test
public void testOneReferenceWithGenericMethodOutOfTheClass() throws Exception {
    final CtClass<?> clazz = getCtClassByName("MyClass");
    final CtClass<?> clazz2 = getCtClassByName("MyClass2");
    CtMethod<?> methodA = getCtMethodByNameFromCtClass(clazz2, "methodA");
    List<CtExecutableReference<?>> refsMethodA = getReferencesOfAMethod(methodA);
    CtMethod<?> expectedMethod1 = getCtMethodByNameFromCtClass(clazz, "method1");
    assertEquals(1, refsMethodA.size());
    CtExecutable execRefsMethods2 = refsMethodA.get(0).getDeclaration();
    // T has more information in the invocation than its declaration because of the argument type
    // assertEquals(expectedMethod1, refsMethodA.get(0).getDeclaration());
    assertEquals(execRefsMethods2.getSignature(), "method1(T extends java.lang.String)");
}
Also used : CtExecutableReference(spoon.reflect.reference.CtExecutableReference) CtExecutable(spoon.reflect.declaration.CtExecutable) Test(org.junit.Test)

Example 22 with CtExecutable

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

the class ExecutableReferenceTest method testCreateReferenceForAnonymousExecutable.

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

        @Override
        public boolean matches(final CtExecutable<?> exec) {
            try {
                exec.getReference();
            } catch (ClassCastException ex) {
                fail(ex.getMessage());
            }
            return super.matches(exec);
        }
    });
}
Also used : Launcher(spoon.Launcher) Launcher(spoon.Launcher) CtExecutable(spoon.reflect.declaration.CtExecutable) Test(org.junit.Test)

Example 23 with CtExecutable

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

the class JDTTreeBuilderHelper method createVariableAccessNoClasspath.

/**
 * Analyzes if {@code singleNameReference} points to a {@link CtVariable} visible in current
 * scope and, if existent, returns its corresponding {@link CtVariableAccess}. Returns
 * {@code null} if {@code singleNameReference} could not be resolved as variable access. Since
 * we are in noclasspath mode this function may also returns {@code null} if
 * {@code singleNameReference} points to a variable declared by an unknown class.
 *
 * @param singleNameReference
 * 		The potential variable access.
 * @return A {@link CtVariableAccess} if {@code singleNameReference} points to a variable
 * 		   visible in current scope, {@code null} otherwise.
 */
<T> CtVariableAccess<T> createVariableAccessNoClasspath(SingleNameReference singleNameReference) {
    final TypeFactory typeFactory = jdtTreeBuilder.getFactory().Type();
    final CoreFactory coreFactory = jdtTreeBuilder.getFactory().Core();
    final ExecutableFactory executableFactory = jdtTreeBuilder.getFactory().Executable();
    final ContextBuilder contextBuilder = jdtTreeBuilder.getContextBuilder();
    final ReferenceBuilder referenceBuilder = jdtTreeBuilder.getReferencesBuilder();
    final PositionBuilder positionBuilder = jdtTreeBuilder.getPositionBuilder();
    final String name = CharOperation.charToString(singleNameReference.token);
    final CtVariable<T> variable = contextBuilder.getVariableDeclaration(name);
    if (variable == null) {
        return null;
    }
    final CtVariableReference<T> variableReference;
    final CtVariableAccess<T> variableAccess;
    if (variable instanceof CtParameter) {
        // create variable of concrete type to avoid type casting while calling methods
        final CtParameterReference<T> parameterReference = coreFactory.createParameterReference();
        if (variable.getParent() instanceof CtLambda) {
        // nothing
        } else {
            // Unfortunately, we can not use `variable.getReference()` here as some parent
            // references (in terms of Java objects) have not been set up yet. Thus, we need to
            // create the required parameter reference by our own.
            // Since the given parameter has not been declared in a lambda expression it must
            // have been declared by a method/constructor.
            final CtExecutable executable = (CtExecutable) variable.getParent();
            // create list of executable's parameter types
            final List<CtTypeReference<?>> parameterTypesOfExecutable = new ArrayList<>();
            @SuppressWarnings("unchecked") final List<CtParameter<?>> parametersOfExecutable = executable.getParameters();
            for (CtParameter<?> parameter : parametersOfExecutable) {
                parameterTypesOfExecutable.add(parameter.getType() != null ? parameter.getType().clone() : // it's the best match :(
                typeFactory.OBJECT.clone());
            }
            // find executable's corresponding jdt element
            AbstractMethodDeclaration executableJDT = null;
            for (final ASTPair astPair : contextBuilder.stack) {
                if (astPair.element == executable) {
                    executableJDT = (AbstractMethodDeclaration) astPair.node;
                }
            }
            assert executableJDT != null;
            // create a reference to executable's declaring class
            final CtTypeReference declaringReferenceOfExecutable = // available
            executableJDT.binding == null ? coreFactory.createTypeReference() : referenceBuilder.getTypeReference(executableJDT.binding.declaringClass);
            // If executable is a constructor, `executable.getType()` returns null since the
            // parent is not available yet. Fortunately, however, the return type of a
            // constructor is its declaring class which, in our case, is already available with
            // declaringReferenceOfExecutable.
            CtTypeReference executableTypeReference = executable instanceof CtConstructor ? // indirectly sets the parent of `rt` and, thus, may break the AST!
            declaringReferenceOfExecutable.clone() : executable.getType().clone();
        }
        variableReference = parameterReference;
        variableAccess = isLhsAssignment(contextBuilder, singleNameReference) ? coreFactory.<T>createVariableWrite() : coreFactory.<T>createVariableRead();
    } else if (variable instanceof CtField) {
        variableReference = variable.getReference();
        variableAccess = isLhsAssignment(contextBuilder, singleNameReference) ? coreFactory.<T>createFieldWrite() : coreFactory.<T>createFieldRead();
    } else {
        // CtLocalVariable, CtCatchVariable, ...
        variableReference = variable.getReference();
        variableAccess = isLhsAssignment(contextBuilder, singleNameReference) ? coreFactory.<T>createVariableWrite() : coreFactory.<T>createVariableRead();
    }
    variableReference.setSimpleName(name);
    variableReference.setPosition(positionBuilder.buildPosition(singleNameReference.sourceStart(), singleNameReference.sourceEnd()));
    variableAccess.setVariable(variableReference);
    return variableAccess;
}
Also used : CtLambda(spoon.reflect.code.CtLambda) ArrayList(java.util.ArrayList) CtParameter(spoon.reflect.declaration.CtParameter) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtField(spoon.reflect.declaration.CtField) CoreFactory(spoon.reflect.factory.CoreFactory) CtExecutable(spoon.reflect.declaration.CtExecutable) CtConstructor(spoon.reflect.declaration.CtConstructor) TypeFactory(spoon.reflect.factory.TypeFactory) ExecutableFactory(spoon.reflect.factory.ExecutableFactory) AbstractMethodDeclaration(org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration)

Example 24 with CtExecutable

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

the class CtStatementImpl method insertBefore.

/**
 * inserts all statements of `statementsToBeInserted` just before `target`
 */
public static void insertBefore(CtStatement target, CtStatementList statementsToBeInserted) throws ParentNotInitializedException {
    CtElement targetParent = target.getParent();
    if (targetParent instanceof CtExecutable) {
        throw new SpoonException("cannot insert in this context (use insertEnd?)");
    }
    try {
        if (target.getParent(CtConstructor.class) != null) {
            if (target instanceof CtInvocation && ((CtInvocation<?>) target).getExecutable().getSimpleName().startsWith(CtExecutableReference.CONSTRUCTOR_NAME)) {
                throw new SpoonException("cannot insert a statement before a super or this invocation.");
            }
        }
    } catch (ParentNotInitializedException ignore) {
    // no parent set somewhere
    }
    new InsertVisitor(target, statementsToBeInserted, InsertType.BEFORE).scan(targetParent);
}
Also used : CtInvocation(spoon.reflect.code.CtInvocation) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) SpoonException(spoon.SpoonException) CtElement(spoon.reflect.declaration.CtElement) CtExecutable(spoon.reflect.declaration.CtExecutable) CtConstructor(spoon.reflect.declaration.CtConstructor)

Example 25 with CtExecutable

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

the class CtStatementImpl method insertAfter.

public static void insertAfter(CtStatement target, CtStatementList statements) throws ParentNotInitializedException {
    CtElement e = target.getParent();
    if (e instanceof CtExecutable) {
        throw new RuntimeException("cannot insert in this context (use insertEnd?)");
    }
    new InsertVisitor(target, statements, InsertType.AFTER).scan(e);
}
Also used : CtElement(spoon.reflect.declaration.CtElement) CtExecutable(spoon.reflect.declaration.CtExecutable)

Aggregations

CtExecutable (spoon.reflect.declaration.CtExecutable)26 Test (org.junit.Test)10 CtType (spoon.reflect.declaration.CtType)9 CtExecutableReference (spoon.reflect.reference.CtExecutableReference)7 Launcher (spoon.Launcher)6 CtElement (spoon.reflect.declaration.CtElement)6 Factory (spoon.reflect.factory.Factory)6 File (java.io.File)5 CtConstructor (spoon.reflect.declaration.CtConstructor)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 SpoonException (spoon.SpoonException)4 CtField (spoon.reflect.declaration.CtField)4 CtMethod (spoon.reflect.declaration.CtMethod)4 SpoonModelBuilder (spoon.SpoonModelBuilder)3 CtParameterRemoveRefactoring (spoon.refactoring.CtParameterRemoveRefactoring)3 CtInvocation (spoon.reflect.code.CtInvocation)3 CtLambda (spoon.reflect.code.CtLambda)3 CtClass (spoon.reflect.declaration.CtClass)3 CtParameter (spoon.reflect.declaration.CtParameter)3