class Vm::Translator

Public Class Methods

new(text, object_name) click to toggle source
# File lib/hackasm/vm/translator.rb, line 7
def initialize(text, object_name)
  @text = text
  @object_name = object_name
end

Public Instance Methods

translate() click to toggle source
# File lib/hackasm/vm/translator.rb, line 12
def translate
  expressions = parser.parse(@text)
  expressions.map do |expression|
    process_instruction(expression)
  end.compact.join("\n") << "\n"
rescue Parslet::ParseFailed => failure
  failure.parse_failure_cause.ascii_tree
end

Private Instance Methods

expressions() click to toggle source
# File lib/hackasm/vm/translator.rb, line 42
def expressions
  @expressions ||= parser.parse(@text)
end
parser() click to toggle source
# File lib/hackasm/vm/translator.rb, line 38
def parser
  @parser ||= VmCodeParser.new
end
process_instruction(instruction) click to toggle source
# File lib/hackasm/vm/translator.rb, line 23
def process_instruction(instruction)
  instruction_name = instruction.keys.first
  instruction_body = instruction.values.first

  case instruction_name
  when :arithmetic_instruction
    Instructions::ArithmeticInstruction.new(instruction_body).to_asm
  when :memory_access_instruction
    Instructions::MemoryAccessInstruction.new(instruction_body, @object_name).to_asm
  when :jump_label
    nil
  else raise "Unknown instruction!"
  end
end