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