Created
March 15, 2013 18:19
-
-
Save halogenandtoast/5171887 to your computer and use it in GitHub Desktop.
A very simple toy vm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| push 5 | |
| ifeq 4 | |
| jump 8 | |
| push -1 | |
| add | |
| jump 2 | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class MochiVM | |
| def initialize source | |
| @iptr = 0 | |
| @stack = [] | |
| @program = parse_program(source) | |
| end | |
| def parse_program source | |
| source.lines.to_a.map { |line| line.split(" ") } | |
| end | |
| def run | |
| while @iptr < @program.length | |
| instr, *values = @program[@iptr] | |
| send(instr.to_sym, *values) | |
| end | |
| end | |
| def step | |
| @iptr += 1 | |
| end | |
| def push num | |
| @stack.push(num.to_i) | |
| step | |
| end | |
| def pop | |
| result = @stack.pop | |
| step | |
| result | |
| end | |
| def add | |
| @stack.push(@stack.pop + @stack.pop) | |
| step | |
| end | |
| def mult | |
| @stack.push(@stack.pop * @stack.pop) | |
| step | |
| end | |
| def sub | |
| top = @stack.pop | |
| @stack.push(@stack.pop - top) | |
| step | |
| end | |
| def div | |
| top = @stack.pop | |
| @stack.push(@stack.pop / top) | |
| step | |
| end | |
| def ifeq address | |
| if @stack.last != 0 | |
| @iptr = address.to_i - 1 | |
| else | |
| step | |
| end | |
| end | |
| def jump address | |
| @iptr = address.to_i - 1 | |
| end | |
| def print | |
| puts @stack.last | |
| step | |
| end | |
| def dup | |
| @stack.push(@stack.last) | |
| step | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment