Contents    Page-10    Prev    Next    Page+10    Index   

Example: Desk Calculator


%{ /* simcalc.y  -- Simple Desk Calculator    */
   /* Aho, Sethi & Ullman, Compilers, Fig. 4.56 */
#include <ctype.h>
#include <stdio.h>
%}
%token DIGIT
%%
line  :  expr '\n'         { printf("%d\n", $1); }
      ;
expr  :  expr '+' term     { $$ = $1 + $3; }
      |  term
      ;
term  :  term '*' factor   { $$ = $1 * $3; }
      |  factor
      ;
factor:  '(' expr ')'      { $$ = $2; }
      |  DIGIT
      ;
%%
yylex() {
    int c;
    c = getchar();
    if (isdigit(c)) {
       yylval = c - '0' ;
       return DIGIT;
    }
    return c;
  }