看matz的streem项目时对其中bison解析语法的几个地方有些不懂, 上网搜了些资料, 把这些记录下来.
bison是啥就不多说了, 网上一搜一大堆. bison官方文档.
1.首先是这个用法
%union { node* nd; strm_id id;}%type <nd> program compstmt%type <nd> stmt expr condition block cond var primary primary0%type <nd> stmts args opt_args opt_block f_args map map_args bparam%type <nd> opt_else opt_elsif%type <id> identifier解释:
Bison中默认将所有的语义值都定义为int类型,可以通过定义宏YYSTYPE来改变值的类型。如果有多个值类型,则需要通过在Bison声明中使用%union列举出所有的类型,然后为每个符号定义相对的类型,终结符使用%token,非终结符使用%type来定义。
使用 宏YYSTYPE 的例子如下:
union lvalue_t { double num; const char *name; point3d_t pt3d; point2d_t pt2d; shape_t shape; struct { point2d_t p[5]; size_t n; } coord; circuit_layout::boundary bc; size_t nblk;};#define YYSTYPE lvalue_t2.还有是关于操作符优先级
%nonassoc op_LOWEST%left op_amper%left op_bar%left op_or%left op_and%nonassoc op_eq op_neq%left op_lt op_le op_gt op_ge%left op_plus op_minus%left op_mult op_div op_mod%right '!' '~'%token op_HIGHEST解释:
%left ADD //左结合
%right NEG //右结合
%nonassoc OP //无结合,如果出现x op y则是语法错误
位于同一行操作符相同, 定义在后面的符号比定义在前面的符号具有更好的优先级, 如乘除法的优先级比加减法要高.
3.指定起始符号
%start Cap3DFile解释:
默认认为语法规则中出现的第一个非终结符是开始符号,也可以通过%start symbol来明确指定。
4.
%pure-parser%parse-param {parser_state *p}%lex-param {p}%{int yylex(YYSTYPE *lval, parser_state *p);static void yyerror(parser_state *p, const char *s);%}解释:
Bison解析通常不是一个可重入的程序,因为它使用静态分配的变量(yylval yylloc)与yylex进行通信。可以通过 %pure_parser 来指定希望解析器是可重入的。
默认情况下 yyparse() 函数是没有参数的, 可以通过%parse-param {param} 来传递参数, 调用的时候也是 yyparse(param)的形式. %lex-param 是对 yylex() 函数增加参数.
参考: http://blog.163.com/zongyuan1987@126/blog/static/1316231562011120112136225/
http://blog.csdn.net/wz3118103/article/details/27635873