Class: HRM::Machine

Inherits:
Object
  • Object
show all
Includes:
Instruction
Defined in:
lib/hrm/machine.rb

Constant Summary collapse

MAX_MEMORY_SIZE =
25

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Instruction

#add, #bumpdown, #bumpup, #copyfrom, #copyto, #inbox, #jump, #jump_if_neg, #jump_if_zero, #outbox, #sub

Constructor Details

#initialize(source) ⇒ Machine

Returns a new instance of Machine.



11
12
13
14
15
16
17
# File 'lib/hrm/machine.rb', line 11

def initialize(source)
  @source = source
  @im = [nil] + parse_source_code
  @value = nil
  @pc = 1
  @memory = Array.new(MAX_MEMORY_SIZE)
end

Class Method Details

.run(filepath) ⇒ Object



7
8
9
# File 'lib/hrm/machine.rb', line 7

def self.run(filepath)
  new(File.read(filepath)).run
end

Instance Method Details

#runObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/hrm/machine.rb', line 19

def run
  loop do
    instruction, arg = @im[@pc]
    @pc += 1

    exit(0) if instruction.nil?

    if arg.nil?
      public_send(instruction)
    else
      if arg =~ /\[\s*(\d+)\s*\]/
        public_send(instruction, @memory[$1.to_i])
      else
        public_send(instruction, arg.to_i)
      end
    end
  end
end