Search in sources :

Example 46 with ASTNode

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

the class SuppressWarningsSubProcessor method addUnknownSuppressWarningProposals.

/**
	 * Adds a proposal to correct the name of the SuppressWarning annotation
	 * @param context the context
	 * @param problem the problem
	 * @param proposals the resulting proposals
	 */
public static void addUnknownSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ASTNode coveringNode = context.getCoveringNode();
    if (!(coveringNode instanceof StringLiteral))
        return;
    AST ast = coveringNode.getAST();
    StringLiteral literal = (StringLiteral) coveringNode;
    String literalValue = literal.getLiteralValue();
    String[] allWarningTokens = CorrectionEngine.getAllWarningTokens();
    for (int i = 0; i < allWarningTokens.length; i++) {
        String curr = allWarningTokens[i];
        if (NameMatcher.isSimilarName(literalValue, curr)) {
            StringLiteral newLiteral = ast.newStringLiteral();
            newLiteral.setLiteralValue(curr);
            ASTRewrite rewrite = ASTRewrite.create(ast);
            rewrite.replace(literal, newLiteral, null);
            String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_fix_suppress_token_label, new String[] { curr });
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.FIX_SUPPRESS_TOKEN, image);
            proposals.add(proposal);
        }
    }
    addRemoveUnusedSuppressWarningProposals(context, problem, proposals);
}
Also used : ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) AST(org.eclipse.jdt.core.dom.AST) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Image(org.eclipse.swt.graphics.Image)

Example 47 with ASTNode

use of org.eclipse.jdt.core.dom.ASTNode 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 48 with ASTNode

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

the class GenerateForLoopAssistProposal method getVariableNameProposals.

/**
	 * Retrieves name proposals for a fresh local variable.
	 * 
	 * @param basename the basename of the proposals
	 * @param excludedName a name that cannot be used for the variable; <code>null</code> if none
	 * @return an array of proposal strings
	 */
private String[] getVariableNameProposals(String basename, String excludedName) {
    ASTNode surroundingBlock = fCurrentNode;
    while ((surroundingBlock = surroundingBlock.getParent()) != null) {
        if (surroundingBlock instanceof Block) {
            break;
        }
    }
    Collection<String> localUsedNames = new ScopeAnalyzer((CompilationUnit) fCurrentExpression.getRoot()).getUsedVariableNames(surroundingBlock.getStartPosition(), surroundingBlock.getLength());
    if (excludedName != null) {
        localUsedNames.add(excludedName);
    }
    String[] names = StubUtility.getLocalNameSuggestions(getCompilationUnit().getJavaProject(), basename, 0, localUsedNames.toArray(new String[localUsedNames.size()]));
    return names;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer)

Example 49 with ASTNode

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

the class MissingReturnTypeCorrectionProposal method getRewrite.

/*(non-Javadoc)
	 * @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
	 */
@Override
protected ASTRewrite getRewrite() {
    AST ast = getAST();
    ITypeBinding returnBinding = getReturnTypeBinding();
    if (fExistingReturn != null) {
        ASTRewrite rewrite = ASTRewrite.create(ast);
        Expression expression = evaluateReturnExpressions(ast, returnBinding, fExistingReturn.getStartPosition());
        if (expression != null) {
            rewrite.set(fExistingReturn, ReturnStatement.EXPRESSION_PROPERTY, expression, null);
            addLinkedPosition(rewrite.track(expression), true, RETURN_EXPRESSION_KEY);
        }
        return rewrite;
    } else {
        ASTRewrite rewrite = ASTRewrite.create(ast);
        ASTNode body = getBody();
        // For lambda the body can be a block or an expression.
        if (body instanceof Block) {
            Block block = (Block) body;
            List<Statement> statements = block.statements();
            int nStatements = statements.size();
            ASTNode lastStatement = null;
            if (nStatements > 0) {
                lastStatement = statements.get(nStatements - 1);
            }
            if (returnBinding != null && lastStatement instanceof ExpressionStatement && lastStatement.getNodeType() != ASTNode.ASSIGNMENT) {
                Expression expression = ((ExpressionStatement) lastStatement).getExpression();
                ITypeBinding binding = expression.resolveTypeBinding();
                if (binding != null && binding.isAssignmentCompatible(returnBinding)) {
                    Expression placeHolder = (Expression) rewrite.createMoveTarget(expression);
                    ReturnStatement returnStatement = ast.newReturnStatement();
                    returnStatement.setExpression(placeHolder);
                    rewrite.replace(lastStatement, returnStatement, null);
                    return rewrite;
                }
            }
            int offset;
            if (lastStatement == null) {
                offset = block.getStartPosition() + 1;
            } else {
                offset = lastStatement.getStartPosition() + lastStatement.getLength();
            }
            ReturnStatement returnStatement = ast.newReturnStatement();
            Expression expression = evaluateReturnExpressions(ast, returnBinding, offset);
            returnStatement.setExpression(expression);
            rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertLast(returnStatement, null);
            addLinkedPosition(rewrite.track(returnStatement.getExpression()), true, RETURN_EXPRESSION_KEY);
        }
        return rewrite;
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) Expression(org.eclipse.jdt.core.dom.Expression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) Statement(org.eclipse.jdt.core.dom.Statement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block)

Example 50 with ASTNode

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

the class NewCUUsingWizardProposal method getTypeName.

private static String getTypeName(int typeKind, Name node) {
    String name = ASTNodes.getSimpleNameIdentifier(node);
    if (typeKind == K_CLASS || typeKind == K_INTERFACE) {
        ASTNode parent = node.getParent();
        if (parent.getLocationInParent() == ParameterizedType.TYPE_PROPERTY) {
            // use 'S' or 'T'
            String typeArgBaseName = name.startsWith(String.valueOf('T')) ? String.valueOf('S') : String.valueOf('T');
            int nTypeArgs = ((ParameterizedType) parent.getParent()).typeArguments().size();
            StringBuffer buf = new StringBuffer(name);
            buf.append('<');
            if (nTypeArgs == 1) {
                buf.append(typeArgBaseName);
            } else {
                for (int i = 0; i < nTypeArgs; i++) {
                    if (i != 0)
                        //$NON-NLS-1$
                        buf.append(", ");
                    buf.append(typeArgBaseName).append(i + 1);
                }
            }
            buf.append('>');
            return buf.toString();
        }
    }
    return name;
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode)

Aggregations

ASTNode (org.eclipse.jdt.core.dom.ASTNode)432 SimpleName (org.eclipse.jdt.core.dom.SimpleName)99 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)98 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)90 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)85 Expression (org.eclipse.jdt.core.dom.Expression)81 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)73 AST (org.eclipse.jdt.core.dom.AST)70 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)69 ArrayList (java.util.ArrayList)62 Type (org.eclipse.jdt.core.dom.Type)62 Block (org.eclipse.jdt.core.dom.Block)61 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)49 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)47 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)45 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)44 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)44 CastExpression (org.eclipse.jdt.core.dom.CastExpression)42 IBinding (org.eclipse.jdt.core.dom.IBinding)41 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)37