-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.y
More file actions
76 lines (60 loc) · 1.35 KB
/
parser.y
File metadata and controls
76 lines (60 loc) · 1.35 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
%{
#include <math.h>
#include <stdio.h>
extern int yylex(void);
int yyerror(char *msg);
void print(long int i) {
if (i >= 32 && i <= 126) {
printf("%ld\t0x%lX\t0b%lb\t'%c'\n", i, i, i, (char)i);
} else {
printf("%ld\t0x%lX\t0b%lb\n", i, i, i);
}
}
long int prev = 0;
#define YYDEBUG 1
%}
%union {
long int i;
int token;
}
%token <i> NUM;
%token NEWLINE;
%token PLUS MINUS LEFT_SHIFT RIGHT_SHIFT MULT DIVIDE;
%token POWER;
%token LPAREN RPAREN;
%token DOLLAR;
%type <i> expr;
%type <i> primary;
%left LEFT_SHIFT RIGHT_SHIFT;
%left PLUS MINUS;
%left MULT DIVIDE;
%left POWER;
%start program
%%
program : stmts {}
| %empty {}
;
stmts : stmts expr NEWLINE { prev = $2; print(prev); }
| expr NEWLINE { prev = $1; print(prev); }
expr :
expr PLUS expr { $$ = $1 + $3; }
| expr MINUS expr { $$ = $1 - $3; }
| expr MULT expr { $$ = $1 * $3; }
| expr DIVIDE expr { /* TODO: error handling */ $$ = $1 / $3; }
| expr LEFT_SHIFT expr { $$ = $1 << $3; }
| expr RIGHT_SHIFT expr { $$ = $1 >> $3; }
| expr POWER expr { $$ = pow($1, $3); }
| primary { $$ = $1; }
;
primary : NUM { $$ = $1; }
| DOLLAR { $$ = prev; }
| LPAREN expr RPAREN { $$ = $2; }
;
%%
int yyerror(char *msg) {
fprintf(stderr, "yyerror: %s\n\n%c\n", msg, yychar);
return 0;
}
int main() {
yyparse();
}