0

Is possible recover the value of a token?

I have a rule that is similar to:

unaryOperation:
      NOT       { $$ = new UnaryOP(NOT); }
    | PLUS      { $$ = new UnaryOP(PLUS); }
    | MINUS     { $$ = new UnaryOP(MINUS); }
    ;

NOT, PLUS and MINUS are tokens and I am using the generated definition in my program too. Is possible recover this data and not repeat myself in the same line?

I'm not interested in the semantic value, so it is not correct for my write this:

unaryOperation:
      NOT       { $$ = new UnaryOP($1); }
    | PLUS      { $$ = new UnaryOP($1); }
    | MINUS     { $$ = new UnaryOP($1); }
    ;

Thank you

4

1 回答 1

0

bison不需要知道哪个令牌被识别,因为该信息实际上是堆栈状态的一部分。但是,如果启用了调试,则野牛表包括每个归约右侧的编码版本,这允许内置跟踪功能生成人类可读的跟踪。

从理论上讲,您也可以使用此信息,但它不会是您想要的,因为 bison 将 flex 令牌编号转换为连续序列(以允许更紧凑的解析表)并且不提供任何将它们翻译回来的方法。所以会很乏味。

更好的解决方案是使用您当前忽略的语义值(假设它具有整数变体)。分配语义值的成本是微不足道的,因为野牛确实需要将每个标记的语义值初始化为某种东西。

因此,一个合理的 flex/bison 解决方案可能是:

柔性

%union {
   int intval;
   /* ... other semantic values */
}

%%

 /* All the other rules come first */

 /* Default rule which just passes any character through to bison
  * (see note)
  */
.  { return (yylval.intval = yytext[0]); }

野牛

 /* This declaration is only necessary because these tokens
  * have a semantic value
  */
%token <intval> '-' '+' '!'

%%

unaryOperation
    : '!'     { $$ = new UnaryOP($1); }
    | '+'     { $$ = new UnaryOP($1); }
    | '-'     { $$ = new UnaryOP($1); }
    ;

注意:我删除了标记名称NOT,因为我PLUSMINUS喜欢使用单字符标记来表示自己的风格。这里的不同之处在于 flex 规则设置了语义值(相同的数字)。如果运算符是多字符的,您也可以这样做:

柔性

'!='   { return (yylval.intval = NOTEQUAL); }
于 2014-10-30T00:25:07.653 回答