Contents    Page-10    Prev    Next    Page+10    Index   

Example


%{  /* Aho, Lam, Sethi, Ullman, Compilers: Fig. 4.59 */
#include <ctype.h>
#include <stdio.h>
#define YYSTYPE double   /* double type for yacc stack */
%}
%token NUMBER
%left '+' '-' 
%left '*' '/' 
%right UMINUS
%%
lines:  lines expr '\n'     { printf("%f\n",$2); }
     |  lines '\n'
     |  /* epsilon */
     |  error '\n'          {yyerror("reenter last line:");
                             yyerrok; }
     ;
expr:   expr '+' expr       { $$ = $1 + $3; }
    |   expr '-' expr       { $$ = $1 - $3; }
    |   expr '*' expr       { $$ = $1 * $3; }
    |   expr '/' expr       { $$ = $1 / $3; }
    |   '(' expr ')'        { $$ = $2; }
    |   '-' expr %prec UMINUS  { $$ = - $2; }
    |   NUMBER
    ;
%%
yylex() {
  int c;
  while ( (c = getchar()) == ' ');
  if ( (c == '.') || (isdigit(c)) ) {
     ungetc(c, stdin);
     scanf("%lf", &yylval);
     return NUMBER;
     }
  return c;  }

yyerror(s)
  char * s;
  { fputs(s,stderr), putc('\n',stderr);  }

main()          /* Call repeatedly to test */
  { int res;
    while (1) { res = yyparse(); } }