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