why does $1 in yacc/bison has a value of 0

[亡魂溺海] 提交于 2019-12-12 03:06:25

问题


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 +

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

EDIT

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:


$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.

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.

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).



来源:https://stackoverflow.com/questions/37578284/why-does-1-in-yacc-bison-has-a-value-of-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!