-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
921 lines (845 loc) · 37.8 KB
/
index.html
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nada Sandbox</title>
<script>
var favIcon = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAGFBMVEUAAABHcEwAAAAAAAAAAAAAAAAAAAAAAACpMnD0AAAAB3RSTlNjAL+fpPk8rO4B2AAAADNJREFUGJVjYEQDDIxsLMxwwMIGFGBgRwIMOAVYgQBZgAlkHNMgEwB6joUB7E8WiOfQAADiPANLertncwAAAABJRU5ErkJggg==";
var docHead = document.getElementsByTagName('head')[0];
var newLink = document.createElement('link');
newLink.rel = 'shortcut icon';
newLink.type = 'image/x-icon';
newLink.href = 'data:image/png;base64,'+favIcon;
docHead.appendChild(newLink);
</script>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cabin" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css"></link>
<link rel="stylesheet" href="https://codemirror.net/5/addon/scroll/simplescrollbars.css"></link>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/theme/monokai.min.css"></link>
<style>
body { min-width:1200px; font-family:'Cabin',sans-serif; }
#pyscript_loading_splash { }
.container { max-width:1260px; }
main { padding:40px; margin-bottom:46px; }
.flex-equal > * { flex:1; }
@media (min-width: 768px) { .flex-md-equal > * { flex:1; } }
.header { padding-bottom:24px; font-size:18px; }
.header > h2 { margin-bottom:2px; font-weight:400; }
.header > hr { width:100%; margin:0px 0px 6px 0px; border-top:1px solid #000000; opacity:1; }
#manager { padding:6px; }
#permalink { width:100%; border:1px solid #000000; font-size:12px; font-family:Monospace; }
#permalink-copy {
width:100%;
padding:6px 6px 6px 6px;
border:1px solid #000000;
background-color:#0000FF;
font-size:14px;
color:#FFFFFF;
}
#examples {
overflow:hidden;
border:1px solid #000000;
padding:4px;
background-color:#F0F0F0;
font-size:11px;
}
.example { display:none; }
.example-link { cursor:pointer; }
.example-link:hover { background-color:#444444; color:#FFFFFF; cursor:pointer; }
.example-link-selected { background-color:blue; color:#FFFFFF; }
.example-link-selected:hover { background-color:blue; color:#FFFFFF; }
#editor-container { font-size:12px; }
#report-container { position:absolute; border:1px solid #777777; padding:5px; overflow:hidden; }
#report { position:relative; font-family:Monospace; font-size:12px; }
.keyword { font-weight:bold; color:#000000; }
.rules-SyntaxError { background-color:#FFFF00; color:#555555; }
.rules-SyntaxRestriction { background-color:#CCCC00; font-weight:bold; color:#000000; }
.types-TypeError { background-color:#FFCCCB; font-weight:bold; color:#B22222; }
.types-TypeErrorRoot { background-color:#FF0000; font-weight:bold; color:#FFFFFF ; }
.types-str { font-weight:bold; color:#000000; }
.types-int { font-weight:bold; color:#000000; }
.types-Party { font-weight:bold; color:#d45cd6; }
.types-Input { font-weight:bold; color:#DAA520; }
.types-Output { font-weight:bold; color:#DAA520; }
.types-PublicInteger { font-weight:bold; color:#009900; }
.types-SecretInteger { font-weight:bold; color:#0000FF; }
#report > div { height:18px; line-height:18px; white-space:pre; }
#report > div span { padding-top:3px; padding-bottom:3px; line-height:18px; cursor:pointer; }
.detail { cursor:pointer; }
.detail:hover { background-color:#DDDDDD; }
#detail {
display:none;
position:absolute;
height:40px !important;
padding:12px;
background-color:#000000;
color:#FFFFFF;
}
.tooltip { font-size:14px; }
.tooltip table { margin:4px 0px 4px 0px; border:1px solid #888888; }
.tooltip td { padding:6px; border:1px solid #888888; text-align:left; }
.panel-tabs {
display:table-cell;
position:relative;
top:-1px;
width:160px;
padding:0px 0px 12px 5px;
vertical-align:top;
font-size:12px; font-weight:bold;
}
.panel-tab {
position:relative;
left:1px;
margin-top:-1px;
padding:8px;
border-left:1px solid #000000; border-top:1px solid #000000; border-bottom:1px solid #000000;
background-color:#F0F0F0;
line-height:16px;
cursor:pointer;
}
.panel-tab > hr { margin:4px 0px 4px 0px; }
.panel-tab-inactive > hr { display:none; }
.panel-tab-inactive > span { display:none; }
.panel-tab-inactive { left:5px; width:150px; background-color:#D0D0D0; }
.panel-tab-inactive:hover { background-color:#FFFFFF; }
.panel {
min-height:300px;
width:100%;
padding:8px;
border-left:1px solid #000000; border-right:1px solid #000000; border-bottom:1px solid #000000;
background-color:#F0F0F0;
}
#interpreter > div { display:inline-flex; width:100%; }
.panel-io { width:50%; margin:4px; }
.panel-io table {
width:100%;
border:1px solid #BBBBBB;
background-color:#FFFFFF;
font-family:Monospace;
font-size:12px;
font-weight:bold;
}
.panel-io td { height:32px; padding:4px; border:1px solid #BBBBBB; }
.panel-io input { border:1px solid #000000; }
.toggle {
position:relative; top:1px;
display:inline-block;
height:39px;
width:25%;
border-top:1px solid #BBBBBB; border-left:1px solid #BBBBBB; border-right:1px solid #BBBBBB;
padding:8px 8px 12px 8px;
background-color:#FFFFFF;
font-size:12px;
font-weight:bold;
cursor:pointer;
}
.toggle:hover { background-color:#444444; color:#FFFFFF; }
.toggle-selected { height:40px; }
.textarea-json {
height:300px;
width:100%;
border:1px solid #BBBBBB;
font-family:Monospace;
font-size:12px;
}
#feedback-console {
width:100%;
padding:10px;
background-color:rgb(39,40,34);
white-space:pre-wrap;
font-family:Monospace;
font-size:12px;
color:#FFFFFF;
}
#feedback-console .information { color:#FFFFFF; }
#feedback-console .success { color:#00FF00; }
#feedback-console .warning { color:#00FFFF; }
#feedback-console .error { color:#FF0000; }
.no-select {
-webkit-touch-callout:none; /* iOS Safari */
-webkit-user-select:none; /* Safari */
-khtml-user-select:none; /* Konqueror HTML */
-moz-user-select:none; /* Old versions of Firefox */
-ms-user-select:none; /* Internet Explorer/Edge */
user-select:none; /* Non-prefixed version, currently
supported by Chrome, Edge, Opera and Firefox */
}
.CodeMirror-overlayscroll-vertical { width:10px; }
.CodeMirror-overlayscroll-horizontal { height:10px; }
.CodeMirror-scrollbar-filler { background-color:#777777;}
</style>
</head>
<body>
<main>
<div>
<div class="header no-select" id="header">
<h2><b>Nada</b> Sandbox</h2>
<hr/>
<span>Write, analyze, and simulate Nada programs in your browser.</span>
</div>
<div style="display:table; width:100%;">
<div style="display:table-row; width:100%;">
<div style="display:table-cell; width:160px;">
<div id="manager">
<div style="position:relative; top:5px;">
<button id="permalink-copy">
Copy permanent link to clipboard
</button>
<input id="permalink" type="text" onclick="this.select();" />
</div>
<br/>
<div id="examples">
<b>Select an example:</b>
<hr style="margin:4px 0px 4px 0px;"/>
</div>
</div>
</div>
<div style="display:table-cell; width:calc(100% - 160px);" id="views">
<div style="display:table;">
<div style="display:table-row;">
<div id="editor-container" style="display:table-cell; width:50%;">
<textarea id="editor"></textarea>
</div>
<div id="report-container" style="display:table-cell;">
<textarea id="payload" style="display:none;"></textarea>
<div id="report" style="font-family:Monospace; text-align:left;">loading</div>
</div>
</div>
</div>
<py-config>
packages = ["parsial~=0.1", "richreports~=0.2", "asttokens~=2.4"]
[[fetch]]
files = ['nada_audit.py']
</py-config>
<section class="pyscript">
<py-script>
from js import document
from pyodide.ffi import create_proxy, to_js
import types
import json
import ast
import inspect
import asttokens
from nada_audit import *
def update(_):
messages = []
source = \
document.getElementById('payload').innerHTML \
.replace('&' + 'amp;', '&') \
.replace('&' + 'lt;', '<') \
.replace('&' + 'gt;', '>')
# Perform static analyses and render the report.
try:
messages.append(['Information', 'Auditing.'])
lines = source.split('\n')
report = audit(source)
rlines = report.render().split('\n')
js.reportDisplay(to_js(rlines))
messages.append(
['Success', 'Auditing step completed.']
)
except Exception as e:
messages.append(
['Error', type(e).__name__ + ": " + str(e)]
)
# Perform abstract interpretation to determine inputs
# and then simulate the program on the inputs (either
# randomly generated or user-supplied).
try:
messages.append(['Information', 'Executing.'])
ins = js.interpreterInputsRetrieve().to_py()
context = {}
Abstract.initialize({k: v for (k, [v, _]) in ins.items()})
exec(source, context)
outs = context['nada_main']()
if len(outs) > 0:
js.interpreterInputsShow(to_js([[i.name, i.ty_str] for i in outs[0].inputs]))
js.interpreterOutputsShow(
to_js([[o.name, o.value.value] for o in outs[0].outputs])
)
messages.append(
['Success', 'Execution completed.']
)
except Exception as e:
messages.append(
['Error', type(e).__name__ + ": " + str(e)]
)
# Display all feedback messages collected during the update.
js.feedbackDisplay(to_js(messages));
document.addEventListener('update', create_proxy(update))
pyscript.write('report', 'ready')
js.resize()
js.update()
</py-script>
</section>
</div>
</div>
<div style="display:table-row; width:100%;">
<div class="panel-tabs" id="panels"></div>
<div style="display:table-cell; width:calc(100% - 160px);">
<div class="panel" id="interpreter">
<div>
<div class="panel-io">
<div class="toggle toggle-selected" id="toggle-inputs" onclick="interpreter.toggleInputs('inputs');">Interactive Table</div>
<div class="toggle" id="toggle-inputs-json" onclick="interpreter.toggleInputs('inputs-json');">JSON</div>
<div class="toggle" id="toggle-inputs-json-schema" onclick="interpreter.toggleInputs('inputs-json-schema');">JSON Schema</div>
<div id="inputs"></div>
<textarea class="textarea-json" id="inputs-json" style="display:none;" readonly></textarea>
<textarea class="textarea-json" id="inputs-json-schema" style="display:none;" readonly></textarea>
</div>
<div class="panel-io">
<div class="toggle toggle-selected" id="toggle-outputs-interpreter" onclick="interpreter.toggleOutputs('outputs-interpreter');">Interpreter</div>
<div class="toggle" id="toggle-outputs-simulator" onclick="interpreter.toggleOutputs('outputs-simulator');">Simulator</div>
<div id="outputs-interpreter"></div>
<div id="outputs-simulator" style="display:none;">
<iframe src="jsnadac.html" style="height:300px; width:100%; border:1px solid #BBBBBB;"></iframe>
</div>
</div>
</div>
</div>
<!--div class="panel" id="metrics">
</div-->
<div class="panel" id="feedback">
<div id="feedback-console"></div>
</div>
</div>
</div>
</div>
</div>
</main>
<footer class="text-center text-lg-start bg-light text-muted fixed-bottom">
<div class="text-center p-4" style="background-color:rgb(0,0,255);">
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js"></script>
<script type="text/javascript" src="https://codemirror.net/5/addon/scroll/simplescrollbars.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/python/python.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<script>
class Manager {
constructor (elementId, width, editor) {
this.element = document.getElementById(elementId);
this.width = width;
this.editor = editor;
}
sizeUpdate () {
this.element.setAttribute("style", "width:" + this.width + "px");
this.element.parentElement.setAttribute("style", "width:" + this.width + "px");
}
buildExampleMenu () {
// Build links to load example programs.
const textareas = document.querySelectorAll('.example');
const links = document.getElementById('examples');
for (let i = 0; i < textareas.length; i++) {
const div = document.createElement("div");
div.appendChild(document.createTextNode(textareas[i].id));
div.classList.add("example-link");
if (i == 0) {
div.classList.add("example-link-selected");
}
const self = this;
div.onclick = function () {
const links_ = document.querySelectorAll('.example-link');
for (let j = 0; j < links_.length; j++) {
links_[j].className = "example-link";
}
div.classList.add("example-link-selected");
self.editor.codeMirror.setValue(document.getElementById(textareas[i].id).innerText);
update();
};
links.appendChild(div);
}
}
buildPermalinkButton () {
// Add event handler for link generator.
const self = this;
document.querySelector("#permalink-copy").addEventListener("click", async function () {
// Based on example at:
// https://dev.to/samternent/json-compression-in-the-browser-with-gzip-and-the-compression-streams-api-4135
const stream = new Blob([self.editor.codeMirror.getValue()], {type: 'text/plain'}).stream();
const compressedReadableStream = stream.pipeThrough(new CompressionStream("gzip"));
const compressedResponse = await new Response(compressedReadableStream);
const blob = await compressedResponse.blob();
const buffer = await blob.arrayBuffer();
const compressedBase64 = encodeURIComponent(btoa(String.fromCharCode( ...new Uint8Array(buffer))));
document.getElementById("permalink").value = (
location.protocol + '//' + location.host + location.pathname +
'?s=' + compressedBase64 // For no compression: btoa(self.editor.codeMirror.getValue())
);
document.querySelector("#permalink").select();
document.execCommand("copy");
});
}
async loadInitialSource () {
// Load the default example (or decode the supplied permalink).
let value = document.getElementById("multiplication_mixed_simple").innerText;
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('s')) {
// Based on example at:
// https://dev.to/samternent/json-compression-in-the-browser-with-gzip-and-the-compression-streams-api-4135
function b64decode(str) {
const binary_string = window.atob(str);
const len = binary_string.length;
const bytes = new Uint8Array(new ArrayBuffer(len));
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes;
}
const compressed = b64decode(decodeURIComponent(urlParams.get('s')));
const stream = new Blob([compressed], {type: "text/plain"}).stream();
const compressedReadableStream = stream.pipeThrough(new DecompressionStream("gzip"));
const resp = await new Response(compressedReadableStream);
const blob = await resp.blob();
value = await blob.text(); // For no compression: atob(b64compressed);
// Ensure that none of the example links are highlighted.
const links = document.querySelectorAll('.example-link');
for (let i = 0; i < links.length; i++) {
links[i].classList.remove("example-link-selected");
}
}
this.editor.codeMirror.setValue(value);
}
}
class Editor {
constructor (elementId, lines, sidebar, update) {
this.element = document.getElementById(elementId);
this.lines = lines; // Number of lines displayed in interactive editor.
this.sidebar = sidebar; // Width of sidebar in pixels.
// Creaete and configure CodeMirror instance.
this.codeMirror = new CodeMirror.fromTextArea(
this.element,
{
lineNumbers: true,
viewportMargin: 2, // Use `Infinity` when disabling scroll.
scrollbarStyle: "overlay",
tabSize: 4,
mode: "python",
theme: "monokai"
}
);
// Add event handlers to CodeMirror instance.
this.codeMirror.on("keyup", update);
this.codeMirror.on("mousemove", update);
let scrollElement = this.codeMirror.getScrollerElement();
scrollElement.addEventListener('mousemove', update);
scrollElement.addEventListener('scroll', update);
this.sizeUpdate(); // Calculate and set the initial size.
}
sizeUpdate () {
const height = (18 * this.lines) + 7;
const width = (document.getElementById("header").offsetWidth - this.sidebar) / 2;
this.element.style.width = width + "px";
const codeMirrorElement = document.getElementsByClassName("CodeMirror")[0];
codeMirrorElement.style.width = width + "px";
this.codeMirror.setSize(width, height);
this.height = this.element.offsetHeight;
this.width = width;
}
}
class Report {
constructor (elementId, editor) {
this.element = document.getElementById(elementId);
this.cache = {'source': null, 'analyses': null, 'report': null, 'rlines': null};
this.editor = editor;
this.sizeUpdate(); // Calculate and set the initial size.
}
sizeUpdate () {
const height = this.editor.height, width = this.editor.width;
this.element.parentElement.style.height = '493px';
this.element.parentElement.style.width = width + 'px';
this.element.style.height = '493px';
this.element.style.width = width + 'px';
}
display (rlines) {
// Use cached HTMl content if there is no updated data.
if (rlines == null) {
rlines = this.cache.rlines;
} else {
this.cache.rlines = rlines;
this.cache.report = {};
}
// Configure visual properties and content for report.
const horizontalScroll = this.editor.codeMirror.getScrollInfo().left;
document.getElementById("report").setAttribute("style", "left:-" + horizontalScroll + "px");
const scrollTop = $(window).scrollTop();
const codeTop = document.querySelector(".CodeMirror-code").getBoundingClientRect().top;
const rowFirst = 0 + Math.round(
.5 + .77777 + 7 + this.editor.codeMirror.getViewport().from - ((codeTop + scrollTop) / 18)
);
// Build and display the report HTML.
let linesOutput = [];
for (let i = rowFirst; i < Math.min(rlines.length, rowFirst + this.editor.lines); i++) {
const row = i + 1;
if (row in this.cache.report) {
linesOutput.push(this.cache.report[row]);
} else {
const html = rlines[i];
linesOutput.push(html);
this.cache.report[row] = html;
}
}
document.getElementById("report").innerHTML = '<div id="detail"></div>' + linesOutput.join("");
// Set up event handlers for detail tooltips.
const elements = document.getElementsByClassName("detail");
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
element.addEventListener("mouseover", function (event) {
const detail = document.getElementById("detail");
detail.style.display = "block";
detail.style.top = element.offsetTop + 24 + "px";
detail.style.left = (
element.offsetLeft +
element.getBoundingClientRect().width -
16
) + "px";
detail.innerHTML = element.dataset.detail;
});
element.addEventListener("mouseout", function (event) {
const detail = document.getElementById("detail");
detail.style.display = "none";
});
}
}
}
class Interpreter {
constructor (elementId) {
this.element = document.getElementById(elementId);
this.cache = {'inputs': {}, 'signature': null };
}
sizeUpdate (factor) {
const width = (document.getElementById("header").offsetWidth - this.sidebar);
this.element.style.width = width + "px";
}
toggleInputs (id) {
document.getElementById("inputs").style.display = "none";
document.getElementById("inputs-json").style.display = "none";
document.getElementById("inputs-json-schema").style.display = "none";
document.getElementById("toggle-inputs").classList.remove("toggle-selected");
document.getElementById("toggle-inputs-json").classList.remove("toggle-selected");
document.getElementById("toggle-inputs-json-schema").classList.remove("toggle-selected");
document.getElementById(id).style.display = "block";
document.getElementById("toggle-" + id).classList.add("toggle-selected");
}
toggleOutputs (id) {
document.getElementById("outputs-interpreter").style.display = "none";
document.getElementById("outputs-simulator").style.display = "none";
document.getElementById("toggle-outputs-interpreter").classList.remove("toggle-selected");
document.getElementById("toggle-outputs-simulator").classList.remove("toggle-selected");
document.getElementById(id).style.display = "block";
document.getElementById("toggle-" + id).classList.add("toggle-selected");
}
inputsRetrieve () {
let inputs = {};
const elements = document.getElementsByClassName("input");
const elementsTypes = document.getElementsByClassName("input-type");
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
inputs[element.id] = [null, null];
inputs[element.id][0] = parseInt(element.value);
}
for (let i = 0; i < elementsTypes.length; i++) {
const element = elements[i];
inputs[element.id][1] = elementsTypes[i].innerHTML;
}
return inputs;
}
inputsShow (ins) {
const signature = ins.join(',');
if (signature == this.cache.signature) {
return;
} else {
this.cache.signature = signature;
}
let inputsJSON = "";
let inputsJSONSchema = {"$schema": "https://json-schema.org/draft/2019-09/schema", "type": "object", "properties": {}};
const element = document.getElementById("inputs");
element.innerHTML = "";
const table = document.createElement("table");
table.innerHTML = "<tr><td>Input Name</td><td>Input Value</td><td>Type</td></tr>";
for (let i = 0; i < ins.length; i++) {
const tr = document.createElement("tr");
const tdName = document.createElement("td");
const name = ins[i][0];
tdName.innerHTML = name;
const tdValue = document.createElement("td");
if (!(name in this.cache.inputs)) {
this.cache.inputs[name] = 1 + Math.floor(Math.random() * 255);
}
const value = this.cache.inputs[name];
tdValue.innerHTML = '<input class="input" id="' + name + '" type="number" value="' + value + '"/>';
const tdType = document.createElement("td");
tdType.classList.add("input-type");
tdType.innerHTML = ins[i][1];
tr.appendChild(tdName);
tr.appendChild(tdValue);
tr.appendChild(tdType);
table.appendChild(tr);
inputsJSON += " \"" + name + "\": " +
JSON.stringify({"value": value, "type": ins[i][1]}, null, 2).replace(/\n/g, '').replace(/\s\s/g, '') +
((i == ins.length - 1) ? "" : ",") + "\n";
inputsJSONSchema["properties"][name] = {
"type": "object",
"properties": {
"value": {"type": "integer", "minimum": 1, "maximumExclusive": "2147483647"},
"type": {"oneOf": [{"const": "PublicInteger"}, {"const": "SecretInteger"}]}
}
};
}
element.appendChild(table);
document.getElementById("inputs-json").value = "{\n" + inputsJSON + "}";
document.getElementById("inputs-json-schema").value = JSON.stringify(inputsJSONSchema, null, 2);
const elements = document.getElementsByClassName("input");
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
const self = this;
const upd = function () {
self.cache.inputs[element.id] = parseInt(element.value);
update(true);
};
element.addEventListener("keyup", upd);
element.addEventListener("change", upd);
}
}
outputsShow (outs) {
const element = document.getElementById("outputs-interpreter");
element.innerHTML = "";
const table = document.createElement("table");
table.innerHTML = "<tr><td>Output Name</td><td>Output Value</td></tr>"
for (let i = 0; i < outs.length; i++) {
const tr = document.createElement("tr");
const tdName = document.createElement("td");
tdName.innerHTML = outs[i][0];
const tdValue = document.createElement("td");
tdValue.innerHTML = outs[i][1];
tr.appendChild(tdName);
tr.appendChild(tdValue);
table.appendChild(tr);
}
element.appendChild(table);
}
}
class Panels {
constructor (elementId, tabs) {
this.element = document.getElementById(elementId);
this.panels = [];
let first = true;
for (let id in tabs) {
const tab = tabs[id];
const panel = document.getElementById(id);
this.panels.push(panel);
const div = document.createElement("div");
div.id = "panel-tab-" + id;
div.innerHTML = "<b>" + tab.title + "</b>";
const self = this;
div.onclick = function () { self.click(div, panel); };
if ("description" in tab) {
div.innerHTML += "<hr/><span>" + tab.description + "</span>";
}
div.classList.add("panel-tab");
div.classList.add("no-select");
if (!first) {
div.classList.add("panel-tab-inactive");
panel.style.display = "none";
}
first = false;
this.element.appendChild(div);
}
}
click (tab, panel) {
const tabs = document.querySelectorAll(".panel-tab");
for (let i = 0; i < tabs.length; i++) {
tabs[i].classList.add("panel-tab-inactive");
}
tab.classList.remove("panel-tab-inactive");
for (let i = 0; i < this.panels.length; i++) {
this.panels[i].style.display = "none";
}
panel.style.display = "block";
}
}
class Feedback {
constructor (elementId) {
this.element = document.getElementById(elementId);
this.console = document.getElementById(elementId + "-console");
}
display (messages) {
this.console.innerHTML = "";
for (let i = 0; i < messages.length; i++) {
const div = document.createElement("div");
const cls = messages[i][0];
const txt = messages[i][1];
div.innerHTML = (
(cls != "Information" ? '<b class="' + cls.toLowerCase() + '">' + cls + '</b>: ' : "") +
txt
);
this.console.appendChild(div);
}
}
}
function update(force) {
// General update of the entire workspace (called at every keyboard/scroll event,
// and also programmatically).
//$('.tooltip').remove();
const source = editor.codeMirror.getValue();
if (report.cache.analyses == null || source != report.cache.source || force) {
report.cache.source = source;
document.getElementById('payload').innerHTML = editor.codeMirror.getValue();
document.dispatchEvent(new CustomEvent('update'));
} else {
report.display();
}
// Update the permanent link.
document.getElementById("permalink").value = (
location.protocol + '//' + location.host + location.pathname +
'?s=' + btoa(editor.codeMirror.getValue())
);
}
function resize() {
manager.sizeUpdate();
editor.sizeUpdate();
report.sizeUpdate();
interpreter.sizeUpdate();
}
window.onload = async function () {
const editorHeight = 27; // Vertical height of editor in lines.
const managerWidth = 160; // Width of manager sidebar in pixels.
// Create all interactive components.
editor = new Editor("editor", editorHeight, managerWidth, update);
report = new Report("report", editor);
interpreter = new Interpreter("interpreter");
feedback = new Feedback("feedback");
manager = new Manager("manager", managerWidth, editor);
// Add tabbed panel dashboard.
panels = new Panels("panels", {
"interpreter": {
"title": "Interpreter & Inputs/Outputs",
"description": (
"Input boxes are generated automatically from the source. Editing inputs updates " +
"outputs via execution or simulation (as selected)."
)
},
/* "metrics": {
"title": "Cost Analysis"
},*/
"feedback": {
"title": "Status, Warnings, & Errors"
}
});
// Resize components on window resize.
window.addEventListener('resize', resize, true);
// Initialize and perform an initial update (in case working code is already present).
manager.buildPermalinkButton();
manager.buildExampleMenu();
manager.loadInitialSource();
resize();
update();
}
// Globals and wrappers for Python and iframe.
let editor = null;
let report = null;
let interpreter = null;
let feedback = null;
let manager = null;
let panels = null;
function reportDisplay(rlines) { report.display(rlines); }
function interpreterInputsRetrieve() { return interpreter.inputsRetrieve(); }
function interpreterInputsShow(ins) { interpreter.inputsShow(ins); }
function interpreterOutputsShow(outs) { interpreter.outputsShow(outs); }
function feedbackDisplay(messages) { feedback.display(messages); }
function editorValue() { return editor.codeMirror.getValue().replace("nada_audit", "nada_dsl"); }
</script>
<pre class="example" id="multiplication_mixed_simple">
# The left-hand panel can scrolled and edited. The right-hand
# panel will automatically be updated with the results of the
# type checking and cost calculation static analyses. Green
# represents public Nada expressions/values and blue represents
# secret Nada expressions/values.
# On the right-hand panel, hover over variable names to see a
# count of the total number of *secret* operations that must be
# executed to determine the value of that variable at that point
# in the program. There is no deduplication (as in the current
# implementation).
from nada_audit import *
def nada_main():
party1 = Party(name="Party1")
my_int1 = PublicInteger(Input(name="my_int1", party=party1))
my_int2 = SecretInteger(Input(name="my_int2", party=party1))
new_int = my_int1 * my_int2
return [Output(new_int, "my_output", party1)]
</pre>
<pre class="example" id="multiplication_mixed_larger">
from nada_audit import *
def nada_main():
p1 = Party("Party1")
p2 = Party("Party2")
p3 = Party("Party3")
p4 = Party("Party4")
a = PublicInteger(Input("a", p1))
b = SecretInteger(Input("b", p1))
c = PublicInteger(Input("c", p2))
d = SecretInteger(Input("d", p2))
e = PublicInteger(Input("e", p3))
f = SecretInteger(Input("f", p3))
g = a * b * c * d * e * f
return [Output(g, "g", p4)]
</pre>
<pre class="example" id="voting-functional-style">
from nada_audit import *
def nada_main():
voters = [Party("Party" + str(v)) for v in range(2)]
outparty = Party(name="OutParty")
votes_per_candidate = [
[
SecretInteger(
Input(
name="v" + str(v) + "_c" + str(c),
party=Party("Party" + str(v))
)
)
for v in range(2)
]
for c in range(4)
]
return [
Output(sum(votes_per_candidate[c]), "c" + str(c), outparty)
for c in range(4)
]
</pre>
<pre class="example" id="voting-imperative-style">
# In this example, note that empty lists must be accompanied by an explicit
# type annotation.
from nada_audit import *
def nada_main():
# Create the voter parties and recipient party.
voters: list[Party] = []
for v in range(2):
voters.append(Party("Party" + str(v)))
outparty = Party(name="OutParty")
# Gather the inputs (one vote for each candidate from each voter).
votes_per_candidate: list[list[SecretInteger]] = []
for c in range(4):
votes_per_candidate.append([])
for v in range(2):
votes_per_candidate[c].append(SecretInteger(
Input(
name="v" + str(v) + "_c" + str(c),
party=Party("Party" + str(v))
)
))
# Calculate the total for each candidate.
outputs: list[Output] = []
for c in range(4):
outputs.append(Output(sum(votes_per_candidate[c]), "c" + str(c), outparty))
return outputs
</pre>
</body>
</html>