class Assembler::SymbolTable

Constants

DEFAULT_SYMBOL_TABLE

Public Class Methods

new(expressions) click to toggle source
# File lib/hackasm/assembler/symbol_table.rb, line 13
def initialize(expressions)
  @expressions = expressions
end

Public Instance Methods

to_h() click to toggle source
# File lib/hackasm/assembler/symbol_table.rb, line 17
def to_h
  DEFAULT_SYMBOL_TABLE.merge(
    label_symbols
  ).merge(
    variable_symbols
  )
end

Private Instance Methods

label_symbols() click to toggle source
# File lib/hackasm/assembler/symbol_table.rb, line 27
def label_symbols
  @label_symbols ||= begin
                     label_count = 0
                     @expressions.each.with_index.with_object({}) do |(expression, index), symbol_table|
                       symbol = expression.dig(:jump_label, :identifier)
                       symbol = symbol && symbol.to_s
                       if symbol
                         symbol_table[symbol] = index - label_count
                         label_count += 1
                       end
                     end
                   end
end
variable_symbols() click to toggle source
# File lib/hackasm/assembler/symbol_table.rb, line 41
def variable_symbols
  memory_location = 16
  @expressions.each.with_index.with_object({}) do |(expression, index), symbol_table|
    symbol = expression.dig(:address_instruction, :identifier)
    symbol = symbol && symbol.to_s
    if symbol && symbol_table[symbol].nil? && DEFAULT_SYMBOL_TABLE[symbol].nil? && label_symbols[symbol].nil?
      symbol_table[symbol] = memory_location
      memory_location += 1
    end
  end
end