Search in sources :

Example 56 with ListRewrite

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

the class NewAnnotationMemberProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fInvocationNode);
    ASTNode typeDecl = astRoot.findDeclaringNode(fSenderBinding);
    ASTNode newTypeDecl = null;
    if (typeDecl != null) {
        newTypeDecl = typeDecl;
    } else {
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
    }
    createImportRewrite(astRoot);
    if (newTypeDecl instanceof AnnotationTypeDeclaration) {
        AnnotationTypeDeclaration newAnnotationTypeDecl = (AnnotationTypeDeclaration) newTypeDecl;
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        AnnotationTypeMemberDeclaration newStub = getStub(rewrite, newAnnotationTypeDecl);
        List<BodyDeclaration> members = newAnnotationTypeDecl.bodyDeclarations();
        int insertIndex = members.size();
        ListRewrite listRewriter = rewrite.getListRewrite(newAnnotationTypeDecl, AnnotationTypeDeclaration.BODY_DECLARATIONS_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) AnnotationTypeMemberDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite)

Example 57 with ListRewrite

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

the class AnonymousTypeCompletionProposal method createNewBody.

private String createNewBody(ImportRewrite importRewrite) throws CoreException {
    if (importRewrite == null)
        return null;
    ICompilationUnit workingCopy = null;
    try {
        //$NON-NLS-1$
        String name = "Type" + System.currentTimeMillis();
        workingCopy = fCompilationUnit.getPrimary().getWorkingCopy(null);
        ISourceRange range = fSuperType.getSourceRange();
        boolean sameUnit = range != null && fCompilationUnit.equals(fSuperType.getCompilationUnit());
        // creates a type that extends the super type
        String dummyClassContent = createDummyType(name);
        StringBuffer workingCopyContents = new StringBuffer(fCompilationUnit.getSource());
        int insertPosition;
        if (sameUnit) {
            insertPosition = range.getOffset() + range.getLength();
        } else {
            ISourceRange firstTypeRange = fCompilationUnit.getTypes()[0].getSourceRange();
            insertPosition = firstTypeRange.getOffset();
        }
        if (fSuperType.isLocal()) {
            // add an extra block: helps the AST to recover
            workingCopyContents.insert(insertPosition, '{' + dummyClassContent + '}');
            insertPosition++;
        } else {
            /*
				 * The two empty lines are added because the trackedDeclaration uses the covered range
				 * and hence would also included comments that directly follow the dummy class.
				 */
            //$NON-NLS-1$
            workingCopyContents.insert(insertPosition, dummyClassContent + "\n\n");
        }
        workingCopy.getBuffer().setContents(workingCopyContents.toString());
        CheASTParser parser = CheASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setResolveBindings(true);
        parser.setStatementsRecovery(true);
        parser.setSource(workingCopy);
        CompilationUnit astRoot = (CompilationUnit) parser.createAST(new NullProgressMonitor());
        ASTNode newType = NodeFinder.perform(astRoot, insertPosition, dummyClassContent.length());
        if (!(newType instanceof AbstractTypeDeclaration))
            return null;
        AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) newType;
        ITypeBinding dummyTypeBinding = declaration.resolveBinding();
        if (dummyTypeBinding == null)
            return null;
        IMethodBinding[] bindings = StubUtility2.getOverridableMethods(astRoot.getAST(), dummyTypeBinding, true);
        if (fSuperType.isInterface()) {
            ITypeBinding[] dummySuperInterfaces = dummyTypeBinding.getInterfaces();
            if (dummySuperInterfaces.length == 0 || dummySuperInterfaces.length == 1 && dummySuperInterfaces[0].isRawType())
                bindings = new IMethodBinding[0];
        } else {
            ITypeBinding dummySuperclass = dummyTypeBinding.getSuperclass();
            if (dummySuperclass == null || dummySuperclass.isRawType())
                bindings = new IMethodBinding[0];
        }
        CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fSuperType.getJavaProject());
        IMethodBinding[] methodsToOverride = null;
        IType type = null;
        if (!fSuperType.isInterface() && !fSuperType.isAnnotation()) {
            IJavaElement typeElement = dummyTypeBinding.getJavaElement();
            // add extra checks here as the recovered code is fragile
            if (typeElement instanceof IType && name.equals(typeElement.getElementName()) && typeElement.exists()) {
                type = (IType) typeElement;
            }
        }
        if (type != null) {
            //TODO window
            throw new UnsupportedOperationException();
        } else {
            settings.createComments = false;
            List<IMethodBinding> result = new ArrayList<IMethodBinding>();
            for (int i = 0; i < bindings.length; i++) {
                IMethodBinding curr = bindings[i];
                if (Modifier.isAbstract(curr.getModifiers()))
                    result.add(curr);
            }
            methodsToOverride = result.toArray(new IMethodBinding[result.size()]);
        }
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        ITrackedNodePosition trackedDeclaration = rewrite.track(declaration);
        ListRewrite rewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
        for (int i = 0; i < methodsToOverride.length; i++) {
            IMethodBinding curr = methodsToOverride[i];
            MethodDeclaration stub = StubUtility2.createImplementationStub(workingCopy, rewrite, importRewrite, null, curr, dummyTypeBinding.getName(), settings, dummyTypeBinding.isInterface());
            rewriter.insertFirst(stub, null);
        }
        IDocument document = new Document(workingCopy.getSource());
        try {
            rewrite.rewriteAST().apply(document);
            int bodyStart = trackedDeclaration.getStartPosition() + dummyClassContent.indexOf('{');
            int bodyEnd = trackedDeclaration.getStartPosition() + trackedDeclaration.getLength();
            return document.get(bodyStart, bodyEnd - bodyStart);
        } catch (MalformedTreeException exception) {
            JavaPlugin.log(exception);
        } catch (BadLocationException exception) {
            JavaPlugin.log(exception);
        }
        return null;
    } finally {
        if (workingCopy != null)
            workingCopy.discardWorkingCopy();
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) ArrayList(java.util.ArrayList) StyledString(org.eclipse.jface.viewers.StyledString) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IType(org.eclipse.jdt.core.IType) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) ISourceRange(org.eclipse.jdt.core.ISourceRange) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 58 with ListRewrite

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

the class OverrideCompletionProposal method updateReplacementString.

/*
     * @see JavaTypeCompletionProposal#updateReplacementString(IDocument,char,int,ImportRewrite)
     */
@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite importRewrite) throws CoreException, BadLocationException {
    Document recoveredDocument = new Document();
    CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
    ImportRewriteContext context;
    if (importRewrite != null) {
        context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);
    } else {
        // create a dummy import rewriter to have one
        importRewrite = StubUtility.createImportRewrite(unit, true);
        context = new // forces that all imports are fully qualified
        ImportRewriteContext() {

            @Override
            public int findInContext(String qualifier, String name, int kind) {
                return RES_NAME_CONFLICT;
            }
        };
    }
    ITypeBinding declaringType = null;
    ChildListPropertyDescriptor descriptor = null;
    ASTNode node = NodeFinder.perform(unit, offset, 1);
    if (node instanceof AnonymousClassDeclaration) {
        declaringType = ((AnonymousClassDeclaration) node).resolveBinding();
        descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
    } else if (node instanceof AbstractTypeDeclaration) {
        AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) node;
        descriptor = declaration.getBodyDeclarationsProperty();
        declaringType = declaration.resolveBinding();
    }
    if (declaringType != null) {
        ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
        IMethodBinding methodToOverride = Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
        if (methodToOverride == null && declaringType.isInterface()) {
            //$NON-NLS-1$
            methodToOverride = Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes);
        }
        if (methodToOverride != null) {
            CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
            MethodDeclaration stub = StubUtility2.createImplementationStub(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType.getName(), settings, declaringType.isInterface());
            ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
            rewriter.insertFirst(stub, null);
            ITrackedNodePosition position = rewrite.track(stub);
            try {
                rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);
                String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
                int generatedIndent = IndentManipulation.measureIndentUnits(getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth, settings.indentWidth);
                String indent = getIndentAt(document, getReplacementOffset(), settings);
                setReplacementString(IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth, settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document)));
            } catch (MalformedTreeException exception) {
                JavaPlugin.log(exception);
            } catch (BadLocationException exception) {
                JavaPlugin.log(exception);
            }
        }
    }
    return true;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) StyledString(org.eclipse.jface.viewers.StyledString) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) 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) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) BadLocationException(org.eclipse.jface.text.BadLocationException) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 59 with ListRewrite

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

the class NewVariableCorrectionProposal method doAddField.

private ASTRewrite doAddField(CompilationUnit astRoot) {
    SimpleName node = fOriginalNode;
    boolean isInDifferentCU = false;
    ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
    if (newTypeDecl == null) {
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
        isInDifferentCU = true;
    }
    ImportRewrite imports = createImportRewrite(astRoot);
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);
    if (newTypeDecl != null) {
        AST ast = newTypeDecl.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
        fragment.setName(ast.newSimpleName(node.getIdentifier()));
        Type type = evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding);
        FieldDeclaration newDecl = ast.newFieldDeclaration(fragment);
        newDecl.setType(type);
        newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));
        if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
            fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
        }
        ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
        List<BodyDeclaration> decls = ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);
        int maxOffset = isInDifferentCU ? -1 : node.getStartPosition();
        int insertIndex = findFieldInsertIndex(decls, newDecl, maxOffset);
        ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
        listRewriter.insertAt(newDecl, insertIndex, null);
        ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), fSenderBinding.isInterface());
        addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
        if (!isInDifferentCU) {
            addLinkedPosition(rewrite.track(node), true, KEY_NAME);
        }
        addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME);
        if (fragment.getInitializer() != null) {
            addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER);
        }
        return rewrite;
    }
    return null;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) 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) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 60 with ListRewrite

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

the class NewVariableCorrectionProposal method doAddParam.

private ASTRewrite doAddParam(CompilationUnit cu) {
    AST ast = cu.getAST();
    SimpleName node = fOriginalNode;
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(node);
    if (decl instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
        ASTRewrite rewrite = ASTRewrite.create(ast);
        ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
        ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
        SingleVariableDeclaration newDecl = ast.newSingleVariableDeclaration();
        newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, methodDeclaration.resolveBinding()));
        newDecl.setName(ast.newSimpleName(node.getIdentifier()));
        ListRewrite listRewriter = rewrite.getListRewrite(decl, MethodDeclaration.PARAMETERS_PROPERTY);
        listRewriter.insertLast(newDecl, null);
        addLinkedPosition(rewrite.track(node), true, KEY_NAME);
        // add javadoc tag
        Javadoc javadoc = methodDeclaration.getJavadoc();
        if (javadoc != null) {
            HashSet<String> leadingNames = new HashSet<String>();
            for (Iterator<SingleVariableDeclaration> iter = methodDeclaration.parameters().iterator(); iter.hasNext(); ) {
                SingleVariableDeclaration curr = iter.next();
                leadingNames.add(curr.getName().getIdentifier());
            }
            SimpleName newTagRef = ast.newSimpleName(node.getIdentifier());
            TagElement newTagElement = ast.newTagElement();
            newTagElement.setTagName(TagElement.TAG_PARAM);
            newTagElement.fragments().add(newTagRef);
            TextElement commentStart = ast.newTextElement();
            newTagElement.fragments().add(commentStart);
            addLinkedPosition(rewrite.track(newTagRef), false, KEY_NAME);
            //$NON-NLS-1$
            addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
            ListRewrite tagsRewriter = rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
            JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames);
        }
        addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(newDecl.getName()), false, KEY_NAME);
        return rewrite;
    }
    return null;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) TextElement(org.eclipse.jdt.core.dom.TextElement) 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) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) HashSet(java.util.HashSet)

Aggregations

ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)79 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)45 ASTNode (org.eclipse.jdt.core.dom.ASTNode)37 AST (org.eclipse.jdt.core.dom.AST)30 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)19 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)19 Block (org.eclipse.jdt.core.dom.Block)18 Type (org.eclipse.jdt.core.dom.Type)18 Image (org.eclipse.swt.graphics.Image)17 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)15 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)15 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)15 ArrayList (java.util.ArrayList)13 IType (org.eclipse.jdt.core.IType)13 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)13 Statement (org.eclipse.jdt.core.dom.Statement)13 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)13 Expression (org.eclipse.jdt.core.dom.Expression)12 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)12 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)12