1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| /* Reverse polish notation calculator. */
%{
#include <stdio.h>
#include <ctype.h>
#define YYSTYPE double
#include <math.h>
int yylex (void);
void yyerror (char const *);
%}
%token NUM
%% /* Grammar rules and actions follow. */
input: /* empty */
| input line
;
line: '\n' { printf ("empty line\n"); }
| exp '\n' { printf ("result : %d\n", $1); }
;
exp: NUM { $$ = $1; printf ("alone\n"); }
| exp exp '+' { $$ = $1 + $2; printf ("add\n"); }
| exp exp '-' { $$ = $1 - $2; printf ("sob\n"); }
| exp exp '*' { $$ = $1 * $2; printf ("mult\n"); }
| exp exp '/' { $$ = $1 / $2; printf ("div\n"); }
| exp exp '^' { $$ = pow ($1, $2); printf ("pow\n"); }
| exp 'n' { $$ = -$1; printf ("neg\n"); }
;
%%
void
yyerror (char const *s)
{
fprintf (stderr, "%s\n", s);
}
int
main (void)
{
return yyparse ();
} |