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