Skip to content

Instantly share code, notes, and snippets.

@anissen
Last active September 23, 2016 08:21
Show Gist options
  • Save anissen/d880e27d054c8a2c1c0bd5ffc49a0919 to your computer and use it in GitHub Desktop.
Save anissen/d880e27d054c8a2c1c0bd5ffc49a0919 to your computer and use it in GitHub Desktop.
Minimal test of a stack machine
Operation: PUSH(40)
· Memory: [] => [40]
Operation: PUSH(2)
· Memory: [40] => [2,40]
Operation: PUSH(3)
· Memory: [2,40] => [3,2,40]
Operation: MULT
· Memory: [3,2,40] => [6,40]
Operation: ADD
· Memory: [6,40] => [46]
Operation: PUSH(5)
· Memory: [46] => [5,46]
Operation: ADD
· Memory: [5,46] => [51]
Operation: PRINT
PRINT: 51
· Memory: [51] => []
// Minimal test of a stack machine (https://en.wikipedia.org/wiki/Stack_machine)
enum Bytecode {
PUSH(v :Int);
ADD;
MULT;
PRINT;
}
class StackMachine {
static function main() {
var input :String = "
push 40
push 2
push 3
multiply
add
push 5
add
print
";
var stack = [
for (line in StringTools.trim(input).split('\n')) {
var codes = StringTools.trim(line).toLowerCase().split(' ');
switch (codes) {
case ['push', v]: PUSH(Std.parseInt(v));
case ['multiply']: MULT;
case ['add']: ADD;
case ['print']: PRINT;
case _: throw 'Unknown: $codes';
}
}
];
var memory :Array<Int> = [];
while (stack.length > 0) {
var op = stack.shift();
var memory_before = memory.copy();
trace('Operation: $op');
switch (op) {
case PUSH(v): memory.push(v);
case ADD: memory.push(memory.pop() + memory.pop());
case MULT: memory.push(memory.pop() * memory.pop());
case PRINT: trace('PRINT: ${memory.pop()}');
}
trace('· Memory: ${memory_before.reverse()} => ${memory.copy().reverse()}');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment