Search in sources :

Example 1 with SpoonClassNotFoundException

use of spoon.support.SpoonClassNotFoundException in project spoon by INRIA.

the class TypeFactory method get.

/**
 * Gets a type from its runtime Java class. If the class isn't in the spoon path,
 * the class will be build from the Java reflection and will be marked as
 * shadow (see {@link spoon.reflect.declaration.CtShadowable}).
 *
 * @param <T>
 * 		actual type of the class
 * @param cl
 * 		the java class: note that this class should be Class&lt;T&gt; but it
 * 		then poses problem when T is a generic type itself
 */
@SuppressWarnings("unchecked")
public <T> CtType<T> get(Class<?> cl) {
    final CtType<T> aType = get(cl.getName());
    if (aType == null) {
        final CtType<T> shadowClass = (CtType<T>) this.shadowCache.get(cl);
        if (shadowClass == null) {
            CtType<T> newShadowClass;
            try {
                newShadowClass = new JavaReflectionTreeBuilder(createFactory()).scan((Class<T>) cl);
            } catch (Throwable e) {
                throw new SpoonClassNotFoundException("cannot create shadow class: " + cl.getName(), e);
            }
            newShadowClass.setFactory(factory);
            newShadowClass.accept(new CtScanner() {

                @Override
                public void scan(CtElement element) {
                    if (element != null) {
                        element.setFactory(factory);
                    }
                }
            });
            this.shadowCache.put(cl, newShadowClass);
            return newShadowClass;
        } else {
            return shadowClass;
        }
    }
    return aType;
}
Also used : CtType(spoon.reflect.declaration.CtType) JavaReflectionTreeBuilder(spoon.support.visitor.java.JavaReflectionTreeBuilder) CtElement(spoon.reflect.declaration.CtElement) SpoonClassNotFoundException(spoon.support.SpoonClassNotFoundException) CtNewClass(spoon.reflect.code.CtNewClass) CtClass(spoon.reflect.declaration.CtClass) CtScanner(spoon.reflect.visitor.CtScanner)

Example 2 with SpoonClassNotFoundException

use of spoon.support.SpoonClassNotFoundException in project spoon by INRIA.

the class CompilationTest method testPrecompile.

@Test
public void testPrecompile() {
    // without precompile
    Launcher l = new Launcher();
    l.setArgs(new String[] { "--noclasspath", "-i", "src/test/resources/compilation/" });
    l.buildModel();
    CtClass klass = l.getFactory().Class().get("compilation.Bar");
    // without precompile, actualClass does not exist (an exception is thrown)
    try {
        klass.getSuperInterfaces().toArray(new CtTypeReference[0])[0].getActualClass();
        fail();
    } catch (SpoonClassNotFoundException ignore) {
    }
    // with precompile
    Launcher l2 = new Launcher();
    l2.setArgs(new String[] { "--precompile", "--noclasspath", "-i", "src/test/resources/compilation/" });
    l2.buildModel();
    CtClass klass2 = l2.getFactory().Class().get("compilation.Bar");
    // with precompile, actualClass is not null
    Class actualClass = klass2.getSuperInterfaces().toArray(new CtTypeReference[0])[0].getActualClass();
    assertNotNull(actualClass);
    assertEquals("IBar", actualClass.getSimpleName());
    // precompile can be used to compile processors on the fly
    Launcher l3 = new Launcher();
    l3.setArgs(new String[] { "--precompile", "--noclasspath", "-i", "src/test/resources/compilation/", "-p", "compilation.SimpleProcessor" });
    l3.run();
}
Also used : CtClass(spoon.reflect.declaration.CtClass) Launcher(spoon.Launcher) SpoonClassNotFoundException(spoon.support.SpoonClassNotFoundException) CtClass(spoon.reflect.declaration.CtClass) Test(org.junit.Test)

Example 3 with SpoonClassNotFoundException

use of spoon.support.SpoonClassNotFoundException in project dspot by STAMP-project.

the class AssertGeneratorHelper method isStmtToLog.

private static boolean isStmtToLog(String filter, CtStatement statement) {
    if (!(statement.getParent() instanceof CtBlock)) {
        return false;
    }
    // contract: for now, we do not log values inside loop
    if (statement.getParent(CtLoop.class) != null) {
        return false;
    }
    if (statement instanceof CtInvocation) {
        CtInvocation invocation = (CtInvocation) statement;
        // type tested by the test class
        String targetType = "";
        if (invocation.getTarget() != null && invocation.getTarget().getType() != null) {
            targetType = invocation.getTarget().getType().getQualifiedName();
        }
        if (targetType.startsWith(filter)) {
            return (!isVoidReturn(invocation) && !isGetter(invocation));
        } else {
            return !isVoidReturn(invocation);
        }
    }
    if (statement instanceof CtLocalVariable || statement instanceof CtAssignment || statement instanceof CtVariableWrite) {
        if (statement instanceof CtNamedElement) {
            if (((CtNamedElement) statement).getSimpleName().startsWith("__DSPOT_")) {
                return false;
            }
        }
        final CtTypeReference type = ((CtTypedElement) statement).getType();
        if (type.getQualifiedName().startsWith(filter)) {
            return true;
        } else {
            try {
                return type.getActualClass() == String.class;
            } catch (SpoonClassNotFoundException e) {
                return false;
            }
        }
    } else {
        return false;
    }
}
Also used : CtTypeReference(spoon.reflect.reference.CtTypeReference) SpoonClassNotFoundException(spoon.support.SpoonClassNotFoundException) CtTypedElement(spoon.reflect.declaration.CtTypedElement) CtNamedElement(spoon.reflect.declaration.CtNamedElement)

Example 4 with SpoonClassNotFoundException

use of spoon.support.SpoonClassNotFoundException in project spoon by INRIA.

the class ContextBuilder method getVariableDeclaration.

@SuppressWarnings("unchecked")
private <T, U extends CtVariable<T>> U getVariableDeclaration(final String name, final Class<U> clazz) {
    final CoreFactory coreFactory = jdtTreeBuilder.getFactory().Core();
    final TypeFactory typeFactory = jdtTreeBuilder.getFactory().Type();
    final ClassFactory classFactory = jdtTreeBuilder.getFactory().Class();
    final InterfaceFactory interfaceFactory = jdtTreeBuilder.getFactory().Interface();
    final FieldFactory fieldFactory = jdtTreeBuilder.getFactory().Field();
    final ReferenceBuilder referenceBuilder = jdtTreeBuilder.getReferencesBuilder();
    final Environment environment = jdtTreeBuilder.getFactory().getEnvironment();
    // there is some extra work to do if we are looking for CtFields (and subclasses)
    final boolean lookingForFields = clazz == null || coreFactory.createField().getClass().isAssignableFrom(clazz);
    // try to find the variable on stack beginning with the most recent element
    for (final ASTPair astPair : stack) {
        // the variable may have been declared directly by one of these elements
        final ScopeRespectingVariableScanner<U> scanner = new ScopeRespectingVariableScanner(name, clazz);
        astPair.element.accept(scanner);
        if (scanner.getResult() != null) {
            return scanner.getResult();
        }
        // the variable may have been declared in a super class/interface
        if (lookingForFields && astPair.node instanceof TypeDeclaration) {
            final TypeDeclaration nodeDeclaration = (TypeDeclaration) astPair.node;
            final Deque<ReferenceBinding> referenceBindings = new ArrayDeque<>();
            // add super class if any
            if (nodeDeclaration.superclass != null && nodeDeclaration.superclass.resolvedType instanceof ReferenceBinding) {
                referenceBindings.push((ReferenceBinding) nodeDeclaration.superclass.resolvedType);
            }
            // add interfaces if any
            if (nodeDeclaration.superInterfaces != null) {
                for (final TypeReference tr : nodeDeclaration.superInterfaces) {
                    if (tr.resolvedType instanceof ReferenceBinding) {
                        referenceBindings.push((ReferenceBinding) tr.resolvedType);
                    }
                }
            }
            while (!referenceBindings.isEmpty()) {
                final ReferenceBinding referenceBinding = referenceBindings.pop();
                for (final FieldBinding fieldBinding : referenceBinding.fields()) {
                    if (name.equals(new String(fieldBinding.readableName()))) {
                        final String qualifiedNameOfParent = new String(referenceBinding.readableName());
                        final CtType parentOfField = referenceBinding.isClass() ? classFactory.create(qualifiedNameOfParent) : interfaceFactory.create(qualifiedNameOfParent);
                        U field = (U) fieldFactory.create(parentOfField, EnumSet.noneOf(ModifierKind.class), referenceBuilder.getTypeReference(fieldBinding.type), name);
                        return field.setExtendedModifiers(JDTTreeBuilderQuery.getModifiers(fieldBinding.modifiers, true, false));
                    }
                }
                // add super class if any
                final ReferenceBinding superclass = referenceBinding.superclass();
                if (superclass != null) {
                    referenceBindings.push(superclass);
                }
                // add interfaces if any
                final ReferenceBinding[] interfaces = referenceBinding.superInterfaces();
                if (interfaces != null) {
                    for (ReferenceBinding rb : interfaces) {
                        referenceBindings.push(rb);
                    }
                }
            }
        }
    }
    // the variable may have been imported statically from another class/interface
    if (lookingForFields) {
        final CtReference potentialReferenceToField = referenceBuilder.getDeclaringReferenceFromImports(name.toCharArray());
        if (potentialReferenceToField != null && potentialReferenceToField instanceof CtTypeReference) {
            final CtTypeReference typeReference = (CtTypeReference) potentialReferenceToField;
            try {
                final Class classOfType = typeReference.getActualClass();
                if (classOfType != null) {
                    final CtType declaringTypeOfField = typeReference.isInterface() ? interfaceFactory.get(classOfType) : classFactory.get(classOfType);
                    final CtField field = declaringTypeOfField.getField(name);
                    if (field != null) {
                        return (U) field;
                    }
                }
            } catch (final SpoonClassNotFoundException scnfe) {
                // field that has been imported statically from another class (or interface).
                if (environment.getNoClasspath()) {
                    // assume a constant value according to JLS.
                    if (name.toUpperCase().equals(name)) {
                        final CtType parentOfField = classFactory.create(typeReference.getQualifiedName());
                        // it is the best thing we can do
                        final CtField field = coreFactory.createField();
                        field.setParent(parentOfField);
                        field.setSimpleName(name);
                        // it is the best thing we can do
                        field.setType(typeFactory.nullType());
                        return (U) field;
                    }
                }
            }
        }
    }
    return null;
}
Also used : FieldFactory(spoon.reflect.factory.FieldFactory) ClassFactory(spoon.reflect.factory.ClassFactory) ReferenceBinding(org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding) CtReference(spoon.reflect.reference.CtReference) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtField(spoon.reflect.declaration.CtField) SpoonClassNotFoundException(spoon.support.SpoonClassNotFoundException) TypeReference(org.eclipse.jdt.internal.compiler.ast.TypeReference) CtTypeReference(spoon.reflect.reference.CtTypeReference) InterfaceFactory(spoon.reflect.factory.InterfaceFactory) CoreFactory(spoon.reflect.factory.CoreFactory) ArrayDeque(java.util.ArrayDeque) CtType(spoon.reflect.declaration.CtType) FieldBinding(org.eclipse.jdt.internal.compiler.lookup.FieldBinding) Environment(spoon.compiler.Environment) TypeFactory(spoon.reflect.factory.TypeFactory) TypeDeclaration(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration)

Example 5 with SpoonClassNotFoundException

use of spoon.support.SpoonClassNotFoundException in project spoon by INRIA.

the class SuperInheritanceHierarchyFunction method apply.

@Override
public void apply(CtTypeInformation input, CtConsumer<Object> outputConsumer) {
    CtTypeReference<?> typeRef;
    CtType<?> type;
    // detect whether input is a class or something else (e.g. interface)
    boolean isClass;
    if (input instanceof CtType) {
        type = (CtType<?>) input;
        typeRef = type.getReference();
    } else {
        typeRef = (CtTypeReference<?>) input;
        try {
            type = typeRef.getTypeDeclaration();
        } catch (SpoonClassNotFoundException e) {
            if (typeRef.getFactory().getEnvironment().getNoClasspath() == false) {
                throw e;
            }
            type = null;
        }
    }
    // if the type is unknown, than we expect it is interface, otherwise we would visit java.lang.Object too, even for interfaces
    isClass = type == null ? false : (type instanceof CtClass);
    if (isClass == false && includingInterfaces == false) {
        // the input is interface, but this scanner should visit only interfaces. Finish
        return;
    }
    ScanningMode mode = enter(typeRef, isClass);
    if (mode == SKIP_ALL) {
        // listener decided to not visit that input. Finish
        return;
    }
    if (includingSelf) {
        sendResult(typeRef, outputConsumer);
        if (query.isTerminated()) {
            mode = SKIP_CHILDREN;
        }
    }
    if (mode == NORMAL) {
        if (isClass == false) {
            visitSuperInterfaces(typeRef, outputConsumer);
        } else {
            // call visitSuperClasses only for input of type class. The contract of visitSuperClasses requires that
            visitSuperClasses(typeRef, outputConsumer, includingInterfaces);
        }
    }
    exit(typeRef, isClass);
}
Also used : CtClass(spoon.reflect.declaration.CtClass) CtType(spoon.reflect.declaration.CtType) SpoonClassNotFoundException(spoon.support.SpoonClassNotFoundException) ScanningMode(spoon.reflect.visitor.chain.ScanningMode)

Aggregations

SpoonClassNotFoundException (spoon.support.SpoonClassNotFoundException)11 CtTypeReference (spoon.reflect.reference.CtTypeReference)5 Test (org.junit.Test)4 CtType (spoon.reflect.declaration.CtType)4 Launcher (spoon.Launcher)3 CtClass (spoon.reflect.declaration.CtClass)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Factory (spoon.reflect.factory.Factory)2 CtScanner (spoon.reflect.visitor.CtScanner)2 ScanningMode (spoon.reflect.visitor.chain.ScanningMode)2 File (java.io.File)1 URLClassLoader (java.net.URLClassLoader)1 ArrayDeque (java.util.ArrayDeque)1 TypeDeclaration (org.eclipse.jdt.internal.compiler.ast.TypeDeclaration)1 TypeReference (org.eclipse.jdt.internal.compiler.ast.TypeReference)1 FieldBinding (org.eclipse.jdt.internal.compiler.lookup.FieldBinding)1 ReferenceBinding (org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding)1 Environment (spoon.compiler.Environment)1 CtFieldAccess (spoon.reflect.code.CtFieldAccess)1