我需要在 Eclipse 的 java 编辑器中获取当前选择的 AST。基本上我想将选定的 java 代码转换为其他形式(可能是其他语言或 XML 等)。所以我想,我需要为选择获取 AST。目前我能够将选择作为简单的文本。有没有办法解决这样的问题?已经谢谢了!!
4 回答
JDT 插件开发人员有许多方便的工具,尤其是AST 视图,它几乎可以满足您的需求。因此,您需要做的就是获取 AST View 的代码并检查它是如何完成的。
该插件可以从以下更新站点安装:http: //www.eclipse.org/jdt/ui/update-site
使用插件 spy(在本文中了解更多信息)开始深入研究视图类。
您正在进入 JDT 的不那么琐碎(并且通常没有记录)的领域,开发您的代码挖掘技能将大大提高您的性能。
以下代码为您提供了来自 CompilationUnitEditor 的当前选定代码的 AST 节点。
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 插件的入口点。
使用方法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 类,这在这里非常有用。
IIRC,Eclipse AST 中的每个节点都包含一个偏移量。您需要做的就是计算您感兴趣的代码部分的偏移量,然后遍历 AST 以选择这些偏移量内的节点。