ANTLR,C 风格的宏定义
在 ANTLR 中实现宏定义最简单(或最好)的方法是什么? 我想要的是一种类似于 C/C++ 语言中存在的机制:
#define FUNCTION(a, b) a+b
#define PI 3.1415
我应该如何以及何时执行替换?
What is the easiest (or the best) way to implement macro definitions in ANTLR?
What I want is a mechanism similar to the one that is present in C/C++ language:
#define FUNCTION(a, b) a+b
#define PI 3.1415
How and when should I perform replacement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您正在执行 C 风格的预处理器,那么您将需要执行单独的第一遍预处理(这就是该术语的含义 - 标准 lex/parse 遍之前的处理遍)。
具体如何进行传递取决于您 - 您可以将输入文本传递给 antlr 中的一种语法,获取结果并将其传递给另一种语法,等等。
或者您可以创建单独的程序,这些程序能够接受在
stdin
上输入并输出到stdout
,或者在管道之间传递文本等。一旦解决了这个问题,查找关键字就很简单了。根据
#define
表检查您看到的每个标记,如果匹配,请将其替换为您拥有的定义。您还必须能够解析函数参数,但这不会增加太多的工作量。If you are doing a pre-processor in the style of C, then you will want to do a separate first pass for pre-processing (which is what this term means - a processing pass before your standard lex/parse pass).
Exactly how you want to do the pass is up to you - you can pass your input text to one grammar in antlr, take the result and hand that off to another grammar, etc.
Or you can create separate programs, which are able to take input on
stdin
and output tostdout
, or pass text between pipes, etc.Once you have that worked out, its a simple matter of looking for your keywords. Check every token that you see against your table of
#define
s, and if it matches, replace it with the definition that you have. You will also have to be able to parse function parameters, but that shouldn't add too much effort.