为什么$ 1的yacc/野牛的价值为0 [英] why does $1 in yacc/bison has a value of 0

查看:108
本文介绍了为什么$ 1的yacc/野牛的价值为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在bison规格中具有以下产品:

I have a following production in a bison spec:

op : '+' { printf("%d %d %c\n", $1, '+', '+'); }

输入+时,将得到以下输出:

When I input a + I get the following output:

0 43 +

有人可以解释为什么$1的值为0,不是43吗?我想念什么?

Can someone explain why $1 has a value of 0, shouldn't it be 43? What am I missing?

编辑

没有弹性文件,但我可以提供bison语法:

There is no flex file, but I can provide a bison grammar:

%{
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int yylex();
int yyerror();

%}

%token NUMBER

%%

lexp : NUMBER 
     | '(' op lexp-seq ')'
     ;
op : '+' { printf("%d %d %c\n", $1, '+', '+'); }
   | '-' { printf("%d %d %c\n", $1, '-', '-'); }
   | '*' { printf("%d %d %c\n", $1, '*', '*'); }
   ;

lexp-seq : lexp-seq lexp
         | lexp
         ;

%%

int main(int argc, char** argv) {
  if (2 == argc && (0 == strcmp("-g", argv[1])))
    yydebug = 1;

  return yyparse();
}

int yylex() {
  int c;

  /* eliminate blanks*/
  while((c = getchar()) == ' ');

  if (isdigit(c)) {
    ungetc(c, stdin);
    scanf("%d", &yylval);
    return (NUMBER);
  }

  /* makes the parse stop */
  if (c == '\n') return 0;

  return (c);
}

int yyerror(char * s) {
  fprintf(stderr, "%s\n", s);
  return 0;
} /* allows for printing of an error message */

推荐答案

$1是右侧第一个符号的语义值,在本例中为'+'.由于该终端是终端,因此其语义值将等于扫描程序向解析器返回'+'令牌时yylval的值.

$1 is the semantic value of the first symbol on the right-hand side, which in this case is '+'. Since that is a terminal, its semantic value will be whatever the value of yylval was when the scanner returned a '+' token to the parser.

由于扫描仪在返回'+'的情况下未设置yylval(这是完全正常的),因此在该产品中使用$1的定义不明确.通常,语法不会引用像'+'这样的标记的语义值,这些标记纯粹是语法上的,没有语义值.

Since your scanner does not set yylval in the case that it returns '+' (which is totally normal), the use of $1 in that production is not well defined. Normally, a grammar doesn't reference the semantic values of tokens like '+', which are purely syntactic and don't have semantic values.

但是,由于yylval是静态变量,因此它将被初始化为0,因此它将继续具有该值,直到将其设置为止(例如,在扫描NUMBER时).

However, since yylval is a static variable, it will have been initialized to 0, so it will continue to have that value until it is set (for example, while scanning a NUMBER).

这篇关于为什么$ 1的yacc/野牛的价值为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆