-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.y
More file actions
50 lines (41 loc) · 1.08 KB
/
Copy pathparser.y
File metadata and controls
50 lines (41 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
%{
#include <stdio.h>
#include <stdlib.h>
void yyerror(const char *s);
int yylex();
%}
%union {
int num; /* Define a type for numerical values */
}
%token <num> NUMBER
%token PLUS MINUS MULTIPLY DIVIDE LPAREN RPAREN
%left PLUS MINUS
%left MULTIPLY DIVIDE
%right UMINUS
%type <num> expr /* Associate expr with int type */
%%
expr:
expr PLUS expr { $$ = $1 + $3; printf("Result: %d\n", $$); }
| expr MINUS expr { $$ = $1 - $3; printf("Result: %d\n", $$); }
| expr MULTIPLY expr { $$ = $1 * $3; printf("Result: %d\n", $$); }
| expr DIVIDE expr {
if ($3 == 0) {
printf("Error: Division by zero\n");
$$ = 0;
} else {
$$ = $1 / $3;
printf("Result: %d\n", $$);
}
}
| LPAREN expr RPAREN { $$ = $2; }
| MINUS expr %prec UMINUS { $$ = -$2; }
| NUMBER { $$ = $1; }
;
%%
void yyerror(const char *s) {
fprintf(stderr, "Error: %s\n", s);
}
int main() {
printf("Enter an expression:\n");
return yyparse(); // Calls the Bison parser
}