calc.y revision 1.1.1.3
1%{
2# include <stdio.h>
3# include <ctype.h>
4
5int regs[26];
6int base;
7
8%}
9
10%start list
11
12%token DIGIT LETTER
13
14%left '|'
15%left '&'
16%left '+' '-'
17%left '*' '/' '%'
18%left UMINUS   /* supplies precedence for unary minus */
19
20%% /* beginning of rules section */
21
22list  :  /* empty */
23      |  list stat '\n'
24      |  list error '\n'
25            {  yyerrok ; }
26      ;
27
28stat  :  expr
29            {  printf("%d\n",$1);}
30      |  LETTER '=' expr
31            {  regs[$1] = $3; }
32      ;
33
34expr  :  '(' expr ')'
35            {  $$ = $2; }
36      |  expr '+' expr
37            {  $$ = $1 + $3; }
38      |  expr '-' expr
39            {  $$ = $1 - $3; }
40      |  expr '*' expr
41            {  $$ = $1 * $3; }
42      |  expr '/' expr
43            {  $$ = $1 / $3; }
44      |  expr '%' expr
45            {  $$ = $1 % $3; }
46      |  expr '&' expr
47            {  $$ = $1 & $3; }
48      |  expr '|' expr
49            {  $$ = $1 | $3; }
50      |  '-' expr %prec UMINUS
51            {  $$ = - $2; }
52      |  LETTER
53            {  $$ = regs[$1]; }
54      |  number
55      ;
56
57number:  DIGIT
58         {  $$ = $1; base = ($1==0) ? 8 : 10; }
59      |  number DIGIT
60         {  $$ = base * $1 + $2; }
61      ;
62
63%% /* start of programs */
64
65#ifdef YYBYACC
66extern int YYLEX_DECL();
67static void YYERROR_DECL();
68#endif
69
70int
71main (void)
72{
73    while(!feof(stdin)) {
74	yyparse();
75    }
76    return 0;
77}
78
79static void
80yyerror(const char *s)
81{
82    fprintf(stderr, "%s\n", s);
83}
84
85int
86yylex(void)
87{
88	/* lexical analysis routine */
89	/* returns LETTER for a lower case letter, yylval = 0 through 25 */
90	/* return DIGIT for a digit, yylval = 0 through 9 */
91	/* all other characters are returned immediately */
92
93    int c;
94
95    while( (c=getchar()) == ' ' )   { /* skip blanks */ }
96
97    /* c is now nonblank */
98
99    if( islower( c )) {
100	yylval = c - 'a';
101	return ( LETTER );
102    }
103    if( isdigit( c )) {
104	yylval = c - '0';
105	return ( DIGIT );
106    }
107    return( c );
108}
109