-
Notifications
You must be signed in to change notification settings - Fork 5
/
eval.c
152 lines (127 loc) · 3.39 KB
/
eval.c
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "eval.h"
#include "parse.h"
#include "subst.h"
#define EVAL_STACK 1024
static inline bool eval_is_value(const struct term *);
static inline bool
eval_is_value(const struct term * pterm)
{
return pterm->type == Tlam || pterm->type == Tvar;
}
void
eval_cbn(struct term ** ppterm)
{
struct term ** stack[EVAL_STACK] = { ppterm };
int stackp = 0;
while (stackp >= 0) {
struct term * pterm = *stack[stackp];
switch (pterm->type) {
case Tlam: {
stackp--;
continue;
}
case Tvar: {
return;
}
case Tapp: {
if (pterm->data.app.left->type == Tlam) {
struct term * lam = pterm->data.app.left;
subst_substitute(lam->data.lam.body, lam->data.lam.var,
pterm->data.app.right);
*stack[stackp] = lam->data.lam.body;
parse_free_term(pterm->data.app.right);
free(pterm);
free(lam);
continue;
}
if (++stackp >= EVAL_STACK) {
puts("Stack overflow.");
return;
}
stack[stackp] = &pterm->data.app.left;
continue;
}
default:
abort();
}
}
}
void
eval_cbv(struct term ** ppterm)
{
struct term ** stack[EVAL_STACK] = { ppterm };
int stackp = 0;
while (stackp >= 0) {
struct term * pterm = *stack[stackp];
switch (pterm->type) {
case Tvar:
case Tlam: {
stackp--;
continue;
}
case Tapp: {
if (eval_is_value(pterm->data.app.right)) {
struct term * lam = pterm->data.app.left;
if (lam->type != Tlam) {
if (lam->type == Tvar)
return;
if (++stackp >= EVAL_STACK) {
puts("Stack overflow.");
return;
}
stack[stackp] = &pterm->data.app.left;
continue;
}
subst_substitute(lam->data.lam.body, lam->data.lam.var,
pterm->data.app.right);
*stack[stackp] = lam->data.lam.body;
parse_free_term(pterm->data.app.right);
free(pterm);
free(lam);
continue;
}
if (++stackp >= EVAL_STACK) {
puts("Stack overflow.");
return;
}
stack[stackp] = &pterm->data.app.right;
continue;
}
default:
abort();
}
}
}
void
eval_deep(struct term ** ppterm)
{
while (1) {
struct term * pterm = *ppterm;
switch(pterm->type) {
case Tvar: {
return;
}
case Tlam: {
eval_deep(&pterm->data.lam.body);
return;
}
case Tapp: {
struct term * left;
eval_deep(&pterm->data.app.left);
left = pterm->data.app.left;
eval_deep(&pterm->data.app.right);
if (left->type == Tlam) {
eval_cbn(ppterm);
continue;
}
return;
}
default:
abort();
}
}
}