76bbdd038dfd70a9bf29908173a654bf7ee3faf6
[ccc.git] / parse.y
1 %{
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5
6 #include "ast.h"
7 #define YYSTYPE struct ast *
8
9 #include "y.tab.h"
10
11 int yylex_debug = 1;
12 int yylex(void);
13
14 void yyerror(struct ast **result, const char *str)
15 {
16 ast_free(*result);
17 fprintf(stderr, "error: %s\n", str);
18 }
19
20 int yywrap()
21 {
22 return 1;
23 }
24
25 %}
26
27 %define parse.error verbose
28 %token INTEGER PLUS MINUS TIMES DIVIDE BOPEN BCLOSE SEMICOLON POWER CONS MODULO
29 %token BINOR BINAND INVERSE VAR ASSIGN IDENT COMMA COPEN CCLOSE IF ELSE WHILE
30 %token BOOL CHAR
31
32 %parse-param { struct ast **result }
33
34 %right BINOR
35 %right BINAND
36 %nonassoc EQ NEQ LEQ LE GEQ GE
37 %right CONS
38 %left PLUS MINUS
39 %left TIMES DIVIDE MODULO
40 %right POWER
41
42 %%
43
44 start : decls { *result = ast_list($1); } ;
45
46 decls
47 : { $$ = NULL; }
48 | decls vardecl SEMICOLON { $$ = ast_cons($2, $1); }
49 | decls fundecl { $$ = ast_cons($2, $1); }
50 ;
51
52 vardecl
53 : VAR IDENT ASSIGN expr { $$ = ast_vardecl($2, $4); }
54 ;
55
56 fundecl
57 : IDENT BOPEN args BCLOSE COPEN body CCLOSE
58 { $$ = ast_fundecl($1, ast_list($3), ast_list($6)); }
59 ;
60
61 args
62 : { $$ = NULL; }
63 | nargs
64 ;
65 nargs
66 : nargs COMMA IDENT { $$ = ast_cons($3, $1); }
67 | IDENT { $$ = ast_cons($1, NULL); }
68 ;
69 body
70 : { $$ = NULL; }
71 | body vardecl SEMICOLON { $$ = ast_cons($2, $1); }
72 | body stmt { $$ = ast_cons($2, $1); }
73 ;
74
75 stmt
76 : IF BOPEN expr BCLOSE COPEN body CCLOSE ELSE COPEN body CCLOSE
77 { $$ = ast_if($3, ast_list($6), ast_list($10)); }
78 | WHILE BOPEN expr BCLOSE COPEN body CCLOSE
79 { $$ = ast_while($3, ast_list($6)); }
80 | expr SEMICOLON { $$ = ast_stmt_expr($1); }
81 ;
82
83 expr
84 : expr BINOR expr { $$ = ast_binop($1, binor, $3); }
85 | expr BINAND expr { $$ = ast_binop($1, binand, $3); }
86 | expr EQ expr { $$ = ast_binop($1, eq, $3); }
87 | expr NEQ expr { $$ = ast_binop($1, neq, $3); }
88 | expr LEQ expr { $$ = ast_binop($1, leq, $3); }
89 | expr LE expr { $$ = ast_binop($1, le, $3); }
90 | expr GEQ expr { $$ = ast_binop($1, geq, $3); }
91 | expr GE expr { $$ = ast_binop($1, ge, $3); }
92 | expr CONS expr { $$ = ast_binop($1, cons, $3); }
93 | expr PLUS expr { $$ = ast_binop($1, plus, $3); }
94 | expr MINUS expr { $$ = ast_binop($1, minus, $3); }
95 | expr TIMES expr { $$ = ast_binop($1, times, $3); }
96 | expr DIVIDE expr { $$ = ast_binop($1, divide, $3); }
97 | expr MODULO expr { $$ = ast_binop($1, modulo, $3); }
98 | expr POWER expr { $$ = ast_binop($1, power, $3); }
99 | MINUS expr { $$ = ast_unop(negate, $2); }
100 | INVERSE expr { $$ = ast_unop(inverse, $2); }
101 | BOPEN expr BCLOSE { $$ = $2; }
102 | INTEGER
103 | BOOL
104 | CHAR
105 | IDENT
106 ;