diff --git a/sketches/assembler.js b/sketches/assembler.js index e9cee51..9452a3d 100644 --- a/sketches/assembler.js +++ b/sketches/assembler.js @@ -22,27 +22,39 @@ function decodeMultipleInstructions(str) { let lines = str.split(/\n/); // returns an array of lines let output = []; lines.forEach( (l) => { - let stripped = stripWhitespaceFromEnds(stripComments(l)); - let decoded = decodeInstruction(stripped); - output.push(decoded.op); - output.push(decoded.arg); + let decoded = decodeInstruction(l); + if (decoded) { + output.push(decoded.op); + output.push(decoded.arg); + } }); return new Uint8Array(output); } +/** + * @param {string} line - A line of assembly code + * @returns {(object|false)} Either {op: machineOp, arg: 0}, or false if the line was blank + */ function decodeInstruction(line) { - let addressingMode = "direct"; // Must be "direct" or "indirect" - op_arg_array = line.split(" "); + line = stripWhitespaceFromEnds(stripComments(line)); + let op_arg_array = line.split(" "); // split line into an array of [op, arg] let opName = op_arg_array[0].toLowerCase(); + let addressingMode = 'direct'; // Must be "direct" or "indirect" - // Handle mnemonics without arguments (eg END) + // Handle blank lines and mnemonics without arguments (eg END) if (op_arg_array.length < 2) { // No argument + // handle blank lines, or lines that just contain a comment: + if (line.length === 0) { return false; } + + // handle mnemonics that aren't paired with an argument: if (mnemonicsWithOptionalArgs.indexOf(opName) < 0) { - throw error("Missing opcode"); + console.error(`Missing opcode: ${line}`); + throw new Error("Missing opcode"); } let machineOp = mnemonics2opcodes[opName][addressingMode]; return { op: machineOp, arg: 0 }; } + // Handle mnemonics with arguments (eg ADD $FF) let arg_str = op_arg_array[1]; if (arg_str.startsWith("(")) {