如何从解析树到Java类文件
我正在使用具有以下功能的命令行工具:
- 使用扩展的Antlr4 Java9语法修改了.java文件。文件中的语法是Java,对包括目的的方法进行了一个修改,例如在此示例中:
public void {Marketing} sendemail(){} {}
- 使用访客收集并删除所有目的。目的的收集和分析是程序的主要功能。
- 编译并执行删除目的的Java文件。
我正在寻找实现步骤3的最简单,最有效的方法。建立完整的编译器的项目范围不超出我的项目范围,我希望在可能的情况下利用Java编译器并运行Javac。我已经考虑了以下方法,但是没有看似最佳的:
- 正如本文提出的那样:将AST汇回源代码。不过,在大型目录上可能会做很多工作。
- 使用ASM生成字节代码,尽管据我了解,我需要有效的Java源代码或类文件才能工作( https://asm.ow2.io/asm4-guide.pdf )。
- 构建一个Java编译器插件,以修改AST并在编译中的解析步骤中删除目的( https://www.baeldung.com/java-build-compiler-plugin )。我不确定在我可以修改AST之前的汇编是否会失败,因为语法无效。
任何输入都非常感谢。
I am working on a command-line tool with the following functionality:
- Parse modified .java files using an extended ANTLR4 Java9 grammar. The syntax in the files is Java, with one modification to the method declaration which includes a purpose, like in this example:
public void {marketing} sendEmail() {}
- Collect and remove all purposes using a visitor. Collection and analysis of the purposes is the main functionality of the program.
- Compile and execute the Java files where the purposes are removed.
I am searching for the simplest and most effective way to achieve step 3. It is out of the scope of my project to build a full compiler, I would prefer to exploit the Java compiler and run javac if possible. I have considered the following approaches, but none seem optimal:
- Prettyprinting (from parse tree to source code) as proposed in this post: Compiling an AST back to source code. It could be a lot of work on large directories though.
- Use ASM to generate byte code, though as I understand I would need valid java source code or class files for this to work (https://asm.ow2.io/asm4-guide.pdf).
- Build a Java compiler plugin, to modify the AST and remove purposes at the parse step in the compilation (https://www.baeldung.com/java-build-compiler-plugin). I am unsure if the compilation would fail before I can modify the AST because the syntax is not valid.
Any input is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 TokenStreamRewriter 来获取没有目的节点的源代码(或完成许多其他重写任务)。下面是一个来自应用程序的示例,我有条件地将顶级
LIMIT
子句添加到 MySQL 查询:这段代码在做什么:
使用此代码,您可以创建一个临时 java 文件进行编译。它可用于同时执行列表中的两个操作(收集目的并删除它们)。
You could use
TokenStreamRewriter
to get the source code without the purpose node (or accomplish many other rewriting tasks). Here's an example from an application where I conditionally add a top levelLIMIT
clause to a MySQL query:What is this code doing:
With this code you can create a temporary java file for compilation. And it could be used to execute two actions from your list at the same time (collect the purposes and remove them).