Sha256: c871bdc77e16b1ba3470958793d972dd169724d1bbf18214c9e3291ca437bb49

Contents?: true

Size: 1.17 KB

Versions: 1

Compression:

Stored size: 1.17 KB

Contents

require_relative "./vm_code_parser"
require_relative "./instructions/arithmetic_instruction"
require_relative "./instructions/memory_access_instruction"

module Vm
  class Translator
    def initialize(text, object_name)
      @text = text
      @object_name = object_name
    end

    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

    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

    def parser
      @parser ||= VmCodeParser.new
    end

    def expressions
      @expressions ||= parser.parse(@text)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hackasm-0.1.0 lib/hackasm/vm/translator.rb