forked from jmoenig/Snap
-
Notifications
You must be signed in to change notification settings - Fork 13
/
threads.js
3211 lines (2815 loc) · 90.6 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) 2014 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
VariableFrame
UpvarReference
credits
-------
John Maloney and Dave Feinberg designed the original Scratch evaluator
Ivan Motyashov contributed initial porting from Squeak
*/
// globals from blocks.js:
/*global ArgMorph, ArrowMorph, BlockHighlightMorph, BlockMorph,
BooleanSlotMorph, BoxMorph, Color, ColorPaletteMorph, ColorSlotMorph,
CommandBlockMorph, CommandSlotMorph, FrameMorph, HatBlockMorph,
InputSlotMorph, MenuMorph, Morph, MultiArgMorph, Point,
ReporterBlockMorph, ScriptsMorph, ShadowMorph, StringMorph,
SyntaxElementMorph, TextMorph, WorldMorph, blocksVersion, contains,
degrees, detect, getDocumentPositionOf, newCanvas, nop, radians,
useBlurredShadows, ReporterSlotMorph, CSlotMorph, RingMorph, IDE_Morph,
ArgLabelMorph, localize, XML_Element, hex_sha512*/
// globals from objects.js:
/*global StageMorph, SpriteMorph, StagePrompterMorph, Note*/
// globals from morphic.js:
/*global modules, isString, copy, isNil*/
// globals from gui.js:
/*global WatcherMorph*/
// globals from lists.js:
/*global List, ListWatcherMorph*/
/*global alert, console*/
// Global stuff ////////////////////////////////////////////////////////
modules.threads = '2014-May-02';
var ThreadManager;
var Process;
var Context;
var VariableFrame;
var UpvarReference;
var wheelMap = {};
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,
specials = [true, false, ''];
// 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 comparision case-insensitive.
if (isString(x) && isString(y)) {
return x.toLowerCase() === y.toLowerCase();
}
return x === y;
}
// ThreadManager ///////////////////////////////////////////////////////
function ThreadManager() {
this.processes = [];
}
ThreadManager.prototype.toggleProcess = function (block) {
var active = this.findProcess(block);
if (active) {
active.stop();
} else {
return this.startProcess(block);
}
};
ThreadManager.prototype.startProcess = function (block, isThreadSafe) {
var active = this.findProcess(block),
top = block.topBlock(),
newProc;
if (active) {
if (isThreadSafe) {
return active;
}
active.stop();
this.removeTerminatedProcesses();
}
top.addHighlight();
newProc = new Process(block.topBlock());
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();
}
});
};
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) {
if (!proc.isRunning() && !proc.errorFlag && !proc.isDead) {
proc.topBlock.removeHighlight();
if (proc.prompter) {
proc.prompter.destroy();
if (proc.homeContext.receiver.stopTalking) {
proc.homeContext.receiver.stopTalking();
}
}
if (proc.topBlock instanceof ReporterBlockMorph) {
if (proc.homeContext.inputs[0] instanceof List) {
proc.topBlock.showBubble(new ListWatcherMorph(
proc.homeContext.inputs[0]
));
} else {
proc.topBlock.showBubble(proc.homeContext.inputs[0]);
}
}
} 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;
}
);
};
// 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
*/
Process.prototype = {};
Process.prototype.contructor = Process;
Process.prototype.timeout = 500; // msecs after which to force yield
Process.prototype.isCatchingErrors = true;
function Process(topBlock) {
this.topBlock = topBlock || null;
this.readyToYield = false;
this.readyToTerminate = false;
this.isDead = 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;
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 () {
/*
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();
}
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;
}
if (this.context.activeNote) {
this.context.activeNote.stop();
}
};
Process.prototype.resume = function () {
this.isPaused = false;
this.pauseOffset = null;
if (this.context.activeNote) {
if (this.context.activeNote.oscillator === null) {
// prevents Note from resuming twice
this.context.activeNote.play();
}
}
};
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 (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) {
// check for special forms
if (contains(['reportOr', 'reportAnd'], block.selector)) {
return this[block.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[block.selector]) {
rcvr = this;
}
if (this.isCatchingErrors) {
try {
this.returnValueToParentContext(
rcvr[block.selector].apply(rcvr, inputs)
);
this.popContext();
} catch (error) {
this.handleError(error, block);
}
} else {
this.returnValueToParentContext(
rcvr[block.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: 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 (contains(
[CommandSlotMorph, ReporterSlotMorph],
input.constructor
) || (input instanceof CSlotMorph && !input.isStatic)) {
// I know, this still needs yet to be done right....
ans = this.reify(ans, new List());
ans.isImplicitLambda = true;
}
}
}
this.returnValueToParentContext(ans);
this.popContext();
};
Process.prototype.evaluateSequence = function (arr) {
var pc = this.context.pc,
outer = this.context.outerContext,
isLambda = this.context.isLambda,
isImplicitLambda = this.context.isImplicitLambda,
isCustomBlock = this.context.isCustomBlock,
upvars = this.context.upvars;
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.isLambda = isLambda;
this.context.isImplicitLambda = isImplicitLambda;
this.context.isCustomBlock = isCustomBlock;
if (upvars) {
this.context.upvars = new UpvarReference(upvars);
}
} 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 isLambda 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],
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 (contains(['reify', 'reportScript'],
this.context.expression.selector)) {
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 Exception Handling
Process.prototype.handleError = function (error, element) {
this.stop();
this.errorFlag = true;
this.topBlock.addErrorHighlight();
(element || this.topBlock).showBubble(
(element ? '' : 'Inside: ')
+ error.name
+ '\n'
+ error.message
);
};
// 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.doRun = function (context, args, isCustomBlock) {
return this.evaluate(context, args, true, isCustomBlock);
};
Process.prototype.evaluate = function (
context,
args,
isCommand
) {
if (!context) {return null; }
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),
runnable,
extra,
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
);
extra = new Context(runnable, 'doYield');
/*
Note: if the context's expression is a ReporterBlockMorph,
the extra context gets popped off immediately without taking
effect (i.e. it doesn't yield within evaluating a stack of
nested reporters)
*/
if (isCommand || (context.expression instanceof ReporterBlockMorph)) {
this.context.parentContext = extra;
} else {
this.context.parentContext = runnable;
}
runnable.isLambda = true;
runnable.isImplicitLambda = context.isImplicitLambda;
runnable.isCustomBlock = false;
// 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]);
}
} else if (context.emptySlots !== 1) {
throw new Error(
'expecting ' + context.emptySlots + ' input(s), '
+ 'but getting ' + parms.length
);
}
}
}
if (this.context.upvars) {
runnable.upvars = new UpvarReference(this.context.upvars);
}
if (runnable.expression instanceof CommandBlockMorph) {
runnable.expression = runnable.expression.blockSequence();
}
};
Process.prototype.fork = function (context, args) {
if (context.isContinuation) {
throw new Error(
'continuations cannot be forked'
);
}
var outer = new Context(null, null, context.outerContext),
runnable = new Context(null,
context.expression,
outer
),
parms = args.asArray(),
i,
value,
stage = this.homeContext.receiver.parentThatIsA(StageMorph),
proc = new Process();
runnable.isLambda = true;
// 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]);
}
} else if (context.emptySlots !== 1) {
throw new Error(
'expecting ' + context.emptySlots + ' input(s), '
+ 'but getting ' + parms.length
);
}
}
}
if (runnable.expression instanceof CommandBlockMorph) {
runnable.expression = runnable.expression.blockSequence();
}
proc.homeContext = context.outerContext;
proc.topBlock = context.expression;
proc.context = runnable;
proc.pushContext('doYield');
stage.threads.processes.push(proc);
};
Process.prototype.doReport = function (value, isCSlot) {
while (this.context && !this.context.isLambda) {
if (this.context.expression === 'doStopWarping') {
this.doStopWarping();
} else {
this.popContext();
}
}
if (this.context && this.context.isImplicitLambda) {
if (this.context.expression === 'doStopWarping') {
this.doStopWarping();
} else {
this.popContext();
}
return this.doReport(value, true);
}
if (this.context && this.context.isCustomBlock) {
// now I'm back at the custom block sequence.
// advance my pc to my expression's length
this.context.pc = this.context.expression.length - 1;
}
if (isCSlot) {
if (this.context.parentContext.expression instanceof Array) {
this.popContext();
}
}
return value;
};
Process.prototype.doStopBlock = function () {
this.doReport();
};
// Process evaluation variants, commented out for now (redundant)
/*
Process.prototype.doRunWithInputList = function (context, args) {
// provide an extra selector for the palette
return this.doRun(context, args);
};
Process.prototype.evaluateWithInputList = function (context, args) {
// provide an extra selector for the palette
return this.evaluate(context, args);
};
Process.prototype.forkWithInputList = function (context, args) {
// provide an extra selector for the palette
return this.fork(context, args);
};
*/
// Process continuations primitives
Process.prototype.doCallCC = function (aContext) {
this.evaluate(aContext, new List([this.context.continuation()]));
};
Process.prototype.reportCallCC = function (aContext) {
this.doCallCC(aContext);
};
Process.prototype.runContinuation = function (aContext, args) {
var parms = args.asArray();
this.context.parentContext = aContext.copyForContinuationCall();
// passing parameter if any was passed
if (parms.length === 1) {
this.context.parentContext.outerContext.variables.addVar(
1,
parms[0]
);
}
};
// Process custom block primitives
Process.prototype.evaluateCustomBlock = function () {
var context = this.context.expression.definition.body,