def translate(input_file_path, output_file): parser = Parser(input_file_path) command = parser.next_command() current_function = "no_function" while command: command_type = get_command_type(command) parts = command.split() if command_type == MEMORY_ACCESS: output_file.write( memory_access.translate_command( parts[0], parts[1], parts[2], get_file_name(input_file_path))) elif command_type == ARITHMETIC: output_file.write(arithmetic.translate_command(command)) elif command_type == PROGRAM_FLOW: output_file.write( program_flow.translate_command(parts[0], parts[1], current_function)) elif command_type == FUNCTION: if parts[0] == FUNCTION_DECLARATION: current_function = parts[1] if len(parts) == 3: output_file.write( function.translate_command(parts[0], parts[1], parts[2])) else: output_file.write(function.translate_command(parts[0], "", "")) command = parser.next_command() output_file.write("\n\n")
def test_not(self): expected = textwrap.dedent(""" // not @SP M=M-1 A=M M=!M @SP M=M+1 """).strip() self.assertEqual(expected, arithmetic.translate_command(NOT))
def test_neg(self): expected = textwrap.dedent(""" // neg @SP M=M-1 //SP-- A=M M=-M //negate @SP M=M+1 //SP++ """).strip() self.assertEqual(expected, arithmetic.translate_command(NEG))
def translate(input_file_path, output_file): parser = Parser(input_file_path) command = parser.next_command() while command: command_type = get_command_type(command) if command_type == MEMORY_ACCESS: parts = command.split() output_file.write( memory_access.translate_command( parts[0], parts[1], parts[2], get_file_name(input_file_path))) elif command_type == ARITHMETIC: output_file.write(arithmetic.translate_command(command)) command = parser.next_command() output_file.write("\n\n")
def test_add(self): expected = textwrap.dedent(""" // add @SP M=M-1 //SP-- A=M D=M @SP M=M-1 //SP-- A=M M=D+M //M=x+y @SP M=M+1 //SP++ """).strip() self.assertEqual(expected, arithmetic.translate_command(ADD))
def test_or(self): expected = textwrap.dedent(""" // or @SP M=M-1 A=M D=M @SP M=M-1 A=M M=M|D @SP M=M+1 """).strip() self.assertEqual(expected, arithmetic.translate_command(OR))
def test_and(self): expected = textwrap.dedent(""" // and @SP M=M-1 A=M D=M @SP M=M-1 A=M M=M&D @SP M=M+1 """).strip() self.assertEqual(expected, arithmetic.translate_command(AND))
def test_sub(self): expected = textwrap.dedent(""" // sub @SP M=M-1 //SP-- A=M D=M @SP M=M-1 //SP-- A=M M=M-D //M=x-y @SP M=M+1 //SP++ """).strip() self.assertEqual(expected, arithmetic.translate_command(SUB))
def test_lt(self): self.assertIsNotNone(arithmetic.translate_command(LT))
def test_eq(self): self.assertIsNotNone(arithmetic.translate_command(EQ))