Lex:多个文件,不同的规则
我必须解析多个文件,每种情况都有不同的规则。也就是说:我需要一些规则在处理文件时起作用,然后再禁用。
我可以简单地使用全局变量来跟踪程序的状态,并让我的规则在其体内决定是否执行任何有用的操作,如下所示:
%{
static int state;
%}
%%
{something} {
if (state == SOMETHING_STATE) ...
}
{something_else} {
if (state == SOMETHING_ELSE_STATE) ...
}
%%
不过,我猜有更好的方法可以做到这一点。有没有?
I have to parse more than one file, with different rules for each case. That is: I need some rules to work when processing a file, and be disabled afterwards.
I could simple use a global variable to track the state of the program, and have my rules decide inside their body whether to do anything useful or not, like this:
%{
static int state;
%}
%%
{something} {
if (state == SOMETHING_STATE) ...
}
{something_else} {
if (state == SOMETHING_ELSE_STATE) ...
}
%%
I'm guessing there's a better way to do this, though. Is there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要启动状态 - 基本上 lex 有一个内置的
state
变量,您可以将规则注释为仅在某些状态下触发您可以在任何 lex 或 flex 书籍中或在 在线 Flex 文档
You want start states -- basically lex has a builtin
state
variable and you can annotate rules as only firing in certain statesYou can find documentation on this in any lex or flex book, or in the online flex documentation
假设您使用的是 Flex 之类的东西而不是原始的 lex,您可以使用
开始状态
。当您解析的内容会改变解析方式时,您会输入一个状态来执行该解析,并使用该状态标记适当的规则。当你解析任何标记该状态结束的内容时,你会执行另一个操作:Assuming you're using something like Flex rather than the original lex, you can use
start states
. When you parse something that changes how you do the parsing, you enter a state to do that parsing, and you tag the appropriate rules with that state. When you parse whatever marks the end of that state, you go do another:使用 Flex 和 Yacc,您还可以构建不同的单独解析器并调整 makefile,以便将它们编译成单个可执行文件。我相信您只使用 Flex,但这也应该是可能的。
我现在无法准确地说明如何做到这一点,但我实际上已经做到了,很久以前,所以如果你环顾四周,你会找到一种方法。基本上,您必须使用不同的前缀(-P)来编译每个解析器,这将生成不同名称的解析函数和不同名称的全局变量供解析器使用。
Using Flex and Yacc you can also build diferent individual parsers and tweak the makefile in order to compile them into a single executable. I believe you're only using Flex, but this should be possible too.
I can't precise exactly how to do it now, but i've already actually done it,quite some time ago, so if you look around you'll find a way. Basiccly you'll have to compile each parser with a diferent prefix (-P), and that will generate diferently named parse functions and diferently named global variables for the parsers to use.