Class: N65::Bytes

Inherits:
InstructionBase show all
Defined in:
lib/n65/directives/bytes.rb

Overview

This directive to include bytes

Defined Under Namespace

Classes: InvalidByteValue

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from InstructionBase

#unresolved_symbols?

Constructor Details

#initialize(bytes_array) ⇒ Bytes

Initialize with a byte array



42
43
44
# File 'lib/n65/directives/bytes.rb', line 42

def initialize(bytes_array)
  @bytes_array = bytes_array
end

Class Method Details

.parse(line) ⇒ Object

Try to parse an incbin directive



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/n65/directives/bytes.rb', line 12

def self.parse(line)
  match_data = line.match(/^\.bytes\s+(.+)$/)
  return nil if match_data.nil?

  bytes_array = match_data[1].split(',').map do |byte_string|
    # Does byte_string represent a numeric literal, or is it a symbol?
    # In numeric captures $2 is always binary, $1 is always hex

    case byte_string.strip
    when Regexp.new("^#{Regexes::Num8}$")
      $2.nil? ? $1.to_i(16) : $2.to_i(2)

    when Regexp.new("^#{Regexes::Num16}$")
      value = $2.nil? ? $1.to_i(16) : $2.to_i(2)

      # Break value up into two bytes
      high = (0xff00 & value) >> 8
      low  = (0x00ff & value)
      [low, high]
    when Regexp.new("^#{Regexes::Sym}$")
      $1
    else
      raise(InvalidByteValue, byte_string)
    end
  end.flatten

  Bytes.new(bytes_array)
end

Instance Method Details

#exec(assembler) ⇒ Object

Execute on the assembler



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/n65/directives/bytes.rb', line 47

def exec(assembler)
  promise = assembler.with_saved_state do |saved_assembler|
    @bytes_array.map! do |byte|
      case byte
      when Integer
        byte
      when String
        saved_assembler.symbol_table.resolve_symbol(byte)
      else
        raise(InvalidByteValue, byte)
      end
    end
    saved_assembler.write_memory(@bytes_array)
  end

  begin
    promise.call
  rescue SymbolTable::UndefinedSymbol
    # Write the bytes but assume a zero page address for all symbols
    # And just write 0xDE for a placeholder
    placeholder_bytes = @bytes_array.map do |byte|
      case bytes
      when Integer
        byte
      when String
        0xDE
      else
        raise(InvalidByteValue, byte)
      end
    end
    assembler.write_memory(placeholder_bytes)
    promise
  end
end

#to_sObject

Display, I don't want to write all these out



83
84
85
# File 'lib/n65/directives/bytes.rb', line 83

def to_s
  ".bytes (#{@bytes_array.length})"
end