Sha256: c798a8a7bffd471be6f740448e1cf02a218fbe2bf3fafb8501e62bb2e748cab7

Contents?: true

Size: 1.23 KB

Versions: 1

Compression:

Stored size: 1.23 KB

Contents

require "pry"
require_relative "./hack_parser"
require_relative "./symbol_table"
require_relative "./instructions/address_instruction"
require_relative "./instructions/command_instruction"

module Assembler
  class Translator
    def initialize(text)
      @text = text
    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 :address_instruction
        Instructions::AddressInstruction.new(instruction_body, symbol_table).to_b
      when :command_instruction
        Instructions::CommandInstruction.new(instruction_body).to_b
      when :jump_label
        nil
      else raise "Unknown instruction!"
      end
    end

    def parser
      @parser ||= HackParser.new
    end

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

    def symbol_table
      @symbol_table ||= SymbolTable.new(expressions).to_h
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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