public
Last active

Example of Translator logic

  • Download Gist
translator.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
class Translator
 
def self.translate!(filenames)
writer = CodeWriter.new('hello codewriter I hope you are feeling fine')
filenames.each do |vm_filename|
puts "Translating #{vm_filename} ..."
parser = Parser.new(vm_filename)
writer.begin!(asm_file_name_for(vm_filename))
while parser.has_more_commands? do
parser.advance
if parser.command_type == :C_ARITHMETIC
puts "#{parser.index}: #{parser.command.collect{|s| s + ' '}} C_ARITHMETIC"
writer.write_arithmetic(parser.arg1)
elsif parser.command_type == :C_PUSH || parser.command_type == :C_POP
puts "#{parser.index}: #{parser.command.collect{|s| s + ' '}} is C_PUSH or C_POP"
writer.write_push_pop(parser.command_type, parser.arg1, parser.arg2)
else
puts "uhoh, outside of my ability! (for now)"
end
end
end
writer.close
end
 
def self.asm_file_name_for(vm_filename)
raise TranslatorException.new('Bad VM filename') unless vm_filename.include?('.vm')
basename = File.basename(vm_filename, '.vm')
path = File.split(vm_filename)[0]
"#{path}/#{basename}.asm"
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.