Search in sources :

Example 1 with ASTNode

use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.

the class AddImportsOperation method evaluateEdits.

private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite, int offset, int length, IProgressMonitor monitor) throws JavaModelException {
    SimpleName nameNode = null;
    if (root != null) {
        // got an AST
        ASTNode node = NodeFinder.perform(root, offset, length);
        if (node instanceof MarkerAnnotation) {
            node = ((Annotation) node).getTypeName();
        }
        if (node instanceof QualifiedName) {
            nameNode = ((QualifiedName) node).getName();
        } else if (node instanceof SimpleName) {
            nameNode = (SimpleName) node;
        }
    }
    String name, simpleName, containerName;
    int qualifierStart;
    int simpleNameStart;
    if (nameNode != null) {
        simpleName = nameNode.getIdentifier();
        simpleNameStart = nameNode.getStartPosition();
        if (nameNode.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
            Name qualifier = ((QualifiedName) nameNode.getParent()).getQualifier();
            containerName = qualifier.getFullyQualifiedName();
            name = JavaModelUtil.concatenateName(containerName, simpleName);
            qualifierStart = qualifier.getStartPosition();
        } else if (nameNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY) {
            NameQualifiedType nameQualifiedType = (NameQualifiedType) nameNode.getParent();
            Name qualifier = nameQualifiedType.getQualifier();
            containerName = qualifier.getFullyQualifiedName();
            name = JavaModelUtil.concatenateName(containerName, simpleName);
            qualifierStart = qualifier.getStartPosition();
            List<Annotation> annotations = nameQualifiedType.annotations();
            if (!annotations.isEmpty()) {
                // don't remove annotations
                simpleNameStart = annotations.get(0).getStartPosition();
            }
        } else if (nameNode.getLocationInParent() == MethodInvocation.NAME_PROPERTY) {
            ASTNode qualifier = ((MethodInvocation) nameNode.getParent()).getExpression();
            if (qualifier instanceof Name) {
                containerName = ASTNodes.asString(qualifier);
                name = JavaModelUtil.concatenateName(containerName, simpleName);
                qualifierStart = qualifier.getStartPosition();
            } else {
                return null;
            }
        } else {
            //$NON-NLS-1$
            containerName = "";
            name = simpleName;
            qualifierStart = simpleNameStart;
        }
        IBinding binding = nameNode.resolveBinding();
        if (binding != null && !binding.isRecovered()) {
            if (binding instanceof ITypeBinding) {
                ITypeBinding typeBinding = ((ITypeBinding) binding).getTypeDeclaration();
                String qualifiedBindingName = typeBinding.getQualifiedName();
                if (containerName.length() > 0 && !qualifiedBindingName.equals(name)) {
                    return null;
                }
                ImportRewriteContext context = new ContextSensitiveImportRewriteContext(root, qualifierStart, importRewrite);
                String res = importRewrite.addImport(typeBinding, context);
                if (containerName.length() > 0 && !res.equals(simpleName)) {
                    // adding import failed
                    fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
                    return null;
                }
                if (containerName.length() == 0 && res.equals(simpleName)) {
                    // no change necessary
                    return null;
                }
                return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, new String());
            } else if (JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject()) && (binding instanceof IVariableBinding || binding instanceof IMethodBinding)) {
                boolean isField = binding instanceof IVariableBinding;
                ITypeBinding declaringClass = isField ? ((IVariableBinding) binding).getDeclaringClass() : ((IMethodBinding) binding).getDeclaringClass();
                if (declaringClass == null) {
                    // variableBinding.getDeclaringClass() is null for array.length
                    return null;
                }
                if (Modifier.isStatic(binding.getModifiers())) {
                    if (containerName.length() > 0) {
                        if (containerName.equals(declaringClass.getName()) || containerName.equals(declaringClass.getQualifiedName())) {
                            ASTNode node = nameNode.getParent();
                            boolean isDirectlyAccessible = false;
                            while (node != null) {
                                if (isTypeDeclarationSubTypeCompatible(node, declaringClass)) {
                                    isDirectlyAccessible = true;
                                    break;
                                }
                                node = node.getParent();
                            }
                            if (!isDirectlyAccessible) {
                                if (Modifier.isPrivate(declaringClass.getModifiers())) {
                                    fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_not_visible_class, BasicElementLabels.getJavaElementName(declaringClass.getName())), null);
                                    return null;
                                }
                                String res = importRewrite.addStaticImport(declaringClass.getQualifiedName(), binding.getName(), isField);
                                if (!res.equals(simpleName)) {
                                    // adding import failed
                                    return null;
                                }
                            }
                            //$NON-NLS-1$
                            return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
                        }
                    }
                }
                // no static imports for packages
                return null;
            } else {
                return null;
            }
        }
        if (binding != null && binding.getKind() != IBinding.TYPE) {
            // recovered binding
            return null;
        }
    } else {
        IBuffer buffer = fCompilationUnit.getBuffer();
        qualifierStart = getNameStart(buffer, offset);
        int nameEnd = getNameEnd(buffer, offset + length);
        int len = nameEnd - qualifierStart;
        name = buffer.getText(qualifierStart, len).trim();
        if (name.length() == 0) {
            return null;
        }
        simpleName = Signature.getSimpleName(name);
        containerName = Signature.getQualifier(name);
        IJavaProject javaProject = fCompilationUnit.getJavaProject();
        if (simpleName.length() == 0 || JavaConventionsUtil.validateJavaTypeName(simpleName, javaProject).matches(IStatus.ERROR) || (containerName.length() > 0 && JavaConventionsUtil.validateJavaTypeName(containerName, javaProject).matches(IStatus.ERROR))) {
            fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_invalid_selection, null);
            return null;
        }
        simpleNameStart = getSimpleNameStart(buffer, qualifierStart, containerName);
        int res = importRewrite.getDefaultImportRewriteContext().findInContext(containerName, simpleName, ImportRewriteContext.KIND_TYPE);
        if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
            fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
            return null;
        } else if (res == ImportRewriteContext.RES_NAME_FOUND) {
            //$NON-NLS-1$
            return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
        }
    }
    IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { fCompilationUnit.getJavaProject() });
    TypeNameMatch[] types = findAllTypes(simpleName, searchScope, nameNode, new SubProgressMonitor(monitor, 1));
    if (types.length == 0) {
        fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_notresolved_message, BasicElementLabels.getJavaElementName(simpleName)), null);
        return null;
    }
    if (monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    TypeNameMatch chosen;
    if (types.length > 1 && fQuery != null) {
        chosen = fQuery.chooseImport(types, containerName);
        if (chosen == null) {
            throw new OperationCanceledException();
        }
    } else {
        chosen = types[0];
    }
    ImportRewriteContext context = root == null ? null : new ContextSensitiveImportRewriteContext(root, simpleNameStart, importRewrite);
    importRewrite.addImport(chosen.getFullyQualifiedName(), context);
    //$NON-NLS-1$
    return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) IBinding(org.eclipse.jdt.core.dom.IBinding) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) IBuffer(org.eclipse.jdt.core.IBuffer) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) MarkerAnnotation(org.eclipse.jdt.core.dom.MarkerAnnotation) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) List(java.util.List) ArrayList(java.util.ArrayList) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 2 with ASTNode

use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.

the class LinkedNodeFinder method findByProblems.

public static SimpleName[] findByProblems(ASTNode parent, SimpleName nameNode) {
    ArrayList<SimpleName> res = new ArrayList<SimpleName>();
    ASTNode astRoot = parent.getRoot();
    if (!(astRoot instanceof CompilationUnit)) {
        return null;
    }
    IProblem[] problems = ((CompilationUnit) astRoot).getProblems();
    int nameNodeKind = getNameNodeProblemKind(problems, nameNode);
    if (nameNodeKind == 0) {
        // no problem on node
        return null;
    }
    int bodyStart = parent.getStartPosition();
    int bodyEnd = bodyStart + parent.getLength();
    String name = nameNode.getIdentifier();
    for (int i = 0; i < problems.length; i++) {
        IProblem curr = problems[i];
        int probStart = curr.getSourceStart();
        int probEnd = curr.getSourceEnd() + 1;
        if (probStart > bodyStart && probEnd < bodyEnd) {
            int currKind = getProblemKind(curr);
            if ((nameNodeKind & currKind) != 0) {
                ASTNode node = NodeFinder.perform(parent, probStart, (probEnd - probStart));
                if (node instanceof SimpleName && name.equals(((SimpleName) node).getIdentifier())) {
                    res.add((SimpleName) node);
                }
            }
        }
    }
    return res.toArray(new SimpleName[res.size()]);
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) ASTNode(org.eclipse.jdt.core.dom.ASTNode) IProblem(org.eclipse.jdt.core.compiler.IProblem)

Example 3 with ASTNode

use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.

the class LocalVariableIndex method internalPerform.

private static int internalPerform(BodyDeclaration methodOrInitializer) {
    // we have to find the outermost method/initializer/field declaration since a local or anonymous
    // type can reference final variables from the outer scope.
    BodyDeclaration target = methodOrInitializer;
    ASTNode parent = target.getParent();
    while (parent != null) {
        if (parent instanceof MethodDeclaration || parent instanceof Initializer || parent instanceof FieldDeclaration) {
            target = (BodyDeclaration) parent;
        }
        parent = parent.getParent();
    }
    return doPerform(target);
}
Also used : Initializer(org.eclipse.jdt.core.dom.Initializer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 4 with ASTNode

use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.

the class ModifierRewrite method copyAllModifiers.

public void copyAllModifiers(ASTNode otherDecl, TextEditGroup editGroup, boolean copyIndividually) {
    ListRewrite modifierList = evaluateListRewrite(fModifierRewrite.getASTRewrite(), otherDecl);
    List<IExtendedModifier> originalList = modifierList.getOriginalList();
    if (originalList.isEmpty()) {
        return;
    }
    if (copyIndividually) {
        for (Iterator<IExtendedModifier> iterator = originalList.iterator(); iterator.hasNext(); ) {
            ASTNode modifier = (ASTNode) iterator.next();
            ASTNode copy = fModifierRewrite.getASTRewrite().createCopyTarget(modifier);
            if (copy != null) {
                //paranoia check (only left here because we're in RC1)
                fModifierRewrite.insertLast(copy, editGroup);
            }
        }
    } else {
        ASTNode copy = modifierList.createCopyTarget((ASTNode) originalList.get(0), (ASTNode) originalList.get(originalList.size() - 1));
        if (copy != null) {
            //paranoia check (only left here because we're in RC1)
            fModifierRewrite.insertLast(copy, editGroup);
        }
    }
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Example 5 with ASTNode

use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.

the class ASTNodeFactory method newType.

public static Type newType(AST ast, String content) {
    StringBuffer buffer = new StringBuffer(TYPE_HEADER);
    buffer.append(content);
    buffer.append(TYPE_FOOTER);
    CheASTParser p = CheASTParser.newParser(ast.apiLevel());
    p.setSource(buffer.toString().toCharArray());
    CompilationUnit root = (CompilationUnit) p.createAST(null);
    List<AbstractTypeDeclaration> list = root.types();
    TypeDeclaration typeDecl = (TypeDeclaration) list.get(0);
    MethodDeclaration methodDecl = typeDecl.getMethods()[0];
    ASTNode type = methodDecl.getReturnType2();
    ASTNode result = ASTNode.copySubtree(ast, type);
    result.accept(new PositionClearer());
    return (Type) result;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) Type(org.eclipse.jdt.core.dom.Type) UnionType(org.eclipse.jdt.core.dom.UnionType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Aggregations

ASTNode (org.eclipse.jdt.core.dom.ASTNode)712 SimpleName (org.eclipse.jdt.core.dom.SimpleName)151 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)148 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)147 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)134 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)126 Expression (org.eclipse.jdt.core.dom.Expression)125 ArrayList (java.util.ArrayList)111 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)108 AST (org.eclipse.jdt.core.dom.AST)106 Type (org.eclipse.jdt.core.dom.Type)92 Block (org.eclipse.jdt.core.dom.Block)89 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)77 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)73 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)67 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)66 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)65 CastExpression (org.eclipse.jdt.core.dom.CastExpression)64 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)62 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)60