在 ANTLR 3 中,如何在运行时而不是提前生成词法分析器(和解析器)?
我想在运行时生成 antlr 词法分析器——也就是说,生成语法并从语法生成词法分析器类及其在运行时的支持位。我很高兴将它输入到 java 编译器中,它可以在运行时访问。
I want to generate an antlr lexer at runtime -- that is, generate the grammar and from the grammar generate the lexer class, and its supporting bits at runtime. I am happy to feed it into the the java compiler, which is accessible at runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一种快速但肮脏的方法:
.g
文件,给定一个字符串作为语法源,.g
文件中.java
文件,Main.java
在像这样(在 *nix 上)
或 Windows 上
编译并运行它之后,会产生以下输出:
Here's a quick and dirty way to:
.g
file given a String as grammar-source,.g
file,.java
files,Main.java
Which, after compiling and running it like this (on *nix):
or on Windows
, produces the following output:
您必须使用 org.antlr.Tool() 类才能使其正常工作。
您可以在 github 上查看 ANTLRWorks 源代码以了解如何使用它,特别是
generate ()
方法此处< /a>:You'll have to use
org.antlr.Tool()
class to get it working.You can check ANTLRWorks source code on github to have an idea how to use it, specifically the
generate()
method here:您是否尝试过使用适当的 String[] 参数调用 org.antlr.Tool.main(String[]) ?
如果这太麻烦了,您可以对
Tool
类进行逆向工程(源代码)来了解它是如何工作的,以及如何完成您需要执行的特定任务。Have you tried calling
org.antlr.Tool.main(String[])
with an appropriate String[] argument?If that's too cumbersome, you could reverse engineer the
Tool
class (source code) to figure out how it works, and how to do the specific tasks you need to do.ANTRL 4
由于我找不到 ANTLR 4 的特定主题,我决定分享一个类似于 的解决方案Bart Kiers 的答案,但专为 ANTLR 4 量身定制。如果您需要在运行时动态生成 ANTLR 词法分析器和解析器,则此解决方案非常有用。但是,请小心:这种方法利用 Java Reflection 并将临时文件写入文件系统,这在某些环境中可能被认为是“脏”且有风险的。
ANTRL 4
Since I couldn’t find a specific topic for ANTLR 4, I decided to share a solution similar to Bart Kiers' answer but tailored for ANTLR 4. This solution is useful if you need to dynamically generate an ANTLR lexer and parser at runtime. However, be cautious: this approach leverages Java Reflection and writes temporary files to the file system, which can be considered "dirty" and risky in certain environments.