Search in sources :

Example 1 with CtType

use of spoon.reflect.declaration.CtType in project Ex2Amplifier by STAMP-project.

the class MainGenerator method generateMainMethodFromTestMethod.

public static CtMethod<?> generateMainMethodFromTestMethod(CtMethod<?> testMethod, CtType<?> testClass) {
    final Factory factory = testMethod.getFactory();
    final CtBlock<?> blockMain = new AssertionRemover().removeAssertion(testMethod).getBody().clone();
    final List<CtLiteral<?>> originalLiterals = blockMain.getElements(Ex2Amplifier.CT_LITERAL_TYPE_FILTER);
    final int[] count = new int[] { 1 };
    final List<CtLocalVariable<?>> localVariables = originalLiterals.stream().map(literal -> factory.createLocalVariable(Utils.getRealTypeOfLiteral(literal), "lit" + count[0]++, factory.createCodeSnippetExpression(createMakeRead(factory, literal)))).collect(Collectors.toList());
    final CtMethod<?> mainMethod = initMainMethod(factory);
    Collections.reverse(localVariables);
    localVariables.forEach(blockMain::insertBegin);
    Collections.reverse(localVariables);
    final Iterator<CtLocalVariable<?>> iterator = localVariables.iterator();
    blockMain.getElements(Ex2Amplifier.CT_LITERAL_TYPE_FILTER).forEach(literal -> literal.replace(factory.createVariableRead(iterator.next().getReference(), false)));
    if (!testMethod.getThrownTypes().isEmpty()) {
        final CtTry largeTryCatchBlock = createLargeTryCatchBlock(testMethod.getThrownTypes(), factory);
        largeTryCatchBlock.setBody(blockMain);
        mainMethod.setBody(largeTryCatchBlock);
    } else {
        mainMethod.setBody(blockMain);
    }
    removeNonStaticElement(mainMethod, testClass);
    return mainMethod;
}
Also used : Ex2Amplifier(eu.stamp.project.ex2amplifier.amplifier.Ex2Amplifier) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtCatch(spoon.reflect.code.CtCatch) CtCatchVariable(spoon.reflect.code.CtCatchVariable) CtThrow(spoon.reflect.code.CtThrow) Function(java.util.function.Function) CtStatement(spoon.reflect.code.CtStatement) AssertionRemover(fr.inria.diversify.dspot.assertGenerator.AssertionRemover) CtType(spoon.reflect.declaration.CtType) CtThisAccess(spoon.reflect.code.CtThisAccess) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) Iterator(java.util.Iterator) Utils(eu.stamp.project.ex2amplifier.Utils) CtTargetedExpression(spoon.reflect.code.CtTargetedExpression) Set(java.util.Set) Factory(spoon.reflect.factory.Factory) Collectors(java.util.stream.Collectors) CtTypeReference(spoon.reflect.reference.CtTypeReference) List(java.util.List) ModifierKind(spoon.reflect.declaration.ModifierKind) Optional(java.util.Optional) CtBlock(spoon.reflect.code.CtBlock) CtTry(spoon.reflect.code.CtTry) CtParameter(spoon.reflect.declaration.CtParameter) CtLiteral(spoon.reflect.code.CtLiteral) Collections(java.util.Collections) CtMethod(spoon.reflect.declaration.CtMethod) Factory(spoon.reflect.factory.Factory) CtTry(spoon.reflect.code.CtTry) CtLocalVariable(spoon.reflect.code.CtLocalVariable) AssertionRemover(fr.inria.diversify.dspot.assertGenerator.AssertionRemover) CtLiteral(spoon.reflect.code.CtLiteral)

Example 2 with CtType

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

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

the class JDTImportBuilder method build.

// package visible method in a package visible class, not in the public API
void build() {
    if (declarationUnit.imports == null || declarationUnit.imports.length == 0) {
        return;
    }
    for (ImportReference importRef : declarationUnit.imports) {
        String importName = importRef.toString();
        if (!importRef.isStatic()) {
            if (importName.endsWith("*")) {
                int lastDot = importName.lastIndexOf(".");
                String packageName = importName.substring(0, lastDot);
                // only get package from the model by traversing from rootPackage the model
                // it does not use reflection to achieve that
                CtPackage ctPackage = this.factory.Package().get(packageName);
                if (ctPackage != null) {
                    this.imports.add(factory.Type().createImport(ctPackage.getReference()));
                }
            } else {
                CtType klass = this.getOrLoadClass(importName);
                if (klass != null) {
                    this.imports.add(factory.Type().createImport(klass.getReference()));
                }
            }
        } else {
            int lastDot = importName.lastIndexOf(".");
            String className = importName.substring(0, lastDot);
            String methodOrFieldName = importName.substring(lastDot + 1);
            CtType klass = this.getOrLoadClass(className);
            if (klass != null) {
                if (methodOrFieldName.equals("*")) {
                    this.imports.add(factory.Type().createImport(factory.Type().createWildcardStaticTypeMemberReference(klass.getReference())));
                } else {
                    List<CtNamedElement> methodOrFields = klass.getElements(new NamedElementFilter<>(CtNamedElement.class, methodOrFieldName));
                    if (methodOrFields.size() > 0) {
                        CtNamedElement methodOrField = methodOrFields.get(0);
                        this.imports.add(factory.Type().createImport(methodOrField.getReference()));
                    }
                }
            }
        }
    }
    spoonUnit.setImports(this.imports);
}
Also used : ImportReference(org.eclipse.jdt.internal.compiler.ast.ImportReference) CtType(spoon.reflect.declaration.CtType) CtPackage(spoon.reflect.declaration.CtPackage) CtNamedElement(spoon.reflect.declaration.CtNamedElement)

Example 4 with CtType

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

the class ParentExiter method visitCtPackage.

@Override
public void visitCtPackage(CtPackage ctPackage) {
    if (child instanceof CtType) {
        if (ctPackage.getTypes().contains(child)) {
            ctPackage.removeType((CtType<?>) child);
        }
        ctPackage.addType((CtType<?>) child);
        if (child.getPosition() != null && child.getPosition().getCompilationUnit() != null) {
            CompilationUnit cu = child.getPosition().getCompilationUnit();
            List<CtType<?>> declaredTypes = new ArrayList<>(cu.getDeclaredTypes());
            declaredTypes.add((CtType<?>) child);
            cu.setDeclaredTypes(declaredTypes);
        }
        return;
    }
    super.visitCtPackage(ctPackage);
}
Also used : CompilationUnit(spoon.reflect.cu.CompilationUnit) CtType(spoon.reflect.declaration.CtType) ArrayList(java.util.ArrayList)

Example 5 with CtType

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

the class StandardEnvironment method report.

@Override
public void report(Processor<?> processor, Level level, CtElement element, String message) {
    StringBuffer buffer = new StringBuffer();
    prefix(buffer, level);
    // Adding message
    buffer.append(message);
    // Add sourceposition (javac format)
    try {
        CtType<?> type = (element instanceof CtType) ? (CtType<?>) element : element.getParent(CtType.class);
        SourcePosition sp = element.getPosition();
        if (sp == null) {
            buffer.append(" (Unknown Source)");
        } else {
            buffer.append(" at " + type.getQualifiedName() + ".");
            CtExecutable<?> exe = (element instanceof CtExecutable) ? (CtExecutable<?>) element : element.getParent(CtExecutable.class);
            if (exe != null) {
                buffer.append(exe.getSimpleName());
            }
            buffer.append("(" + sp.getFile().getName() + ":" + sp.getLine() + ")");
        }
    } catch (ParentNotInitializedException e) {
        buffer.append(" (invalid parent)");
    }
    print(buffer.toString(), level);
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtType(spoon.reflect.declaration.CtType) SourcePosition(spoon.reflect.cu.SourcePosition) CtExecutable(spoon.reflect.declaration.CtExecutable)

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