Search in sources :

Example 16 with TextEditGroup

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

the class IntroduceFactoryRefactoring method addAllChangesFor.

/**
	 * Add all changes necessary on the <code>ICompilationUnit</code> in the given
	 * <code>SearchResultGroup</code> to implement the refactoring transformation
	 * to the given <code>CompilationUnitChange</code>.
	 * @param rg the <code>SearchResultGroup</code> for which changes should be created
	 * @param unitHandle
	 * @param unitChange the CompilationUnitChange object for the compilation unit in question
	 * @return <code>true</code> iff a change has been added
	 * @throws CoreException
	 */
private boolean addAllChangesFor(SearchResultGroup rg, ICompilationUnit unitHandle, CompilationUnitChange unitChange) throws CoreException {
    //		ICompilationUnit	unitHandle= rg.getCompilationUnit();
    Assert.isTrue(rg == null || rg.getCompilationUnit() == unitHandle);
    CompilationUnit unit = getASTFor(unitHandle);
    ASTRewrite unitRewriter = ASTRewrite.create(unit.getAST());
    MultiTextEdit root = new MultiTextEdit();
    boolean someChange = false;
    unitChange.setEdit(root);
    fImportRewriter = StubUtility.createImportRewrite(unit, true);
    // First create the factory method
    if (unitHandle.equals(fFactoryUnitHandle)) {
        TextEditGroup factoryGD = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_addFactoryMethod);
        createFactoryChange(unitRewriter, unit, factoryGD);
        unitChange.addTextEditGroup(factoryGD);
        someChange = true;
    }
    // Now rewrite all the constructor calls to use the factory method
    if (rg != null)
        if (replaceConstructorCalls(rg, unit, unitRewriter, unitChange))
            someChange = true;
    // Finally, make the constructor private, if requested.
    if (shouldProtectConstructor() && isConstructorUnit(unitHandle)) {
        TextEditGroup declGD = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_protectConstructor);
        if (protectConstructor(unit, unitRewriter, declGD)) {
            unitChange.addTextEditGroup(declGD);
            someChange = true;
        }
    }
    if (someChange) {
        root.addChild(unitRewriter.rewriteAST());
        root.addChild(fImportRewriter.rewriteImports(null));
    }
    return someChange;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 17 with TextEditGroup

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

the class ExtractMethodRefactoring method replaceDuplicates.

private void replaceDuplicates(CompilationUnitChange result, int modifiers) {
    int numberOf = getNumberOfDuplicates();
    if (numberOf == 0 || !fReplaceDuplicates)
        return;
    String label = null;
    if (numberOf == 1)
        label = Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_single, BasicElementLabels.getJavaElementName(fMethodName));
    else
        label = Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_multi, BasicElementLabels.getJavaElementName(fMethodName));
    TextEditGroup description = new TextEditGroup(label);
    result.addTextEditGroup(description);
    for (int d = 0; d < fDuplicates.length; d++) {
        SnippetFinder.Match duplicate = fDuplicates[d];
        if (!duplicate.isInvalidNode()) {
            if (isDestinationReachable(duplicate.getEnclosingMethod())) {
                ASTNode[] callNodes = createCallNodes(duplicate, modifiers);
                ASTNode[] duplicateNodes = duplicate.getNodes();
                for (int i = 0; i < duplicateNodes.length; i++) {
                    ASTNode parent = duplicateNodes[i].getParent();
                    if (parent instanceof ParenthesizedExpression) {
                        duplicateNodes[i] = parent;
                    }
                }
                new StatementRewrite(fRewriter, duplicateNodes).replace(callNodes, description);
            }
        }
    }
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) StatementRewrite(org.eclipse.jdt.internal.corext.dom.StatementRewrite) ASTNode(org.eclipse.jdt.core.dom.ASTNode) TextEditGroup(org.eclipse.text.edits.TextEditGroup)

Example 18 with TextEditGroup

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

the class InlineMethodRefactoring method checkFinalConditions.

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 20);
    fChangeManager = new TextChangeManager();
    RefactoringStatus result = new RefactoringStatus();
    fSourceProvider.initialize();
    fTargetProvider.initialize();
    pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
    RefactoringStatus searchStatus = new RefactoringStatus();
    String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
    ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
    ICompilationUnit[] units = fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
    binaryRefs.addErrorIfNecessary(searchStatus);
    if (searchStatus.hasFatalError()) {
        result.merge(searchStatus);
        return result;
    }
    IFile[] filesToBeModified = getFilesToBeModified(units);
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError())
        return result;
    result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
    checkOverridden(result, new SubProgressMonitor(pm, 4));
    IProgressMonitor sub = new SubProgressMonitor(pm, 15);
    //$NON-NLS-1$
    sub.beginTask("", units.length * 3);
    for (int c = 0; c < units.length; c++) {
        ICompilationUnit unit = units[c];
        sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit)));
        CallInliner inliner = null;
        try {
            boolean added = false;
            MultiTextEdit root = new MultiTextEdit();
            CompilationUnitChange change = (CompilationUnitChange) fChangeManager.get(unit);
            change.setEdit(root);
            BodyDeclaration[] bodies = fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
            if (bodies.length == 0)
                continue;
            inliner = new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
            for (int b = 0; b < bodies.length; b++) {
                BodyDeclaration body = bodies[b];
                inliner.initialize(body);
                RefactoringStatus nestedInvocations = new RefactoringStatus();
                ASTNode[] invocations = removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
                for (int i = 0; i < invocations.length; i++) {
                    ASTNode invocation = invocations[i];
                    result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
                    if (result.hasFatalError())
                        break;
                    if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
                        added = true;
                        TextEditGroup group = new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
                        change.addTextEditGroup(group);
                        result.merge(inliner.perform(group));
                    } else {
                        fDeleteSource = false;
                    }
                }
                // to generate the modifications.
                if (!nestedInvocations.isOK()) {
                    result.merge(nestedInvocations);
                    fDeleteSource = false;
                }
            }
            if (!added) {
                fChangeManager.remove(unit);
            } else {
                root.addChild(inliner.getModifications());
                ImportRewrite rewrite = inliner.getImportEdit();
                if (rewrite.hasRecordedChanges()) {
                    TextEdit edit = rewrite.rewriteImports(null);
                    if (edit instanceof MultiTextEdit ? ((MultiTextEdit) edit).getChildrenSize() > 0 : true) {
                        root.addChild(edit);
                        change.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] { edit }));
                    }
                }
            }
        } finally {
            if (inliner != null)
                inliner.dispose();
        }
        sub.worked(1);
        if (sub.isCanceled())
            throw new OperationCanceledException();
    }
    result.merge(searchStatus);
    sub.done();
    pm.done();
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IFile(org.eclipse.core.resources.IFile) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextChangeManager(org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 19 with TextEditGroup

use of org.eclipse.text.edits.TextEditGroup in project eclipse.platform.text by eclipse.

the class ReplaceRefactoring method createFileChange.

private TextChange createFileChange(IFile file, Pattern pattern, Set<FileMatch> matches, RefactoringStatus resultingStatus, Collection<MatchGroup> matchGroups) throws PatternSyntaxException, CoreException {
    PositionTracker tracker = InternalSearchUI.getInstance().getPositionTracker();
    TextFileChange change = new TextFileChange(Messages.format(SearchMessages.ReplaceRefactoring_group_label_change_for_file, file.getName()), file);
    change.setEdit(new MultiTextEdit());
    ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
    manager.connect(file.getFullPath(), LocationKind.IFILE, null);
    try {
        ITextFileBuffer textFileBuffer = manager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
        if (textFileBuffer == null) {
            resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_accessing_file_buffer, file.getName()));
            return null;
        }
        IDocument document = textFileBuffer.getDocument();
        String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
        for (FileMatch match : matches) {
            int offset = match.getOffset();
            int length = match.getLength();
            Position currentPosition = tracker.getCurrentPosition(match);
            if (currentPosition != null) {
                offset = currentPosition.offset;
                if (length != currentPosition.length) {
                    resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                    continue;
                }
            }
            String originalText = getOriginalText(document, offset, length);
            if (originalText == null) {
                resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                continue;
            }
            String replacementString = PatternConstructor.interpretReplaceEscapes(fReplaceString, originalText, lineDelimiter);
            replacementString = computeReplacementString(pattern, document, offset, replacementString);
            if (replacementString == null) {
                resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                continue;
            }
            ReplaceEdit replaceEdit = new ReplaceEdit(offset, length, replacementString);
            change.addEdit(replaceEdit);
            TextEditChangeGroup textEditChangeGroup = new TextEditChangeGroup(change, new TextEditGroup(SearchMessages.ReplaceRefactoring_group_label_match_replace, replaceEdit));
            change.addTextEditChangeGroup(textEditChangeGroup);
            matchGroups.add(new MatchGroup(textEditChangeGroup, match));
        }
    } finally {
        manager.disconnect(file.getFullPath(), LocationKind.IFILE, null);
    }
    return change;
}
Also used : ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) Position(org.eclipse.jface.text.Position) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) TextEditChangeGroup(org.eclipse.ltk.core.refactoring.TextEditChangeGroup) PositionTracker(org.eclipse.search2.internal.ui.text.PositionTracker) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) IDocument(org.eclipse.jface.text.IDocument)

Example 20 with TextEditGroup

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

the class InlineMethodRefactoring method createChange.

@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    if (fDeleteSource && fCurrentMode == Mode.INLINE_ALL) {
        TextChange change = fChangeManager.get((ICompilationUnit) fSourceProvider.getTypeRoot());
        TextEdit delete = fSourceProvider.getDeleteEdit();
        TextEditGroup description = new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_delete, new TextEdit[] { delete });
        TextEdit root = change.getEdit();
        if (root != null) {
            // TODO instead of finding the right insert position the call inliner should
            // reuse the AST & rewriter of the source provide and we should rewrite the
            // whole AST at the end. However, since recursive calls aren't allowed there
            // shouldn't be a text edit overlap.
            // root.addChild(delete);
            TextChangeCompatibility.insert(root, delete);
        } else {
            change.setEdit(delete);
        }
        change.addTextEditGroup(description);
    }
    final Map<String, String> arguments = new HashMap<String, String>();
    String project = null;
    IJavaProject javaProject = fInitialTypeRoot.getJavaProject();
    if (javaProject != null)
        project = javaProject.getElementName();
    int flags = RefactoringDescriptor.STRUCTURAL_CHANGE | JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
    final IMethodBinding binding = fSourceProvider.getDeclaration().resolveBinding();
    final ITypeBinding declaring = binding.getDeclaringClass();
    if (!Modifier.isPrivate(binding.getModifiers()))
        flags |= RefactoringDescriptor.MULTI_CHANGE;
    final String description = Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(binding.getName()));
    final String header = Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(declaring, JavaElementLabels.ALL_FULLY_QUALIFIED) });
    final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header);
    comment.addSetting(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)));
    if (fDeleteSource)
        comment.addSetting(RefactoringCoreMessages.InlineMethodRefactoring_remove_method);
    if (fCurrentMode == Mode.INLINE_ALL)
        comment.addSetting(RefactoringCoreMessages.InlineMethodRefactoring_replace_references);
    final InlineMethodDescriptor descriptor = RefactoringSignatureDescriptorFactory.createInlineMethodDescriptor(project, description, comment.asString(), arguments, flags);
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fInitialTypeRoot));
    //$NON-NLS-1$
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString());
    arguments.put(ATTRIBUTE_DELETE, Boolean.valueOf(fDeleteSource).toString());
    arguments.put(ATTRIBUTE_MODE, new Integer(fCurrentMode == Mode.INLINE_ALL ? 1 : 0).toString());
    return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.InlineMethodRefactoring_edit_inlineCall, fChangeManager.getAllChanges());
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) HashMap(java.util.HashMap) DynamicValidationRefactoringChange(org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange) TextChange(org.eclipse.ltk.core.refactoring.TextChange) JDTRefactoringDescriptorComment(org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment) IJavaProject(org.eclipse.jdt.core.IJavaProject) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) InlineMethodDescriptor(org.eclipse.jdt.core.refactoring.descriptors.InlineMethodDescriptor) TextEditGroup(org.eclipse.text.edits.TextEditGroup)

Aggregations

TextEditGroup (org.eclipse.text.edits.TextEditGroup)34 ASTNode (org.eclipse.jdt.core.dom.ASTNode)12 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)12 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)11 TextEdit (org.eclipse.text.edits.TextEdit)10 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)6 AST (org.eclipse.jdt.core.dom.AST)6 CategorizedTextEditGroup (org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup)6 SimpleName (org.eclipse.jdt.core.dom.SimpleName)5 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)4 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)4 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)4 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)4 CompilationUnitChange (org.eclipse.jdt.core.refactoring.CompilationUnitChange)4 ArrayList (java.util.ArrayList)3 IFile (org.eclipse.core.resources.IFile)3 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)3 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)3 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)3 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)3