Interactive Bootstraps“Going FORTH” →When the stacks are odd, make them even

ec89e7c27b553f0915fa3069537366f15108e55e
🐶
Make it possible to define functions and call them
By creating the return stack, we can call functions, and return to the
point after we called them.
TODO: We could have used C recursion, why didn't we?

⟨forth.c⟩≡

@@ -7,16+7,28@@typedef void instruction(void **pc);
7 7
 
8 8
 int stack[100];
9 9
 unsigned stack_p;
10
+void **rstack[100];
11
+unsigned ret_p;
10 12
 
11 13
 void push(int value) { stack[stack_p++] = value; }
12 14
 int pop(void) { return stack[--stack_p]; }
15
+void rpush(void **value) { rstack[ret_p++] = value; }
16
+void **rpop(void) { return rstack[--ret_p]; }
13 17
 
14 18
 instruction lit;
19
+instruction call;
20
+instruction return_;
15 21
 instruction stop;
16 22
 
17
-instruction *prog[] = {
23
+instruction *method[] = {
18 24
 	&lit,
19 25
 	(instruction *)3,
26
+	&return_,
27
+};
28
+
29
+instruction *prog[] = {
30
+	&call,
31
+	(instruction *)method,
20 32
 	&stop,
21 33
 };
22 34
 
@@ -30,6+42,13@@void lit(void **pc) {
30 42
 	next(pc);
31 43
 }
32 44
 
45
+void call(void **pc) {
46
+	rpush(pc + 1);
47
+	next(*(int *)pc);
48
+}
49
+
50
+void return_(void **pc) { next(rpop()); }
51
+
33 52
 void stop(void **pc) {}
34 53
 
35 54
 int main(int argc, char *argv[]) {