Search in sources :

Example 1 with ITrackedNodePosition

use of org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition in project flux by eclipse.

the class ModifierRewrite method internalSetModifiers.

/**
	 * Sets the given modifiers and removes all other modifiers that match the consideredFlags mask.
	 * Does not touch other flags and leaves annotations in place.
	 * 
	 * @param modifiers the modifiers to set
	 * @param consideredFlags mask of modifiers to consider
	 * @param editGroup the edit group in which to collect the corresponding text edits, or
	 *            <code>null</code> if ungrouped
	 * @return a tracked position that contains the changed modifiers
	 */
private PositionInformation internalSetModifiers(int modifiers, int consideredFlags, TextEditGroup editGroup) {
    int newModifiers = modifiers & consideredFlags;
    ITrackedNodePosition trackedFallback = null;
    List<ITrackedNodePosition> trackedNodes = new ArrayList<ITrackedNodePosition>();
    // remove modifiers
    List<IExtendedModifier> originalList = fModifierRewrite.getOriginalList();
    for (int i = 0; i < originalList.size(); i++) {
        ASTNode curr = (ASTNode) originalList.get(i);
        if (curr instanceof Modifier) {
            int flag = ((Modifier) curr).getKeyword().toFlagValue();
            if ((consideredFlags & flag) != 0) {
                if ((newModifiers & flag) == 0) {
                    fModifierRewrite.remove(curr, editGroup);
                    if (trackedFallback == null)
                        trackedFallback = fModifierRewrite.getASTRewrite().track(curr);
                }
                newModifiers &= ~flag;
            }
        }
    }
    // find last annotation
    IExtendedModifier lastAnnotation = null;
    List<IExtendedModifier> extendedList = fModifierRewrite.getRewrittenList();
    for (int i = 0; i < extendedList.size(); i++) {
        IExtendedModifier curr = extendedList.get(i);
        if (curr.isAnnotation())
            lastAnnotation = curr;
    }
    // add modifiers
    List<Modifier> newNodes = ASTNodeFactory.newModifiers(fAst, newModifiers);
    for (int i = 0; i < newNodes.size(); i++) {
        Modifier curr = newNodes.get(i);
        if ((curr.getKeyword().toFlagValue() & VISIBILITY_MODIFIERS) != 0) {
            if (lastAnnotation != null)
                fModifierRewrite.insertAfter(curr, (ASTNode) lastAnnotation, editGroup);
            else
                fModifierRewrite.insertFirst(curr, editGroup);
        } else {
            fModifierRewrite.insertLast(curr, editGroup);
        }
        trackedNodes.add(fModifierRewrite.getASTRewrite().track(curr));
    }
    if (trackedNodes.isEmpty()) {
        if (trackedFallback == null) {
            // out of tricks...
            trackedFallback = fModifierRewrite.getASTRewrite().track(fModifierRewrite.getParent());
        }
        return new LinkedProposalPositionGroup.StartPositionInformation(trackedFallback);
    } else {
        return new LinkedProposalPositionGroup.TrackedNodesPosition(trackedNodes);
    }
}
Also used : ArrayList(java.util.ArrayList) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Modifier(org.eclipse.jdt.core.dom.Modifier) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Example 2 with ITrackedNodePosition

use of org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition 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 3 with ITrackedNodePosition

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

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

the class ModifierRewrite method internalSetModifiers.

/**
	 * Sets the given modifiers and removes all other modifiers that match the consideredFlags mask.
	 * Does not touch other flags and leaves annotations in place.
	 *
	 * @param modifiers the modifiers to set
	 * @param consideredFlags mask of modifiers to consider
	 * @param editGroup the edit group in which to collect the corresponding text edits, or
	 *            <code>null</code> if ungrouped
	 * @return a tracked position that contains the changed modifiers
	 */
private PositionInformation internalSetModifiers(int modifiers, int consideredFlags, TextEditGroup editGroup) {
    int newModifiers = modifiers & consideredFlags;
    ITrackedNodePosition trackedFallback = null;
    List<ITrackedNodePosition> trackedNodes = new ArrayList<ITrackedNodePosition>();
    // remove modifiers
    List<IExtendedModifier> originalList = fModifierRewrite.getOriginalList();
    for (int i = 0; i < originalList.size(); i++) {
        ASTNode curr = (ASTNode) originalList.get(i);
        if (curr instanceof Modifier) {
            int flag = ((Modifier) curr).getKeyword().toFlagValue();
            if ((consideredFlags & flag) != 0) {
                if ((newModifiers & flag) == 0) {
                    fModifierRewrite.remove(curr, editGroup);
                    if (trackedFallback == null)
                        trackedFallback = fModifierRewrite.getASTRewrite().track(curr);
                }
                newModifiers &= ~flag;
            }
        }
    }
    // find last annotation
    IExtendedModifier lastAnnotation = null;
    List<IExtendedModifier> extendedList = fModifierRewrite.getRewrittenList();
    for (int i = 0; i < extendedList.size(); i++) {
        IExtendedModifier curr = extendedList.get(i);
        if (curr.isAnnotation())
            lastAnnotation = curr;
    }
    // add modifiers
    List<Modifier> newNodes = ASTNodeFactory.newModifiers(fAst, newModifiers);
    for (int i = 0; i < newNodes.size(); i++) {
        Modifier curr = newNodes.get(i);
        if ((curr.getKeyword().toFlagValue() & VISIBILITY_MODIFIERS) != 0) {
            if (lastAnnotation != null)
                fModifierRewrite.insertAfter(curr, (ASTNode) lastAnnotation, editGroup);
            else
                fModifierRewrite.insertFirst(curr, editGroup);
        } else {
            fModifierRewrite.insertLast(curr, editGroup);
        }
        trackedNodes.add(fModifierRewrite.getASTRewrite().track(curr));
    }
    if (trackedNodes.isEmpty()) {
        if (trackedFallback == null) {
            // out of tricks...
            trackedFallback = fModifierRewrite.getASTRewrite().track(fModifierRewrite.getParent());
        }
        return new LinkedProposalPositionGroup.StartPositionInformation(trackedFallback);
    } else {
        return new LinkedProposalPositionGroup.TrackedNodesPosition(trackedNodes);
    }
}
Also used : ArrayList(java.util.ArrayList) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) Modifier(org.eclipse.jdt.core.dom.Modifier) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Aggregations

ASTNode (org.eclipse.jdt.core.dom.ASTNode)4 ITrackedNodePosition (org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition)4 ArrayList (java.util.ArrayList)3 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)2 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)2 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)2 IExtendedModifier (org.eclipse.jdt.core.dom.IExtendedModifier)2 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)2 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)2 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)2 Modifier (org.eclipse.jdt.core.dom.Modifier)2 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)2 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)2 CodeGenerationSettings (org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings)2 BadLocationException (org.eclipse.jface.text.BadLocationException)2 Document (org.eclipse.jface.text.Document)2 IDocument (org.eclipse.jface.text.IDocument)2 StyledString (org.eclipse.jface.viewers.StyledString)2 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)2 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)1