yacc / bison识别结果

时间:2012-07-06 17:35:23

标签: bison yacc parser-generator

我正在使用Jflex,byacc,java来解析类似于

的语句
where expr,expr having expr

,语法看起来像

%token WHERE HAVING COMMA
%%

stmt : whereclause havingclause

whereclause : WHERE conditionlist { move tmpList to whereClause};
havingclause : HAVING conditionlist { move tmpList to havingClause};

conditionlist : condition | condition COMMA conditionlist;

condition : expr { tmpList.add($1); 
                  /How do I know this is being executed for whereclause or havingclause /};

expr : ....

如果条件是whereclause或havingclause的一部分,我无法区分,所以我将条件存储在临时列表中,然后转到右边的子句。 这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

最常见的是,您在规则操作中构建数据结构,将指针分配给$$,然后在更高级别的规则中读取它们。类似的东西:

%token WHERE HAVING COMMA
%union {
    class List *listptr;
    class Expr *exprptr;
}
%type<listptr> whereclasue havingclause conditionlist
%type<exprptr> condition expr
%destructor { delete $$; } <listptr>
%destructor { delete $$; } <exprptr>
%%

stmt : whereclause havingclause { do something with $1 and $2... }

whereclause : WHERE conditionlist { $$ = $2; };
havingclause : HAVING conditionlist { $$ = $2 };

conditionlist : condition { $$ = new List($1); }
              | condition COMMA conditionlist { $$ = $2->prepend($1); };

condition : expr { $$ = $1; }

expr : ....

请注意%destructor操作是一个bison扩展,并且在语法错误时需要避免内存泄漏。