Summary Files Commits Branches @commit @diff @stats
path: root / src / blog / sane-explanation-of-compilers / part-1 / proper / parser.y
blob: 9946346e89e362552999fbf2255848efb6549b81 (plain) (blame)
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
%{
#include <stdio.h>
#include "tree.h"

extern FILE* yyin;

int yylex();
int yyerror(const char *s);
%}

%union {
	int num;
	char chr;
	node *n;
}
%token <num> NUMBER <chr> MATHOP <chr> LBRACE <chr> RBRACE
%type <n> expr

%%

start : expr       { printTree($1, 0); freeNode($1); }
	  | expr start { printTree($1, 0); freeNode($1); }
	  ;

expr : NUMBER                         { $$ = newNode($1 + '0', NULL, NULL); }
	 | LBRACE expr MATHOP expr RBRACE { $$ = newNode($3, $2, $4); }
	 ;

%%

int yyerror(const char *s) {
	printf("Error: %s\n", s);
	return 0;
}

int main(int argc, char* argv[]) {
	FILE* input = fopen(argv[1], "r");
	if (input == NULL) {
		yyerror("reading input file!");
		return 1;
	}

	yyin = input;
	yyparse();
}