add alpha renaming
[lambda.git] / lambda.y
1 %{
2 #include "lambda.h"
3 #include "lambda.tab.h"
4 #include "mem.h"
5 #include "print.h"
6
7 struct lambda *result;
8 struct decllist *decls = NULL;
9 extern int yylex();
10
11 int yydebug=1;
12 void yyerror(const char *str)
13 {
14 fprintf(stderr, "parse error: %s\n", str);
15 }
16
17 int yywrap()
18 {
19 return 1;
20 }
21
22 struct lambda *make_lambda()
23 {
24 return malloc(sizeof (struct lambda));
25 }
26
27 struct lambda *make_ident(char *i)
28 {
29 struct lambda *r = make_lambda();
30 r->which = lambda_ident;
31 r->data.identifier.ident = strdup(i);
32 r->data.identifier.revision = 0;
33 return r;
34 }
35
36 struct lambda *make_abstraction(char *i, struct lambda *t)
37 {
38 struct lambda *r = make_lambda();
39 r->which = lambda_abs;
40 r->data.abstraction.ident = strdup(i);
41 r->data.abstraction.expr = t;
42 return r;
43 }
44
45 struct lambda *make_application(struct lambda *t1, struct lambda *t2)
46 {
47 struct lambda *r = make_lambda();
48 r->which = lambda_app;
49 r->data.application.expr1 = t1;
50 r->data.application.expr2 = t2;
51 return r;
52 }
53
54 void decls_prepend(char *ident, struct lambda *value)
55 {
56 struct decllist *head = malloc(sizeof (struct decllist));
57 head->next = decls;
58 head->ident = ident;
59 head->value = value;
60 printf("Declared %s as ", ident);
61 lambda_print(value);
62 decls = head;
63 }
64
65 struct lambda *decls_lookup(char *ident)
66 {
67 struct decllist *c = decls;
68 while(c != NULL){
69 if(strcmp(c->ident, ident) == 0)
70 return copy(c->value);
71 c = c->next;
72 }
73 return make_ident(ident);
74 }
75
76 %}
77
78 %token LAMBDA DOT OBRACE CBRACE IDENT FUNC SEMICOLON ASSIGN
79
80 %%
81
82 lambda
83 : decl lambda
84 | term
85 { result = $$; }
86 decl
87 : FUNC ASSIGN term SEMICOLON
88 { decls_prepend($1->data.identifier.ident, $3); }
89 term
90 : term appterm
91 { $$ = make_application($1, $2); }
92 | appterm
93 { $$ = $1; }
94 appterm
95 : FUNC
96 {
97 $$ = decls_lookup($1->data.identifier.ident);
98 lambda_free($1);
99 }
100 | IDENT
101 {
102 $$ = make_ident($1->data.identifier.ident);
103 lambda_free($1);
104 }
105 | LAMBDA abstraction
106 { $$ = $2; }
107 | OBRACE term CBRACE
108 { $$ = $2; }
109 abstraction
110 : IDENT abstraction
111 {
112 $$ = make_abstraction($1->data.identifier.ident, $2);
113 lambda_free($1);
114 }
115 | DOT term
116 { $$ = $2; }