private static void findLabels(Parser parser, SymbolTable symbols) { int ROM = 0; string symbol; while (parser.hasMoreCommands()) { try { parser.advance(); } catch (EndOfStreamException) { break; } switch (parser.commandType()) { case Parser.L_COMMAND: symbol = parser.symbol(); if (symbols.contains(symbol)) { throw new InvalidOperationException("Cannot redefine label: " + symbol); } symbols.addEntry(symbol, ROM); break; case Parser.A_COMMAND: case Parser.C_COMMAND: ROM++; break; } } parser.reset(); }
private static void assemble(Parser parser, SymbolTable symbols, StreamWriter output) { Code translator = new Code(); int RAM = 16; while (parser.hasMoreCommands()) { int value = 0; try { parser.advance(); } catch (EndOfStreamException) { break; } switch (parser.commandType()) { case Parser.A_COMMAND: int address; string symbol = parser.symbol(); bool isNumber = int.TryParse(symbol, out address); if (!isNumber) { if (!symbols.contains(symbol)) { symbols.addEntry(symbol, RAM++); } address = symbols.getAddress(symbol); } value = address; break; case Parser.C_COMMAND: value |= 7 << 13; // 1110000000000000 == 57344 value |= translator.comp(parser.comp()); value |= translator.dest(parser.dest()); value |= translator.jump(parser.jump()); break; case Parser.L_COMMAND: continue; } string instruction = Convert.ToString(value, 2).PadLeft(16, '0'); output.WriteLine(instruction); } parser.reset(); }