CS152
Chris Pollett
Sep 22, 2021
Yacc refers to parts of a rule using variables which begin with a dollar sign:
expression : expression '+' expression {$$ = $1 + $3;} | expression '-' expression {$$ = $1 - $3;} | NUMBER {$$ =$1;} ;
$$ refers to the left hand side of the rule value. $n refers to the nth item on the right hand side.
To set up YYSTYPE in your grammar (will appear in y.tab.h file after yacc'ing):
%{ //stuff %} %union { double dval; // in this case we have two possibilities int ival; // could have more. In real world possibilities // would include a struct for a syntax tree. } %token <ival> INTEGER %token <dval> DOUBLE %type <dval> expression /*notice can say type of nonterminal */
[0-9]+ {yylval.ival = atoi(yytext); return INTEGER;}
integer_expr : INTEGER {$$ = (double)$1;} //$1 would have been an int
int yyerror( char *s) { fprintf(stderr, "You caused the error: %s , bozo.\n", s); return 1; }