Search in sources :

Example 81 with CtType

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

the class TypeReferenceTest method testGetTypeDeclaration.

@Test
public void testGetTypeDeclaration() throws Exception {
    Launcher l = new Launcher();
    l.addInputResource("src/test/resources/compilation/compilation-tests/");
    l.buildModel();
    CtType<?> bar = l.getFactory().Type().get("compilation.Bar");
    CtType iBar = bar.getSuperInterfaces().toArray(new CtTypeReference[0])[0].getTypeDeclaration();
    assertNotNull(iBar);
    assertEquals("compilation.IBar", iBar.getQualifiedName());
}
Also used : CtType(spoon.reflect.declaration.CtType) Launcher(spoon.Launcher) Test(org.junit.Test)

Example 82 with CtType

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

the class ElasticsearchStackoverflowTest method testStackOverflow.

@Test
public void testStackOverflow() {
    Launcher launcher = new Launcher();
    launcher.addInputResource("./src/test/resources/noclasspath/elasticsearch-stackoverflow");
    launcher.getEnvironment().setNoClasspath(true);
    launcher.buildModel();
    CtModel model = launcher.getModel();
    Scanner scanner = new Scanner();
    scanner.scan(model.getRootPackage());
    List<CtExecutableReference> executables = launcher.getModel().getElements(new TypeFilter<CtExecutableReference>(CtExecutableReference.class));
    assertFalse(executables.isEmpty());
    boolean result = false;
    for (CtExecutableReference execRef : executables) {
        if (execRef.getSimpleName().equals("setParentTask")) {
            CtTypeReference typeRef = execRef.getDeclaringType();
            assertTrue(typeRef instanceof CtTypeParameterReference);
            assertEquals("ShardRequest", typeRef.getSimpleName());
            CtType typeRefDecl = typeRef.getDeclaration();
            assertEquals("BroadcastShardRequest", typeRefDecl.getSuperclass().getSimpleName());
            assertNull(execRef.getDeclaration());
            result = true;
        }
    }
    assertTrue(result);
}
Also used : CtScanner(spoon.reflect.visitor.CtScanner) CtTypeParameterReference(spoon.reflect.reference.CtTypeParameterReference) CtType(spoon.reflect.declaration.CtType) CtTypeReference(spoon.reflect.reference.CtTypeReference) Launcher(spoon.Launcher) CtExecutableReference(spoon.reflect.reference.CtExecutableReference) CtModel(spoon.reflect.CtModel) Test(org.junit.Test)

Example 83 with CtType

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

the class JavaOutputProcessor method createJavaFile.

/**
 * Creates the Java file associated to the given element. Splits top-level
 * classes in different files (even if they are in the same file in the
 * original sources).
 */
public void createJavaFile(CtType<?> element) {
    Path typePath = getElementPath(element);
    getEnvironment().debugMessage("printing " + element.getQualifiedName() + " to " + typePath);
    // we only create a file for top-level classes
    if (!element.isTopLevel()) {
        throw new IllegalArgumentException();
    }
    CompilationUnit cu = this.getFactory().CompilationUnit().getOrCreate(element);
    List<CtType<?>> toBePrinted = new ArrayList<>();
    toBePrinted.add(element);
    printer.calculate(cu, toBePrinted);
    PrintStream stream = null;
    // print type
    try {
        File file = typePath.toFile();
        file.createNewFile();
        if (!printedFiles.contains(file)) {
            printedFiles.add(file);
        }
        stream = new PrintStream(file);
        stream.print(printer.getResult());
        for (CtType<?> t : toBePrinted) {
            lineNumberMappings.put(t.getQualifiedName(), printer.getLineNumberMapping());
        }
        stream.close();
    } catch (IOException e) {
        Launcher.LOGGER.error(e.getMessage(), e);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
Also used : Path(java.nio.file.Path) CompilationUnit(spoon.reflect.cu.CompilationUnit) PrintStream(java.io.PrintStream) CtType(spoon.reflect.declaration.CtType) ArrayList(java.util.ArrayList) IOException(java.io.IOException) File(java.io.File)

Example 84 with CtType

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

the class CompilationUnitWrapper method getContents.

@Override
public char[] getContents() {
    DefaultJavaPrettyPrinter printer = new DefaultJavaPrettyPrinter(type.getFactory().getEnvironment());
    List<CtType<?>> types = new ArrayList<>();
    types.add(type);
    printer.calculate(type.getPosition().getCompilationUnit(), types);
    String result = printer.getResult();
    char[] content = result.toCharArray();
    return content;
}
Also used : CtType(spoon.reflect.declaration.CtType) ArrayList(java.util.ArrayList) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter)

Example 85 with CtType

use of spoon.reflect.declaration.CtType 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)

Aggregations

CtType (spoon.reflect.declaration.CtType)134 Test (org.junit.Test)67 Launcher (spoon.Launcher)60 ArrayList (java.util.ArrayList)42 CtMethod (spoon.reflect.declaration.CtMethod)38 CtTypeReference (spoon.reflect.reference.CtTypeReference)30 DefaultJavaPrettyPrinter (spoon.reflect.visitor.DefaultJavaPrettyPrinter)20 File (java.io.File)19 Factory (spoon.reflect.factory.Factory)19 PrettyPrinter (spoon.reflect.visitor.PrettyPrinter)19 List (java.util.List)18 Collectors (java.util.stream.Collectors)17 CtField (spoon.reflect.declaration.CtField)17 CtElement (spoon.reflect.declaration.CtElement)16 CtPackage (spoon.reflect.declaration.CtPackage)16 InputConfiguration (fr.inria.diversify.utils.sosiefier.InputConfiguration)14 IOException (java.io.IOException)12 SpoonException (spoon.SpoonException)12 DSpotCompiler (fr.inria.diversify.utils.compilation.DSpotCompiler)11 Set (java.util.Set)11