diff --git a/gir.js b/gir.js index 7725207..bd055b0 100644 --- a/gir.js +++ b/gir.js @@ -40,7 +40,7 @@ const jumpIfNonZero = Symbol('jumpIfNonZero'); class ParsingError extends Error {} // (string) → [commandObjects] -// May throw +// May throw ParsingError function parse(program) { // (string, int, bool) → {parsed: [commandObjects], lastIndex: int} // index is the index of the next character to consume @@ -159,10 +159,12 @@ function parse(program) { return parsed; } -// ([commandObjects/offsetCommandObjects]) -function prettyPrint(parsed) { - // ([commandObjects/offsetCommandObjects], string) - function printIndented(parsed, indent = '') { +// ([commandObjects/offsetCommandObjects]) → str +function prettifyIR(parsed) { + // ([commandObjects/offsetCommandObjects], string) → str + function worker(parsed, indent = '') { + let lines = []; + for(let i = 0; i < parsed.length; i++) { let command = parsed[i]; @@ -172,48 +174,50 @@ function prettyPrint(parsed) { if('offset' in command) { line += ` (${command.offset})`; } - console.log(line); + lines.push(line); } else if(command.type == moveHead) { line += `moveHead ${command.value}`; - console.log(line); + lines.push(line); } else if(command.type == writeByte) { line += 'writeByte'; if('offset' in command) { line += ` (${command.offset})`; } - console.log(line); + lines.push(line); } else if(command.type == readByte) { line += 'readByte'; if('offset' in command) { line += ` (${command.offset})`; } - console.log(line); + lines.push(line); } else if(command.type == loop) { line += 'loop'; if('isBalanced' in command) { line += ` (balanced: ${command.isBalanced})`; } - console.log(line); - printIndented(command.contents, indent + ' '); + lines.push(line); + lines = lines.concat(worker(command.contents, indent + ' ')); } else if(command.type == clear) { line += 'clear'; if('offset' in command) { line += ` (${command.offset})`; } - console.log(line); + lines.push(line); } else if(command.type == jumpIfZero) { line += `jumpIfZero ${command.target}`; - console.log(line); + lines.push(line); } else if(command.type == jumpIfNonZero) { line += `jumpIfNonZero ${command.target}`; - console.log(line); + lines.push(line); } else { line += `unknown ${command.type}`; - console.log(line); + lines.push(line); } } + + return lines.join('\n'); } - printIndented(parsed); + return worker(parsed); } // ------------------------------------------------------------------