I have a following production in a bison
spec:
op : '+' { printf("%d %d %c
", $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
", $1, '+', '+'); }
| '-' { printf("%d %d %c
", $1, '-', '-'); }
| '*' { printf("%d %d %c
", $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 == '
') return 0;
return (c);
}
int yyerror(char * s) {
fprintf(stderr, "%s
", s);
return 0;
} /* allows for printing of an error message */
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…