class Assembler::Translator

Public Class Methods

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

Public Instance Methods

translate() click to toggle source
# File lib/hackasm/assembler/translator.rb, line 13
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/assembler/translator.rb, line 43
def expressions
  @expressions ||= parser.parse(@text)
end
parser() click to toggle source
# File lib/hackasm/assembler/translator.rb, line 39
def parser
  @parser ||= HackParser.new
end
process_instruction(instruction) click to toggle source
# File lib/hackasm/assembler/translator.rb, line 24
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
symbol_table() click to toggle source
# File lib/hackasm/assembler/translator.rb, line 47
def symbol_table
  @symbol_table ||= SymbolTable.new(expressions).to_h
end