/*
 * Whitespace-JS / inst/io.js
 * copyright (c) 2016 Susisu
 */

"use strict";

function end() {
    module.exports = Object.freeze({
        IO,
        PutChar,
        Print,
        GetChar,
        Read
    });
}

const inst = require("./inst.js");

class IO extends inst.Instruction {
    constructor(pos) {
        super(pos);
    }

    toWhitespace() {
        return inst.TAB + inst.LF + this.toSubWhitespace();
    }

    toSubWhitespace() {
        throw new Error("unknown instruction");
    }
}

class PutChar extends IO {
    constructor(pos) {
        super(pos);
    }

    toSubWhitespace() {
        return inst.SPACE + inst.SPACE;
    }

    toUnWhitespace() {
        return "putchar";
    }
}

class Print extends IO {
    constructor(pos) {
        super(pos);
    }

    toSubWhitespace() {
        return inst.SPACE + inst.TAB;
    }

    toUnWhitespace() {
        return "print";
    }
}

class GetChar extends IO {
    constructor(pos) {
        super(pos);
    }

    toSubWhitespace() {
        return inst.TAB + inst.SPACE;
    }

    toUnWhitespace() {
        return "getchar";
    }
}

class Read extends IO {
    constructor(pos) {
        super(pos);
    }

    toSubWhitespace() {
        return inst.TAB + inst.TAB;
    }

    toUnWhitespace() {
        return "read";
    }
}

end();

@@ -214,16 +214,43 @@
  %7D);%0A%7D%0A%0A
+const co = require(%22co%22);%0A%0A
 const in
@@ -276,16 +276,16 @@
 t.js%22);%0A
-
 %0Aclass I
@@ -726,32 +726,138 @@
 %22putchar%22;%0A    %7D
+%0A%0A    doSub(vm) %7B%0A        let c = vm.state.pop(this.pos);%0A        vm.output(String.fromCharCode(c));%0A    %7D
 %0A%7D%0A%0Aclass Print 
@@ -1032,32 +1032,128 @@
 n %22print%22;%0A    %7D
+%0A%0A    doSub(vm) %7B%0A        let n = vm.state.pop(this.pos);%0A        vm.output(n.toString());%0A    %7D
 %0A%7D%0A%0Aclass GetCha
@@ -1336,24 +1336,141 @@
 char%22;%0A    %7D
+%0A%0A    doSub(vm) %7B%0A        return vm.input().then(c =%3E %7B%0A            vm.state.push(c.charCodeAt(0));%0A        %7D);%0A    %7D
 %0A%7D%0A%0Aclass Re
@@ -1617,32 +1617,32 @@
 nWhitespace() %7B%0A
-
         return %22
@@ -1649,23 +1649,352 @@
 read%22;%0A    %7D
+%0A%0A    doSub(vm) %7B%0A        return co(function * () %7B%0A            let str = %22%22;%0A            while (true) %7B%0A                let c = yield vm.input();%0A                if (c === %22%5Cn%22) %7B%0A                    break;%0A                %7D%0A                str += c;%0A            %7D%0A            vm.state.push(parseInt(str) %7C 0);%0A        %7D);%0A    %7D
 %0A%7D%0A%0Aend();%0A

Add IO instructions