Class: Base::VM

Inherits:
Object
  • Object
show all
Defined in:
lib/base/vm.rb

Constant Summary collapse

Error =
Class.new(StandardError)
MAX_MEMORY =
1048576
COMMANDS =
%w(debug push discard duplicate write read add subtract multiply divide jump bltz bgtz betz bnetz out halt)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(program, debug: false) ⇒ VM

Returns a new instance of VM.



11
12
13
14
15
16
# File 'lib/base/vm.rb', line 11

def initialize(program, debug: false)
  @ip = program.start_location
  @memory = program.memory
  @debug = debug
  @stack = Stack.new
end

Instance Attribute Details

#ipObject (readonly)

Returns the value of attribute ip.



7
8
9
# File 'lib/base/vm.rb', line 7

def ip
  @ip
end

#memoryObject (readonly)

Returns the value of attribute memory.



7
8
9
# File 'lib/base/vm.rb', line 7

def memory
  @memory
end

#stackObject (readonly)

Returns the value of attribute stack.



7
8
9
# File 'lib/base/vm.rb', line 7

def stack
  @stack
end

Instance Method Details

#runObject

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/base/vm.rb', line 18

def run
  loop do
    raise Error, "IP reached end of memory" if memory[ip].nil?

    @debug = Debugger.new(self).debug if @debug

    begin
      result = execute
      break if result == :halt
    rescue Error => e
      $stderr.puts("error: #{e.message}")
      @debug = true
    end
  end

  raise Error, "warning: stack not empty at program termination, #{stack.inner}" unless @stack.empty?
end