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