                Listing Four


%{
/* yacc grammar for 4-function calculator */
/* Similar to examples provided with MKS lex and yacc */

#define YYSTYPE long
#include <stdio.h>
#include <stdlib.h>

%}

%token INTEGER QUIT
%left '+' '-'
%left '*' '/'

%%

program:
    program expression '\n'
    {
        printf("%d\n", $2);
    }
|   program '\n'            { /* no action */ }
|   program error '\n'      {   yyerrok;    }
|   program QUIT '\n'       {   YYACCEPT;   }
|   /* NULL */
    {
        printf("Simple 4-function calculator\n");
    }
;

expression:
    INTEGER
|   expression '+' expression   {   $$ = $1 + $3;   }
|   expression '-' expression   {   $$ = $1 - $3;   }
|   expression '*' expression   {   $$ = $1 * $3;   }
|   expression '/' expression
    {
        if ($3 == 0 ) { /* can't divide by zero */
            yyerror( "error -- division by zero" );
            YYERROR;
        } else
            $$ = $1 / $3;
    }
|   '(' expression ')'      { $$ = $2; }
;

%%

int main()
{
    return yyparse();
}
