Search in sources :

Example 1 with VariableDeclarationExpression

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

the class SuppressWarningsSubProcessor method addSuppressWarningsProposalIfPossible.

/**
	 * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance).
	 *
	 * @param cu the compilation unit
	 * @param node the node on which to add a SuppressWarning token
	 * @param warningToken the warning token to add
	 * @param relevance the proposal's relevance
	 * @param proposals collector to which the proposal should be added
	 * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal
	 *
	 * @since 3.6
	 */
private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) {
    ChildListPropertyDescriptor property;
    String name;
    boolean isLocalVariable = false;
    switch(node.getNodeType()) {
        case ASTNode.SINGLE_VARIABLE_DECLARATION:
            property = SingleVariableDeclaration.MODIFIERS2_PROPERTY;
            name = ((SingleVariableDeclaration) node).getName().getIdentifier();
            isLocalVariable = true;
            break;
        case ASTNode.VARIABLE_DECLARATION_STATEMENT:
            property = VariableDeclarationStatement.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments());
            isLocalVariable = true;
            break;
        case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
            property = VariableDeclarationExpression.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments());
            isLocalVariable = true;
            break;
        case ASTNode.TYPE_DECLARATION:
            property = TypeDeclaration.MODIFIERS2_PROPERTY;
            name = ((TypeDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.ANNOTATION_TYPE_DECLARATION:
            property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY;
            name = ((AnnotationTypeDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.ENUM_DECLARATION:
            property = EnumDeclaration.MODIFIERS2_PROPERTY;
            name = ((EnumDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.FIELD_DECLARATION:
            property = FieldDeclaration.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((FieldDeclaration) node).fragments());
            break;
        // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations
        case ASTNode.METHOD_DECLARATION:
            property = MethodDeclaration.MODIFIERS2_PROPERTY;
            //$NON-NLS-1$
            name = ((MethodDeclaration) node).getName().getIdentifier() + "()";
            break;
        case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
            property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY;
            //$NON-NLS-1$
            name = ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + "()";
            break;
        case ASTNode.ENUM_CONSTANT_DECLARATION:
            property = EnumConstantDeclaration.MODIFIERS2_PROPERTY;
            name = ((EnumConstantDeclaration) node).getName().getIdentifier();
            break;
        default:
            return relevance;
    }
    String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) });
    ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance);
    proposals.add(proposal);
    return isLocalVariable ? relevance - 1 : 0;
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) EnumConstantDeclaration(org.eclipse.jdt.core.dom.EnumConstantDeclaration) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration)

Example 2 with VariableDeclarationExpression

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

the class GenerateForLoopAssistProposal method getIndexBasedForBodyAssignment.

/**
	 * Creates an {@link Assignment} as first expression appearing in an index based
	 * <code>for</code> loop's body. This Assignment declares a local variable and initializes it
	 * using the {@link List}'s current element identified by the loop index.
	 * 
	 * @param rewrite the current {@link ASTRewrite} instance
	 * @param loopVariableName the name of the index variable in String representation
	 * @return a completed {@link Assignment} containing the mentioned declaration and
	 *         initialization
	 */
private Expression getIndexBasedForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) {
    AST ast = rewrite.getAST();
    ITypeBinding loopOverType = extractElementType(ast);
    Assignment assignResolvedVariable = ast.newAssignment();
    // left hand side
    SimpleName resolvedVariableName = resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
    VariableDeclarationFragment resolvedVariableDeclarationFragment = ast.newVariableDeclarationFragment();
    resolvedVariableDeclarationFragment.setName(resolvedVariableName);
    VariableDeclarationExpression resolvedVariableDeclaration = ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
    resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
    assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);
    // right hand side
    MethodInvocation invokeGetExpression = ast.newMethodInvocation();
    //$NON-NLS-1$
    invokeGetExpression.setName(ast.newSimpleName("get"));
    SimpleName indexVariableName = ast.newSimpleName(loopVariableName.getIdentifier());
    addLinkedPosition(rewrite.track(indexVariableName), LinkedPositionGroup.NO_STOP, indexVariableName.getIdentifier());
    invokeGetExpression.arguments().add(indexVariableName);
    invokeGetExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
    assignResolvedVariable.setRightHandSide(invokeGetExpression);
    assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);
    return assignResolvedVariable;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation)

Example 3 with VariableDeclarationExpression

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

the class NewVariableCorrectionProposal method doAddLocal.

private ASTRewrite doAddLocal(CompilationUnit cu) {
    AST ast = cu.getAST();
    Block body;
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(fOriginalNode);
    IBinding targetContext = null;
    if (decl instanceof MethodDeclaration) {
        body = (((MethodDeclaration) decl).getBody());
        targetContext = ((MethodDeclaration) decl).resolveBinding();
    } else if (decl instanceof Initializer) {
        body = (((Initializer) decl).getBody());
        targetContext = Bindings.getBindingOfParentType(decl);
    } else {
        return null;
    }
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
    SimpleName[] names = getAllReferences(body);
    ASTNode dominant = getDominantNode(names);
    Statement dominantStatement = ASTResolving.findParentStatement(dominant);
    if (ASTNodes.isControlStatementBody(dominantStatement.getLocationInParent())) {
        dominantStatement = (Statement) dominantStatement.getParent();
    }
    SimpleName node = names[0];
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
    if (isAssigned(dominantStatement, node)) {
        // x = 1; -> int x = 1;
        Assignment assignment = (Assignment) node.getParent();
        // trick to avoid comment removal around the statement: keep the expression statement
        // and replace the assignment with an VariableDeclarationExpression
        VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
        VariableDeclarationExpression newDecl = ast.newVariableDeclarationExpression(newDeclFrag);
        newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
        Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
        newDeclFrag.setInitializer(placeholder);
        newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
        rewrite.replace(assignment, newDecl, null);
        addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
        setEndPosition(rewrite.track(assignment.getParent()));
        return rewrite;
    } else if ((dominant != dominantStatement) && isForStatementInit(dominantStatement, node)) {
        //	for (x = 1;;) ->for (int x = 1;;)
        Assignment assignment = (Assignment) node.getParent();
        VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
        VariableDeclarationExpression expression = ast.newVariableDeclarationExpression(frag);
        frag.setName(ast.newSimpleName(node.getIdentifier()));
        Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
        frag.setInitializer(placeholder);
        expression.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
        rewrite.replace(assignment, expression, null);
        addLinkedPosition(rewrite.track(expression.getType()), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(frag.getName()), true, KEY_NAME);
        setEndPosition(rewrite.track(expression));
        return rewrite;
    } else if ((dominant != dominantStatement) && isEnhancedForStatementVariable(dominantStatement, node)) {
        //	for (x: collectionOfT) -> for (T x: collectionOfT)
        EnhancedForStatement enhancedForStatement = (EnhancedForStatement) dominantStatement;
        SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
        Expression expression = enhancedForStatement.getExpression();
        SimpleName newName = (SimpleName) rewrite.createMoveTarget(node);
        rewrite.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, newName, null);
        ITypeBinding elementBinding = null;
        ITypeBinding typeBinding = expression.resolveTypeBinding();
        if (typeBinding != null) {
            if (typeBinding.isArray()) {
                elementBinding = typeBinding.getElementType();
            } else {
                //$NON-NLS-1$
                ITypeBinding iterable = Bindings.findTypeInHierarchy(typeBinding, "java.lang.Iterable");
                if (iterable != null) {
                    ITypeBinding[] typeArguments = iterable.getTypeArguments();
                    if (typeArguments.length == 1) {
                        elementBinding = typeArguments[0];
                        elementBinding = Bindings.normalizeForDeclarationUse(elementBinding, ast);
                    }
                }
            }
        }
        Type type;
        if (elementBinding != null) {
            type = imports.addImport(elementBinding, ast, importRewriteContext);
        } else {
            //$NON-NLS-1$
            type = ast.newSimpleType(ast.newSimpleName("Object"));
        }
        rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
        addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(newName), true, KEY_NAME);
        setEndPosition(rewrite.track(expression));
        return rewrite;
    }
    //	foo(x) -> int x; foo(x)
    VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
    VariableDeclarationStatement newDecl = ast.newVariableDeclarationStatement(newDeclFrag);
    newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
    newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
    //		newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
    addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
    addLinkedPosition(rewrite.track(node), true, KEY_NAME);
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
    Statement statement = dominantStatement;
    List<? extends ASTNode> list = ASTNodes.getContainingList(statement);
    while (list == null && statement.getParent() instanceof Statement) {
        // parent must be if, for or while
        statement = (Statement) statement.getParent();
        list = ASTNodes.getContainingList(statement);
    }
    if (list != null) {
        ASTNode parent = statement.getParent();
        StructuralPropertyDescriptor childProperty = statement.getLocationInParent();
        if (childProperty.isChildListProperty()) {
            rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) childProperty).insertBefore(newDecl, statement, null);
            return rewrite;
        } else {
            return null;
        }
    }
    return rewrite;
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) IBinding(org.eclipse.jdt.core.dom.IBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Assignment(org.eclipse.jdt.core.dom.Assignment) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Initializer(org.eclipse.jdt.core.dom.Initializer) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 4 with VariableDeclarationExpression

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

the class GenerateForLoopAssistProposal method getIteratorBasedForInitializer.

/**
	 * Generates the initializer for an iterator based <code>for</code> loop, which declares and
	 * initializes the variable to loop over.
	 * 
	 * @param rewrite the instance of {@link ASTRewrite}
	 * @param loopVariableName the proposed name of the loop variable
	 * @return a {@link VariableDeclarationExpression} to use as initializer
	 */
private VariableDeclarationExpression getIteratorBasedForInitializer(ASTRewrite rewrite, SimpleName loopVariableName) {
    AST ast = rewrite.getAST();
    //$NON-NLS-1$
    IMethodBinding iteratorMethodBinding = Bindings.findMethodInHierarchy(fExpressionType, "iterator", new ITypeBinding[] {});
    // initializing fragment
    VariableDeclarationFragment varDeclarationFragment = ast.newVariableDeclarationFragment();
    varDeclarationFragment.setName(loopVariableName);
    MethodInvocation iteratorExpression = ast.newMethodInvocation();
    iteratorExpression.setName(ast.newSimpleName(iteratorMethodBinding.getName()));
    iteratorExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
    varDeclarationFragment.setInitializer(iteratorExpression);
    // declaration
    VariableDeclarationExpression varDeclarationExpression = ast.newVariableDeclarationExpression(varDeclarationFragment);
    varDeclarationExpression.setType(getImportRewrite().addImport(iteratorMethodBinding.getReturnType(), ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
    return varDeclarationExpression;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation)

Example 5 with VariableDeclarationExpression

use of org.eclipse.jdt.core.dom.VariableDeclarationExpression 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)

Aggregations

VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)22 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)18 Expression (org.eclipse.jdt.core.dom.Expression)12 AST (org.eclipse.jdt.core.dom.AST)11 ASTNode (org.eclipse.jdt.core.dom.ASTNode)10 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)10 Assignment (org.eclipse.jdt.core.dom.Assignment)8 Block (org.eclipse.jdt.core.dom.Block)7 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)7 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)7 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)7 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)6 SimpleName (org.eclipse.jdt.core.dom.SimpleName)6 Type (org.eclipse.jdt.core.dom.Type)6 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)6 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)5 ForStatement (org.eclipse.jdt.core.dom.ForStatement)5 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)5 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)5 Statement (org.eclipse.jdt.core.dom.Statement)5