forked from jmoenig/Snap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads.js
3443 lines (3067 loc) · 100 KB
/
threads.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
/*
threads.js
a tail call optimized blocks-based programming language interpreter
based on morphic.js and blocks.js
inspired by Scratch, Scheme and Squeak
written by Jens Mönig
Copyright (C) 2016 by Jens Mönig
This file is part of Snap!.
Snap! is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
prerequisites:
--------------
needs blocks.js and objects.js
toc
---
the following list shows the order in which all constructors are
defined. Use this list to locate code in this document:
ThreadManager
Process
Context
Variable
VariableFrame
credits
-------
John Maloney and Dave Feinberg designed the original Scratch evaluator
Ivan Motyashov contributed initial porting from Squeak
*/
// Global stuff ////////////////////////////////////////////////////////
/*global ArgMorph, BlockMorph, CommandBlockMorph, CommandSlotMorph, Morph,
MultiArgMorph, Point, ReporterBlockMorph, SyntaxElementMorph, contains,
degrees, detect, nop, radians, ReporterSlotMorph, CSlotMorph, RingMorph,
IDE_Morph, ArgLabelMorph, localize, XML_Element, hex_sha512, TableDialogMorph,
StageMorph, SpriteMorph, StagePrompterMorph, Note, modules, isString, copy,
isNil, WatcherMorph, List, ListWatcherMorph, alert, console, TableMorph,
TableFrameMorph*/
modules.threads = '2016-March-16';
var ThreadManager;
var Process;
var Context;
var VariableFrame;
function snapEquals(a, b) {
if (a instanceof List || (b instanceof List)) {
if (a instanceof List && (b instanceof List)) {
return a.equalTo(b);
}
return false;
}
var x = +a,
y = +b,
i,
specials = [true, false, ''];
// "zum Schneckengang verdorben, was Adlerflug geworden wäre"
// collecting edge-cases that somebody complained about
// on Github. Folks, take it easy and keep it fun, okay?
// Shit like this is patently ugly and slows Snap down. Tnx!
for (i = 9; i <= 13; i += 1) {
specials.push(String.fromCharCode(i));
}
specials.push(String.fromCharCode(160));
// check for special values before coercing to numbers
if (isNaN(x) || isNaN(y) ||
[a, b].some(function (any) {return contains(specials, any) ||
(isString(any) && (any.indexOf(' ') > -1)); })) {
x = a;
y = b;
}
// handle text comparison case-insensitive.
if (isString(x) && isString(y)) {
return x.toLowerCase() === y.toLowerCase();
}
return x === y;
}
function invoke(
action, // a BlockMorph or a Context, a reified ("ringified") block
contextArgs, // optional List of arguments for the context, or null
receiver, // optional sprite or environment
timeout, // msecs
timeoutErrorMsg, // string
suppressErrors // bool
) {
// execute the given block or context synchronously without yielding.
// Apply context (not a block) to a list of optional arguments.
// Receiver (sprite, stage or environment), timeout etc. are optional.
// If a timeout (in milliseconds) is specified, abort execution
// after the timeout has been reached and throw an error.
// SuppressErrors (bool) if non-timeout errors occurring in the
// block are handled elsewhere.
// This is highly experimental.
// Caution: Kids, do not try this at home!
// Use ThreadManager::startProcess with a callback instead
var proc = new Process(),
deadline = (timeout ? Date.now() + timeout : null),
rcvr;
if (action instanceof Context) {
if (receiver) {
action = proc.reportContextFor(receiver);
}
proc.initializeFor(action, contextArgs || new List());
} else if (action instanceof BlockMorph) {
proc.topBlock = action;
rcvr = receiver || action.receiver();
if (rcvr) {
proc.homeContext = new Context();
proc.homeContext.receiver = rcvr;
if (rcvr.variables) {
proc.homeContext.variables.parentFrame = rcvr.variables;
}
}
proc.context = new Context(
null,
action.blockSequence(),
proc.homeContext
);
} else {
throw new Error('expecting a block or ring but getting ' + action);
}
if (suppressErrors) {
proc.isCatchingErrors = false;
}
while (proc.isRunning()) {
if (deadline && (Date.now() > deadline)) {
throw (new Error(
localize(
timeoutErrorMsg ||
"a synchronous Snap! script has timed out")
)
);
}
proc.runStep(deadline);
}
return proc.homeContext.inputs[0];
}
// ThreadManager ///////////////////////////////////////////////////////
function ThreadManager() {
this.processes = [];
}
ThreadManager.prototype.pauseCustomHatBlocks = false;
ThreadManager.prototype.toggleProcess = function (block) {
var active = this.findProcess(block);
if (active) {
active.stop();
} else {
return this.startProcess(block, null, null, null, true);
}
};
ThreadManager.prototype.startProcess = function (
block,
isThreadSafe,
exportResult,
callback,
isClicked
) {
var active = this.findProcess(block),
top = block.topBlock(),
newProc;
if (active) {
if (isThreadSafe) {
return active;
}
active.stop();
this.removeTerminatedProcesses();
}
newProc = new Process(block.topBlock(), callback);
newProc.exportResult = exportResult;
newProc.isClicked = isClicked || false;
if (!newProc.homeContext.receiver.isClone) {
top.addHighlight();
}
this.processes.push(newProc);
return newProc;
};
ThreadManager.prototype.stopAll = function (excpt) {
// excpt is optional
this.processes.forEach(function (proc) {
if (proc !== excpt) {
proc.stop();
}
});
};
ThreadManager.prototype.stopAllForReceiver = function (rcvr, excpt) {
// excpt is optional
this.processes.forEach(function (proc) {
if (proc.homeContext.receiver === rcvr && proc !== excpt) {
proc.stop();
if (rcvr.isClone) {
proc.isDead = true;
}
}
});
};
ThreadManager.prototype.stopProcess = function (block) {
var active = this.findProcess(block);
if (active) {
active.stop();
}
};
ThreadManager.prototype.pauseAll = function (stage) {
this.processes.forEach(function (proc) {
proc.pause();
});
if (stage) {
stage.pauseAllActiveSounds();
}
};
ThreadManager.prototype.isPaused = function () {
return detect(this.processes, function (proc) {return proc.isPaused; })
!== null;
};
ThreadManager.prototype.resumeAll = function (stage) {
this.processes.forEach(function (proc) {
proc.resume();
});
if (stage) {
stage.resumeAllActiveSounds();
}
};
ThreadManager.prototype.step = function () {
// run each process until it gives up control, skipping processes
// for sprites that are currently picked up, then filter out any
// processes that have been terminated
this.processes.forEach(function (proc) {
if (!proc.homeContext.receiver.isPickedUp() && !proc.isDead) {
proc.runStep();
}
});
this.removeTerminatedProcesses();
};
ThreadManager.prototype.removeTerminatedProcesses = function () {
// and un-highlight their scripts
var remaining = [];
this.processes.forEach(function (proc) {
var result;
if ((!proc.isRunning() && !proc.errorFlag) || proc.isDead) {
if (proc.topBlock instanceof BlockMorph) {
proc.topBlock.removeHighlight();
}
if (proc.prompter) {
proc.prompter.destroy();
if (proc.homeContext.receiver.stopTalking) {
proc.homeContext.receiver.stopTalking();
}
}
if (proc.topBlock instanceof ReporterBlockMorph ||
proc.isShowingResult) {
result = proc.homeContext.inputs[0];
if (proc.onComplete instanceof Function) {
proc.onComplete(result);
} else {
if (result instanceof List) {
proc.topBlock.showBubble(
result.isTable() ?
new TableFrameMorph(
new TableMorph(result, 10)
)
: new ListWatcherMorph(result),
proc.exportResult
);
} else {
proc.topBlock.showBubble(
result,
proc.exportResult
);
}
}
}
} else {
remaining.push(proc);
}
});
this.processes = remaining;
};
ThreadManager.prototype.findProcess = function (block) {
var top = block.topBlock();
return detect(
this.processes,
function (each) {
return each.topBlock === top;
}
);
};
ThreadManager.prototype.doWhen = function (block, stopIt) {
if (this.pauseCustomHatBlocks) {return; }
var pred = block.inputs()[0], world;
if (block.removeHighlight()) {
world = block.world();
if (world) {
world.hand.destroyTemporaries();
}
}
if (stopIt) {return; }
if ((!block) ||
!(pred instanceof ReporterBlockMorph) ||
this.findProcess(block)
) {return; }
try {
if (invoke(
pred,
null,
null,
20,
'the predicate takes\ntoo long for a\ncustom hat block',
true // suppress errors => handle them right here instead
) === true) {
this.startProcess(block);
}
} catch (error) {
block.addErrorHighlight();
block.showBubble(
error.name
+ '\n'
+ error.message
);
}
};
// Process /////////////////////////////////////////////////////////////
/*
A Process is what brings a stack of blocks to life. The process
keeps track of which block to run next, evaluates block arguments,
handles control structures, and so forth.
The ThreadManager is the (passive) scheduler, telling each process
when to run by calling its runStep() method. The runStep() method
will execute some number of blocks, then voluntarily yield control
so that the ThreadManager can run another process.
The Scratch etiquette is that a process should yield control at the
end of every loop iteration, and while it is running a timed command
(e.g. "wait 5 secs") or a synchronous command (e.g. "broadcast xxx
and wait"). Since Snap also has lambda and custom blocks Snap adds
yields at the beginning of each non-atomic custom command block
execution, and - to let users escape infinite loops and recursion -
whenever the process runs into a timeout.
a Process runs for a receiver, i.e. a sprite or the stage or any
blocks-scriptable object that we'll introduce.
structure:
topBlock the stack's first block, of which all others
are children
receiver object (sprite) to which the process applies,
cached from the top block
context the Context describing the current state
of this process
homeContext stores information relevant to the whole process,
i.e. its receiver, result etc.
isPaused boolean indicating whether to pause
readyToYield boolean indicating whether to yield control to
another process
readyToTerminate boolean indicating whether the stop method has
been called
isDead boolean indicating a terminated clone process
timeout msecs after which to force yield
lastYield msecs when the process last yielded
errorFlag boolean indicating whether an error was encountered
prompter active instance of StagePrompterMorph
httpRequest active instance of an HttpRequest or null
pauseOffset msecs between the start of an interpolated operation
and when the process was paused
isClicked boolean flag indicating whether the process was
initiated by a user-click on a block
isShowingResult boolean flag indicating whether a "report" command
has been executed in a user-clicked process
exportResult boolean flag indicating whether a picture of the top
block along with the result bubble shoud be exported
onComplete an optional callback function to be executed when
the process is done
procedureCount number counting procedure call entries,
used to tag custom block calls, so "stop block"
invocations can catch them
*/
Process.prototype = {};
Process.prototype.constructor = Process;
Process.prototype.timeout = 500; // msecs after which to force yield
Process.prototype.isCatchingErrors = true;
function Process(topBlock, onComplete) {
this.topBlock = topBlock || null;
this.readyToYield = false;
this.readyToTerminate = false;
this.isDead = false;
this.isClicked = false;
this.isShowingResult = false;
this.errorFlag = false;
this.context = null;
this.homeContext = new Context();
this.lastYield = Date.now();
this.isAtomic = false;
this.prompter = null;
this.httpRequest = null;
this.isPaused = false;
this.pauseOffset = null;
this.frameCount = 0;
this.exportResult = false;
this.onComplete = onComplete || null;
this.procedureCount = 0;
if (topBlock) {
this.homeContext.receiver = topBlock.receiver();
this.homeContext.variables.parentFrame =
this.homeContext.receiver.variables;
this.context = new Context(
null,
topBlock.blockSequence(),
this.homeContext
);
this.pushContext('doYield'); // highlight top block
}
}
// Process accessing
Process.prototype.isRunning = function () {
return (this.context !== null) && (!this.readyToTerminate);
};
// Process entry points
Process.prototype.runStep = function (deadline) {
// a step is an an uninterruptable 'atom', it can consist
// of several contexts, even of several blocks
if (this.isPaused) { // allow pausing in between atomic steps:
return this.pauseStep();
}
this.readyToYield = false;
while (!this.readyToYield
&& this.context
&& (this.isAtomic ?
(Date.now() - this.lastYield < this.timeout) : true)
) {
// also allow pausing inside atomic steps - for PAUSE block primitive:
if (this.isPaused) {
return this.pauseStep();
}
if (deadline && (Date.now() > deadline)) {
if (this.isAtomic &&
this.homeContext.receiver &&
this.homeContext.receiver.endWarp) {
this.homeContext.receiver.endWarp();
}
return;
}
this.evaluateContext();
}
this.lastYield = Date.now();
// make sure to redraw atomic things
if (this.isAtomic &&
this.homeContext.receiver &&
this.homeContext.receiver.endWarp) {
this.homeContext.receiver.endWarp();
this.homeContext.receiver.startWarp();
}
if (this.readyToTerminate) {
while (this.context) {
this.popContext();
}
if (this.homeContext.receiver) {
if (this.homeContext.receiver.endWarp) {
// pen optimization
this.homeContext.receiver.endWarp();
}
}
}
};
Process.prototype.stop = function () {
this.readyToYield = true;
this.readyToTerminate = true;
this.errorFlag = false;
if (this.context) {
this.context.stopMusic();
}
};
Process.prototype.pause = function () {
this.isPaused = true;
if (this.context && this.context.startTime) {
this.pauseOffset = Date.now() - this.context.startTime;
}
};
Process.prototype.resume = function () {
this.isPaused = false;
this.pauseOffset = null;
};
Process.prototype.pauseStep = function () {
this.lastYield = Date.now();
if (this.context && this.context.startTime) {
this.context.startTime = this.lastYield - this.pauseOffset;
}
};
// Process evaluation
Process.prototype.evaluateContext = function () {
var exp = this.context.expression;
this.frameCount += 1;
if (this.context.tag === 'exit') {
this.expectReport();
}
if (exp instanceof Array) {
return this.evaluateSequence(exp);
}
if (exp instanceof MultiArgMorph) {
return this.evaluateMultiSlot(exp, exp.inputs().length);
}
if (exp instanceof ArgLabelMorph) {
return this.evaluateArgLabel(exp);
}
if (exp instanceof ArgMorph || exp.bindingID) {
return this.evaluateInput(exp);
}
if (exp instanceof BlockMorph) {
return this.evaluateBlock(exp, exp.inputs().length);
}
if (isString(exp)) {
return this[exp]();
}
this.popContext(); // default: just ignore it
};
Process.prototype.evaluateBlock = function (block, argCount) {
var selector = block.selector;
// check for special forms
if (selector === 'reportOr' ||
selector === 'reportAnd' ||
selector === 'doReport') {
return this[selector](block);
}
// first evaluate all inputs, then apply the primitive
var rcvr = this.context.receiver || this.topBlock.receiver(),
inputs = this.context.inputs;
if (argCount > inputs.length) {
this.evaluateNextInput(block);
} else {
if (this[selector]) {
rcvr = this;
}
if (this.isCatchingErrors) {
try {
this.returnValueToParentContext(
rcvr[selector].apply(rcvr, inputs)
);
this.popContext();
} catch (error) {
this.handleError(error, block);
}
} else {
this.returnValueToParentContext(
rcvr[selector].apply(rcvr, inputs)
);
this.popContext();
}
}
};
// Process: Special Forms Blocks Primitives
Process.prototype.reportOr = function (block) {
var inputs = this.context.inputs;
if (inputs.length < 1) {
this.evaluateNextInput(block);
} else if (inputs[0]) {
this.returnValueToParentContext(true);
this.popContext();
} else if (inputs.length < 2) {
this.evaluateNextInput(block);
} else {
this.returnValueToParentContext(inputs[1] === true);
this.popContext();
}
};
Process.prototype.reportAnd = function (block) {
var inputs = this.context.inputs;
if (inputs.length < 1) {
this.evaluateNextInput(block);
} else if (!inputs[0]) {
this.returnValueToParentContext(false);
this.popContext();
} else if (inputs.length < 2) {
this.evaluateNextInput(block);
} else {
this.returnValueToParentContext(inputs[1] === true);
this.popContext();
}
};
Process.prototype.doReport = function (block) {
var outer = this.context.outerContext;
if (this.isClicked && (block.topBlock() === this.topBlock)) {
this.isShowingResult = true;
}
if (this.context.expression.partOfCustomCommand) {
this.doStopCustomBlock();
this.popContext();
} else {
while (this.context && this.context.tag !== 'exit') {
if (this.context.expression === 'doStopWarping') {
this.doStopWarping();
} else {
this.popContext();
}
}
if (this.context) {
if (this.context.expression === 'expectReport') {
// pop off inserted top-level exit context
this.popContext();
} else {
// un-tag and preserve original caller
this.context.tag = null;
}
}
}
// in any case evaluate (and ignore)
// the input, because it could be
// and HTTP Request for a hardware extension
this.pushContext(block.inputs()[0], outer);
};
// Process: Non-Block evaluation
Process.prototype.evaluateMultiSlot = function (multiSlot, argCount) {
// first evaluate all subslots, then return a list of their values
var inputs = this.context.inputs,
ans;
if (multiSlot.bindingID) {
if (this.isCatchingErrors) {
try {
ans = this.context.variables.getVar(multiSlot.bindingID);
} catch (error) {
this.handleError(error, multiSlot);
}
} else {
ans = this.context.variables.getVar(multiSlot.bindingID);
}
this.returnValueToParentContext(ans);
this.popContext();
} else {
if (argCount > inputs.length) {
this.evaluateNextInput(multiSlot);
} else {
this.returnValueToParentContext(new List(inputs));
this.popContext();
}
}
};
Process.prototype.evaluateArgLabel = function (argLabel) {
// perform the ID function on an ArgLabelMorph element
var inputs = this.context.inputs;
if (inputs.length < 1) {
this.evaluateNextInput(argLabel);
} else {
this.returnValueToParentContext(inputs[0]);
this.popContext();
}
};
Process.prototype.evaluateInput = function (input) {
// evaluate the input unless it is bound to an implicit parameter
var ans;
if (input.bindingID) {
if (this.isCatchingErrors) {
try {
ans = this.context.variables.getVar(input.bindingID);
} catch (error) {
this.handleError(error, input);
}
} else {
ans = this.context.variables.getVar(input.bindingID);
}
} else {
ans = input.evaluate();
if (ans) {
if (input.constructor === CommandSlotMorph ||
input.constructor === ReporterSlotMorph ||
(input instanceof CSlotMorph &&
(!input.isStatic || input.isLambda))) {
// I know, this still needs yet to be done right....
ans = this.reify(ans, new List());
}
}
}
this.returnValueToParentContext(ans);
this.popContext();
};
Process.prototype.evaluateSequence = function (arr) {
var pc = this.context.pc,
outer = this.context.outerContext,
isCustomBlock = this.context.isCustomBlock;
if (pc === (arr.length - 1)) { // tail call elimination
this.context = new Context(
this.context.parentContext,
arr[pc],
this.context.outerContext,
this.context.receiver
);
this.context.isCustomBlock = isCustomBlock;
} else {
if (pc >= arr.length) {
this.popContext();
} else {
this.context.pc += 1;
this.pushContext(arr[pc], outer);
}
}
};
/*
// version w/o tail call optimization:
--------------------------------------
Caution: we cannot just revert to this version of the method, because to make
tail call elimination work many tweaks had to be done to various primitives.
For the most part these tweaks are about schlepping the outer context (for
the variable bindings) and the isCustomBlock flag along, and are indicated
by a short comment in the code. But to really revert would take a good measure
of trial and error as well as debugging. In the developers file archive there
is a version of threads.js dated 120119(2) which basically resembles the
last version before introducing tail call optimization on 120123.
Process.prototype.evaluateSequence = function (arr) {
var pc = this.context.pc;
if (pc >= arr.length) {
this.popContext();
} else {
this.context.pc += 1;
this.pushContext(arr[pc]);
}
};
*/
Process.prototype.evaluateNextInput = function (element) {
var nxt = this.context.inputs.length,
args = element.inputs(),
exp = args[nxt],
sel = this.context.expression.selector,
outer = this.context.outerContext; // for tail call elimination
if (exp.isUnevaluated) {
if (exp.isUnevaluated === true || exp.isUnevaluated()) {
// just return the input as-is
/*
Note: we only reify the input here, if it's not an
input to a reification primitive itself (THE BLOCK,
THE SCRIPT), because those allow for additional
explicit parameter bindings.
*/
if (sel === 'reify' || sel === 'reportScript') {
this.context.addInput(exp);
} else {
this.context.addInput(this.reify(exp, new List()));
}
} else {
this.pushContext(exp, outer);
}
} else {
this.pushContext(exp, outer);
}
};
Process.prototype.doYield = function () {
this.popContext();
if (!this.isAtomic) {
this.readyToYield = true;
}
};
Process.prototype.expectReport = function () {
this.handleError(new Error("reporter didn't report"));
};
// Process Exception Handling
Process.prototype.handleError = function (error, element) {
var m = element;
this.stop();
this.errorFlag = true;
this.topBlock.addErrorHighlight();
if (isNil(m) || isNil(m.world())) {m = this.topBlock; }
m.showBubble(
(m === element ? '' : 'Inside: ')
+ error.name
+ '\n'
+ error.message,
this.exportResult
);
};
Process.prototype.errorObsolete = function () {
throw new Error('a custom block definition is missing');
};
// Process Lambda primitives
Process.prototype.reify = function (topBlock, parameterNames, isCustomBlock) {
var context = new Context(
null,
null,
this.context ? this.context.outerContext : null
),
i = 0;
if (topBlock) {
context.expression = topBlock.fullCopy();
context.expression.show(); // be sure to make visible if in app mode
if (!isCustomBlock) {
// mark all empty slots with an identifier
context.expression.allEmptySlots().forEach(function (slot) {
i += 1;
if (slot instanceof MultiArgMorph) {
slot.bindingID = ['arguments'];
} else {
slot.bindingID = i;
}
});
// and remember the number of detected empty slots
context.emptySlots = i;
}
} else {
context.expression = [this.context.expression.fullCopy()];
}
context.inputs = parameterNames.asArray();
context.receiver
= this.context ? this.context.receiver : topBlock.receiver();
return context;
};
Process.prototype.reportScript = function (parameterNames, topBlock) {
return this.reify(topBlock, parameterNames);
};
Process.prototype.reifyScript = function (topBlock, parameterNames) {
return this.reify(topBlock, parameterNames);
};
Process.prototype.reifyReporter = function (topBlock, parameterNames) {
return this.reify(topBlock, parameterNames);
};
Process.prototype.reifyPredicate = function (topBlock, parameterNames) {
return this.reify(topBlock, parameterNames);
};
Process.prototype.reportJSFunction = function (parmNames, body) {
return Function.apply(
null,
parmNames.asArray().concat([body])
);
};
Process.prototype.doRun = function (context, args) {
return this.evaluate(context, args, true);
};
Process.prototype.evaluate = function (
context,
args,
isCommand
) {
if (!context) {return null; }
if (context instanceof Function) {
return context.apply(
this.blockReceiver(),
args.asArray().concat([this])
);
}
if (context.isContinuation) {
return this.runContinuation(context, args);
}
if (!(context instanceof Context)) {
throw new Error('expecting a ring but getting ' + context);
}
var outer = new Context(null, null, context.outerContext),
caller = this.context.parentContext,
exit,
runnable,
parms = args.asArray(),
i,
value;
if (!outer.receiver) {
outer.receiver = context.receiver; // for custom blocks
}
runnable = new Context(
this.context.parentContext,
context.expression,
outer,
context.receiver
);
this.context.parentContext = runnable;
if (context.expression instanceof ReporterBlockMorph) {
// auto-"warp" nested reporters
this.readyToYield = (Date.now() - this.lastYield > this.timeout);
}
// assign parameters if any were passed
if (parms.length > 0) {
// assign formal parameters
for (i = 0; i < context.inputs.length; i += 1) {
value = 0;
if (!isNil(parms[i])) {
value = parms[i];
}
outer.variables.addVar(context.inputs[i], value);
}
// assign implicit parameters if there are no formal ones
if (context.inputs.length === 0) {
// assign the actual arguments list to the special
// parameter ID ['arguments'], to be used for variadic inputs
outer.variables.addVar(['arguments'], args);
// in case there is only one input
// assign it to all empty slots
if (parms.length === 1) {
for (i = 1; i <= context.emptySlots; i += 1) {
outer.variables.addVar(i, parms[0]);
}
// if the number of inputs matches the number
// of empty slots distribute them sequentially
} else if (parms.length === context.emptySlots) {
for (i = 1; i <= parms.length; i += 1) {
outer.variables.addVar(i, parms[i - 1]);