Created
March 14, 2010 00:33
-
-
Save ybakos/331665 to your computer and use it in GitHub Desktop.
Example of Translator logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
while parser.has_more_commands? do | |
writer.begin!(asm_file_name_for(vm_filename)) | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment