Search in sources :

Example 11 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project eclipse.platform.text by eclipse.

the class LinkedPositionGroup method handleEvent.

/**
 * Creates an edition of a document change that will forward any
 * modification in one position to all linked siblings. The return value is
 * a map from <code>IDocument</code> to <code>TextEdit</code>.
 *
 * @param event the document event to check
 * @return a map of edits, grouped by edited document, or <code>null</code>
 *         if there are no edits
 */
Map<IDocument, TextEdit> handleEvent(DocumentEvent event) {
    if (fLastPosition != null) {
        Map<IDocument, List<ReplaceEdit>> map = new HashMap<>();
        int relativeOffset = event.getOffset() - fLastRegion.getOffset();
        if (relativeOffset < 0) {
            relativeOffset = 0;
        }
        int eventEnd = event.getOffset() + event.getLength();
        int lastEnd = fLastRegion.getOffset() + fLastRegion.getLength();
        int length;
        if (eventEnd > lastEnd)
            length = lastEnd - relativeOffset - fLastRegion.getOffset();
        else
            length = eventEnd - relativeOffset - fLastRegion.getOffset();
        String text = event.getText();
        if (text == null)
            // $NON-NLS-1$
            text = "";
        for (LinkedPosition p : fPositions) {
            if (p == fLastPosition || p.isDeleted())
                // don't re-update the origin of the change
                continue;
            List<ReplaceEdit> edits = map.get(p.getDocument());
            if (edits == null) {
                edits = new ArrayList<>();
                map.put(p.getDocument(), edits);
            }
            if (fMustEnforceEqualContents) {
                try {
                    edits.add(new ReplaceEdit(p.getOffset(), p.getLength(), fLastPosition.getContent()));
                } catch (BadLocationException e) {
                    // should not happen
                    throw new RuntimeException(e);
                }
            } else {
                edits.add(new ReplaceEdit(p.getOffset() + relativeOffset, length, text));
            }
        }
        fMustEnforceEqualContents = false;
        try {
            Map<IDocument, TextEdit> result = new HashMap<>();
            for (IDocument d : map.keySet()) {
                TextEdit edit = new MultiTextEdit(0, d.getLength());
                edit.addChildren(map.get(d).toArray(new TextEdit[0]));
                result.put(d, edit);
            }
            return result;
        } catch (MalformedTreeException x) {
            // manager
            return null;
        }
    }
    return null;
}
Also used : HashMap(java.util.HashMap) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 12 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project eclipse.jdt.ls 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());
        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()) {
            workingCopyContents.insert(insertPosition, '{' + dummyClassContent + '}');
            insertPosition++;
        } else {
            // $NON-NLS-1$
            workingCopyContents.insert(insertPosition, dummyClassContent + "\n\n");
        }
        workingCopy.getBuffer().setContents(workingCopyContents.toString());
        ASTParser parser = ASTParser.newParser(IASTSharedValues.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 = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject());
        IMethodBinding[] methodsToOverride = null;
        settings.createComments = false;
        List<IMethodBinding> result = new ArrayList<>();
        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()]);
        // used to find @NonNullByDefault effective at that current context
        IBinding contextBinding = null;
        if (fCompilationUnit.getJavaProject().getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true).equals(JavaCore.ENABLED)) {
            ASTNode focusNode = NodeFinder.perform(astRoot, fReplacementOffset + dummyClassContent.length(), 0);
            contextBinding = getEnclosingDeclaration(focusNode);
        }
        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++) {
            boolean snippetSupport = i == methodsToOverride.length - 1 ? fSnippetSupport : false;
            IMethodBinding curr = methodsToOverride[i];
            MethodDeclaration stub = StubUtility2.createImplementationStub(workingCopy, rewrite, importRewrite, null, curr, dummyTypeBinding, settings, dummyTypeBinding.isInterface(), contextBinding, snippetSupport);
            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) {
            JavaLanguageServerPlugin.logException(exception.getMessage(), exception);
        } catch (BadLocationException exception) {
            JavaLanguageServerPlugin.logException(exception.getMessage(), 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.ls.core.internal.corext.codemanipulation.CodeGenerationSettings) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) 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) ASTParser(org.eclipse.jdt.core.dom.ASTParser) 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) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 13 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project eclipse.jdt.ls by eclipse.

the class DocumentLifeCycleHandler method handleChanged.

public void handleChanged(DidChangeTextDocumentParams params) {
    ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
    if (unit == null || !unit.isWorkingCopy() || params.getContentChanges().isEmpty()) {
        return;
    }
    try {
        if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
            sharedASTProvider.disposeAST();
        }
        List<TextDocumentContentChangeEvent> contentChanges = params.getContentChanges();
        for (TextDocumentContentChangeEvent changeEvent : contentChanges) {
            Range range = changeEvent.getRange();
            int length;
            if (range != null) {
                length = changeEvent.getRangeLength().intValue();
            } else {
                // range is optional and if not given, the whole file content is replaced
                length = unit.getSource().length();
                range = JDTUtils.toRange(unit, 0, length);
            }
            int startOffset = JsonRpcHelpers.toOffset(unit.getBuffer(), range.getStart().getLine(), range.getStart().getCharacter());
            TextEdit edit = null;
            String text = changeEvent.getText();
            if (length == 0) {
                edit = new InsertEdit(startOffset, text);
            } else if (text.isEmpty()) {
                edit = new DeleteEdit(startOffset, length);
            } else {
                edit = new ReplaceEdit(startOffset, length, text);
            }
            IDocument document = JsonRpcHelpers.toDocument(unit.getBuffer());
            edit.apply(document, TextEdit.NONE);
        }
        triggerValidation(unit);
    } catch (JavaModelException | MalformedTreeException | BadLocationException e) {
        JavaLanguageServerPlugin.logException("Error while handling document change", e);
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) InsertEdit(org.eclipse.text.edits.InsertEdit) JavaModelException(org.eclipse.jdt.core.JavaModelException) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) Range(org.eclipse.lsp4j.Range) DeleteEdit(org.eclipse.text.edits.DeleteEdit) TextDocumentContentChangeEvent(org.eclipse.lsp4j.TextDocumentContentChangeEvent) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 14 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project jbosstools-hibernate by jbosstools.

the class CodeGenExternalProcessExecutionTest method formatJavaFile.

/**
 * format string as java file.
 *
 * @param str
 * @return
 */
public String formatJavaFile(String str) {
    Document doc = new Document(str);
    TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, str, 0, str.length(), 0, null);
    try {
        edit.apply(doc);
    } catch (MalformedTreeException e) {
    } catch (BadLocationException e) {
    }
    return doc.get();
}
Also used : TextEdit(org.eclipse.text.edits.TextEdit) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) Document(org.eclipse.jface.text.Document) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 15 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project jbosstools-hibernate by jbosstools.

the class AllEntitiesProcessor method performCommit.

protected void performCommit(final Map<String, EntityInfo> entities) {
    final ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
    for (int i = 0; i < changes.size(); i++) {
        ChangeStructure cs = changes.get(i);
        if (cs.textEdit != null && ((cs.change != null && cs.change.isEnabled()) || (cs.change == null))) {
            ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(cs.path, LocationKind.IFILE);
            IDocument document = textFileBuffer.getDocument();
            try {
                cs.textEdit.apply(document);
            } catch (MalformedTreeException e) {
                // $NON-NLS-1$
                HibernateConsolePlugin.getDefault().logErrorMessage("MalformedTreeException: ", e);
            } catch (BadLocationException e) {
                // $NON-NLS-1$
                HibernateConsolePlugin.getDefault().logErrorMessage("BadLocationException: ", e);
            }
            try {
                // commit changes to underlying file
                textFileBuffer.commit(null, true);
            } catch (CoreException e) {
                // $NON-NLS-1$
                HibernateConsolePlugin.getDefault().logErrorMessage("CoreException: ", e);
            }
        }
    }
}
Also used : CoreException(org.eclipse.core.runtime.CoreException) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)52 BadLocationException (org.eclipse.jface.text.BadLocationException)38 IDocument (org.eclipse.jface.text.IDocument)25 TextEdit (org.eclipse.text.edits.TextEdit)19 CoreException (org.eclipse.core.runtime.CoreException)12 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)12 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)11 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)11 Document (org.eclipse.jface.text.Document)11 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)11 Test (org.junit.Test)11 ITextFileBufferManager (org.eclipse.core.filebuffers.ITextFileBufferManager)10 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)10 ITextFileBuffer (org.eclipse.core.filebuffers.ITextFileBuffer)9 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)9 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)8 InsertEdit (org.eclipse.text.edits.InsertEdit)8 IPath (org.eclipse.core.runtime.IPath)7 ASTNode (org.eclipse.jdt.core.dom.ASTNode)7 ArrayList (java.util.ArrayList)6