Skip to content

Instantly share code, notes, and snippets.

@halogenandtoast
Created March 15, 2013 18:19
Show Gist options
  • Select an option

  • Save halogenandtoast/5171887 to your computer and use it in GitHub Desktop.

Select an option

Save halogenandtoast/5171887 to your computer and use it in GitHub Desktop.
A very simple toy vm
push 5
ifeq 4
jump 8
print
push -1
add
jump 2
print
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