Search in sources :

Example 1 with Block

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

the class StubUtility2 method createConstructorStub.

public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, ITypeBinding typeBinding, IMethodBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, CodeGenerationSettings settings) throws CoreException {
    AST ast = rewrite.getAST();
    MethodDeclaration decl = ast.newMethodDeclaration();
    decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
    decl.setName(ast.newSimpleName(typeBinding.getName()));
    decl.setConstructor(true);
    List<SingleVariableDeclaration> parameters = decl.parameters();
    if (superConstructor != null) {
        createTypeParameters(imports, context, ast, superConstructor, decl);
        createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, null, decl);
        createThrownExceptions(decl, superConstructor, imports, context, ast);
    }
    Block body = ast.newBlock();
    decl.setBody(body);
    String delimiter = StubUtility.getLineDelimiterUsed(unit);
    if (superConstructor != null) {
        SuperConstructorInvocation invocation = ast.newSuperConstructorInvocation();
        SingleVariableDeclaration varDecl = null;
        for (Iterator<SingleVariableDeclaration> iterator = parameters.iterator(); iterator.hasNext(); ) {
            varDecl = iterator.next();
            invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
        }
        body.statements().add(invocation);
    }
    List<String> prohibited = new ArrayList<String>();
    for (final Iterator<SingleVariableDeclaration> iterator = parameters.iterator(); iterator.hasNext(); ) prohibited.add(iterator.next().getName().getIdentifier());
    String param = null;
    List<String> list = new ArrayList<String>(prohibited);
    String[] excluded = null;
    for (int i = 0; i < variableBindings.length; i++) {
        SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
        var.setType(imports.addImport(variableBindings[i].getType(), ast, context));
        excluded = new String[list.size()];
        list.toArray(excluded);
        param = suggestParameterName(unit, variableBindings[i], excluded);
        list.add(param);
        var.setName(ast.newSimpleName(param));
        parameters.add(var);
    }
    list = new ArrayList<String>(prohibited);
    for (int i = 0; i < variableBindings.length; i++) {
        excluded = new String[list.size()];
        list.toArray(excluded);
        final String paramName = suggestParameterName(unit, variableBindings[i], excluded);
        list.add(paramName);
        final String fieldName = variableBindings[i].getName();
        Expression expression = null;
        if (paramName.equals(fieldName) || settings.useKeywordThis) {
            FieldAccess access = ast.newFieldAccess();
            access.setExpression(ast.newThisExpression());
            access.setName(ast.newSimpleName(fieldName));
            expression = access;
        } else
            expression = ast.newSimpleName(fieldName);
        Assignment assignment = ast.newAssignment();
        assignment.setLeftHandSide(expression);
        assignment.setRightHandSide(ast.newSimpleName(paramName));
        assignment.setOperator(Assignment.Operator.ASSIGN);
        body.statements().add(ast.newExpressionStatement(assignment));
    }
    if (settings != null && settings.createComments) {
        String string = CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, delimiter);
        if (string != null) {
            Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
            decl.setJavadoc(javadoc);
        }
    }
    return decl;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ArrayList(java.util.ArrayList) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Assignment(org.eclipse.jdt.core.dom.Assignment) Expression(org.eclipse.jdt.core.dom.Expression) Block(org.eclipse.jdt.core.dom.Block) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess)

Example 2 with Block

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

the class ReturnTypeSubProcessor method addMissingReturnStatementProposals.

public static void addMissingReturnStatementProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
    if (selectedNode == null) {
        return;
    }
    ReturnStatement existingStatement = (selectedNode instanceof ReturnStatement) ? (ReturnStatement) selectedNode : null;
    // Lambda Expression can be in a MethodDeclaration or a Field Declaration
    if (selectedNode instanceof LambdaExpression) {
        MissingReturnTypeInLambdaCorrectionProposal proposal = new MissingReturnTypeInLambdaCorrectionProposal(cu, (LambdaExpression) selectedNode, existingStatement, IProposalRelevance.MISSING_RETURN_TYPE);
        proposals.add(proposal);
    } else {
        BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
        if (decl instanceof MethodDeclaration) {
            MethodDeclaration methodDecl = (MethodDeclaration) decl;
            Block block = methodDecl.getBody();
            if (block == null) {
                return;
            }
            proposals.add(new MissingReturnTypeCorrectionProposal(cu, methodDecl, existingStatement, IProposalRelevance.MISSING_RETURN_TYPE));
            Type returnType = methodDecl.getReturnType2();
            if (returnType != null && !"void".equals(ASTNodes.asString(returnType))) {
                //$NON-NLS-1$
                AST ast = methodDecl.getAST();
                ASTRewrite rewrite = ASTRewrite.create(ast);
                rewrite.replace(returnType, ast.newPrimitiveType(PrimitiveType.VOID), null);
                Javadoc javadoc = methodDecl.getJavadoc();
                if (javadoc != null) {
                    TagElement tagElement = JavadocTagsSubProcessor.findTag(javadoc, TagElement.TAG_RETURN, null);
                    if (tagElement != null) {
                        rewrite.remove(tagElement, null);
                    }
                }
                String label = CorrectionMessages.ReturnTypeSubProcessor_changetovoid_description;
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_RETURN_TYPE_TO_VOID, image);
                proposals.add(proposal);
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) MissingReturnTypeInLambdaCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.MissingReturnTypeInLambdaCorrectionProposal) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) MissingReturnTypeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.MissingReturnTypeCorrectionProposal) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 3 with Block

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

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

the class GenerateForLoopAssistProposal method generateForRewrite.

/**
	 * Helper to generate an index based <code>for</code> loop to iterate over an array.
	 * 
	 * @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
	 * @return an applicable {@link ASTRewrite} instance
	 */
private ASTRewrite generateForRewrite(AST ast) {
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ForStatement loopStatement = ast.newForStatement();
    //$NON-NLS-1$
    SimpleName loopVariableName = resolveLinkedVariableNameWithProposals(rewrite, "int", null, true);
    loopStatement.initializers().add(getForInitializer(ast, loopVariableName));
    FieldAccess getArrayLengthExpression = ast.newFieldAccess();
    getArrayLengthExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
    //$NON-NLS-1$
    getArrayLengthExpression.setName(ast.newSimpleName("length"));
    loopStatement.setExpression(getLinkedInfixExpression(rewrite, loopVariableName.getIdentifier(), getArrayLengthExpression, InfixExpression.Operator.LESS));
    loopStatement.updaters().add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier()));
    Block forLoopBody = ast.newBlock();
    forLoopBody.statements().add(ast.newExpressionStatement(getForBodyAssignment(rewrite, loopVariableName)));
    forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
    loopStatement.setBody(forLoopBody);
    rewrite.replace(fCurrentNode, loopStatement, null);
    return rewrite;
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess)

Example 5 with Block

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

Aggregations

Block (org.eclipse.jdt.core.dom.Block)89 ASTNode (org.eclipse.jdt.core.dom.ASTNode)53 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)43 AST (org.eclipse.jdt.core.dom.AST)41 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)38 Statement (org.eclipse.jdt.core.dom.Statement)37 Expression (org.eclipse.jdt.core.dom.Expression)36 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)33 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)33 ForStatement (org.eclipse.jdt.core.dom.ForStatement)32 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)31 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)27 IfStatement (org.eclipse.jdt.core.dom.IfStatement)26 WhileStatement (org.eclipse.jdt.core.dom.WhileStatement)25 DoStatement (org.eclipse.jdt.core.dom.DoStatement)24 Type (org.eclipse.jdt.core.dom.Type)24 SimpleName (org.eclipse.jdt.core.dom.SimpleName)20 SwitchStatement (org.eclipse.jdt.core.dom.SwitchStatement)19 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)19 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)17