Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AST for current selected code in eclipse editor?

I need to get the AST for the current selection in the java editor fo eclipse. Basically I want to convert the selected java code in to some other form(maybe some other language or XML etc..). So I guess, I need to get the AST for the selection. Currently I am able to get the selection as simple text. Is there any way out for such problem? Thanks already!!

like image 562
Suraj Chandran Avatar asked Dec 18 '22 05:12

Suraj Chandran


2 Answers

There are a number of handy tools for JDT plugin developers, especially the AST View which does pretty much what you are looking for. So, all you need to do is grab the code for 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 plugin spy (read more about it in this article) to start digging into the view classes.

You are traveling into less trivial (and often undocumented) areas of JDT, developing your code digging skills will greatly improve your performance.

like image 168
zvikico Avatar answered Jan 09 '23 14:01

zvikico


The following Code provides you the AST Node of the current selected Code from the 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();

The JavaUI is the entry point to the JDT UI plugin.

like image 35
mastermind.reloaded Avatar answered Jan 09 '23 13:01

mastermind.reloaded