AST for the currently selected code in eclipse editor?

I need to get AST for the current selection in the java editor for eclipse. Basically, I want to convert the selected Java code to some other form (maybe a different language or XML, etc.). Therefore, I think I need to get an AST to choose. Currently, I can get the selection as plain text. Is there any way out for such a problem? Thanks already!

+4
source share
4 answers

There are many handy tools for JDT plugin developers, especially AST View , which does pretty much what you are looking for. So, all you have to do is grab the code for the AST View and check how it is done.

The plugin can be installed from the following update site: http://www.eclipse.org/jdt/ui/update-site

JDT ASTView

Use the spy plugin (read more about this in this article ) to start digging into view classes.

As you travel to less trivial (and often undocumented) areas of JDT, developing code digging skills will greatly improve your productivity.

+7
source

The following code provides you with an AST Node of the currently selected code from CompilationUnitEditor.

        ITextEditor editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
        ITextSelection sel  = (ITextSelection) editor.getSelectionProvider().getSelection();
        ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor.getEditorInput());
        ICompilationUnit icu = (ICompilationUnit) typeRoot.getAdapter(ICompilationUnit.class);
        CompilationUnit cu = parse(icu);
        NodeFinder finder = new NodeFinder(cu, sel.getOffset(), sel.getLength());
        ASTNode node = finder.getCoveringNode();

JavaUI - JDT UI.

+4

org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.getActiveEditorJavaInput(). Java, . org.eclipse.jdt.core.IJavaElement, Java, org.eclipse.jdt.core.ICompilationUnit.

AST, .. org.eclipse.jdt.core.dom.CompilationUnit, :

public static CompilationUnit getCompilationUnit(ICompilationUnit icu,
        IProgressMonitor monitor) {
    final ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(icu);
    parser.setResolveBindings(true);
    final CompilationUnit ret = (CompilationUnit) parser.createAST(monitor);
    return ret;
}

, Java >= 5. ASTParser.newParser().

, , EditorUtility, .

+1

IIRC, each node in the Eclipse AST contains an offset. All you have to do is calculate the offsets for the part of the code you are interested in, and then go through the AST to select the nodes at these offsets.

0
source

All Articles