/* File: ex.y */ %{ int vbltable[26]; %} %token NAME %token NUMBER %token EQ %token PLUS MINUS TIMES DIV %left MINUS PLUS %left TIMES DIV %nonassoc UMINUS %% statement_list : statement | statement statement_list statement : NAME EQ expression ';' {vbltable[$1] = $3; } expression : expression PLUS expression {$$ = $1 + $3;} | expression MINUS expression {$$ = $1 - $3;} | expression TIMES expression {$$ = $1 * $3;} | expression DIV expression {$$ = $1 / $3;} | MINUS expression %prec UMINUS {$$ = - $2;} | '(' expression ')' { $$ = $2; } | NUMBER | NAME { $$ = vbltable[$1]; } %% main() { int i; for (i = 0; i < 26; i++) vbltable[i] = 0; yyparse(); for (i = 0; i < 26; i++) if (vbltable[i] != 0) printf("Table: %d :%d\n", i, vbltable[i]); }
Corresponding Lex file
/* File: ex.l */ %{ #include "y.tab.h" extern int yylval; %} digit [0-9] letter [a-z] %% "+" {return PLUS;} "=" {return EQ;} "-" {return MINUS;} "*" {return TIMES;} "/" {return DIV;} {digit}+ {yylval = atoi(yytext); return NUMBER; } {letter} {yylval = yytext[0] - 'a'; return NAME;} [ \t]+ ; \n ; . {return yytext[0];} %%