bork
[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 = strdup(i);
32 return r;
33 }
34
35 struct lambda *make_abstraction(char *i, struct lambda *t)
36 {
37 struct lambda *r = make_lambda();
38 r->which = lambda_abs;
39 r->data.abstraction.ident = strdup(i);
40 r->data.abstraction.expr = t;
41 return r;
42 }
43
44 struct lambda *make_application(struct lambda *t1, struct lambda *t2)
45 {
46 struct lambda *r = make_lambda();
47 r->which = lambda_app;
48 r->data.application.expr1 = t1;
49 r->data.application.expr2 = t2;
50 return r;
51 }
52
53 void decls_prepend(char *ident, struct lambda *value)
54 {
55 struct decllist *head = malloc(sizeof (struct decllist));
56 head->next = decls;
57 head->ident = ident;
58 head->value = value;
59 printf("Declared %s as ", ident);
60 lambda_print(value);
61 decls = head;
62 }
63
64 struct lambda *decls_lookup(char *ident)
65 {
66 struct decllist *c = decls;
67 while(c != NULL){
68 if(strcmp(c->ident, ident) == 0)
69 return copy(c->value);
70 c = c->next;
71 }
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 abstraction
105 { $$ = $2; }
106 | OBRACE term CBRACE
107 { $$ = $2; }
108 abstraction
109 : IDENT abstraction
110 {
111 $$ = make_abstraction($1->data.identifier, $2);
112 lambda_free($1);
113 }
114 | DOT term
115 { $$ = $2; }