Interactive Bootstraps“Going FORTH” →Introduction to stack machines

08db48b7113cb649a567b5c695c681a4d54adf82
kovirobi@gmail.com
First experiment with a stack-machine
Here we set the scene for how a stack machine can work. We simulate a
simple, hard-coded program which just puts zero onto the stack, then
increments it. At the end, we print the stack.
Try experimenting by customising the hard-coded program, and see what
you end up with.
Can you add an instruction to take the top two numbers from the stack,
add them together and put it back on the stack?

⟨forth.c⟩≡

@@ -0,0+1,35@@
1
+#include <stdio.h>
2
+
3
+#define ASIZE(x) (sizeof((x)) / sizeof((x)[0]))
4
+
5
+typedef void instruction(void);
6
+
7
+int stack[100];
8
+unsigned stack_p;
9
+
10
+void push(int value) { stack[stack_p++] = value; }
11
+int pop(void) { return stack[--stack_p]; }
12
+
13
+instruction put_0;
14
+instruction increment;
15
+
16
+instruction *prog[] = {
17
+	&put_0,
18
+	&increment,
19
+};
20
+int pc = 0;
21
+
22
+void put_0(void) { push(0); }
23
+
24
+void increment(void) { push(pop() + 1); }
25
+
26
+int main(int argc, char *argv[]) {
27
+	for (pc = 0; pc < ASIZE(prog); pc++) {
28
+		prog[pc]();
29
+	}
30
+
31
+	// Print stack after exit
32
+	printf("<%u>", stack_p);
33
+	for (int i = 0; i < stack_p; i++)
34
+		printf(" %d", stack[i]);
35
+}