/* Code of Figure 4.13, pages 111-112 from Kenneth C. Louden, Programming Languages Principles and Practice 2nd Edition Copyright (C) Brooks-Cole/ITP, 2003 */ %{ #include %} %% command : expr '\n' { printf("The result is: %d\n",$1); } ; expr : expr '+' term { $$ = $1 + $3; } | term { $$ = $1; } ; term : term '*' factor { $$ = $1 * $3; } | factor { $$ = $1; } ; factor : number { $$ = $1; } | '(' expr ')' { $$ = $2; } ; number : number digit { $$ = 10 * $1 + $2; } | digit { $$ = $1; } ; digit : '0' { $$ = 0; } | '1' { $$ = 1; } | '2' { $$ = 2; } | '3' { $$ = 3; } | '4' { $$ = 4; } | '5' { $$ = 5; } | '6' { $$ = 6; } | '7' { $$ = 7; } | '8' { $$ = 8; } | '9' { $$ = 9; } ; %% main() { yyparse(); return 0; } int yylex(void) { static int done = 0; /* flag to end parse */ int c; if (done) return 0; /* stop parse */ c = getchar(); if (c == '\n') done = 1; /* next call will end parse */ return c; } int yyerror(char *s) /* allows for printing error message */ { printf("%s\n",s); }