class CodeTest(unittest.TestCase): def setUp(self): self.coder = Code() def testDest(self): self.assertEqual(0b000, self.coder.dest('null')) self.assertEqual(0b001, self.coder.dest('M')) def testComp(self): self.assertEqual(0b0101010, self.coder.comp('0')) self.assertEqual(0b0001111, self.coder.comp('-D')) def testJump(self): self.assertEqual(0b000, self.coder.jump('null')) self.assertEqual(0b101, self.coder.jump('JNE'))
def second_pass(parser, symbols): is_variable = re.compile(u'^[^\d]') variable_address = 15 coder = Code() translated = [] parser.reset() while parser.hasMoreCommands: parser.advance() command_type = parser.commandType if command_type == 'A_COMMAND': address = parser.symbol if is_variable.match(address): if symbols.contains(address): address = symbols.GetAddress(address) else: variable_address = variable_address + 1 symbols.addEntry(address, variable_address) address = variable_address else: address = int(address) translated.append(A_COMM_TMPL.format(address)[0:16]) if command_type == 'C_COMMAND': comp = coder.comp(parser.comp) dest = coder.dest(parser.dest) jump = coder.jump(parser.jump) translated.append(C_COMM_TMPL.format(comp, dest, jump)[0:16]) return '\n'.join(translated)
def test_code(self): code = Code() self.assertEqual(code.dest(None), "000") self.assertEqual(code.dest("AD"), "110") self.assertEqual(code.comp("D-M"), "1010011") self.assertEqual(code.dest("D"), "010")
def test_comp(self): self.assertEqual(Code.comp('A=0'), '0101010') self.assertEqual(Code.comp('A=0;JGE'), '0101010') self.assertEqual(Code.comp('A=1;JGE'), '0111111') self.assertEqual(Code.comp('M=-1;JEQ'), '0111010') self.assertEqual(Code.comp('A=D;JGE'), '0001100') self.assertEqual(Code.comp('M=A;JGE'), '0110000') self.assertEqual(Code.comp('D=M;JGE'), '1110000')