Class: SimpleSem::Program

Inherits:
Object
  • Object
show all
Defined in:
lib/simplesem/simplesem_program.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filepath = nil) ⇒ Program

Create a SimpleSemProgram instance Params:

(String)filepath: path to SimpleSem source file.
Optional because it's useful to use in tests without needing to load a file


20
21
22
23
24
25
26
27
28
29
30
# File 'lib/simplesem/simplesem_program.rb', line 20

def initialize filepath=nil
  @code = Array.new
  if filepath
    IO.foreach(filepath) do |line|
      @code << line.split("//", 2)[0].strip # seperate the comment from the code
    end
  end

  @data = Array.new
  @pc = 0
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



13
14
15
# File 'lib/simplesem/simplesem_program.rb', line 13

def code
  @code
end

#dataObject

Returns the value of attribute data.



14
15
16
# File 'lib/simplesem/simplesem_program.rb', line 14

def data
  @data
end

#pcObject

Returns the value of attribute pc.



14
15
16
# File 'lib/simplesem/simplesem_program.rb', line 14

def pc
  @pc
end

Instance Method Details

#inspect_dataObject



47
48
49
50
51
# File 'lib/simplesem/simplesem_program.rb', line 47

def inspect_data
  res = String.new
  @data.each_with_index {|loc, i| res += "#{i}: #{loc.last}\n" }
  res
end

#inspect_data_with_historyObject



53
54
55
56
57
# File 'lib/simplesem/simplesem_program.rb', line 53

def inspect_data_with_history
  res = String.new
  @data.each_with_index {|loc, i| res += "#{i}: #{loc.inspect}\n" }
  res
end

#runObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/simplesem/simplesem_program.rb', line 32

def run
  @parser = SimpleSemParser.new

  @pc = 0
  loop do
    instruction = @code[@pc]  # fetch
    @pc += 1                  # increment
    begin
      @parser.parse(instruction).execute(self)  # decode and execute
    rescue ProgramHalt
      break
    end
  end
end