Class: SnesUtils::Vas

Inherits:
Object
  • Object
show all
Defined in:
lib/vas/vas.rb

Constant Summary collapse

WDC65816 =
:wdc65816
SPC700 =
:spc700
SUPERFX =
:superfx
DIRECTIVE =
[
  '.65816', '.spc700', '.superfx', '.org', '.base', '.db', '.rb', '.incbin'
]
LABEL_OPERATORS =
['@', '!', '<', '>', '\^']

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, outfile) ⇒ Vas

Returns a new instance of Vas.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/vas/vas.rb', line 15

def initialize(filename, outfile)
  raise "File not found: #{filename}" unless File.file?(filename)

  @filename = filename
  @outfile = outfile
  @file = []
  @label_registry = []
  @reading_macro = false
  @current_macro = nil
  @macros_registry = {}
  @define_registry = {}
  @incbin_list = []
  @byte_sequence_list = []
  @memory = []
end

Class Method Details

.hex(num, rjust_len = 2) ⇒ Object



233
234
235
# File 'lib/vas/vas.rb', line 233

def self.hex(num, rjust_len = 2)
  (num || 0).to_s(16).rjust(rjust_len, '0').upcase
end

.replace_eval_label(registry, arg) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/vas/vas.rb', line 277

def self.replace_eval_label(registry, arg)
  return arg unless matches = /({(.*)})(w)?$/.match(arg)

  found = {}

  registry.each do |key, val|
    if arg.match(/\b#{key}\b/)
      found[key] = val
    end
  end

  return arg.to_i(16) if found.empty?

  new_arg = matches[2]

  found.each do |key, val|
    new_arg = new_arg.gsub(/\b#{key}\b/, val.to_s)
  end

  if matches[3] == 'w'
    res = eval(new_arg).to_s(16).rjust(4, '0')[-4..-1]
    arg[0..-2].gsub(matches[1], res)
  else
    res = eval(new_arg).to_s(16).rjust(2, '0')[-2..-1]
    arg.gsub(matches[1], res)
  end
end

Instance Method Details

#assembleObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/vas/vas.rb', line 31

def assemble
  construct_file

  2.times do |pass|
    @program_counter = 0
    @origin = 0
    @base = 0
    @cpu = WDC65816

    assemble_file(pass)
  end

  write_label_registry
  insert_bytes
  incbin
  write(@outfile)
end

#assemble_file(pass) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/vas/vas.rb', line 166

def assemble_file(pass)
  @file.each do |line|
    @line = line[:line]

    if @line.include?(':')
      arr = @line.split(':')
      label = arr[0].strip.chomp
      unless /^\w+$/ =~ label
        raise "Invalid label: #{label}"
      end
      register_label(label, pass) # if pass == 0
      next unless arr[1]
      instruction = arr[1].strip.chomp
    else
      instruction = @line
    end

    next if instruction.empty?

    if instruction.start_with?(*DIRECTIVE)
      process_directive(instruction, pass, line)
      next
    end

    begin
      bytes = LineAssembler.new(instruction, **options).assemble
    rescue => e
      puts "Error at line #{line[:filename]}##{line[:line_no]} - (#{line[:orig_line]}) : #{e}"
      exit(1)
    end

    insert(bytes) if pass == 1
    @program_counter += bytes.size
  end
end

#call_macro(name, raw_args, line_no) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/vas/vas.rb', line 113

def call_macro(name, raw_args, line_no)
  macro = @macros_registry[name]
  uuid = SecureRandom.uuid
  raise "line #{line_no}: call of undefined macro `#{name}`" if macro.nil?

  args_names = @macros_registry[name][:args]
  if args_names.count != raw_args.count
    raise "line #{line_no}: wrong number of arguments for macro `#{name}` expected : #{args_names.count}, given: #{raw_args.count}"
  end
  args = {}
  args_names.count.times do |i|
    args[args_names[i]] = raw_args[i]
  end

  macro[:lines].each_with_index do |line_info|
    line = line_info[:line]

    if line.include?('%')
      # replace variable with arg
      matches = line.match(/%(\w+)%?/)
      if matches[1] == 'MACRO_ID'
        value = uuid.delete('-')
      else
        value = args[matches[1]]
      end
      raise "line #{line_no}: undefined variable `#{matches[1]}` for macro `#{name}`" if value.nil?
      replaced_line = line.gsub(/#{matches[0]}/, value)
      @file << line_info.merge(line: replace_define(replaced_line))
    else
      @file << line_info
    end
  end
end

#construct_file(filename = @filename) ⇒ Object



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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/vas/vas.rb', line 49

def construct_file(filename = @filename)
  File.open(filename).each_with_index do |raw_line, line_no|
    line = raw_line.split(';').first.strip.chomp
    next if line.empty?

    if line.start_with?('.include')
      raise "can't include file within macro" if @reading_macro

      directive = line.split(' ')
      inc_filename = directive[1].to_s.strip.chomp
      dir = File.dirname(filename)

      construct_file(File.join(dir, inc_filename))
    elsif line.start_with?('.define')
      raise "can't define variable within macro" if @reading_macro

      args = line.split(' ')
      key = "#{args[1]}"
      raw_val = args[2..-1].join(' ').split(';').first
      raise "Missing value for : #{key}" if raw_val.nil?

      val = raw_val.strip.chomp

      raise "Already defined: #{key}" unless @define_registry[key].nil?
      @define_registry[key] = val
    elsif line.start_with?('.call')
      raise "can't call macro within macro" if @reading_macro

      args = line.split(' ')
      macro_name = args[1]
      macro_args = args[2..-1].join.split(',')
      call_macro(macro_name, macro_args, line_no + 1)
    elsif line.start_with?('.macro')
      raise "can't have nested macro" if @reading_macro

      args = line.split(' ')
      macro_name = args[1]
      macro_args = args[2..-1].join.split(',')
      init_macro(macro_name, macro_args)
    else
      new_line = replace_define(line)
      line_info = { line: new_line, orig_line: line, line_no: line_no + 1, filename: filename }

      if @reading_macro
        line.start_with?('.endm') ? save_macro : @current_macro[:lines] << line_info
      else
        @file << line_info
      end
    end
  end
end

#define_bytes(raw_bytes, pass) ⇒ Object



334
335
336
337
338
339
340
341
342
343
# File 'lib/vas/vas.rb', line 334

def define_bytes(raw_bytes, pass)
  bytes = raw_bytes.split(',').map { |rb| rb.scan(/.{2}/).reverse }.flatten.map do |b|
    bv = b.to_i(16)
    raise "Invalid byte: #{b} : #{@line}" if bv < 0 || bv > 0xff
    bv
  end

  @byte_sequence_list << [bytes, insert_index] if pass == 0
  bytes.size
end

#incbinObject



325
326
327
328
329
330
331
332
# File 'lib/vas/vas.rb', line 325

def incbin
  @incbin_list.each do |filename, index|
    file = File.open(filename)
    bytes = file.each_byte.to_a
    @line = filename
    insert(bytes, index)
  end
end

#init_macro(name, args) ⇒ Object



101
102
103
104
# File 'lib/vas/vas.rb', line 101

def init_macro(name, args)
  @current_macro = { name: name, args: args, lines: [] }
  @reading_macro = true
end

#insert(bytes, insert_at = insert_index) ⇒ Object



212
213
214
# File 'lib/vas/vas.rb', line 212

def insert(bytes, insert_at = insert_index)
  @memory[insert_at..insert_at + bytes.size - 1] = bytes
end

#insert_bytesObject



345
346
347
348
349
# File 'lib/vas/vas.rb', line 345

def insert_bytes
  @byte_sequence_list.each do |bytes, index|
    insert(bytes, index)
  end
end

#insert_indexObject



216
217
218
# File 'lib/vas/vas.rb', line 216

def insert_index
  @program_counter + @base
end

#optionsObject



237
238
239
240
241
242
243
244
# File 'lib/vas/vas.rb', line 237

def options
  {
    program_counter: @program_counter,
    origin: @origin,
    cpu: @cpu,
    label_registry: @label_registry
  }
end

#prepare_incbin(filename, pass) ⇒ Object



318
319
320
321
322
323
# File 'lib/vas/vas.rb', line 318

def prepare_incbin(filename, pass)
  raise "Incbin: file not found: #{filename}" unless File.file?(filename)

  @incbin_list << [filename, insert_index] if pass == 0
  File.size(filename) || 0
end

#process_directive(instruction, pass, line_info) ⇒ Object



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/vas/vas.rb', line 246

def process_directive(instruction, pass, line_info)
  directive = instruction.split(' ')

  case directive[0]
  when '.65816'
    @cpu = WDC65816
  when '.spc700'
    @cpu = SPC700
  when '.superfx'
    @cpu = SUPERFX
  when '.org'
    update_origin(directive[1].to_i(16))
  when '.base'
    @base = directive[1].to_i(16)
  when '.incbin'
    inc_filename = directive[1].to_s.strip.chomp
    dir = File.dirname(line_info[:filename])
    @program_counter += prepare_incbin(File.join(dir, inc_filename), pass)
  when '.db'
    raw_line = directive[1..-1].join.to_s.strip.chomp
    line = LineAssembler.new(raw_line, **options).replace_labels(raw_line)

    @program_counter += define_bytes(line, pass)
  when '.rb'
    arg = directive[1..-1].join

    count = self.class.replace_eval_label(@label_registry, arg)
    @program_counter += count.is_a?(String) ? count.to_i(16) : count
  end
end

#register_label(label, pass) ⇒ Object



202
203
204
205
206
207
208
209
210
# File 'lib/vas/vas.rb', line 202

def register_label(label, pass)
  if pass == 0
    raise "Label already defined: #{label}" if @label_registry.detect { |l| l[0] == label }
    @label_registry << [label, @program_counter + @origin]
  else
    index = @label_registry.index { |l| l[0] == label }
    @label_registry[index][1] = @program_counter + @origin
  end
end

#replace_define(line) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/vas/vas.rb', line 147

def replace_define(line)
  # TODO also support multiple define on same line
  # hint : generalize replace_eval_label ?
  found = nil

  @define_registry.keys.each do |key|
    if line.match(/\b#{key}\b/)
      found = key
      break
    end
  end

  return line if found.nil?

  val = @define_registry[found]

  line.gsub(/\b#{found}\b/, val)
end

#save_macroObject



106
107
108
109
110
111
# File 'lib/vas/vas.rb', line 106

def save_macro
  name = @current_macro[:name]
  raise "macro `#{name}` already defined" unless @macros_registry[name].nil?
  @macros_registry[name] = @current_macro
  @reading_macro = false
end

#update_base_from_originObject



312
313
314
315
316
# File 'lib/vas/vas.rb', line 312

def update_base_from_origin
  # TODO: automatically update base
  # lorom/hirom scheme
  # spc700 scheme
end

#update_origin(param) ⇒ Object



305
306
307
308
309
310
# File 'lib/vas/vas.rb', line 305

def update_origin(param)
  @origin = param
  @program_counter = 0

  update_base_from_origin
end

#write(filename) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/vas/vas.rb', line 220

def write(filename)
  if filename.nil?
    dir = File.dirname(@filename)
    filename = File.join(dir, 'out.sfc')
  end

  File.open(filename, 'w+b') do |file|
    file.write([@memory.map { |i| Vas::hex(i) }.join].pack('H*'))
  end

  filename
end

#write_label_registryObject



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/vas/vas.rb', line 351

def write_label_registry
  longest = @label_registry.map{|r| r[0] }.max_by(&:length)

  if @outfile.nil?
    dir = File.dirname(@filename)
  else
    dir = File.dirname(@outfile)
  end

  File.open(File.join(dir, 'labels.txt'), 'w+b') do |file|
    @label_registry.each do |label|
      adjusted_label = label[0].ljust(longest.length, ' ')
      raw_address = Vas::hex(label[1], 6)
      address = "#{raw_address[0..1]}/#{raw_address[2..-1]}"
      file.write "#{adjusted_label} #{address}\n"
    end
  end
  File.open(File.join(dir, 'labels.msl'), 'w+b') do |file|
    @label_registry.each do |label|
      if label[1] >= 0x7e0000 && label[1] <= 0x7fffff
        bank = label[1] & 0xff0000
        address = "WORK:#{Vas::hex(label[1] - bank)}:#{label[0]}:"
      else
        bank = label[1] & 0xff0000
        bank_i = bank >> 16 & 0xf
        # low rom only for now
        prg_addr = label[1] - bank - 0x8000 + bank_i * 0x8000
        address = "PRG:#{Vas::hex(prg_addr)}:#{label[0]}:"
      end
      file.write "#{address}\n"
    end
  end
end