Search in sources :

Example 61 with BodyDeclaration

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

the class UnresolvedElementsSubProcessor method createTypeRefChangeProposal.

private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance, int maxProposals) {
    ImportRewrite importRewrite = null;
    String simpleName = fullName;
    String packName = Signature.getQualifier(fullName);
    if (packName.length() > 0) {
        // no imports for primitive types, type variables
        importRewrite = StubUtility.createImportRewrite((CompilationUnit) node.getRoot(), true);
        // can be null in package-info.java
        BodyDeclaration scope = ASTResolving.findParentBodyDeclaration(node);
        ImportRewriteContext context = new ContextSensitiveImportRewriteContext(scope != null ? scope : node, importRewrite);
        simpleName = importRewrite.addImport(fullName, context);
    }
    if (!isLikelyTypeName(simpleName)) {
        relevance -= 2;
    }
    ASTRewriteCorrectionProposal proposal;
    if (importRewrite != null && node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) {
        // import only
        // import only
        String[] arg = { BasicElementLabels.getJavaElementName(simpleName), BasicElementLabels.getJavaElementName(packName) };
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, arg);
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
        int boost = QualifiedTypeNameHistory.getBoost(fullName, 0, maxProposals);
        proposal = new AddImportCorrectionProposal(label, cu, relevance + 100 + boost, image, packName, simpleName, (SimpleName) node);
        proposal.setCommandId(ADD_IMPORT_ID);
    } else {
        String label;
        if (packName.length() == 0) {
            label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetype_nopack_description, BasicElementLabels.getJavaElementName(simpleName));
        } else {
            String[] arg = { BasicElementLabels.getJavaElementName(simpleName), BasicElementLabels.getJavaElementName(packName) };
            label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetype_description, arg);
        }
        ASTRewrite rewrite = ASTRewrite.create(node.getAST());
        rewrite.replace(node, rewrite.createStringPlaceholder(simpleName, ASTNode.SIMPLE_TYPE), null);
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance, image);
    }
    if (importRewrite != null) {
        proposal.setImportRewrite(importRewrite);
    }
    return proposal;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) AddImportCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.AddImportCorrectionProposal) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 62 with BodyDeclaration

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

the class AssignToVariableAssistProposal method doAddField.

private ASTRewrite doAddField() {
    boolean isParamToField = fNodeToAssign.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION;
    ASTNode newTypeDecl = ASTResolving.findParentType(fNodeToAssign);
    if (newTypeDecl == null) {
        return null;
    }
    Expression expression = isParamToField ? ((SingleVariableDeclaration) fNodeToAssign).getName() : ((ExpressionStatement) fNodeToAssign).getExpression();
    AST ast = newTypeDecl.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    createImportRewrite((CompilationUnit) fNodeToAssign.getRoot());
    BodyDeclaration bodyDecl = ASTResolving.findParentBodyDeclaration(fNodeToAssign);
    Block body;
    if (bodyDecl instanceof MethodDeclaration) {
        body = ((MethodDeclaration) bodyDecl).getBody();
    } else if (bodyDecl instanceof Initializer) {
        body = ((Initializer) bodyDecl).getBody();
    } else {
        return null;
    }
    IJavaProject project = getCompilationUnit().getJavaProject();
    boolean isAnonymous = newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
    boolean isStatic = Modifier.isStatic(bodyDecl.getModifiers()) && !isAnonymous;
    boolean isConstructorParam = isParamToField && fNodeToAssign.getParent() instanceof MethodDeclaration && ((MethodDeclaration) fNodeToAssign.getParent()).isConstructor();
    int modifiers = Modifier.PRIVATE;
    if (isStatic) {
        modifiers |= Modifier.STATIC;
    } else if (isConstructorParam) {
    //			String saveActionsKey= AbstractSaveParticipantPreferenceConfiguration.EDITOR_SAVE_PARTICIPANT_PREFIX + CleanUpPostSaveListener.POSTSAVELISTENER_ID;
    //			IScopeContext[] scopes= { InstanceScope.INSTANCE, new ProjectScope(project.getProject()) };
    //			boolean safeActionsEnabled= Platform.getPreferencesService().getBoolean(JavaPlugin.getPluginId(), saveActionsKey, false, scopes);
    }
    if (/*CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(
					CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS, project))
			&&*/
    CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL, project)) && CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, project))) {
        int constructors = 0;
        if (newTypeDecl instanceof AbstractTypeDeclaration) {
            List<BodyDeclaration> bodyDeclarations = ((AbstractTypeDeclaration) newTypeDecl).bodyDeclarations();
            for (BodyDeclaration decl : bodyDeclarations) {
                if (decl instanceof MethodDeclaration && ((MethodDeclaration) decl).isConstructor()) {
                    constructors++;
                }
            }
        }
        if (constructors == 1) {
            modifiers |= Modifier.FINAL;
        }
    }
    VariableDeclarationFragment newDeclFrag = addFieldDeclaration(rewrite, newTypeDecl, modifiers, expression);
    String varName = newDeclFrag.getName().getIdentifier();
    Assignment assignment = ast.newAssignment();
    assignment.setRightHandSide((Expression) rewrite.createCopyTarget(expression));
    boolean needsThis = StubUtility.useThisForFieldAccess(project);
    if (isParamToField) {
        needsThis |= varName.equals(((SimpleName) expression).getIdentifier());
    }
    SimpleName accessName = ast.newSimpleName(varName);
    if (needsThis) {
        FieldAccess fieldAccess = ast.newFieldAccess();
        fieldAccess.setName(accessName);
        if (isStatic) {
            String typeName = ((AbstractTypeDeclaration) newTypeDecl).getName().getIdentifier();
            fieldAccess.setExpression(ast.newSimpleName(typeName));
        } else {
            fieldAccess.setExpression(ast.newThisExpression());
        }
        assignment.setLeftHandSide(fieldAccess);
    } else {
        assignment.setLeftHandSide(accessName);
    }
    ASTNode selectionNode;
    if (isParamToField) {
        // assign parameter to field
        ExpressionStatement statement = ast.newExpressionStatement(assignment);
        int insertIdx = findAssignmentInsertIndex(body.statements());
        rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertAt(statement, insertIdx, null);
        selectionNode = statement;
    } else {
        if (needsSemicolon(expression)) {
            rewrite.replace(expression, ast.newExpressionStatement(assignment), null);
        } else {
            rewrite.replace(expression, assignment, null);
        }
        selectionNode = fNodeToAssign;
    }
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
    if (!isParamToField) {
        FieldDeclaration fieldDeclaration = (FieldDeclaration) newDeclFrag.getParent();
        addLinkedPosition(rewrite.track(fieldDeclaration.getType()), false, KEY_TYPE);
    }
    addLinkedPosition(rewrite.track(accessName), true, KEY_NAME);
    IVariableBinding variableBinding = newDeclFrag.resolveBinding();
    if (variableBinding != null) {
        SimpleName[] linkedNodes = LinkedNodeFinder.findByBinding(fNodeToAssign.getRoot(), variableBinding);
        for (int i = 0; i < linkedNodes.length; i++) {
            addLinkedPosition(rewrite.track(linkedNodes[i]), false, KEY_NAME);
        }
    }
    setEndPosition(rewrite.track(selectionNode));
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) Assignment(org.eclipse.jdt.core.dom.Assignment) IJavaProject(org.eclipse.jdt.core.IJavaProject) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Initializer(org.eclipse.jdt.core.dom.Initializer) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 63 with BodyDeclaration

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

the class AbstractMethodCorrectionProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fNode);
    ASTNode typeDecl = astRoot.findDeclaringNode(fSenderBinding);
    ASTNode newTypeDecl = null;
    boolean isInDifferentCU;
    if (typeDecl != null) {
        isInDifferentCU = false;
        newTypeDecl = typeDecl;
    } else {
        isInDifferentCU = true;
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
    }
    createImportRewrite(astRoot);
    if (newTypeDecl != null) {
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        MethodDeclaration newStub = getStub(rewrite, newTypeDecl);
        ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
        List<BodyDeclaration> members = ASTNodes.getBodyDeclarations(newTypeDecl);
        int insertIndex;
        if (isConstructor()) {
            insertIndex = findConstructorInsertIndex(members);
        } else if (!isInDifferentCU) {
            insertIndex = findMethodInsertIndex(members, fNode.getStartPosition());
        } else {
            insertIndex = members.size();
        }
        ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
        listRewriter.insertAt(newStub, insertIndex, null);
        return rewrite;
    }
    return null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor)

Example 64 with BodyDeclaration

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

the class AssignToVariableAssistProposal method addFieldDeclaration.

private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression) {
    if (fExistingFragment != null) {
        return fExistingFragment;
    }
    ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
    List<BodyDeclaration> decls = ASTNodes.getBodyDeclarations(newTypeDecl);
    AST ast = newTypeDecl.getAST();
    String[] varNames = suggestFieldNames(fTypeBinding, expression, modifiers);
    for (int i = 0; i < varNames.length; i++) {
        addLinkedPositionProposal(KEY_NAME, varNames[i], null);
    }
    String varName = varNames[0];
    VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
    newDeclFrag.setName(ast.newSimpleName(varName));
    FieldDeclaration newDecl = ast.newFieldDeclaration(newDeclFrag);
    Type type = evaluateType(ast);
    newDecl.setType(type);
    newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));
    ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), false);
    int insertIndex = findFieldInsertIndex(decls, fNodeToAssign.getStartPosition());
    rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null);
    return newDeclFrag;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) Type(org.eclipse.jdt.core.dom.Type) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor)

Example 65 with BodyDeclaration

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

the class ReturnTypeSubProcessor method addVoidMethodReturnsProposals.

public static void addVoidMethodReturnsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl instanceof MethodDeclaration && selectedNode.getNodeType() == ASTNode.RETURN_STATEMENT) {
        ReturnStatement returnStatement = (ReturnStatement) selectedNode;
        Expression expr = returnStatement.getExpression();
        if (expr != null) {
            AST ast = astRoot.getAST();
            ITypeBinding binding = Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
            if (binding == null) {
                //$NON-NLS-1$
                binding = ast.resolveWellKnownType("java.lang.Object");
            }
            if (binding.isWildcardType()) {
                binding = ASTResolving.normalizeWildcardType(binding, true, ast);
            }
            MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
            ASTRewrite rewrite = ASTRewrite.create(ast);
            String label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_voidmethodreturns_description, BindingLabelProvider.getBindingLabel(binding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.VOID_METHOD_RETURNS, image);
            ImportRewrite imports = proposal.createImportRewrite(astRoot);
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(methodDeclaration, imports);
            Type newReturnType = imports.addImport(binding, ast, importRewriteContext);
            if (methodDeclaration.isConstructor()) {
                rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
                rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, newReturnType, null);
            } else {
                rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
            }
            //$NON-NLS-1$
            String key = "return_type";
            proposal.addLinkedPosition(rewrite.track(newReturnType), true, key);
            ITypeBinding[] bindings = ASTResolving.getRelaxingTypes(ast, binding);
            for (int i = 0; i < bindings.length; i++) {
                proposal.addLinkedPositionProposal(key, bindings[i]);
            }
            Javadoc javadoc = methodDeclaration.getJavadoc();
            if (javadoc != null) {
                TagElement newTag = ast.newTagElement();
                newTag.setTagName(TagElement.TAG_RETURN);
                TextElement commentStart = ast.newTextElement();
                newTag.fragments().add(commentStart);
                JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
                //$NON-NLS-1$
                proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
            }
            proposals.add(proposal);
        }
        ASTRewrite rewrite = ASTRewrite.create(decl.getAST());
        rewrite.remove(returnStatement.getExpression(), null);
        String label = CorrectionMessages.ReturnTypeSubProcessor_removereturn_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_RETURN, image);
        proposals.add(proposal);
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) TextElement(org.eclipse.jdt.core.dom.TextElement) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Aggregations

BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)98 ASTNode (org.eclipse.jdt.core.dom.ASTNode)61 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)53 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)28 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)27 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)26 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)26 Type (org.eclipse.jdt.core.dom.Type)25 AST (org.eclipse.jdt.core.dom.AST)23 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)18 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)17 Expression (org.eclipse.jdt.core.dom.Expression)16 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)15 Initializer (org.eclipse.jdt.core.dom.Initializer)15 SimpleName (org.eclipse.jdt.core.dom.SimpleName)15 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)15 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)14 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)14 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)13 ArrayList (java.util.ArrayList)12