Search in sources :

Example 1 with ParentNotInitializedException

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

Example 2 with ParentNotInitializedException

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

the class CtBodyHolderTest method checkCtBody.

private void checkCtBody(CtBodyHolder p_bodyHolder, String p_constant, int off) {
    CtStatement body = p_bodyHolder.getBody();
    assertTrue(body instanceof CtBlock<?>);
    CtBlock<?> block = (CtBlock) body;
    assertEquals(1 + off, block.getStatements().size());
    assertTrue(block.getStatement(off) instanceof CtAssignment);
    CtAssignment assignment = block.getStatement(off);
    assertEquals(p_constant, ((CtLiteral<String>) assignment.getAssignment().partiallyEvaluate()).getValue());
    Factory f = body.getFactory();
    CtStatement newStat = new CWBStatementTemplate("xx").apply(body.getParent(CtType.class));
    try {
        newStat.getParent();
        fail();
    } catch (ParentNotInitializedException e) {
    // expected exception
    }
    // try to set statement and get CtBlock
    p_bodyHolder.setBody(newStat);
    CtBlock newBlock = (CtBlock) p_bodyHolder.getBody();
    assertSame(p_bodyHolder, newBlock.getParent());
    assertSame(newBlock, newStat.getParent());
    // try to set CtBlock and get the same CtBlock
    CtStatement newStat2 = newStat.clone();
    try {
        newStat2.getParent();
        fail();
    } catch (ParentNotInitializedException e) {
    // expected exception
    }
    CtBlock newBlock2 = f.Code().createCtBlock(newStat2);
    assertSame(newBlock2, newStat2.getParent());
    try {
        newBlock2.getParent();
        fail();
    } catch (ParentNotInitializedException e) {
    // expected exception
    }
    p_bodyHolder.setBody(newBlock2);
    assertSame(newBlock2, p_bodyHolder.getBody());
    assertSame(p_bodyHolder, newBlock2.getParent());
    assertSame(newBlock2, newStat2.getParent());
}
Also used : CtAssignment(spoon.reflect.code.CtAssignment) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtBlock(spoon.reflect.code.CtBlock) CtType(spoon.reflect.declaration.CtType) CtStatement(spoon.reflect.code.CtStatement) Factory(spoon.reflect.factory.Factory) CWBStatementTemplate(spoon.test.ctBodyHolder.testclasses.CWBStatementTemplate)

Example 3 with ParentNotInitializedException

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

the class DefaultJavaPrettyPrinter method visitCtInvocation.

@Override
public <T> void visitCtInvocation(CtInvocation<T> invocation) {
    enterCtStatement(invocation);
    enterCtExpression(invocation);
    if (invocation.getExecutable().isConstructor()) {
        // It's a constructor (super or this)
        elementPrinterHelper.writeActualTypeArguments(invocation.getExecutable());
        CtType<?> parentType;
        try {
            parentType = invocation.getParent(CtType.class);
        } catch (ParentNotInitializedException e) {
            parentType = null;
        }
        if (parentType != null && parentType.getQualifiedName() != null && parentType.getQualifiedName().equals(invocation.getExecutable().getDeclaringType().getQualifiedName())) {
            printer.writeKeyword("this");
        } else {
            if (invocation.getTarget() != null && !invocation.getTarget().isImplicit()) {
                scan(invocation.getTarget());
                printer.writeSeparator(".");
            }
            printer.writeKeyword("super");
        }
    } else {
        // It's a method invocation
        boolean isImported = this.isImported(invocation.getExecutable());
        if (!isImported) {
            try (Writable _context = context.modify()) {
                if (invocation.getTarget() instanceof CtTypeAccess) {
                    _context.ignoreGenerics(true);
                }
                if (invocation.getTarget() != null && !invocation.getTarget().isImplicit()) {
                    scan(invocation.getTarget());
                    printer.writeSeparator(".");
                }
            }
        }
        elementPrinterHelper.writeActualTypeArguments(invocation);
        if (env.isPreserveLineNumbers()) {
            getPrinterHelper().adjustStartPosition(invocation);
        }
        printer.writeIdentifier(invocation.getExecutable().getSimpleName());
    }
    try (ListPrinter lp = elementPrinterHelper.createListPrinter(false, "(", false, false, ",", true, false, ")")) {
        for (CtExpression<?> e : invocation.getArguments()) {
            lp.printSeparatorIfAppropriate();
            scan(e);
        }
    }
    exitCtExpression(invocation);
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtType(spoon.reflect.declaration.CtType) Writable(spoon.reflect.visitor.PrintingContext.Writable) CtTypeAccess(spoon.reflect.code.CtTypeAccess)

Example 4 with ParentNotInitializedException

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

the class DefaultJavaPrettyPrinter method isInitializeStaticFinalField.

/**
 * Check if the target expression is a static final field initialized in a static anonymous block.
 */
private <T> boolean isInitializeStaticFinalField(CtExpression<T> targetExp) {
    final CtElement parent;
    final CtAnonymousExecutable anonymousParent;
    try {
        parent = targetExp.getParent();
        anonymousParent = targetExp.getParent(CtAnonymousExecutable.class);
    } catch (ParentNotInitializedException e) {
        return false;
    }
    if (parent instanceof CtFieldWrite && targetExp.equals(((CtFieldWrite) parent).getTarget()) && anonymousParent != null && ((CtFieldWrite) parent).getVariable() != null && ((CtFieldWrite) parent).getVariable().getModifiers().contains(ModifierKind.STATIC) && ((CtFieldWrite) parent).getVariable().getModifiers().contains(ModifierKind.FINAL)) {
        return true;
    }
    return false;
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtElement(spoon.reflect.declaration.CtElement) CtFieldWrite(spoon.reflect.code.CtFieldWrite) CtAnonymousExecutable(spoon.reflect.declaration.CtAnonymousExecutable)

Example 5 with ParentNotInitializedException

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

ParentNotInitializedException (spoon.reflect.declaration.ParentNotInitializedException)17 CtElement (spoon.reflect.declaration.CtElement)9 CtInvocation (spoon.reflect.code.CtInvocation)4 CtExecutable (spoon.reflect.declaration.CtExecutable)4 CtStatement (spoon.reflect.code.CtStatement)3 CtMethod (spoon.reflect.declaration.CtMethod)3 CtParameter (spoon.reflect.declaration.CtParameter)3 CtType (spoon.reflect.declaration.CtType)3 Factory (spoon.reflect.factory.Factory)3 CtFieldReference (spoon.reflect.reference.CtFieldReference)3 CtTypeReference (spoon.reflect.reference.CtTypeReference)3 HashSet (java.util.HashSet)2 List (java.util.List)2 Test (org.junit.Test)2 CtBinaryOperator (spoon.reflect.code.CtBinaryOperator)2 CtBlock (spoon.reflect.code.CtBlock)2 CtCatch (spoon.reflect.code.CtCatch)2 CtIf (spoon.reflect.code.CtIf)2 CtLiteral (spoon.reflect.code.CtLiteral)2 CtStatementList (spoon.reflect.code.CtStatementList)2