Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/utils/lib/narwhal/repl.js
blob: 4eab332e14d6730c4bc1d15250b1789bdd2159c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
try {
    var Narcissus = require("narcissus/parse");
} catch(e) {
}

var util = require('util');

var PROMPT_NORMAL       = "js> ",
    PROMPT_INCOMPLETE   = "  > "

var buffer = "";
function readln(input) {
    while (!(/\n/).test(buffer))
        buffer += input.read(100).toString();
        
    var lines = buffer.split("\n"),
        line = lines.shift();

    buffer = lines.join("\n");

    return line
}

exports.repl = function() {

    var buffer = "",
        bufferedLines = [],
        pendingLines = [];
        
    system.stdout.write(PROMPT_NORMAL);
    system.stdout.flush();
    
    while (true) {

        // TODO: replace with real readln
        var line = system.stdin.readLine();
        if (!line) {
            system.stdout.write("\n");
            system.stdout.flush();
            break;
        }
        
        line = util.trimEnd(line);
        var text = pendingLines.join("\n") + "\n" + line;
        if (line == "" || !incomplete(text)) {
            
            pendingLines = [];
                
            try {
                var result = system.evalGlobal(text);
                var repr = util.repr(result);
                if (repr.length > 76 || /\n/.test(repr))
                    repr = String(result);
                if (!util.no(result)) {
                    system.stdout.write(repr + '\n');
                    system.stdout.flush();
                    global._ = result;
                }
            } catch (e) {
                system.stdout.write("    exception from uncaught JavaScript throw: " + e + "\n");
            }
                
        } else
            pendingLines.push(line);
    
        if (pendingLines.length > 0)
            system.stdout.write(PROMPT_INCOMPLETE);
        else
            system.stdout.write(PROMPT_NORMAL);
        system.stdout.flush();

    }
}

function incomplete(text) {
    if (!Narcissus)
        return false;

    var incomp = true;
    try {
        var t = new Narcissus.Tokenizer(text);
        var x = new Narcissus.CompilerContext(false);
        var n = Narcissus.Script(t, x);
        incomp = !t.done;
    } catch (e) {
        if (!t.done) {
            print(e);
            return false;
        }
    }
    return incomp;
}

if (module.id == require.main)
    exports.repl();