-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrepl.js
More file actions
120 lines (106 loc) · 2.5 KB
/
repl.js
File metadata and controls
120 lines (106 loc) · 2.5 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
var REPL = (function () {
var repl_in;
var repl_out;
var ready = false;
var evalList = [];
var evalIndex = 0;
function init(in_textArea, out_div) {
repl_in = in_textArea;
repl_out = out_div;
// INFO(Richo):
// For some reason, the ENTER key must be handled with onkeypress but the
// arrow keys must be handled with onkeyup...
repl_in.onkeypress = function () {
if (event.which === 10 && event.ctrlKey) {
// ENTER
REPL.evaluate();
}
};
repl_in.onkeyup = function () {
if (event.which === 38 && event.ctrlKey) {
// UP
evalIndex--;
update();
} else if (event.which === 40 && event.ctrlKey) {
// DOWN
evalIndex++;
update();
}
};
}
function update() {
if (evalList.length === 0) return;
evalIndex = positiveMod(evalIndex, evalList.length);
repl_in.value = evalList[evalIndex];
}
function positiveMod(a, b) {
return ((a%b)+b)%b;
}
function parse(src) {
if (src === undefined) {
src = repl_in.value;
repl_in.value = "";
}
show(src, JSON.stringify(parser.parse(src)));
}
function compile(src) {
if (src === undefined) {
src = repl_in.value;
repl_in.value = "";
}
show(src, compiler.compile(src));
}
function evaluate(src) {
if (src === undefined) {
src = repl_in.value;
repl_in.value = "";
}
if (!ready) {
var msg = "The system is not initialized yet.";
console.log(msg);
show(src, msg);
return;
}
try {
var result = compiler.evaluate(src);
console.log(result);
show(src, result.receive('toString')().toString());
} catch (ex) {
console.log(ex);
show(src, ex.toString());
}
}
function show(expr, result) {
if (expr.length > 0) {
if (expr !== evalList[evalList.length - 1]) {
evalList.push(expr);
}
evalIndex = evalList.length;
}
var p = document.createElement("p");
split(expr).forEach(function (line, index) {
var exprDiv = document.createElement("div");
exprDiv.setAttribute("class", "expr");
exprDiv.textContent = (index == 0 ? ">> " : " ") + line;
p.appendChild(exprDiv);
});
split(result).forEach(function (line) {
var resDiv = document.createElement("div");
resDiv.setAttribute("class", "result");
resDiv.textContent = line;
p.appendChild(resDiv);
});
repl_out.insertBefore(p, repl_out.firstChild);
}
function split(str) {
return str.match(/[^\r\n]+/g);
}
return {
init: init,
parse: parse,
compile: compile,
evaluate: evaluate,
show: show,
start: function () { ready = true; }
};
})();