Search in sources :

Example 1 with ReplaceEdit

use of org.eclipse.text.edits.ReplaceEdit 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 ReplaceEdit

use of org.eclipse.text.edits.ReplaceEdit in project che by eclipse.

the class RenameTypeProcessor method addConstructorRenames.

private void addConstructorRenames(TextChangeManager manager) throws CoreException {
    ICompilationUnit cu = fType.getCompilationUnit();
    IMethod[] methods = fType.getMethods();
    int typeNameLength = fType.getElementName().length();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].isConstructor()) {
            /*
				 * constructor declarations cannot be fully qualified so we can use simple replace here
				 *
				 * if (methods[i].getNameRange() == null), then it's a binary file so it's wrong anyway
				 * (checked as a precondition)
				 */
            String name = RefactoringCoreMessages.RenameTypeRefactoring_rename_constructor;
            TextChangeCompatibility.addTextEdit(manager.get(cu), name, new ReplaceEdit(methods[i].getNameRange().getOffset(), typeNameLength, getNewElementName()));
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IMethod(org.eclipse.jdt.core.IMethod)

Example 3 with ReplaceEdit

use of org.eclipse.text.edits.ReplaceEdit in project che by eclipse.

the class RenameTypeProcessor method addTypeDeclarationUpdate.

private void addTypeDeclarationUpdate(TextChangeManager manager) throws CoreException {
    String name = RefactoringCoreMessages.RenameTypeRefactoring_update;
    int typeNameLength = fType.getElementName().length();
    ICompilationUnit cu = fType.getCompilationUnit();
    TextChangeCompatibility.addTextEdit(manager.get(cu), name, new ReplaceEdit(fType.getNameRange().getOffset(), typeNameLength, getNewElementName()));
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit)

Example 4 with ReplaceEdit

use of org.eclipse.text.edits.ReplaceEdit in project che by eclipse.

the class RenameNonVirtualMethodProcessor method addDeclarationUpdate.

private void addDeclarationUpdate(TextChangeManager manager) throws CoreException {
    if (getDelegateUpdating()) {
        // create the delegate
        CompilationUnitRewrite rewrite = new CompilationUnitRewrite(getDeclaringCU());
        rewrite.setResolveBindings(true);
        MethodDeclaration methodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(getMethod(), rewrite.getRoot());
        DelegateMethodCreator creator = new DelegateMethodCreator();
        creator.setDeclaration(methodDeclaration);
        creator.setDeclareDeprecated(getDeprecateDelegates());
        creator.setSourceRewrite(rewrite);
        creator.setCopy(true);
        creator.setNewElementName(getNewElementName());
        creator.prepareDelegate();
        creator.createEdit();
        CompilationUnitChange cuChange = rewrite.createChange(true);
        if (cuChange != null) {
            cuChange.setKeepPreviewEdits(true);
            manager.manage(getDeclaringCU(), cuChange);
        }
    }
    String editName = RefactoringCoreMessages.RenameMethodRefactoring_update_declaration;
    ISourceRange nameRange = getMethod().getNameRange();
    ReplaceEdit replaceEdit = new ReplaceEdit(nameRange.getOffset(), nameRange.getLength(), getNewElementName());
    addTextEdit(manager.get(getDeclaringCU()), editName, replaceEdit);
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) DelegateMethodCreator(org.eclipse.jdt.internal.corext.refactoring.delegates.DelegateMethodCreator) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 5 with ReplaceEdit

use of org.eclipse.text.edits.ReplaceEdit in project che by eclipse.

the class StringFix method createFix.

public static StringFix createFix(CompilationUnit compilationUnit, IProblemLocation problem, boolean removeNLSTag, boolean addNLSTag) throws CoreException {
    TextEdit addEdit = null;
    ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement();
    //TODO NLS
    //		if (addNLSTag) {
    //			addEdit = NLSUtil.createNLSEdit(cu, problem.getOffset());
    //		}
    ReplaceEdit removeEdit = null;
    if (removeNLSTag) {
        IBuffer buffer = cu.getBuffer();
        if (buffer != null) {
            removeEdit = getReplace(problem.getOffset(), problem.getLength(), buffer, true);
        }
    }
    if (addEdit != null && removeEdit != null) {
        String label = FixMessages.StringFix_AddRemoveNonNls_description;
        return new StringFix(label, compilationUnit, new TextEditGroup[] { new TextEditGroup(label, addEdit), new TextEditGroup(label, removeEdit) });
    } else if (addEdit != null) {
        String label = FixMessages.StringFix_AddNonNls_description;
        return new StringFix(label, compilationUnit, new TextEditGroup[] { new TextEditGroup(label, addEdit) });
    } else if (removeEdit != null) {
        String label = FixMessages.StringFix_RemoveNonNls_description;
        return new StringFix(label, compilationUnit, new TextEditGroup[] { new TextEditGroup(label, removeEdit) });
    } else {
        return null;
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) CategorizedTextEditGroup(org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup) TextEditGroup(org.eclipse.text.edits.TextEditGroup) IBuffer(org.eclipse.jdt.core.IBuffer)

Aggregations

ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)117 TextEdit (org.eclipse.text.edits.TextEdit)48 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)42 Test (org.junit.Test)34 InsertEdit (org.eclipse.text.edits.InsertEdit)24 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)14 IDocument (org.eclipse.jface.text.IDocument)13 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)13 MoveSourceEdit (org.eclipse.text.edits.MoveSourceEdit)13 MoveTargetEdit (org.eclipse.text.edits.MoveTargetEdit)13 UndoEdit (org.eclipse.text.edits.UndoEdit)13 BadLocationException (org.eclipse.jface.text.BadLocationException)12 DeleteEdit (org.eclipse.text.edits.DeleteEdit)12 TextFileChange (org.eclipse.ltk.core.refactoring.TextFileChange)10 ArrayList (java.util.ArrayList)9 List (java.util.List)7 Document (org.eclipse.jface.text.Document)7 CoreException (org.eclipse.core.runtime.CoreException)6 Position (org.eclipse.jface.text.Position)6 TextChange (org.eclipse.ltk.core.refactoring.TextChange)6