-
Notifications
You must be signed in to change notification settings - Fork 924
/
edu-python.js
1202 lines (974 loc) · 39.1 KB
/
edu-python.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
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Online Python Tutor
Copyright (C) 2010-2011 Philip J. Guo (philip@pgbovine.net)
https://github.com/pgbovine/OnlinePythonTutor/
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// code that is common to all Online Python Tutor pages
var appMode = 'edit'; // 'edit', 'visualize', or 'grade' (only for question.html)
// set to true to use jsPlumb library to render connections between
// stack and heap objects
var useJsPlumbRendering = true;
// if true, then render the stack as growing downwards
// (if useJsPlumbRendering is true)
var stackGrowsDown = true;
/* colors - see edu-python.css */
var lightYellow = '#F5F798';
var lightLineColor = '#FFFFCC';
var errorColor = '#F87D76';
var visitedLineColor = '#3D58A2';
var lightGray = "#cccccc";
//var lightGray = "#dddddd";
var darkBlue = "#3D58A2";
var lightBlue = "#899CD1";
var pinkish = "#F15149";
var darkRed = "#9D1E18";
// ugh globals!
var curTrace = null;
var curInstr = 0;
// true iff trace ended prematurely since maximum instruction limit has
// been reached
var instrLimitReached = false;
function assert(cond) {
if (!cond) {
alert("Error: ASSERTION FAILED");
}
}
// taken from http://www.toao.net/32-my-htmlspecialchars-function-for-javascript
function htmlspecialchars(str) {
if (typeof(str) == "string") {
str = str.replace(/&/g, "&"); /* must do & first */
// ignore these for now ...
//str = str.replace(/"/g, """);
//str = str.replace(/'/g, "'");
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
// replace spaces:
str = str.replace(/ /g, " ");
}
return str;
}
function processTrace(traceData, jumpToEnd) {
curTrace = traceData;
curInstr = 0;
// delete all stale output
$("#pyStdout").val('');
if (curTrace.length > 0) {
var lastEntry = curTrace[curTrace.length - 1];
// GLOBAL!
instrLimitReached = (lastEntry.event == 'instruction_limit_reached');
if (instrLimitReached) {
curTrace.pop() // kill last entry
var warningMsg = lastEntry.exception_msg;
$("#errorOutput").html(htmlspecialchars(warningMsg));
$("#errorOutput").show();
}
// as imran suggests, for a (non-error) one-liner, SNIP off the
// first instruction so that we start after the FIRST instruction
// has been executed ...
else if (curTrace.length == 2) {
curTrace.shift();
}
if (jumpToEnd) {
// if there's an exception, then jump to the FIRST occurrence of
// that exception. otherwise, jump to the very end of execution.
curInstr = curTrace.length - 1;
for (var i = 0; i < curTrace.length; i++) {
var curEntry = curTrace[i];
if (curEntry.event == 'exception' ||
curEntry.event == 'uncaught_exception') {
curInstr = i;
break;
}
}
}
}
updateOutput();
}
function highlightCodeLine(curLine, visitedLinesSet, hasError, isTerminated) {
var tbl = $("table#pyCodeOutput");
// reset then set:
tbl.find('td.lineNo').css('color', '');
tbl.find('td.lineNo').css('font-weight', '');
$.each(visitedLinesSet, function(k, v) {
tbl.find('td.lineNo:eq(' + (k - 1) + ')').css('color', visitedLineColor);
tbl.find('td.lineNo:eq(' + (k - 1) + ')').css('font-weight', 'bold');
});
var lineBgCol = lightLineColor;
if (hasError) {
lineBgCol = errorColor;
}
// put a default white top border to keep space usage consistent
tbl.find('td.cod').css('border-top', '1px solid #ffffff');
if (!hasError && !isTerminated) {
tbl.find('td.cod:eq(' + (curLine - 1) + ')').css('border-top', '1px solid #F87D76');
}
tbl.find('td.cod').css('background-color', '');
if (!isTerminated || hasError) {
tbl.find('td.cod:eq(' + (curLine - 1) + ')').css('background-color', lineBgCol);
}
else if (isTerminated) {
tbl.find('td.cod:eq(' + (curLine - 1) + ')').css('background-color', lightBlue);
}
}
// relies on curTrace and curInstr globals
function updateOutput() {
if (!curTrace) {
return;
}
useJsPlumbRendering = !($("#classicModeCheckbox").prop("checked"));
var curEntry = curTrace[curInstr];
var hasError = false;
// render VCR controls:
var totalInstrs = curTrace.length;
// to be user-friendly, if we're on the LAST instruction, print "Program has terminated"
// and DON'T highlight any lines of code in the code display
if (curInstr == (totalInstrs-1)) {
if (instrLimitReached) {
$("#vcrControls #curInstr").html("Instruction limit reached");
}
else {
$("#vcrControls #curInstr").html("Program has terminated");
}
}
else {
$("#vcrControls #curInstr").html("About to do step " + (curInstr + 1) + " of " + (totalInstrs-1));
}
$("#vcrControls #jmpFirstInstr").attr("disabled", false);
$("#vcrControls #jmpStepBack").attr("disabled", false);
$("#vcrControls #jmpStepFwd").attr("disabled", false);
$("#vcrControls #jmpLastInstr").attr("disabled", false);
if (curInstr == 0) {
$("#vcrControls #jmpFirstInstr").attr("disabled", true);
$("#vcrControls #jmpStepBack").attr("disabled", true);
}
if (curInstr == (totalInstrs-1)) {
$("#vcrControls #jmpLastInstr").attr("disabled", true);
$("#vcrControls #jmpStepFwd").attr("disabled", true);
}
// render error (if applicable):
if (curEntry.event == 'exception' ||
curEntry.event == 'uncaught_exception') {
assert(curEntry.exception_msg);
if (curEntry.exception_msg == "Unknown error") {
$("#errorOutput").html('Unknown error: Please email a bug report to philip@pgbovine.net');
}
else {
$("#errorOutput").html(htmlspecialchars(curEntry.exception_msg));
}
$("#errorOutput").show();
hasError = true;
}
else {
if (!instrLimitReached) { // ugly, I know :/
$("#errorOutput").hide();
}
}
// render code output:
if (curEntry.line) {
// calculate all lines that have been 'visited'
// by execution up to (but NOT INCLUDING) curInstr:
var visitedLinesSet = {}
for (var i = 0; i < curInstr; i++) {
if (curTrace[i].line) {
visitedLinesSet[curTrace[i].line] = true;
}
}
highlightCodeLine(curEntry.line, visitedLinesSet, hasError,
/* if instrLimitReached, then treat like a normal non-terminating line */
(!instrLimitReached && (curInstr == (totalInstrs-1))));
}
// render stdout:
// keep original horizontal scroll level:
var oldLeft = $("#pyStdout").scrollLeft();
$("#pyStdout").val(curEntry.stdout);
$("#pyStdout").scrollLeft(oldLeft);
// scroll to bottom, tho:
$("#pyStdout").scrollTop($("#pyStdout").attr('scrollHeight'));
// finally, render all the data structures!!!
renderDataStructures(curEntry, "#dataViz");
}
// Renders the current trace entry (curEntry) into the div named by vizDiv
function renderDataStructures(curEntry, vizDiv) {
if (useJsPlumbRendering) {
renderDataStructuresVersion2(curEntry, vizDiv);
}
else {
renderDataStructuresVersion1(curEntry, vizDiv);
}
}
// The ORIGINAL "1.0" version of renderDataStructures, which renders
// variables and values INLINE within each stack frame without any
// explicit representation of data structure aliasing.
//
// This version was originally created in January 2010
function renderDataStructuresVersion1(curEntry, vizDiv) {
// render data structures:
$(vizDiv).empty(); // jQuery empty() is better than .html('')
// render locals on stack:
if (curEntry.stack_locals != undefined) {
$.each(curEntry.stack_locals, function (i, frame) {
var funcName = htmlspecialchars(frame[0]); // might contain '<' or '>' for weird names like <genexpr>
var localVars = frame[1];
$(vizDiv).append('<div class="vizFrame">Local variables for <span style="font-family: Andale mono, monospace;">' + funcName + '</span>:</div>');
// render locals in alphabetical order for tidiness:
var orderedVarnames = [];
// use plain ole' iteration rather than jQuery $.each() since
// the latter breaks when a variable is named "length"
for (varname in localVars) {
orderedVarnames.push(varname);
}
orderedVarnames.sort();
if (orderedVarnames.length > 0) {
$(vizDiv + " .vizFrame:last").append('<br/><table class="frameDataViz"></table>');
var tbl = $("#pyOutputPane table:last");
$.each(orderedVarnames, function(i, varname) {
var val = localVars[varname];
tbl.append('<tr><td class="varname"></td><td class="val"></td></tr>');
var curTr = tbl.find('tr:last');
if (varname == '__return__') {
curTr.find("td.varname").html('<span style="font-size: 10pt; font-style: italic;">return value</span>');
}
else {
curTr.find("td.varname").html(varname);
}
renderData(val, curTr.find("td.val"), false);
});
tbl.find("tr:last").find("td.varname").css('border-bottom', '0px');
tbl.find("tr:last").find("td.val").css('border-bottom', '0px');
}
else {
$(vizDiv + " .vizFrame:last").append(' <i>none</i>');
}
});
}
// render globals LAST:
$(vizDiv).append('<div class="vizFrame">Global variables:</div>');
var nonEmptyGlobals = false;
var curGlobalFields = {};
if (curEntry.globals != undefined) {
// use plain ole' iteration rather than jQuery $.each() since
// the latter breaks when a variable is named "length"
for (varname in curEntry.globals) {
curGlobalFields[varname] = true;
nonEmptyGlobals = true;
}
}
if (nonEmptyGlobals) {
$(vizDiv + " .vizFrame:last").append('<br/><table class="frameDataViz"></table>');
// render all global variables IN THE ORDER they were created by the program,
// in order to ensure continuity:
//
// TODO: in the future, the back-end can actually pre-compute this
// list so that the front-end doesn't have to do any extra work!
var orderedGlobals = []
// iterating over ALL instructions (could be SLOW if not for our optimization below)
for (var i = 0; i <= curInstr; i++) {
// some entries (like for exceptions) don't have GLOBALS
if (curTrace[i].globals == undefined) continue;
// use plain ole' iteration rather than jQuery $.each() since
// the latter breaks when a variable is named "length"
for (varname in curTrace[i].globals) {
// eliminate duplicates (act as an ordered set)
if ($.inArray(varname, orderedGlobals) == -1) {
orderedGlobals.push(varname);
curGlobalFields[varname] = undefined; // 'unset it'
}
}
var earlyStop = true;
// as an optimization, STOP as soon as you've found everything in curGlobalFields:
for (o in curGlobalFields) {
if (curGlobalFields[o] != undefined) {
earlyStop = false;
break;
}
}
if (earlyStop) {
break;
}
}
var tbl = $("#pyOutputPane table:last");
// iterate IN ORDER (it's possible that not all vars are in curEntry.globals)
$.each(orderedGlobals, function(i, varname) {
var val = curEntry.globals[varname];
// (use '!==' to do an EXACT match against undefined)
if (val !== undefined) { // might not be defined at this line, which is OKAY!
tbl.append('<tr><td class="varname"></td><td class="val"></td></tr>');
var curTr = tbl.find('tr:last');
curTr.find("td.varname").html(varname);
renderData(val, curTr.find("td.val"), false);
}
});
tbl.find("tr:last").find("td.varname").css('border-bottom', '0px');
tbl.find("tr:last").find("td.val").css('border-bottom', '0px');
}
else {
$(vizDiv + " .vizFrame:last").append(' <i>none</i>');
}
}
// make sure varname doesn't contain any weird
// characters that are illegal for CSS ID's ...
//
// I know for a fact that iterator tmp variables named '_[1]'
// are NOT legal names for CSS ID's.
// I also threw in '{', '}', '(', ')', '<', '>' as illegal characters.
//
// TODO: what other characters are illegal???
var lbRE = new RegExp('\\[|{|\\(|<', 'g');
var rbRE = new RegExp('\\]|}|\\)|>', 'g');
function varnameToCssID(varname) {
return varname.replace(lbRE, 'LeftB_').replace(rbRE, '_RightB');
}
// The "2.0" version of renderDataStructures, which renders variables in
// a stack and values in a separate heap, with data structure aliasing
// explicitly represented via line connectors (thanks to jsPlumb lib).
//
// This version was originally created in September 2011
function renderDataStructuresVersion2(curEntry, vizDiv) {
// before we wipe out the old state of the visualization, CLEAR all
// the click listeners first
$(".stackFrameHeader").unbind();
// VERY VERY IMPORTANT --- and reset ALL jsPlumb state to prevent
// weird mis-behavior!!!
jsPlumb.reset();
$(vizDiv).empty(); // jQuery empty() is better than .html('')
// create a tabular layout for stack and heap side-by-side
// TODO: figure out how to do this using CSS in a robust way!
$(vizDiv).html('<table id="stackHeapTable"><tr><td id="stack_td"><div id="stack"></div></td><td id="heap_td"><div id="heap"></div></td></tr></table>');
$(vizDiv + " #stack").append('<div id="stackHeader">Stack grows <select id="stack_growth_selector"><option>down</option><option>up</option></select></div>');
// select a state based on stackGrowsDown global variable:
if (stackGrowsDown) {
$("#stack_growth_selector").val('down');
}
else {
$("#stack_growth_selector").val('up');
}
// add trigger
$("#stack_growth_selector").change(function() {
var v = $("#stack_growth_selector").val();
if (v == 'down') {
stackGrowsDown = true;
}
else {
stackGrowsDown = false;
}
updateOutput(); // refresh display!!!
});
var nonEmptyGlobals = false;
var curGlobalFields = {};
if (curEntry.globals != undefined) {
// use plain ole' iteration rather than jQuery $.each() since
// the latter breaks when a variable is named "length"
for (varname in curEntry.globals) {
curGlobalFields[varname] = true;
nonEmptyGlobals = true;
}
}
// render all global variables IN THE ORDER they were created by the program,
// in order to ensure continuity:
var orderedGlobals = []
if (nonEmptyGlobals) {
// iterating over ALL instructions up to curInstr
// (could be SLOW if not for our optimization below)
//
// TODO: this loop still seems like it can be optimized further if necessary
for (var i = 0; i <= curInstr; i++) {
// some entries (like for exceptions) don't have GLOBALS
if (curTrace[i].globals == undefined) continue;
// use plain ole' iteration rather than jQuery $.each() since
// the latter breaks when a variable is named "length"
for (varname in curTrace[i].globals) {
// eliminate duplicates (act as an ordered set)
if ($.inArray(varname, orderedGlobals) == -1) {
orderedGlobals.push(varname);
curGlobalFields[varname] = undefined; // 'unset it'
}
}
var earlyStop = true;
// as an optimization, STOP as soon as you've found everything in curGlobalFields:
for (o in curGlobalFields) {
if (curGlobalFields[o] != undefined) {
earlyStop = false;
break;
}
}
if (earlyStop) {
break;
}
}
}
// Key: CSS ID of the div element representing the variable
// Value: CSS ID of the div element representing the value rendered in the heap
connectionEndpointIDs = {};
// nested helper functions are helpful!
function renderGlobals() {
// render global variables:
if (orderedGlobals.length > 0) {
$(vizDiv + " #stack").append('<div class="stackFrame" id="globals"><div id="globals_header" class="stackFrameHeader inactiveStackFrameHeader">Global variables</div></div>');
$(vizDiv + " #stack #globals").append('<table class="stackFrameVarTable" id="global_table"></table>');
var tbl = $(vizDiv + " #global_table");
// iterate IN ORDER (it's possible that not all vars are in curEntry.globals)
$.each(orderedGlobals, function(i, varname) {
var val = curEntry.globals[varname];
// (use '!==' to do an EXACT match against undefined)
if (val !== undefined) { // might not be defined at this line, which is OKAY!
tbl.append('<tr><td class="stackFrameVar">' + varname + '</td><td class="stackFrameValue"></td></tr>');
var curTr = tbl.find('tr:last');
// render primitives inline
if (isPrimitiveType(val)) {
renderData(val, curTr.find("td.stackFrameValue"), false);
}
else {
// add a stub so that we can connect it with a connector later.
// IE needs this div to be NON-EMPTY in order to properly
// render jsPlumb endpoints, so that's why we add an " "!
// make sure varname doesn't contain any weird
// characters that are illegal for CSS ID's ...
var varDivID = 'global__' + varnameToCssID(varname);
curTr.find("td.stackFrameValue").append('<div id="' + varDivID + '"> </div>');
assert(connectionEndpointIDs[varDivID] === undefined);
var heapObjID = 'heap_object_' + getObjectID(val);
connectionEndpointIDs[varDivID] = heapObjID;
}
}
});
}
}
function renderStackFrame(frame) {
var funcName = htmlspecialchars(frame[0]); // might contain '<' or '>' for weird names like <genexpr>
var localVars = frame[1];
// the stackFrame div's id is simply its index ("stack<index>")
var divClass = (i==0) ? "stackFrame topStackFrame" : "stackFrame";
var divID = "stack" + i;
$(vizDiv + " #stack").append('<div class="' + divClass + '" id="' + divID + '"></div>');
var headerDivID = "stack_header" + i;
$(vizDiv + " #stack #" + divID).append('<div id="' + headerDivID + '" class="stackFrameHeader inactiveStackFrameHeader">' + funcName + '</div>');
// render locals in alphabetical order for tidiness:
// TODO: later on, render locals in order of first appearance, for consistency!!!
// (the back-end can actually pre-compute this list so that the
// front-end doesn't have to do any extra work!)
var orderedVarnames = [];
// use plain ole' iteration rather than jQuery $.each() since
// the latter breaks when a variable is named "length"
for (varname in localVars) {
orderedVarnames.push(varname);
}
orderedVarnames.sort();
if (orderedVarnames.length > 0) {
var tableID = divID + '_table';
$(vizDiv + " #stack #" + divID).append('<table class="stackFrameVarTable" id="' + tableID + '"></table>');
var tbl = $(vizDiv + " #" + tableID);
// put return value at the VERY END (if it exists)
var retvalIdx = $.inArray('__return__', orderedVarnames); // more robust than indexOf()
if (retvalIdx > -1) {
orderedVarnames.splice(retvalIdx, 1);
orderedVarnames.push('__return__');
}
$.each(orderedVarnames, function(i, varname) {
var val = localVars[varname];
// special treatment for displaying return value and indicating
// that the function is about to return to its caller
if (varname == '__return__') {
assert(curEntry.event == 'return'); // sanity check
tbl.append('<tr><td colspan="2" class="returnWarning">About to return to caller</td></tr>');
tbl.append('<tr><td class="stackFrameVar"><span class="retval">Return value:</span></td><td class="stackFrameValue"></td></tr>');
}
else {
tbl.append('<tr><td class="stackFrameVar">' + varname + '</td><td class="stackFrameValue"></td></tr>');
}
var curTr = tbl.find('tr:last');
// render primitives inline and compound types on the heap
if (isPrimitiveType(val)) {
renderData(val, curTr.find("td.stackFrameValue"), false);
}
else {
// add a stub so that we can connect it with a connector later.
// IE needs this div to be NON-EMPTY in order to properly
// render jsPlumb endpoints, so that's why we add an " "!
// make sure varname doesn't contain any weird
// characters that are illegal for CSS ID's ...
var varDivID = divID + '__' + varnameToCssID(varname);
curTr.find("td.stackFrameValue").append('<div id="' + varDivID + '"> </div>');
assert(connectionEndpointIDs[varDivID] === undefined);
var heapObjID = 'heap_object_' + getObjectID(val);
connectionEndpointIDs[varDivID] = heapObjID;
}
});
}
}
// first render the stack (and global vars)
if (stackGrowsDown) {
renderGlobals();
if (curEntry.stack_locals) {
for (var i = curEntry.stack_locals.length - 1; i >= 0; i--) {
var frame = curEntry.stack_locals[i];
renderStackFrame(frame);
}
}
}
else {
if (curEntry.stack_locals) {
for (var i = 0; i < curEntry.stack_locals.length; i++) {
var frame = curEntry.stack_locals[i];
renderStackFrame(frame);
}
}
renderGlobals();
}
// then render the heap
alreadyRenderedObjectIDs = {}; // set of object IDs that have already been rendered
// if addToEnd is true, then APPEND to the end of the heap,
// otherwise PREPEND to the front
function renderHeapObject(obj, addToEnd) {
var objectID = getObjectID(obj);
if (alreadyRenderedObjectIDs[objectID] === undefined) {
var heapObjID = 'heap_object_' + objectID;
var newDiv = '<div class="heapObject" id="' + heapObjID + '"></div>';
if (addToEnd) {
$(vizDiv + ' #heap').append(newDiv);
}
else {
$(vizDiv + ' #heap').prepend(newDiv);
}
renderData(obj, $(vizDiv + ' #heap #' + heapObjID), false);
alreadyRenderedObjectIDs[objectID] = 1;
}
}
// if there are multiple aliases to the same object, we want to render
// the one deepest in the stack, so that we can hopefully prevent
// objects from jumping around as functions are called and returned.
// e.g., if a list L appears as a global variable and as a local in a
// function, we want to render L when rendering the global frame.
if (stackGrowsDown) {
// this is straightforward: just go through globals first and then
// each stack frame in order :)
$.each(orderedGlobals, function(i, varname) {
var val = curEntry.globals[varname];
// primitive types are already rendered in the stack
if (!isPrimitiveType(val)) {
renderHeapObject(val, true); // APPEND
}
});
if (curEntry.stack_locals) {
$.each(curEntry.stack_locals, function(i, frame) {
var localVars = frame[1];
var orderedVarnames = [];
// use plain ole' iteration rather than jQuery $.each() since
// the latter breaks when a variable is named "length"
for (varname in localVars) {
orderedVarnames.push(varname);
}
orderedVarnames.sort();
$.each(orderedVarnames, function(i2, varname) {
var val = localVars[varname];
// primitive types are already rendered in the stack
if (!isPrimitiveType(val)) {
renderHeapObject(val, true); // APPEND
}
});
});
}
}
else {
// to accomplish this goal, go BACKWARDS starting at globals and
// crawl up the stack, PREPENDING elements to the front of #heap
for (var i = orderedGlobals.length - 1; i >= 0; i--) {
var varname = orderedGlobals[i];
var val = curEntry.globals[varname];
// primitive types are already rendered in the stack
if (!isPrimitiveType(val)) {
renderHeapObject(val, false); // PREPEND
}
}
if (curEntry.stack_locals) {
// go BACKWARDS
for (var i = curEntry.stack_locals.length - 1; i >= 0; i--) {
var frame = curEntry.stack_locals[i];
var localVars = frame[1];
var orderedVarnames = [];
// use plain ole' iteration rather than jQuery $.each() since
// the latter breaks when a variable is named "length"
for (varname in localVars) {
orderedVarnames.push(varname);
}
orderedVarnames.sort();
orderedVarnames.reverse(); // so that we can iterate backwards
$.each(orderedVarnames, function(i, varname) {
var val = localVars[varname];
// primitive types are already rendered in the stack
if (!isPrimitiveType(val)) {
renderHeapObject(val, false); // PREPEND
}
});
}
}
}
// prepend heap header after all the dust settles:
$(vizDiv + ' #heap').prepend('<div id="heapHeader">Heap</div>');
// finally connect stack variables to heap objects via connectors
for (varID in connectionEndpointIDs) {
var valueID = connectionEndpointIDs[varID];
jsPlumb.connect({source: varID, target: valueID});
}
// add an on-click listener to all stack frame headers
$(".stackFrameHeader").click(function() {
var enclosingStackFrame = $(this).parent();
var enclosingStackFrameID = enclosingStackFrame.attr('id');
var allConnections = jsPlumb.getConnections();
for (var i = 0; i < allConnections.length; i++) {
var c = allConnections[i];
// this is VERY VERY fragile code, since it assumes that going up
// five layers of parent() calls will get you from the source end
// of the connector to the enclosing stack frame
var stackFrameDiv = c.source.parent().parent().parent().parent().parent();
// if this connector starts in the selected stack frame ...
if (stackFrameDiv.attr('id') == enclosingStackFrameID) {
// then HIGHLIGHT IT!
c.setPaintStyle({lineWidth:2, strokeStyle: darkBlue});
c.endpoints[0].setPaintStyle({fillStyle: darkBlue});
c.endpoints[1].setVisible(false, true, true); // JUST set right endpoint to be invisible
// ... and move it to the VERY FRONT
$(c.canvas).css("z-index", 1000);
}
else {
// else unhighlight it
c.setPaintStyle({lineWidth:1, strokeStyle: lightGray});
c.endpoints[0].setPaintStyle({fillStyle: lightGray});
c.endpoints[1].setVisible(false, true, true); // JUST set right endpoint to be invisible
$(c.canvas).css("z-index", 0);
}
}
// clear everything, then just activate $(this) one ...
$(".stackFrame").removeClass("selectedStackFrame");
$(".stackFrameHeader").addClass("inactiveStackFrameHeader");
enclosingStackFrame.addClass("selectedStackFrame");
$(this).removeClass("inactiveStackFrameHeader");
});
// 'click' on the top-most stack frame if available,
// or on "Global variables" otherwise
if (curEntry.stack_locals != undefined && curEntry.stack_locals.length > 0) {
$('#stack_header0').trigger('click');
}
else {
$('#globals_header').trigger('click');
}
}
function isPrimitiveType(obj) {
var typ = typeof obj;
return ((obj == null) || (typ != "object"));
}
function getObjectID(obj) {
// pre-condition
assert(!isPrimitiveType(obj));
assert($.isArray(obj));
if ((obj[0] == 'INSTANCE') || (obj[0] == 'CLASS')) {
return obj[2];
}
else {
return obj[1];
}
}
// render the JS data object obj inside of jDomElt,
// which is a jQuery wrapped DOM object
// (obj is in a format encoded by cgi-bin/pg_encoder.py)
function renderData(obj, jDomElt, ignoreIDs) {
// dispatch on types:
var typ = typeof obj;
if (obj == null) {
jDomElt.append('<span class="nullObj">None</span>');
}
else if (typ == "number") {
jDomElt.append('<span class="numberObj">' + obj + '</span>');
}
else if (typ == "boolean") {
if (obj) {
jDomElt.append('<span class="boolObj">True</span>');
}
else {
jDomElt.append('<span class="boolObj">False</span>');
}
}
else if (typ == "string") {
// escape using htmlspecialchars to prevent HTML/script injection
var literalStr = htmlspecialchars(obj);
// print as a double-quoted string literal
literalStr = literalStr.replace(new RegExp('\"', 'g'), '\\"'); // replace ALL
literalStr = '"' + literalStr + '"';
jDomElt.append('<span class="stringObj">' + literalStr + '</span>');
}
else if (typ == "object") {
assert($.isArray(obj));
var idStr = '';
if (!ignoreIDs) {
idStr = ' (id=' + getObjectID(obj) + ')';
}
if (obj[0] == 'LIST') {
assert(obj.length >= 2);
if (obj.length == 2) {
jDomElt.append('<div class="typeLabel">empty list' + idStr + '</div>');
}
else {
jDomElt.append('<div class="typeLabel">list' + idStr + ':</div>');
jDomElt.append('<table class="listTbl"><tr></tr><tr></tr></table>');
var tbl = jDomElt.children('table');
var headerTr = tbl.find('tr:first');
var contentTr = tbl.find('tr:last');
jQuery.each(obj, function(ind, val) {
if (ind < 2) return; // skip 'LIST' tag and ID entry
// add a new column and then pass in that newly-added column
// as jDomElt to the recursive call to child:
headerTr.append('<td class="listHeader"></td>');
headerTr.find('td:last').append(ind - 2);
contentTr.append('<td class="listElt"></td>');
renderData(val, contentTr.find('td:last'), ignoreIDs);
});
}
}
else if (obj[0] == 'TUPLE') {
assert(obj.length >= 2);
if (obj.length == 2) {
jDomElt.append('<div class="typeLabel">empty tuple' + idStr + '</div>');
}
else {
jDomElt.append('<div class="typeLabel">tuple' + idStr + ':</div>');
jDomElt.append('<table class="tupleTbl"><tr></tr><tr></tr></table>');
var tbl = jDomElt.children('table');
var headerTr = tbl.find('tr:first');
var contentTr = tbl.find('tr:last');
jQuery.each(obj, function(ind, val) {
if (ind < 2) return; // skip 'TUPLE' tag and ID entry
// add a new column and then pass in that newly-added column
// as jDomElt to the recursive call to child:
headerTr.append('<td class="tupleHeader"></td>');
headerTr.find('td:last').append(ind - 2);
contentTr.append('<td class="tupleElt"></td>');
renderData(val, contentTr.find('td:last'), ignoreIDs);
});
}
}
else if (obj[0] == 'SET') {
assert(obj.length >= 2);
if (obj.length == 2) {
jDomElt.append('<div class="typeLabel">empty set' + idStr + '</div>');
}
else {
jDomElt.append('<div class="typeLabel">set' + idStr + ':</div>');
jDomElt.append('<table class="setTbl"></table>');
var tbl = jDomElt.children('table');
// create an R x C matrix:
var numElts = obj.length - 2;
// gives roughly a 3x5 rectangular ratio, square is too, err,
// 'square' and boring
var numRows = Math.round(Math.sqrt(numElts));
if (numRows > 3) {
numRows -= 1;
}
var numCols = Math.round(numElts / numRows);
// round up if not a perfect multiple:
if (numElts % numRows) {
numCols += 1;
}
jQuery.each(obj, function(ind, val) {
if (ind < 2) return; // skip 'SET' tag and ID entry
if (((ind - 2) % numCols) == 0) {
tbl.append('<tr></tr>');
}
var curTr = tbl.find('tr:last');
curTr.append('<td class="setElt"></td>');
renderData(val, curTr.find('td:last'), ignoreIDs);
});
}
}
else if (obj[0] == 'DICT') {
assert(obj.length >= 2);
if (obj.length == 2) {
jDomElt.append('<div class="typeLabel">empty dict' + idStr + '</div>');
}
else {
jDomElt.append('<div class="typeLabel">dict' + idStr + ':</div>');
jDomElt.append('<table class="dictTbl"></table>');
var tbl = jDomElt.children('table');
$.each(obj, function(ind, kvPair) {
if (ind < 2) return; // skip 'DICT' tag and ID entry
tbl.append('<tr class="dictEntry"><td class="dictKey"></td><td class="dictVal"></td></tr>');
var newRow = tbl.find('tr:last');
var keyTd = newRow.find('td:first');
var valTd = newRow.find('td:last');
renderData(kvPair[0], keyTd, ignoreIDs);
renderData(kvPair[1], valTd, ignoreIDs);