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