1235723Sbapt%{ 2235723Sbapt# include <stdio.h> 3235723Sbapt# include <ctype.h> 4235723Sbapt 5235723Sbaptint regs[26]; 6235723Sbaptint base; 7235723Sbapt 8235723Sbaptextern int yylex(void); 9235723Sbaptstatic void yyerror(const char *s); 10235723Sbapt 11235723Sbapt%} 12235723Sbapt 13235723Sbapt%start list 14235723Sbapt 15235723Sbapt%token DIGIT LETTER 16235723Sbapt 17235723Sbapt%left '|' 18235723Sbapt%left '&' 19235723Sbapt%left '+' '-' 20235723Sbapt%left '*' '/' '%' 21235723Sbapt%left UMINUS /* supplies precedence for unary minus */ 22235723Sbapt 23235723Sbapt%% /* beginning of rules section */ 24235723Sbapt 25235723Sbaptlist : /* empty */ 26235723Sbapt | list stat '\n' 27235723Sbapt | list error '\n' 28235723Sbapt { yyerrok ; } 29235723Sbapt ; 30235723Sbapt 31235723Sbaptstat : expr 32235723Sbapt { printf("%d\n",$1);} 33235723Sbapt | LETTER '=' expr 34235723Sbapt { regs[$1] = $3; } 35235723Sbapt ; 36235723Sbapt 37235723Sbaptexpr : '(' expr ')' 38235723Sbapt { $$ = $2; } 39235723Sbapt | expr '+' expr 40235723Sbapt { $$ = $1 + $3; } 41235723Sbapt | expr '-' expr 42235723Sbapt { $$ = $1 - $3; } 43235723Sbapt | expr '*' expr 44235723Sbapt { $$ = $1 * $3; } 45235723Sbapt | expr '/' expr 46235723Sbapt { $$ = $1 / $3; } 47235723Sbapt | expr '%' expr 48235723Sbapt { $$ = $1 % $3; } 49235723Sbapt | expr '&' expr 50235723Sbapt { $$ = $1 & $3; } 51235723Sbapt | expr '|' expr 52235723Sbapt { $$ = $1 | $3; } 53235723Sbapt | '-' expr %prec UMINUS 54235723Sbapt { $$ = - $2; } 55235723Sbapt | LETTER 56235723Sbapt { $$ = regs[$1]; } 57235723Sbapt | number 58235723Sbapt ; 59235723Sbapt 60235723Sbaptnumber: DIGIT 61235723Sbapt { $$ = $1; base = ($1==0) ? 8 : 10; } 62235723Sbapt | number DIGIT 63235723Sbapt { $$ = base * $1 + $2; } 64235723Sbapt ; 65235723Sbapt 66235723Sbapt%% /* start of programs */ 67235723Sbapt 68235723Sbaptint 69235723Sbaptmain (void) 70235723Sbapt{ 71235723Sbapt while(!feof(stdin)) { 72235723Sbapt yyparse(); 73235723Sbapt } 74235723Sbapt return 0; 75235723Sbapt} 76235723Sbapt 77235723Sbaptstatic void 78235723Sbaptyyerror(const char *s) 79235723Sbapt{ 80235723Sbapt fprintf(stderr, "%s\n", s); 81235723Sbapt} 82235723Sbapt 83235723Sbaptint 84235723Sbaptyylex(void) 85235723Sbapt{ 86235723Sbapt /* lexical analysis routine */ 87235723Sbapt /* returns LETTER for a lower case letter, yylval = 0 through 25 */ 88235723Sbapt /* return DIGIT for a digit, yylval = 0 through 9 */ 89235723Sbapt /* all other characters are returned immediately */ 90235723Sbapt 91235723Sbapt int c; 92235723Sbapt 93235723Sbapt while( (c=getchar()) == ' ' ) { /* skip blanks */ } 94235723Sbapt 95235723Sbapt /* c is now nonblank */ 96235723Sbapt 97235723Sbapt if( islower( c )) { 98235723Sbapt yylval = c - 'a'; 99235723Sbapt return ( LETTER ); 100235723Sbapt } 101235723Sbapt if( isdigit( c )) { 102235723Sbapt yylval = c - '0'; 103235723Sbapt return ( DIGIT ); 104235723Sbapt } 105235723Sbapt return( c ); 106235723Sbapt} 107