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