void Assembler::translate(std::ostream& out) const { // PRE: The symbol table has been populated by the constructor. Parser p(input_filename_); Code c; while (p.hasMoreCommands()) { p.advance(); switch (p.commandType()) { case A_COMMAND: { std::string s = p.symbol(); // immediate or a memory position std::bitset<16> addr; // defined by a symbol. if (isdigit(s.front())) { // Starts with a number => immediate. addr = c.immediate(s); } else { // Reference to a variable. assert(symbol_table_.count(s)); addr = symbol_table_.at(s); } out << std::bitset<16>(addr) << std::endl; break; } case C_COMMAND: { std::bitset<16> dest(c.dest(p.dest())); // All the codes are stored std::bitset<16> jump(c.jump(p.jump())); // with an appropriate padding std::bitset<16> comp(c.comp(p.comp())); // to OR them and call it done. std::bitset<16> instr(comp | dest | jump); out << instr << std::endl; break; } case L_COMMAND: break; } } }
int main(int argc, char *argv[]) { string ar(argv[1]); string goPerl = "perl perl.pl "+ar; system(goPerl.c_str()); Parser p("out.txt"); Code code; SymbolTable myTable; int address = 16; int counter = 0; //Записали в таблицу все лейбы while(p.advance()) { char Type = p.commandType(); switch(Type) { case 'A' : ++counter; break; case 'C' : ++counter; break; case 'L' : if(p.removeBKT(), !myTable.contains(p.aSymbol()) ) { myTable.addEntry(p.aSymbol(), counter); } break; } } p.backFile(); //Вернуть указатель на начало файла //Записали в таблицу все А-переменные while(p.advance()) { char Type = p.commandType(); switch(Type) { case 'A' : if( p.aIsSymbol() && !myTable.contains(p.aSymbol()) && !p.aIsUpper() ) { myTable.addEntry(p.aSymbol(), address); ++address; } break; } } p.backFile(); //Вернуть указатель на начало файла ofstream ofs("out.hack"); //Заменили все значения битами while(p.advance()) { char Type = p.commandType(); switch(Type) { case 'A' : p.aIsSymbol() ? ofs << bitset<16>( myTable.getAddress(p.aSymbol()) ) << "\n" : ofs << bitset<16>( p.aInteger() ) << "\n"; break; case 'C' : ofs << "111" << code.comp(p.comp()) << code.dest(p.dest()) << code.jump(p.jump()) << "\n"; break; } } }