source: liacs/coco/assignment1/calc.y@ 330

Last change on this file since 330 was 2, checked in by Rick van der Zwet, 15 years ago

Initial import of data of old repository ('data') worth keeping (e.g. tracking
means of URL access statistics)

File size: 2.3 KB
Line 
1/* C declarations */
2/* vi: set et ts=4: */
3
4%{
5
6#include <stdio.h>
7#include <math.h>
8
9int base = 10;
10
11/* Prototypes */
12static void yyerror(const char *);
13static int fac(int x);
14
15/* import from spascal.l */
16extern int lineno;
17extern int yylex(void);
18
19%}
20
21
22/* Start symbol */
23%start line
24
25/* Tokens */
26%token DIGIT
27%token PI
28%token OPEN_PAREN CLOSE_PAREN
29%token '|'
30
31/* Tokens with precedence assigned */
32/* The sooner the operator is defined, the lower its precedence */
33%left '-' '+'
34%left '*' '/' '%'
35%left UMINUS
36%left '!'
37%right EXPONENT
38
39
40
41/* Rules */
42%%
43
44line:
45 |
46
47 line stmt '\n'
48
49 |
50
51 line error '\n'
52 {
53 yyerrok;
54 }
55 ;
56
57
58stmt:
59 expr
60 {
61 printf("%d\n",$1);
62 }
63 ;
64
65
66expr:
67 OPEN_PAREN expr CLOSE_PAREN
68 {
69 $$ = $2;
70 }
71
72 |
73
74 '|' expr '|'
75 {
76 $$ = (int)fabs((double)$2);
77 }
78
79 |
80
81 expr '*' expr
82 {
83 $$ = $1 * $3;
84 }
85
86 |
87
88 expr '/' expr
89 {
90 $$ = $1 / $3;
91 }
92
93 |
94
95 expr '%' expr
96 {
97 $$ = $1 % $3;
98 }
99
100 |
101
102 expr '-' expr
103 {
104 $$ = $1 - $3;
105 }
106
107 |
108
109 expr '+' expr
110 {
111 $$ = $1 + $3;
112 }
113
114 |
115
116 expr '!'
117 {
118 if ($1 < 0) {
119 fprintf(stderr, "Negative values for faculty are undefined.\n");
120 YYERROR;
121 }
122 $$ = fac($1);
123 }
124
125 |
126
127 expr EXPONENT expr
128 {
129 $$ = (int)pow((double)$1, (double)$3);
130 }
131
132 |
133
134 '-' expr %prec UMINUS
135 {
136 $$ = -$2;
137 }
138
139 |
140
141 number
142 ;
143
144
145number:
146 PI
147 {
148 $$ = 3;
149 }
150
151 |
152
153 DIGIT
154 {
155 $$ = $1;
156 }
157
158 |
159
160 number DIGIT
161 {
162 $$ = base * $1 + $2;
163 }
164 ;
165%%
166/* End of rules, more C code will follow now */
167
168
169int main()
170{
171 return yyparse();
172}
173
174static void yyerror(const char *s)
175{
176 fprintf(stderr, "%s\n",s);
177}
178
179int yywrap()
180{
181 return(1);
182}
183
184int fac(int x)
185{
186 return (x > 1) ? x*fac(x-1) : 1;
187}
Note: See TracBrowser for help on using the repository browser.