Search in sources :

Example 1 with CtLiteral

use of spoon.reflect.code.CtLiteral in project Ex2Amplifier by STAMP-project.

the class JBSEAmplifier method generateNewTestMethod.

private CtMethod<?> generateNewTestMethod(CtMethod<?> testMethod, Map<String, List<String>> conditionForParameter) {
    final CtMethod clone = AmplificationHelper.cloneTestMethodForAmp(testMethod, "_Ex2_JBSE");
    final List<?> solutions = SMTSolver.solve(conditionForParameter);
    final Iterator<?> iterator = solutions.iterator();
    final List<CtLiteral> originalLiterals = clone.getElements(new TypeFilter<>(CtLiteral.class));
    conditionForParameter.keySet().forEach(s -> {
        try {
            final int indexOfLit = Integer.parseInt(s.substring("param".length()));
            final CtLiteral literalToBeReplaced = originalLiterals.get(indexOfLit);
            final CtLiteral<?> newLiteral = testMethod.getFactory().createLiteral(iterator.next());
            if (!this.intermediateAmplification.containsKey(literalToBeReplaced)) {
                this.intermediateAmplification.put(literalToBeReplaced, new ArrayList<>());
            }
            this.intermediateAmplification.get(literalToBeReplaced).add(newLiteral);
            if (literalToBeReplaced.getParent() instanceof CtUnaryOperator) {
                literalToBeReplaced.getParent().replace(newLiteral);
            } else {
                literalToBeReplaced.replace(newLiteral);
            }
        } catch (Exception e) {
            LOGGER.warn("Error when trying to generate a value for {}", s);
        }
    });
    return clone;
}
Also used : CtLiteral(spoon.reflect.code.CtLiteral) CtUnaryOperator(spoon.reflect.code.CtUnaryOperator) CtMethod(spoon.reflect.declaration.CtMethod)

Example 2 with CtLiteral

use of spoon.reflect.code.CtLiteral 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 3 with CtLiteral

use of spoon.reflect.code.CtLiteral in project spoon by INRIA.

the class CommentTest method testWildComments.

@Test
public void testWildComments() {
    // contract: tests that value of comment is correct even for wild combinations of characters. See WildComments class for details
    Factory f = getSpoonFactory();
    CtClass<?> type = (CtClass<?>) f.Type().get(WildComments.class);
    List<CtLiteral<String>> literals = (List) ((CtNewArray<?>) type.getField("comments").getDefaultExpression()).getElements();
    assertTrue(literals.size() > 10);
    /*
		 * each string literal has a comment and string value, which defines expected value of it's comment
		 */
    for (CtLiteral<String> literal : literals) {
        assertEquals(1, literal.getComments().size());
        CtComment comment = literal.getComments().get(0);
        String expected = literal.getValue();
        assertEquals(literal.getPosition().toString(), expected, comment.getContent());
    }
}
Also used : CtClass(spoon.reflect.declaration.CtClass) CtComment(spoon.reflect.code.CtComment) CtLiteral(spoon.reflect.code.CtLiteral) DefaultCoreFactory(spoon.support.DefaultCoreFactory) Factory(spoon.reflect.factory.Factory) List(java.util.List) ArrayList(java.util.ArrayList) WildComments(spoon.test.comment.testclasses.WildComments) Test(org.junit.Test)

Example 4 with CtLiteral

use of spoon.reflect.code.CtLiteral in project spoon by INRIA.

the class ReplaceTest method testReplaceExpression.

@Test
public void testReplaceExpression() {
    CtMethod<?> sample = factory.Package().get("spoon.test.replace.testclasses").getType("Foo").getMethod("foo");
    CtVariable<?> var = sample.getBody().getStatement(0);
    Assert.assertTrue(var.getDefaultExpression() instanceof CtLiteral);
    Assert.assertEquals(3, ((CtLiteral<?>) var.getDefaultExpression()).getValue());
    CtLiteral replacement = factory.Core().createLiteral();
    replacement.setValue(42);
    var.getDefaultExpression().replace(replacement);
    Assert.assertEquals(42, ((CtLiteral<?>) var.getDefaultExpression()).getValue());
}
Also used : CtLiteral(spoon.reflect.code.CtLiteral) Test(org.junit.Test)

Example 5 with CtLiteral

use of spoon.reflect.code.CtLiteral in project spoon by INRIA.

the class ImportScannerImpl method isTypeInCollision.

/**
 * Test if the reference can be imported, i.e. test if the importation could lead to a collision.
 * @param ref
 * @return true if the ref should be imported.
 */
protected boolean isTypeInCollision(CtReference ref, boolean fqnMode) {
    if (targetType != null && targetType.getSimpleName().equals(ref.getSimpleName()) && !targetType.equals(ref)) {
        return true;
    }
    try {
        CtElement parent;
        if (ref instanceof CtTypeReference) {
            parent = ref.getParent();
        } else {
            parent = ref;
        }
        // i.e. a string, an int, etc.
        if (parent instanceof CtLiteral) {
            return false;
        }
        Set<String> localVariablesOfBlock = new HashSet<>();
        if (parent instanceof CtField) {
            this.fieldAndMethodsNames.add(((CtField) parent).getSimpleName());
        } else if (parent instanceof CtMethod) {
            this.fieldAndMethodsNames.add(((CtMethod) parent).getSimpleName());
        } else {
            localVariablesOfBlock = this.lookForLocalVariables(parent);
        }
        while (!(parent instanceof CtPackage)) {
            if ((parent instanceof CtFieldReference) || (parent instanceof CtExecutableReference) || (parent instanceof CtInvocation)) {
                CtReference parentType;
                if (parent instanceof CtInvocation) {
                    parentType = ((CtInvocation) parent).getExecutable();
                } else {
                    parentType = (CtReference) parent;
                }
                LinkedList<String> qualifiedNameTokens = new LinkedList<>();
                // we don't want to test the current ref name, as we risk to create field import and make autoreference
                if (parentType != parent) {
                    qualifiedNameTokens.add(parentType.getSimpleName());
                }
                CtTypeReference typeReference;
                if (parent instanceof CtFieldReference) {
                    typeReference = ((CtFieldReference) parent).getDeclaringType();
                } else if (parent instanceof CtExecutableReference) {
                    typeReference = ((CtExecutableReference) parent).getDeclaringType();
                } else {
                    typeReference = ((CtInvocation) parent).getExecutable().getDeclaringType();
                }
                if (typeReference != null) {
                    qualifiedNameTokens.addFirst(typeReference.getSimpleName());
                    if (typeReference.getPackage() != null) {
                        StringTokenizer token = new StringTokenizer(typeReference.getPackage().getSimpleName(), CtPackage.PACKAGE_SEPARATOR);
                        int index = 0;
                        while (token.hasMoreElements()) {
                            qualifiedNameTokens.add(index, token.nextToken());
                            index++;
                        }
                    }
                }
                if (!qualifiedNameTokens.isEmpty()) {
                    // if the first package name is a variable name somewhere, it could lead to a collision
                    if (fieldAndMethodsNames.contains(qualifiedNameTokens.getFirst()) || localVariablesOfBlock.contains(qualifiedNameTokens.getFirst())) {
                        qualifiedNameTokens.removeFirst();
                        if (fqnMode) {
                            // for example: spoon.Launcher if a field spoon and another one Launcher exists
                            if (ref instanceof CtTypeReference) {
                                if (qualifiedNameTokens.isEmpty()) {
                                    return true;
                                }
                                // but if the other package names are not a variable name, it's ok to import
                                for (int i = 0; i < qualifiedNameTokens.size(); i++) {
                                    String testedToken = qualifiedNameTokens.get(i);
                                    if (!fieldAndMethodsNames.contains(testedToken) && !localVariablesOfBlock.contains(testedToken)) {
                                        return true;
                                    }
                                }
                                return false;
                            // However if it is a static method/field, we always accept to import them in this case
                            // It is the last possibility for managing import for us
                            } else {
                                return true;
                            }
                        } else {
                            // but if the other package names are not a variable name, it's ok to import
                            for (int i = 0; i < qualifiedNameTokens.size(); i++) {
                                String testedToken = qualifiedNameTokens.get(i);
                                if (!fieldAndMethodsNames.contains(testedToken) && !localVariablesOfBlock.contains(testedToken)) {
                                    return false;
                                }
                            }
                            return true;
                        }
                    }
                }
            }
            parent = parent.getParent();
        }
    } catch (ParentNotInitializedException e) {
        return false;
    }
    return false;
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtElement(spoon.reflect.declaration.CtElement) CtFieldReference(spoon.reflect.reference.CtFieldReference) LinkedList(java.util.LinkedList) CtInvocation(spoon.reflect.code.CtInvocation) StringTokenizer(java.util.StringTokenizer) CtLiteral(spoon.reflect.code.CtLiteral) CtReference(spoon.reflect.reference.CtReference) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtField(spoon.reflect.declaration.CtField) CtExecutableReference(spoon.reflect.reference.CtExecutableReference) CtPackage(spoon.reflect.declaration.CtPackage) CtMethod(spoon.reflect.declaration.CtMethod) HashSet(java.util.HashSet)

Aggregations

CtLiteral (spoon.reflect.code.CtLiteral)38 Test (org.junit.Test)28 CtMethod (spoon.reflect.declaration.CtMethod)19 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)19 AbstractTest (fr.inria.AbstractTest)13 Factory (spoon.reflect.factory.Factory)10 Launcher (spoon.Launcher)8 CtInvocation (spoon.reflect.code.CtInvocation)6 CtStatement (spoon.reflect.code.CtStatement)6 CtTypeReference (spoon.reflect.reference.CtTypeReference)6 CtExpression (spoon.reflect.code.CtExpression)5 List (java.util.List)4 CtLocalVariable (spoon.reflect.code.CtLocalVariable)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 CtIf (spoon.reflect.code.CtIf)3 CtClass (spoon.reflect.declaration.CtClass)3 CtElement (spoon.reflect.declaration.CtElement)3 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)3 AssertionRemover (fr.inria.diversify.dspot.assertGenerator.AssertionRemover)2