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