Search in sources :

Example 41 with ASTRewrite

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

the class AssignToVariableAssistProposal method doAddLocal.

private ASTRewrite doAddLocal() {
    Expression expression = ((ExpressionStatement) fNodeToAssign).getExpression();
    AST ast = fNodeToAssign.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    createImportRewrite((CompilationUnit) fNodeToAssign.getRoot());
    String[] varNames = suggestLocalVariableNames(fTypeBinding, expression);
    for (int i = 0; i < varNames.length; i++) {
        addLinkedPositionProposal(KEY_NAME, varNames[i], null);
    }
    VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
    newDeclFrag.setName(ast.newSimpleName(varNames[0]));
    newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression));
    Type type = evaluateType(ast);
    if (ASTNodes.isControlStatementBody(fNodeToAssign.getLocationInParent())) {
        Block block = ast.newBlock();
        block.statements().add(rewrite.createMoveTarget(fNodeToAssign));
        rewrite.replace(fNodeToAssign, block, null);
    }
    if (needsSemicolon(expression)) {
        VariableDeclarationStatement varStatement = ast.newVariableDeclarationStatement(newDeclFrag);
        varStatement.setType(type);
        rewrite.replace(expression, varStatement, null);
    } else {
        // trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement
        VariableDeclarationExpression varExpression = ast.newVariableDeclarationExpression(newDeclFrag);
        varExpression.setType(type);
        rewrite.replace(expression, varExpression, null);
    }
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
    addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
    // set cursor after expression statement
    setEndPosition(rewrite.track(fNodeToAssign));
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) Type(org.eclipse.jdt.core.dom.Type) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement)

Example 42 with ASTRewrite

use of org.eclipse.jdt.core.dom.rewrite.ASTRewrite in project flux by eclipse.

the class AdvancedQuickAssistProcessor method getPickOutStringProposals.

private static boolean getPickOutStringProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    // we work with String's
    if (!(node instanceof StringLiteral)) {
        return false;
    }
    // user should select part of String
    int selectionPos = context.getSelectionOffset();
    int selectionLen = context.getSelectionLength();
    if (selectionLen == 0) {
        return false;
    }
    int valueStart = node.getStartPosition() + 1;
    int valueEnd = node.getStartPosition() + node.getLength() - 1;
    // selection must be inside node and the quotes and not contain the full value
    if (selectionPos < valueStart || selectionPos + selectionLen > valueEnd || valueEnd - valueStart == selectionLen) {
        return false;
    }
    // prepare string parts positions
    StringLiteral stringLiteral = (StringLiteral) node;
    String stringValue = stringLiteral.getEscapedValue();
    int firstPos = selectionPos - node.getStartPosition();
    int secondPos = firstPos + selectionLen;
    // prepare new string literals
    AST ast = node.getAST();
    StringLiteral leftLiteral = ast.newStringLiteral();
    StringLiteral centerLiteral = ast.newStringLiteral();
    StringLiteral rightLiteral = ast.newStringLiteral();
    try {
        leftLiteral.setEscapedValue('"' + stringValue.substring(1, firstPos) + '"');
        centerLiteral.setEscapedValue('"' + stringValue.substring(firstPos, secondPos) + '"');
        rightLiteral.setEscapedValue('"' + stringValue.substring(secondPos, stringValue.length() - 1) + '"');
    } catch (IllegalArgumentException e) {
        return false;
    }
    if (resultingCollections == null) {
        return true;
    }
    ASTRewrite rewrite = ASTRewrite.create(ast);
    // prepare new expression instead of StringLiteral
    InfixExpression expression = ast.newInfixExpression();
    expression.setOperator(InfixExpression.Operator.PLUS);
    if (firstPos != 1) {
        expression.setLeftOperand(leftLiteral);
    }
    if (firstPos == 1) {
        expression.setLeftOperand(centerLiteral);
    } else {
        expression.setRightOperand(centerLiteral);
    }
    if (secondPos < stringValue.length() - 1) {
        if (firstPos == 1) {
            expression.setRightOperand(rightLiteral);
        } else {
            expression.extendedOperands().add(rightLiteral);
        }
    }
    // use new expression instead of old StirngLiteral
    rewrite.replace(stringLiteral, expression, null);
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_pickSelectedString;
    //		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.PICK_SELECTED_STRING);
    //$NON-NLS-1$
    proposal.addLinkedPosition(rewrite.track(centerLiteral), true, "CENTER_STRING");
    resultingCollections.add(proposal);
    return true;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 43 with ASTRewrite

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

the class SourceProvider method getDeleteEdit.

public TextEdit getDeleteEdit() {
    final ASTRewrite rewriter = ASTRewrite.create(fDeclaration.getAST());
    rewriter.remove(fDeclaration, null);
    return rewriter.rewriteAST(fDocument, fTypeRoot.getJavaProject().getOptions(true));
}
Also used : ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 44 with ASTRewrite

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

the class SourceProvider method getCodeBlocks.

public String[] getCodeBlocks(CallContext context, ImportRewrite importRewrite) throws CoreException {
    final ASTRewrite rewriter = ASTRewrite.create(fDeclaration.getAST());
    replaceParameterWithExpression(rewriter, context, importRewrite);
    updateImplicitReceivers(rewriter, context);
    makeNamesUnique(rewriter, context.scope);
    updateTypeReferences(rewriter, context);
    updateStaticReferences(rewriter, context);
    updateTypeVariables(rewriter, context);
    updateMethodTypeVariable(rewriter, context);
    List<IRegion> ranges = null;
    if (hasReturnValue()) {
        if (context.callMode == ASTNode.RETURN_STATEMENT) {
            ranges = getStatementRanges();
        } else {
            ranges = getExpressionRanges();
        }
    } else {
        ASTNode last = getLastStatement();
        if (last != null && last.getNodeType() == ASTNode.RETURN_STATEMENT) {
            ranges = getReturnStatementRanges();
        } else {
            ranges = getStatementRanges();
        }
    }
    final TextEdit dummy = rewriter.rewriteAST(fDocument, fTypeRoot.getJavaProject().getOptions(true));
    int size = ranges.size();
    RangeMarker[] markers = new RangeMarker[size];
    for (int i = 0; i < markers.length; i++) {
        IRegion range = ranges.get(i);
        markers[i] = new RangeMarker(range.getOffset(), range.getLength());
    }
    int split;
    if (size <= 1) {
        split = Integer.MAX_VALUE;
    } else {
        IRegion region = ranges.get(0);
        split = region.getOffset() + region.getLength();
    }
    TextEdit[] edits = dummy.removeChildren();
    for (int i = 0; i < edits.length; i++) {
        TextEdit edit = edits[i];
        int pos = edit.getOffset() >= split ? 1 : 0;
        markers[pos].addChild(edit);
    }
    MultiTextEdit root = new MultiTextEdit(0, fDocument.getLength());
    root.addChildren(markers);
    try {
        TextEditProcessor processor = new TextEditProcessor(fDocument, root, TextEdit.CREATE_UNDO | TextEdit.UPDATE_REGIONS);
        UndoEdit undo = processor.performEdits();
        String[] result = getBlocks(markers);
        // It is faster to undo the changes than coping the buffer over and over again.
        processor = new TextEditProcessor(fDocument, undo, TextEdit.UPDATE_REGIONS);
        processor.performEdits();
        return result;
    } catch (MalformedTreeException exception) {
        JavaPlugin.log(exception);
    } catch (BadLocationException exception) {
        JavaPlugin.log(exception);
    }
    return new String[] {};
}
Also used : TextEditProcessor(org.eclipse.text.edits.TextEditProcessor) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) RangeMarker(org.eclipse.text.edits.RangeMarker) IRegion(org.eclipse.jface.text.IRegion) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) UndoEdit(org.eclipse.text.edits.UndoEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 45 with ASTRewrite

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

the class PromoteTempToFieldRefactoring method createChange.

/*
     * @see org.eclipse.jdt.internal.corext.refactoring.base.IRefactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
     */
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 1);
    try {
        if (fFieldName.length() == 0) {
            fFieldName = getInitialFieldName();
        }
        ASTRewrite rewrite = ASTRewrite.create(fCompilationUnitNode.getAST());
        if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer())
            addLocalDeclarationSplit(rewrite);
        else
            addLocalDeclarationRemoval(rewrite);
        if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
            addInitializersToConstructors(rewrite);
        addTempRenames(rewrite);
        addFieldDeclaration(rewrite);
        CompilationUnitChange result = new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu);
        result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
        TextEdit resultingEdits = rewrite.rewriteAST();
        TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits);
        return result;
    } finally {
        pm.done();
    }
}
Also used : TextEdit(org.eclipse.text.edits.TextEdit) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange) RefactoringChangeDescriptor(org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor)

Aggregations

ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)180 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)93 Image (org.eclipse.swt.graphics.Image)80 AST (org.eclipse.jdt.core.dom.AST)78 ASTNode (org.eclipse.jdt.core.dom.ASTNode)69 Expression (org.eclipse.jdt.core.dom.Expression)54 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)49 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)44 Block (org.eclipse.jdt.core.dom.Block)38 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)35 SimpleName (org.eclipse.jdt.core.dom.SimpleName)34 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)34 CastExpression (org.eclipse.jdt.core.dom.CastExpression)33 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)32 Type (org.eclipse.jdt.core.dom.Type)30 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)30 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)29 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)29 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)29 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)29