0

我正在使用 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 的一部分,因此我将条件存储在临时列表中,然后移至正确的子句。这样做的正确方法是什么?

4

1 回答 1

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操作是野牛扩展,在出现语法错误时需要避免内存泄漏。

于 2012-07-06T23:53:13.907 回答