如何编写 Lex 和 Yacc 来解析部分文件
让我用一个例子来讲述。 假设文本文件的内容如下:
function fun1 {
整数a、b、c;
函数 fun2 {
int d, e;
字符fg;
函数 fun3 {
int h, i;
}
}
在上面的文本文件中,左大括号的数量与右大括号的数量不匹配。该文件作为一个整体不遵循语法。然而,部分函数 fun2 和 fun3 遵循语法。通常,文本文件非常大。
如果用户想要解析整个文件,即函数 fun1,那么程序应该输出错误,因为大括号不匹配。但是,如果用户只想解析部分文件,即函数 fun2/fun3,则程序不应抛出错误,因为大括号匹配。
我现在有一个问题 1.有没有办法让Lex和Yacc只加载一个 部分文件?如果是的话那么需要如何完成。
Let me tell with an example.
Suppose the contents of a text file are as follows:
function fun1 {
int a, b, c;
function fun2 {
int d, e;
char f g;
function fun3 {
int h, i;
}
}
In the above text file, the number of opening braces are not matching the number of closing braces. The file as a whole doesn't follow the syntax. However the partial functions fun2 and fun3 follows the syntax. Typically the text file is very large.
If the user wants to parse the entire file ie function fun1, then the program should output an error as the braces are not matching. However, if the user wants to parse only the partial file ie function fun2/fun3, then the program shouldn't throw out an error as the braces are matching.
I have a question now
1. Is there a way to let the Lex and Yacc load only a
partial file ? If so then how it needs to be done.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用的是 bison/flex 还是普通的 yacc/lex ?
玩yacc已经很久了。
这两对工具的技术答案是不同的。
使用flex,你必须处理缓冲机制 。
最终的代码会更干净。
使用 lex,您必须手动完成所有工作。
至少你必须重新定义输入和输出宏。
您还可以尝试使用 yyin 和
fseek
。在解析器方面,您必须处理错误管理(
yyerrok
宏)和error
标记http://dinosaur.compilertools.net/bison/bison_9.html#SEC81
Are you using bison/flex or plain old yacc/lex ?
It's a long time I played with yacc.
The technical answer is different for both pair of tool.
With flex you'll have to deal with the buffer mechanism.
The final code will be cleaner.
With lex you'll have to do all by hand.
At least you have to redefine input and unput macro.
You can also try to play with yyin and
fseek
.On the parser side you'll have to deal with error management (
yyerrok
macro) anderror
tokenhttp://dinosaur.compilertools.net/bison/bison_9.html#SEC81