Search in sources :

Example 1 with Environment

use of spoon.compiler.Environment in project dspot by STAMP-project.

the class DSpotUtils method printCtTypeToGivenDirectory.

public static void printCtTypeToGivenDirectory(CtType<?> type, File directory) {
    Factory factory = type.getFactory();
    Environment env = factory.getEnvironment();
    env.setAutoImports(true);
    env.setCommentEnabled(withComment);
    JavaOutputProcessor processor = new JavaOutputProcessor(new DefaultJavaPrettyPrinter(env));
    processor.setFactory(factory);
    processor.setOutputDirectory(directory);
    processor.createJavaFile(type);
    env.setAutoImports(false);
}
Also used : LoggerFactory(org.slf4j.LoggerFactory) Factory(spoon.reflect.factory.Factory) Environment(spoon.compiler.Environment) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) JavaOutputProcessor(spoon.support.JavaOutputProcessor)

Example 2 with Environment

use of spoon.compiler.Environment in project spoon by INRIA.

the class Launcher method run.

/**
 * Runs Spoon using the given compiler, with the given run options. A Spoon
 * run will perform the following tasks:
 *
 * <ol>
 * <li>Source model building in the given compiler:
 * {@link SpoonModelBuilder#build()}.</li>
 * <li>Template model building in the given factory (if any template source
 * is given): {@link SpoonModelBuilder#build()}.</li>
 * <li>Model processing with the list of given processors if any:
 * {@link SpoonModelBuilder#instantiateAndProcess(List)}.</li>
 * <li>Processed Source code printing and generation (can be disabled with
 * {@link OutputType#NO_OUTPUT}):
 * {@link SpoonModelBuilder#generateProcessedSourceFiles(OutputType)}.</li>
 * <li>Processed source code compilation (optional):
 * </ol>
 */
@Override
public void run() {
    Environment env = modelBuilder.getFactory().getEnvironment();
    env.reportProgressMessage(getVersionMessage());
    env.reportProgressMessage("running Spoon...");
    env.reportProgressMessage("start processing...");
    long t = 0;
    long tstart = System.currentTimeMillis();
    buildModel();
    process();
    prettyprint();
    if (env.shouldCompile()) {
        // we compile the types from the factory, they may have been modified by some processors
        modelBuilder.compile(InputType.CTTYPES);
    }
    t = System.currentTimeMillis();
    env.debugMessage("program spooning done in " + (t - tstart) + " ms");
    env.reportEnd();
}
Also used : StandardEnvironment(spoon.support.StandardEnvironment) Environment(spoon.compiler.Environment)

Example 3 with Environment

use of spoon.compiler.Environment in project spoon by INRIA.

the class DefaultPrettyPrinterTest method importsFromMultipleTypesSupported.

@Test
public void importsFromMultipleTypesSupported() {
    final Launcher launcher = new Launcher();
    launcher.addInputResource("./src/test/java/spoon/test/prettyprinter/testclasses/A.java");
    launcher.run();
    Environment env = launcher.getEnvironment();
    env.setAutoImports(true);
    DefaultJavaPrettyPrinter printer = new DefaultJavaPrettyPrinter(env);
    printer.calculate(null, Arrays.asList(launcher.getFactory().Class().get("spoon.test.prettyprinter.testclasses.A"), launcher.getFactory().Class().get("spoon.test.prettyprinter.testclasses.B")));
    assertTrue(printer.getResult().contains("import java.util.ArrayList;"));
}
Also used : Launcher(spoon.Launcher) Environment(spoon.compiler.Environment) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) Test(org.junit.Test)

Example 4 with Environment

use of spoon.compiler.Environment 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 Environment

use of spoon.compiler.Environment in project spoon by INRIA.

the class JDTBasedSpoonCompiler method getCompilationUnitInputStream.

protected InputStream getCompilationUnitInputStream(String path) {
    Environment env = factory.getEnvironment();
    spoon.reflect.cu.CompilationUnit cu = factory.CompilationUnit().getMap().get(path);
    List<CtType<?>> toBePrinted = cu.getDeclaredTypes();
    PrettyPrinter printer = new DefaultJavaPrettyPrinter(env);
    printer.calculate(cu, toBePrinted);
    return new ByteArrayInputStream(printer.getResult().toString().getBytes());
}
Also used : PrettyPrinter(spoon.reflect.visitor.PrettyPrinter) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) CtType(spoon.reflect.declaration.CtType) ByteArrayInputStream(java.io.ByteArrayInputStream) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) Environment(spoon.compiler.Environment) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter)

Aggregations

Environment (spoon.compiler.Environment)10 File (java.io.File)4 Test (org.junit.Test)4 DefaultJavaPrettyPrinter (spoon.reflect.visitor.DefaultJavaPrettyPrinter)4 StandardEnvironment (spoon.support.StandardEnvironment)3 Launcher (spoon.Launcher)2 CtType (spoon.reflect.declaration.CtType)2 JavaOutputProcessor (spoon.support.JavaOutputProcessor)2 JSAPException (com.martiansoftware.jsap.JSAPException)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 Charset (java.nio.charset.Charset)1 ArrayDeque (java.util.ArrayDeque)1 ArrayList (java.util.ArrayList)1 TypeDeclaration (org.eclipse.jdt.internal.compiler.ast.TypeDeclaration)1 TypeReference (org.eclipse.jdt.internal.compiler.ast.TypeReference)1 INameEnvironment (org.eclipse.jdt.internal.compiler.env.INameEnvironment)1 FieldBinding (org.eclipse.jdt.internal.compiler.lookup.FieldBinding)1 ReferenceBinding (org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding)1