-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdemo.js
323 lines (264 loc) · 8.48 KB
/
demo.js
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
'use strict';
let mod = null;
const mod_promise = import('./pkg/cubiml_demo.js').then(
m => (mod = m, mod.default()));
const HTML = `
<style>
#container {
height: 32em;
position: relative;
font: medium monospace;
}
#container.loading {
opacity: 85%;
}
#container form {
margin: 0;
}
#container, #prompt, #editor {
background: darkslategrey;
color: white;
}
#loading {
position: absolute;
top: 15%;
left: 12%;
}
#pane1, #pane2 {
float: left;
width: 50%;
height: 100%;
display: flex;
flex-direction: column;
}
#editor {
height: 100%;
resize: none;
margin: 0;
}
#container .error {
background: darkred;
}
#container pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
margin: 0;
}
#output {
overflow-y: scroll;
}
#input-line {
display: flex;
}
#prompt {
flex-grow: 1;
border: 0;
}
#space-below-prompt {
flex-grow: 1;
}
</style>
<div id=container class=loading>
<div id=loading>Loading, please wait...</div>
<div id=pane1>
<textarea id=editor>
(* calculate fibonacci numbers recursively *)
let fib =
let rec fib_sub = fun {n; a; b} ->
if n <= 1 then
a
else
fib_sub {n=n - 1; a=a + b; b=a}
in
fun n -> fib_sub {n; a=1; b=1};
(* matching on case types *)
let area = fun x ->
match x with
| \`Square x -> x.len *. x.len
| \`Rect x -> x.height *. x.width;
print "area \`Square {len=4.}; =", area \`Square {len=4.};
print "area \`Rect {height=4.; width=2.5}; =", area \`Rect {height=4.; width=2.5};
(* wildcard match delegates to first area function
for the non-Circle cases in a type safe manner *)
let area = fun x ->
match x with
| \`Circle x -> x.radius *. x.radius *. 3.1415926
| x -> area x;
print "area \`Square {len=4.}; =", area \`Square {len=4.};
print "area \`Rect {height=4.; width=2.5}; =", area \`Rect {height=4.; width=2.5};
print "area \`Circle {radius=1.2}; =", area \`Circle {radius=1.2};
(* ints are arbitrary precision *)
(* 999th fibonacci number = 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875 *)
print "fib 999 =", fib 999;
</textarea>
<button id=compile-and-run type=button>Compile and run</button>
</div>
<div id=pane2>
<div id=output>
</div>
<form id=rhs-form>
<pre id=input-line>>> <input id=prompt type="text" autocomplete="off" placeholder="Enter code here or to the left" disabled></pre>
</form>
<div id=space-below-prompt></div>
</div>
</div>
`;
class CubimlDemo extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
// Create a shadow root
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = HTML;
mod_promise.then(
wasm => initializeRepl(shadow, mod.State.new(), Printer)).catch(
e => {shadow.getElementById('loading').textContent = 'Failed to load demo: ' + e});
}
}
customElements.define('cubiml-demo', CubimlDemo);
function initializeRepl(root, compiler, Printer) {
console.log('Initializing REPL');
const container = root.getElementById('container');
const output = root.getElementById('output');
const prompt = root.getElementById('prompt');
const editor = root.getElementById('editor');
function addOutput(line, cls) {
const l = document.createElement('pre');
l.textContent = line;
if (cls) {
l.classList.add(cls);
}
output.appendChild(l);
return l;
}
const $ = Object.create(null);
const history = [];
let history_offset = -1;
function execCode(script) {
let compiled;
try {
if (!compiler.process(script)) {return [false, compiler.get_err()];}
compiled = '(' + compiler.get_output() + ')';
} catch (e) {
return [false, 'Internal compiler error: ' + e.toString()];
}
try {
const p = new Printer;
const val = eval(compiled);
p.visit(val);
return [true, p.parts.join('')];
} catch (e) {
return [false, 'An error occurred during evaluation in the repl: ' + e.toString()];
}
}
function processCode(script) {
const [success, res] = execCode(script);
addOutput(res, success ? 'success' : 'error');
// scroll output window to the bottom
output.scrollTop = output.scrollHeight;
return success;
}
function processReplInput(line) {
line = line.trim();
if (!line) {return;}
history_offset = -1;
if (history[history.length-1] !== line) {history.push(line);}
// \u00a0 = non breaking space
addOutput('>>\u00a0' + line, 'input');
processCode(line);
}
root.getElementById('compile-and-run').addEventListener('click', e => {
const s = editor.value.trim();
if (!s) {return;}
// Clear repl output
output.textContent = '';
compiler.reset();
if (processCode(s)) {prompt.focus({preventScroll: true})}
});
// Implement repl command history
prompt.addEventListener('keydown', e => {
switch (e.key) {
case 'ArrowDown': history_offset -= 1; break;
case 'ArrowUp': history_offset += 1; break;
default: return;
}
e.preventDefault();
if (history_offset >= history.length) {history_offset = history.length - 1;}
if (history_offset < 0) {history_offset = 0;}
prompt.value = history[history.length - history_offset - 1];
});
// If they click in the space below the prompt, focus on the prompt to make it easier to select
root.getElementById('space-below-prompt').addEventListener('click', e => {
e.preventDefault();
prompt.focus({preventScroll: true});
});
root.getElementById('rhs-form').addEventListener('submit', e => {
e.preventDefault();
const s = prompt.value.trim();
prompt.value = '';
if (!s) {return;}
processReplInput(s);
});
container.classList.remove('loading');
prompt.disabled = false;
container.removeChild(root.getElementById('loading'));
console.log('Initialized REPL');
// Run the example code
processCode(editor.value.trim())
}
class Printer {
constructor() {
this.parts = [];
this.seen = new WeakSet;
}
visit(e) {
const type = typeof e;
if (type === 'boolean' || type === 'bigint') {this.parts.push(e.toString()); return;}
if (type === 'string') {this.parts.push(JSON.stringify(e)); return;}
if (type === 'number') {
let s = e.toString();
if (/^-?\d+$/.test(s)) {s += '.0'}
this.parts.push(s);
return;
}
if (type === 'function') {this.parts.push('<fun>'); return;}
if (type === 'symbol') {this.parts.push('<sym>'); return;}
if (e === null) {this.parts.push('null'); return;}
if (e === undefined) {this.parts.push('<undefined>'); return;}
if (this.seen.has(e)) {this.parts.push('...'); return;}
this.seen.add(e);
if (e.$tag) {
this.parts.push(e.$tag);
if (!e.$val || typeof e.$val !== 'object') {
this.parts.push(' ');
}
this.visit(e.$val);
} else if ('$p' in e) {
this.parts.push('ref ');
this.visit(e.$p);
} else {
this.parts.push('{');
let first = true;
for (const [k, v] of Object.entries(e)) {
if (!first) {this.parts.push('; ')}
first = false;
this.parts.push(k + '=');
this.visit(v);
}
this.parts.push('}');
}
}
println(...args) {
for (let arg of args) {
if (typeof arg === 'string') {
this.parts.push(arg);
} else {
this.visit(arg);
}
this.parts.push(' ');
}
this.parts.pop();
this.parts.push('\n');
}
// print(e) {this.visit(e); return this.parts.join('');}
}