我是靠谱客的博主 传统电灯胆,这篇文章主要介绍bison(yacc)学习笔记,现在分享给大家,希望可以做个参考。

看matz的streem项目时对其中bison解析语法的几个地方有些不懂, 上网搜了些资料, 把这些记录下来.

bison是啥就不多说了, 网上一搜一大堆. bison官方文档.

1.首先是这个用法

复制代码
1
2
3
4
5
6
7
8
9
10
%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 的例子如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
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_t

2.还有是关于操作符优先级

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
%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.指定起始符号

复制代码
1
%start Cap3DFile

解释:

默认认为语法规则中出现的第一个非终结符是开始符号,也可以通过%start symbol来明确指定。

4.

复制代码
1
2
3
4
5
6
7
%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

最后

以上就是传统电灯胆最近收集整理的关于bison(yacc)学习笔记的全部内容,更多相关bison(yacc)学习笔记内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部