Lex&Yacc使用总结

1.flex处理多行注释

在lex中,可以使用yy_push_state(state),yy_pop_state()轻松处理各种语言的注释,以及ifdef....else...endif之类的宏。以下是从网上找的一个处理/**/注释的lex程序

<INITIAL>"<!--"                  {yy_push_state(COMMENT);}
<COMMENT>"-->"               {yy_pop_state();}
<COMMENT>"\n"                 {}
<COMMENT>.                      {}

COMMENT是定义的一个开始状态(start state),yy_push_state()将COMMENT状态压到栈顶,yy_pop_state()则弹出这个状态。


2.yacc文件的调试

`$$' 表示 `yyval' ,`$n' 转换成 `yypvt[n-m]' ,其中m是规约规则右边符号的个数。所以,如果有以下的规约规则,

expr : expr binop expr { ... }

可以在gdb中使用以下的命令查看

print yyval       # print $$
print yypvt[-2] # print $1
print yypvt[-1] # print $2
print yypvt[0]  # print $3

3.多个Lex&Yacc Parser的处理

Most programs that use Bison parse only one language and therefore contain only one Bison parser. But what if you want to parse more than one language with the same program? Then you need to avoid a name conflict between different definitions of yyparse, yylval, and so on.

The easy way to do this is to use the option ‘-p prefix’ (see Invoking Bison). This renames the interface functions and variables of the Bison parser to start with prefix instead of ‘yy’. You can use this to give each parser distinct names that do not conflict.

The precise list of symbols renamed is yyparse, yylex, yyerror, yynerrs, yylval, yylloc, yychar and yydebug. If you use a push parser, yypush_parse, yypull_parse, yypstate,yypstate_new and yypstate_delete will also be renamed. For example, if you use ‘-p c’, the names become cparse, clex, and so on.

All the other variables and macros associated with Bison are not renamed. These others are not global; there is no conflict if the same name is used in different parsers. For example, YYSTYPE is not renamed, but defining this in different ways in different parsers causes no trouble (see Data Types of Semantic Values).

The ‘-p’ option works by adding macro definitions to the beginning of the parser source file, defining yyparse as prefixparse, and so on. This effectively substitutes one name for the other in the entire parser file.

 

受影响的有

yyparse, yylex, yyerror, yynerrs, yylval, yylloc, yychar, yydebug. yypush_parse, yypull_parse, yypstate,yypstate_new , yypstate_delete

其余不受影响

如:yyleng, yyless, yymore, yyterminate, yy_push_state, yy_pop_state, ...

原文:
1.Using Lex to recognize a multiple line comment
http://osdir.com/ml/lex.flex.general/2005-04/msg00014.html

2.how to debug yacc file using gdb
http://compilers.iecc.com/comparch/article/95-01-013

3.Multiple Lex/Yacc Parsers in the Same Program
http://www.gnu.org/software/bison/manual/bison.html#Multiple-Parsers

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值