Search in sources :

Example 1 with TextEditGroup

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

the class ExtractToNullCheckedLocalProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    // infrastructure:
    AST ast = this.compilationUnit.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ImportRewrite imports = ImportRewrite.create(this.compilationUnit, true);
    TextEditGroup group = new TextEditGroup(FixMessages.ExtractToNullCheckedLocalProposal_extractCheckedLocal_editName);
    LinkedProposalPositionGroup localNameGroup = new LinkedProposalPositionGroup(LOCAL_NAME_POSITION_GROUP);
    getLinkedProposalModel().addPositionGroup(localNameGroup);
    // AST context:
    Statement origStmt = (Statement) ASTNodes.getParent(this.fieldReference, Statement.class);
    // determine suitable strategy for rearranging elements towards a new code structure:
    RearrangeStrategy rearrangeStrategy = RearrangeStrategy.create(origStmt, rewrite, group);
    Expression toReplace;
    ASTNode directParent = this.fieldReference.getParent();
    if (directParent instanceof FieldAccess) {
        toReplace = (Expression) directParent;
    } else if (directParent instanceof QualifiedName && this.fieldReference.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
        toReplace = (Expression) directParent;
    } else {
        toReplace = this.fieldReference;
    }
    // new local declaration initialized from the field reference
    VariableDeclarationFragment localFrag = ast.newVariableDeclarationFragment();
    VariableDeclarationStatement localDecl = ast.newVariableDeclarationStatement(localFrag);
    // ... type
    localDecl.setType(newType(toReplace.resolveTypeBinding(), ast, imports));
    localDecl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
    // ... name
    String localName = proposeLocalName(this.fieldReference, this.compilationUnit, getCompilationUnit().getJavaProject());
    localFrag.setName(ast.newSimpleName(localName));
    // ... initialization
    localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, toReplace));
    rearrangeStrategy.insertLocalDecl(localDecl);
    // if statement:
    IfStatement ifStmt = ast.newIfStatement();
    // condition:
    InfixExpression nullCheck = ast.newInfixExpression();
    nullCheck.setLeftOperand(ast.newSimpleName(localName));
    nullCheck.setRightOperand(ast.newNullLiteral());
    nullCheck.setOperator(InfixExpression.Operator.NOT_EQUALS);
    ifStmt.setExpression(nullCheck);
    // then block: the original statement
    Block thenBlock = ast.newBlock();
    thenBlock.statements().add(rearrangeStrategy.createMoveTargetForOrigStmt());
    ifStmt.setThenStatement(thenBlock);
    // ... but with the field reference replaced by the new local:
    SimpleName dereferencedName = ast.newSimpleName(localName);
    rewrite.replace(toReplace, dereferencedName, group);
    // else block: a Todo comment
    Block elseBlock = ast.newBlock();
    //$NON-NLS-1$
    String elseStatement = "// TODO " + FixMessages.ExtractToNullCheckedLocalProposal_todoHandleNullDescription;
    if (origStmt instanceof ReturnStatement) {
        Type returnType = newType(((ReturnStatement) origStmt).getExpression().resolveTypeBinding(), ast, imports);
        ReturnStatement returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
        elseStatement += '\n' + ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
    }
    EmptyStatement todoNode = (EmptyStatement) rewrite.createStringPlaceholder(elseStatement, ASTNode.EMPTY_STATEMENT);
    elseBlock.statements().add(todoNode);
    ifStmt.setElseStatement(elseBlock);
    // link all three occurrences of the new local variable:
    addLinkedPosition(rewrite.track(localFrag.getName()), true, /*first*/
    LOCAL_NAME_POSITION_GROUP);
    addLinkedPosition(rewrite.track(nullCheck.getLeftOperand()), false, LOCAL_NAME_POSITION_GROUP);
    addLinkedPosition(rewrite.track(dereferencedName), false, LOCAL_NAME_POSITION_GROUP);
    rearrangeStrategy.insertIfStatement(ifStmt, thenBlock);
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) Block(org.eclipse.jdt.core.dom.Block) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) TextEditGroup(org.eclipse.text.edits.TextEditGroup) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup)

Example 2 with TextEditGroup

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

the class InlineTempRefactoring method inlineTemp.

private void inlineTemp(CompilationUnitRewrite cuRewrite) throws JavaModelException {
    SimpleName[] references = getReferences();
    TextEditGroup groupDesc = cuRewrite.createGroupDescription(RefactoringCoreMessages.InlineTempRefactoring_inline_edit_name);
    ASTRewrite rewrite = cuRewrite.getASTRewrite();
    for (int i = 0; i < references.length; i++) {
        SimpleName curr = references[i];
        ASTNode initializerCopy = getInitializerSource(cuRewrite, curr);
        rewrite.replace(curr, initializerCopy, groupDesc);
    }
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TextEditGroup(org.eclipse.text.edits.TextEditGroup)

Example 3 with TextEditGroup

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

the class ExtractMethodRefactoring method replaceBranches.

private void replaceBranches(final CompilationUnitChange result) {
    ASTNode[] selectedNodes = fAnalyzer.getSelectedNodes();
    for (int i = 0; i < selectedNodes.length; i++) {
        ASTNode astNode = selectedNodes[i];
        astNode.accept(new ASTVisitor() {

            private LinkedList<String> fOpenLoopLabels = new LinkedList<String>();

            private void registerLoopLabel(Statement node) {
                String identifier;
                if (node.getParent() instanceof LabeledStatement) {
                    LabeledStatement labeledStatement = (LabeledStatement) node.getParent();
                    identifier = labeledStatement.getLabel().getIdentifier();
                } else {
                    identifier = null;
                }
                fOpenLoopLabels.add(identifier);
            }

            @Override
            public boolean visit(ForStatement node) {
                registerLoopLabel(node);
                return super.visit(node);
            }

            @Override
            public void endVisit(ForStatement node) {
                fOpenLoopLabels.removeLast();
            }

            @Override
            public boolean visit(WhileStatement node) {
                registerLoopLabel(node);
                return super.visit(node);
            }

            @Override
            public void endVisit(WhileStatement node) {
                fOpenLoopLabels.removeLast();
            }

            @Override
            public boolean visit(EnhancedForStatement node) {
                registerLoopLabel(node);
                return super.visit(node);
            }

            @Override
            public void endVisit(EnhancedForStatement node) {
                fOpenLoopLabels.removeLast();
            }

            @Override
            public boolean visit(DoStatement node) {
                registerLoopLabel(node);
                return super.visit(node);
            }

            @Override
            public void endVisit(DoStatement node) {
                fOpenLoopLabels.removeLast();
            }

            @Override
            public void endVisit(ContinueStatement node) {
                final SimpleName label = node.getLabel();
                if (fOpenLoopLabels.isEmpty() || (label != null && !fOpenLoopLabels.contains(label.getIdentifier()))) {
                    TextEditGroup description = new TextEditGroup(RefactoringCoreMessages.ExtractMethodRefactoring_replace_continue);
                    result.addTextEditGroup(description);
                    ReturnStatement rs = fAST.newReturnStatement();
                    IVariableBinding returnValue = fAnalyzer.getReturnValue();
                    if (returnValue != null) {
                        rs.setExpression(fAST.newSimpleName(getName(returnValue)));
                    }
                    fRewriter.replace(node, rs, description);
                }
            }
        });
    }
}
Also used : DoStatement(org.eclipse.jdt.core.dom.DoStatement) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) LinkedList(java.util.LinkedList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) TextEditGroup(org.eclipse.text.edits.TextEditGroup) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement)

Example 4 with TextEditGroup

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

the class ExtractMethodRefactoring method createChange.

/* (non-Javadoc)
	 * Method declared in IRefactoring
	 */
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    if (fMethodName == null)
        return null;
    //$NON-NLS-1$
    pm.beginTask("", 2);
    try {
        fAnalyzer.aboutToCreateChange();
        BodyDeclaration declaration = fAnalyzer.getEnclosingBodyDeclaration();
        fRewriter = ASTRewrite.create(declaration.getAST());
        final CompilationUnitChange result = new CompilationUnitChange(RefactoringCoreMessages.ExtractMethodRefactoring_change_name, fCUnit);
        result.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
        result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
        MultiTextEdit root = new MultiTextEdit();
        result.setEdit(root);
        ASTNode[] selectedNodes = fAnalyzer.getSelectedNodes();
        fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(selectedNodes, fCUnit.getBuffer(), fSelectionStart, fSelectionLength));
        TextEditGroup substituteDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_substitute_with_call, BasicElementLabels.getJavaElementName(fMethodName)));
        result.addTextEditGroup(substituteDesc);
        MethodDeclaration mm = createNewMethod(selectedNodes, fCUnit.findRecommendedLineSeparator(), substituteDesc);
        if (fLinkedProposalModel != null) {
            LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
            typeGroup.addPosition(fRewriter.track(mm.getReturnType2()), false);
            ITypeBinding typeBinding = fAnalyzer.getReturnTypeBinding();
            if (typeBinding != null) {
                ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(fAST, typeBinding);
                for (int i = 0; i < relaxingTypes.length; i++) {
                    typeGroup.addProposal(relaxingTypes[i], fCUnit, relaxingTypes.length - i);
                }
            }
            LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
            nameGroup.addPosition(fRewriter.track(mm.getName()), false);
            ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, fRewriter, mm.modifiers(), false);
        }
        TextEditGroup insertDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_add_method, BasicElementLabels.getJavaElementName(fMethodName)));
        result.addTextEditGroup(insertDesc);
        if (fDestination == ASTResolving.findParentType(declaration.getParent())) {
            ChildListPropertyDescriptor desc = (ChildListPropertyDescriptor) declaration.getLocationInParent();
            ListRewrite container = fRewriter.getListRewrite(declaration.getParent(), desc);
            container.insertAfter(mm, declaration, insertDesc);
        } else {
            BodyDeclarationRewrite container = BodyDeclarationRewrite.create(fRewriter, fDestination);
            container.insert(mm, insertDesc);
        }
        replaceDuplicates(result, mm.getModifiers());
        replaceBranches(result);
        if (fImportRewriter.hasRecordedChanges()) {
            TextEdit edit = fImportRewriter.rewriteImports(null);
            root.addChild(edit);
            result.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.ExtractMethodRefactoring_organize_imports, new TextEdit[] { edit }));
        }
        root.addChild(fRewriter.rewriteAST());
        return result;
    } finally {
        pm.done();
    }
}
Also used : SelectionAwareSourceRangeComputer(org.eclipse.jdt.internal.corext.refactoring.util.SelectionAwareSourceRangeComputer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) RefactoringChangeDescriptor(org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) BodyDeclarationRewrite(org.eclipse.jdt.internal.corext.dom.BodyDeclarationRewrite) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TextEditGroup(org.eclipse.text.edits.TextEditGroup) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 5 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)

Aggregations

TextEditGroup (org.eclipse.text.edits.TextEditGroup)33 ASTNode (org.eclipse.jdt.core.dom.ASTNode)12 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)12 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)10 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 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)3