From 7186a895d27b3a02b3c8a36d8a4dd251f6447dec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juhani=20Krekel=C3=A4?= Date: Wed, 23 May 2018 21:57:07 +0300 Subject: [PATCH] =?UTF-8?q?prettyPrint=20=E2=86=92=20prettifyIR=20(make=20?= =?UTF-8?q?return=20string=20instead=20of=20printing)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gir.js | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) 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); } // ------------------------------------------------------------------