forked from scratchfoundation/scratch-vm
-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathjsgen.js
1487 lines (1345 loc) · 59.6 KB
/
jsgen.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
const log = require('../util/log');
const Cast = require('../util/cast');
const BlockType = require('../extension-support/block-type');
const VariablePool = require('./variable-pool');
const jsexecute = require('./jsexecute');
const environment = require('./environment');
// Imported for JSDoc types, not to actually use
// eslint-disable-next-line no-unused-vars
const {IntermediateScript, IntermediateRepresentation} = require('./intermediate');
/**
* @fileoverview Convert intermediate representations to JavaScript functions.
*/
/* eslint-disable max-len */
/* eslint-disable prefer-template */
const sanitize = string => {
if (typeof string !== 'string') {
log.warn(`sanitize got unexpected type: ${typeof string}`);
string = '' + string;
}
return JSON.stringify(string).slice(1, -1);
};
const TYPE_NUMBER = 1;
const TYPE_STRING = 2;
const TYPE_BOOLEAN = 3;
const TYPE_UNKNOWN = 4;
const TYPE_NUMBER_NAN = 5;
// Pen-related constants
const PEN_EXT = 'runtime.ext_pen';
const PEN_STATE = `${PEN_EXT}._getPenState(target)`;
/**
* Variable pool used for factory function names.
*/
const factoryNameVariablePool = new VariablePool('factory');
/**
* Variable pool used for generated functions (non-generator)
*/
const functionNameVariablePool = new VariablePool('fun');
/**
* Variable pool used for generated generator functions.
*/
const generatorNameVariablePool = new VariablePool('gen');
/**
* @typedef Input
* @property {() => string} asNumber
* @property {() => string} asNumberOrNaN
* @property {() => string} asString
* @property {() => string} asBoolean
* @property {() => string} asColor
* @property {() => string} asUnknown
* @property {() => string} asSafe
* @property {() => boolean} isAlwaysNumber
* @property {() => boolean} isAlwaysNumberOrNaN
* @property {() => boolean} isNeverNumber
*/
/**
* @implements {Input}
*/
class TypedInput {
constructor (source, type) {
// for debugging
if (typeof type !== 'number') throw new Error('type is invalid');
this.source = source;
this.type = type;
}
asNumber () {
if (this.type === TYPE_NUMBER) return this.source;
if (this.type === TYPE_NUMBER_NAN) return `(${this.source} || 0)`;
return `(+${this.source} || 0)`;
}
asNumberOrNaN () {
if (this.type === TYPE_NUMBER || this.type === TYPE_NUMBER_NAN) return this.source;
return `(+${this.source})`;
}
asString () {
if (this.type === TYPE_STRING) return this.source;
return `("" + ${this.source})`;
}
asBoolean () {
if (this.type === TYPE_BOOLEAN) return this.source;
return `toBoolean(${this.source})`;
}
asColor () {
return this.asUnknown();
}
asUnknown () {
return this.source;
}
asSafe () {
return this.asUnknown();
}
isAlwaysNumber () {
return this.type === TYPE_NUMBER;
}
isAlwaysNumberOrNaN () {
return this.type === TYPE_NUMBER || this.type === TYPE_NUMBER_NAN;
}
isNeverNumber () {
return false;
}
}
/**
* @implements {Input}
*/
class ConstantInput {
constructor (constantValue, safe) {
this.constantValue = constantValue;
this.safe = safe;
}
asNumber () {
// Compute at compilation time
const numberValue = +this.constantValue;
if (numberValue) {
// It's important that we use the number's stringified value and not the constant value
// Using the constant value allows numbers such as "010" to be interpreted as 8 (or SyntaxError in strict mode) instead of 10.
return numberValue.toString();
}
// numberValue is one of 0, -0, or NaN
if (Object.is(numberValue, -0)) {
return '-0';
}
return '0';
}
asNumberOrNaN () {
return this.asNumber();
}
asString () {
return `"${sanitize('' + this.constantValue)}"`;
}
asBoolean () {
// Compute at compilation time
return Cast.toBoolean(this.constantValue).toString();
}
asColor () {
// Attempt to parse hex code at compilation time
if (/^#[0-9a-f]{6,8}$/i.test(this.constantValue)) {
const hex = this.constantValue.substr(1);
return Number.parseInt(hex, 16).toString();
}
return this.asUnknown();
}
asUnknown () {
// Attempt to convert strings to numbers if it is unlikely to break things
if (typeof this.constantValue === 'number') {
// todo: handle NaN?
return this.constantValue;
}
const numberValue = +this.constantValue;
if (numberValue.toString() === this.constantValue) {
return this.constantValue;
}
return this.asString();
}
asSafe () {
if (this.safe) {
return this.asUnknown();
}
return this.asString();
}
isAlwaysNumber () {
const value = +this.constantValue;
if (Number.isNaN(value)) {
return false;
}
// Empty strings evaluate to 0 but should not be considered a number.
if (value === 0) {
return this.constantValue.toString().trim() !== '';
}
return true;
}
isAlwaysNumberOrNaN () {
return this.isAlwaysNumber();
}
isNeverNumber () {
return Number.isNaN(+this.constantValue);
}
}
/**
* @implements {Input}
*/
class VariableInput {
constructor (source) {
this.source = source;
this.type = TYPE_UNKNOWN;
/**
* The value this variable was most recently set to, if any.
* @type {Input}
* @private
*/
this._value = null;
}
/**
* @param {Input} input The input this variable was most recently set to.
*/
setInput (input) {
if (input instanceof VariableInput) {
// When being set to another variable, extract the value it was set to.
// Otherwise, you may end up with infinite recursion in analysis methods when a variable is set to itself.
if (input._value) {
input = input._value;
} else {
this.type = TYPE_UNKNOWN;
this._value = null;
return;
}
}
this._value = input;
if (input instanceof TypedInput) {
this.type = input.type;
} else {
this.type = TYPE_UNKNOWN;
}
}
asNumber () {
if (this.type === TYPE_NUMBER) return this.source;
if (this.type === TYPE_NUMBER_NAN) return `(${this.source} || 0)`;
return `(+${this.source} || 0)`;
}
asNumberOrNaN () {
if (this.type === TYPE_NUMBER || this.type === TYPE_NUMBER_NAN) return this.source;
return `(+${this.source})`;
}
asString () {
if (this.type === TYPE_STRING) return this.source;
return `("" + ${this.source})`;
}
asBoolean () {
if (this.type === TYPE_BOOLEAN) return this.source;
return `toBoolean(${this.source})`;
}
asColor () {
return this.asUnknown();
}
asUnknown () {
return this.source;
}
asSafe () {
return this.asUnknown();
}
isAlwaysNumber () {
if (this._value) {
return this._value.isAlwaysNumber();
}
return false;
}
isAlwaysNumberOrNaN () {
if (this._value) {
return this._value.isAlwaysNumberOrNaN();
}
return false;
}
isNeverNumber () {
if (this._value) {
return this._value.isNeverNumber();
}
return false;
}
}
const getNamesOfCostumesAndSounds = runtime => {
const result = new Set();
for (const target of runtime.targets) {
if (target.isOriginal) {
const sprite = target.sprite;
for (const costume of sprite.costumes) {
result.add(costume.name);
}
for (const sound of sprite.sounds) {
result.add(sound.name);
}
}
}
return result;
};
const isSafeConstantForEqualsOptimization = input => {
const numberValue = +input.constantValue;
// Do not optimize 0
if (!numberValue) {
return false;
}
// Do not optimize numbers when the original form does not match
return numberValue.toString() === input.constantValue.toString();
};
/**
* A frame contains some information about the current substack being compiled.
*/
class Frame {
constructor (isLoop) {
/**
* Whether the current stack runs in a loop (while, for)
* @type {boolean}
* @readonly
*/
this.isLoop = isLoop;
/**
* Whether the current block is the last block in the stack.
* @type {boolean}
*/
this.isLastBlock = false;
}
}
class JSGenerator {
/**
* @param {IntermediateScript} script
* @param {IntermediateRepresentation} ir
* @param {Target} target
*/
constructor (script, ir, target) {
this.script = script;
this.ir = ir;
this.target = target;
this.source = '';
/**
* @type {Object.<string, VariableInput>}
*/
this.variableInputs = {};
this.isWarp = script.isWarp;
this.isProcedure = script.isProcedure;
this.warpTimer = script.warpTimer;
/**
* Stack of frames, most recent is last item.
* @type {Frame[]}
*/
this.frames = [];
/**
* The current Frame.
* @type {Frame}
*/
this.currentFrame = null;
this.namesOfCostumesAndSounds = getNamesOfCostumesAndSounds(target.runtime);
this.localVariables = new VariablePool('a');
this._setupVariablesPool = new VariablePool('b');
this._setupVariables = {};
this.descendedIntoModulo = false;
this.isInHat = false;
this.debug = this.target.runtime.debug;
}
/**
* Enter a new frame
* @param {Frame} frame New frame.
*/
pushFrame (frame) {
this.frames.push(frame);
this.currentFrame = frame;
}
/**
* Exit the current frame
*/
popFrame () {
this.frames.pop();
this.currentFrame = this.frames[this.frames.length - 1];
}
/**
* @returns {boolean} true if the current block is the last command of a loop
*/
isLastBlockInLoop () {
for (let i = this.frames.length - 1; i >= 0; i--) {
const frame = this.frames[i];
if (!frame.isLastBlock) {
return false;
}
if (frame.isLoop) {
return true;
}
}
return false;
}
/**
* @param {object} node Input node to compile.
* @returns {Input} Compiled input.
*/
descendInput (node) {
switch (node.kind) {
case 'addons.call':
return new TypedInput(`(${this.descendAddonCall(node)})`, TYPE_UNKNOWN);
case 'args.boolean':
return new TypedInput(`toBoolean(p${node.index})`, TYPE_BOOLEAN);
case 'args.stringNumber':
return new TypedInput(`p${node.index}`, TYPE_UNKNOWN);
case 'compat':
if (node.blockType === BlockType.INLINE) {
const branchVariable = this.localVariables.next();
const returnVariable = this.localVariables.next();
let source = '(yield* (function*() {\n';
source += `let ${returnVariable} = undefined;\n`;
source += `const ${branchVariable} = createBranchInfo(false);\n`;
source += `${returnVariable} = (${this.generateCompatibilityLayerCall(node, false, branchVariable)});\n`;
source += `${branchVariable}.branch = globalState.blockUtility._startedBranch[0];\n`;
source += `switch (${branchVariable}.branch) {\n`;
for (const index in node.substacks) {
source += `case ${+index}: {\n`;
source += this.descendStackForSource(node.substacks[index], new Frame(false));
source += `break;\n`;
source += `}\n`; // close case
}
source += '}\n'; // close switch
source += `return ${returnVariable};\n`;
source += '})())'; // close function and yield
return new TypedInput(source, TYPE_UNKNOWN);
}
// Compatibility layer inputs never use flags.
return new TypedInput(`(${this.generateCompatibilityLayerCall(node, false)})`, TYPE_UNKNOWN);
case 'constant':
return this.safeConstantInput(node.value);
case 'counter.get':
return new TypedInput('runtime.ext_scratch3_control._counter', TYPE_NUMBER);
case 'keyboard.pressed':
return new TypedInput(`runtime.ioDevices.keyboard.getKeyIsDown(${this.descendInput(node.key).asSafe()})`, TYPE_BOOLEAN);
case 'list.contains':
return new TypedInput(`listContains(${this.referenceVariable(node.list)}, ${this.descendInput(node.item).asUnknown()})`, TYPE_BOOLEAN);
case 'list.contents':
return new TypedInput(`listContents(${this.referenceVariable(node.list)})`, TYPE_STRING);
case 'list.get': {
const index = this.descendInput(node.index);
if (environment.supportsNullishCoalescing) {
if (index.isAlwaysNumberOrNaN()) {
return new TypedInput(`(${this.referenceVariable(node.list)}.value[(${index.asNumber()} | 0) - 1] ?? "")`, TYPE_UNKNOWN);
}
if (index instanceof ConstantInput && index.constantValue === 'last') {
return new TypedInput(`(${this.referenceVariable(node.list)}.value[${this.referenceVariable(node.list)}.value.length - 1] ?? "")`, TYPE_UNKNOWN);
}
}
return new TypedInput(`listGet(${this.referenceVariable(node.list)}.value, ${index.asUnknown()})`, TYPE_UNKNOWN);
}
case 'list.indexOf':
return new TypedInput(`listIndexOf(${this.referenceVariable(node.list)}, ${this.descendInput(node.item).asUnknown()})`, TYPE_NUMBER);
case 'list.length':
return new TypedInput(`${this.referenceVariable(node.list)}.value.length`, TYPE_NUMBER);
case 'looks.size':
return new TypedInput('Math.round(target.size)', TYPE_NUMBER);
case 'looks.backdropName':
return new TypedInput('stage.getCostumes()[stage.currentCostume].name', TYPE_STRING);
case 'looks.backdropNumber':
return new TypedInput('(stage.currentCostume + 1)', TYPE_NUMBER);
case 'looks.costumeName':
return new TypedInput('target.getCostumes()[target.currentCostume].name', TYPE_STRING);
case 'looks.costumeNumber':
return new TypedInput('(target.currentCostume + 1)', TYPE_NUMBER);
case 'motion.direction':
return new TypedInput('target.direction', TYPE_NUMBER);
case 'motion.x':
return new TypedInput('limitPrecision(target.x)', TYPE_NUMBER);
case 'motion.y':
return new TypedInput('limitPrecision(target.y)', TYPE_NUMBER);
case 'mouse.down':
return new TypedInput('runtime.ioDevices.mouse.getIsDown()', TYPE_BOOLEAN);
case 'mouse.x':
return new TypedInput('runtime.ioDevices.mouse.getScratchX()', TYPE_NUMBER);
case 'mouse.y':
return new TypedInput('runtime.ioDevices.mouse.getScratchY()', TYPE_NUMBER);
case 'noop':
return new TypedInput('""', TYPE_STRING);
case 'op.abs':
return new TypedInput(`Math.abs(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
case 'op.acos':
// Needs to be marked as NaN because Math.acos(1.0001) === NaN
return new TypedInput(`((Math.acos(${this.descendInput(node.value).asNumber()}) * 180) / Math.PI)`, TYPE_NUMBER_NAN);
case 'op.add':
// Needs to be marked as NaN because Infinity + -Infinity === NaN
return new TypedInput(`(${this.descendInput(node.left).asNumber()} + ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
case 'op.and':
return new TypedInput(`(${this.descendInput(node.left).asBoolean()} && ${this.descendInput(node.right).asBoolean()})`, TYPE_BOOLEAN);
case 'op.asin':
// Needs to be marked as NaN because Math.asin(1.0001) === NaN
return new TypedInput(`((Math.asin(${this.descendInput(node.value).asNumber()}) * 180) / Math.PI)`, TYPE_NUMBER_NAN);
case 'op.atan':
return new TypedInput(`((Math.atan(${this.descendInput(node.value).asNumber()}) * 180) / Math.PI)`, TYPE_NUMBER);
case 'op.ceiling':
return new TypedInput(`Math.ceil(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
case 'op.contains':
return new TypedInput(`(${this.descendInput(node.string).asString()}.toLowerCase().indexOf(${this.descendInput(node.contains).asString()}.toLowerCase()) !== -1)`, TYPE_BOOLEAN);
case 'op.cos':
return new TypedInput(`(Math.round(Math.cos((Math.PI * ${this.descendInput(node.value).asNumber()}) / 180) * 1e10) / 1e10)`, TYPE_NUMBER_NAN);
case 'op.divide':
// Needs to be marked as NaN because 0 / 0 === NaN
return new TypedInput(`(${this.descendInput(node.left).asNumber()} / ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
case 'op.equals': {
const left = this.descendInput(node.left);
const right = this.descendInput(node.right);
// When both operands are known to never be numbers, only use string comparison to avoid all number parsing.
if (left.isNeverNumber() || right.isNeverNumber()) {
return new TypedInput(`(${left.asString()}.toLowerCase() === ${right.asString()}.toLowerCase())`, TYPE_BOOLEAN);
}
const leftAlwaysNumber = left.isAlwaysNumber();
const rightAlwaysNumber = right.isAlwaysNumber();
// When both operands are known to be numbers, we can use ===
if (leftAlwaysNumber && rightAlwaysNumber) {
return new TypedInput(`(${left.asNumber()} === ${right.asNumber()})`, TYPE_BOOLEAN);
}
// In certain conditions, we can use === when one of the operands is known to be a safe number.
if (leftAlwaysNumber && left instanceof ConstantInput && isSafeConstantForEqualsOptimization(left)) {
return new TypedInput(`(${left.asNumber()} === ${right.asNumber()})`, TYPE_BOOLEAN);
}
if (rightAlwaysNumber && right instanceof ConstantInput && isSafeConstantForEqualsOptimization(right)) {
return new TypedInput(`(${left.asNumber()} === ${right.asNumber()})`, TYPE_BOOLEAN);
}
// No compile-time optimizations possible - use fallback method.
return new TypedInput(`compareEqual(${left.asUnknown()}, ${right.asUnknown()})`, TYPE_BOOLEAN);
}
case 'op.e^':
return new TypedInput(`Math.exp(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
case 'op.floor':
return new TypedInput(`Math.floor(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
case 'op.greater': {
const left = this.descendInput(node.left);
const right = this.descendInput(node.right);
// When the left operand is a number and the right operand is a number or NaN, we can use >
if (left.isAlwaysNumber() && right.isAlwaysNumberOrNaN()) {
return new TypedInput(`(${left.asNumber()} > ${right.asNumberOrNaN()})`, TYPE_BOOLEAN);
}
// When the left operand is a number or NaN and the right operand is a number, we can negate <=
if (left.isAlwaysNumberOrNaN() && right.isAlwaysNumber()) {
return new TypedInput(`!(${left.asNumberOrNaN()} <= ${right.asNumber()})`, TYPE_BOOLEAN);
}
// When either operand is known to never be a number, avoid all number parsing.
if (left.isNeverNumber() || right.isNeverNumber()) {
return new TypedInput(`(${left.asString()}.toLowerCase() > ${right.asString()}.toLowerCase())`, TYPE_BOOLEAN);
}
// No compile-time optimizations possible - use fallback method.
return new TypedInput(`compareGreaterThan(${left.asUnknown()}, ${right.asUnknown()})`, TYPE_BOOLEAN);
}
case 'op.join':
return new TypedInput(`(${this.descendInput(node.left).asString()} + ${this.descendInput(node.right).asString()})`, TYPE_STRING);
case 'op.length':
return new TypedInput(`${this.descendInput(node.string).asString()}.length`, TYPE_NUMBER);
case 'op.less': {
const left = this.descendInput(node.left);
const right = this.descendInput(node.right);
// When the left operand is a number or NaN and the right operand is a number, we can use <
if (left.isAlwaysNumberOrNaN() && right.isAlwaysNumber()) {
return new TypedInput(`(${left.asNumberOrNaN()} < ${right.asNumber()})`, TYPE_BOOLEAN);
}
// When the left operand is a number and the right operand is a number or NaN, we can negate >=
if (left.isAlwaysNumber() && right.isAlwaysNumberOrNaN()) {
return new TypedInput(`!(${left.asNumber()} >= ${right.asNumberOrNaN()})`, TYPE_BOOLEAN);
}
// When either operand is known to never be a number, avoid all number parsing.
if (left.isNeverNumber() || right.isNeverNumber()) {
return new TypedInput(`(${left.asString()}.toLowerCase() < ${right.asString()}.toLowerCase())`, TYPE_BOOLEAN);
}
// No compile-time optimizations possible - use fallback method.
return new TypedInput(`compareLessThan(${left.asUnknown()}, ${right.asUnknown()})`, TYPE_BOOLEAN);
}
case 'op.letterOf':
return new TypedInput(`((${this.descendInput(node.string).asString()})[(${this.descendInput(node.letter).asNumber()} | 0) - 1] || "")`, TYPE_STRING);
case 'op.ln':
// Needs to be marked as NaN because Math.log(-1) == NaN
return new TypedInput(`Math.log(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER_NAN);
case 'op.log':
// Needs to be marked as NaN because Math.log(-1) == NaN
return new TypedInput(`(Math.log(${this.descendInput(node.value).asNumber()}) / Math.LN10)`, TYPE_NUMBER_NAN);
case 'op.mod':
this.descendedIntoModulo = true;
// Needs to be marked as NaN because mod(0, 0) (and others) == NaN
return new TypedInput(`mod(${this.descendInput(node.left).asNumber()}, ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
case 'op.multiply':
// Needs to be marked as NaN because Infinity * 0 === NaN
return new TypedInput(`(${this.descendInput(node.left).asNumber()} * ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
case 'op.not':
return new TypedInput(`!${this.descendInput(node.operand).asBoolean()}`, TYPE_BOOLEAN);
case 'op.or':
return new TypedInput(`(${this.descendInput(node.left).asBoolean()} || ${this.descendInput(node.right).asBoolean()})`, TYPE_BOOLEAN);
case 'op.random':
if (node.useInts) {
// Both inputs are ints, so we know neither are NaN
return new TypedInput(`randomInt(${this.descendInput(node.low).asNumber()}, ${this.descendInput(node.high).asNumber()})`, TYPE_NUMBER);
}
if (node.useFloats) {
return new TypedInput(`randomFloat(${this.descendInput(node.low).asNumber()}, ${this.descendInput(node.high).asNumber()})`, TYPE_NUMBER_NAN);
}
return new TypedInput(`runtime.ext_scratch3_operators._random(${this.descendInput(node.low).asUnknown()}, ${this.descendInput(node.high).asUnknown()})`, TYPE_NUMBER_NAN);
case 'op.round':
return new TypedInput(`Math.round(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
case 'op.sin':
return new TypedInput(`(Math.round(Math.sin((Math.PI * ${this.descendInput(node.value).asNumber()}) / 180) * 1e10) / 1e10)`, TYPE_NUMBER_NAN);
case 'op.sqrt':
// Needs to be marked as NaN because Math.sqrt(-1) === NaN
return new TypedInput(`Math.sqrt(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER_NAN);
case 'op.subtract':
// Needs to be marked as NaN because Infinity - Infinity === NaN
return new TypedInput(`(${this.descendInput(node.left).asNumber()} - ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
case 'op.tan':
return new TypedInput(`tan(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER_NAN);
case 'op.10^':
return new TypedInput(`(10 ** ${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
case 'procedures.call': {
const procedureCode = node.code;
const procedureVariant = node.variant;
const procedureData = this.ir.procedures[procedureVariant];
if (procedureData.stack === null) {
// TODO still need to evaluate arguments for side effects
return new TypedInput('""', TYPE_STRING);
}
// Recursion makes this complicated because:
// - We need to yield *between* each call in the same command block
// - We need to evaluate arguments *before* that yield happens
const procedureReference = `thread.procedures["${sanitize(procedureVariant)}"]`;
const args = [];
for (const input of node.arguments) {
args.push(this.descendInput(input).asSafe());
}
const joinedArgs = args.join(',');
const yieldForRecursion = !this.isWarp && procedureCode === this.script.procedureCode;
const yieldForHat = this.isInHat;
if (yieldForRecursion || yieldForHat) {
const runtimeFunction = procedureData.yields ? 'yieldThenCallGenerator' : 'yieldThenCall';
return new TypedInput(`(yield* ${runtimeFunction}(${procedureReference}, ${joinedArgs}))`, TYPE_UNKNOWN);
}
if (procedureData.yields) {
return new TypedInput(`(yield* ${procedureReference}(${joinedArgs}))`, TYPE_UNKNOWN);
}
return new TypedInput(`${procedureReference}(${joinedArgs})`, TYPE_UNKNOWN);
}
case 'sensing.answer':
return new TypedInput(`runtime.ext_scratch3_sensing._answer`, TYPE_STRING);
case 'sensing.colorTouchingColor':
return new TypedInput(`target.colorIsTouchingColor(colorToList(${this.descendInput(node.target).asColor()}), colorToList(${this.descendInput(node.mask).asColor()}))`, TYPE_BOOLEAN);
case 'sensing.date':
return new TypedInput(`(new Date().getDate())`, TYPE_NUMBER);
case 'sensing.dayofweek':
return new TypedInput(`(new Date().getDay() + 1)`, TYPE_NUMBER);
case 'sensing.daysSince2000':
return new TypedInput('daysSince2000()', TYPE_NUMBER);
case 'sensing.distance':
// TODO: on stages, this can be computed at compile time
return new TypedInput(`distance(${this.descendInput(node.target).asString()})`, TYPE_NUMBER);
case 'sensing.hour':
return new TypedInput(`(new Date().getHours())`, TYPE_NUMBER);
case 'sensing.minute':
return new TypedInput(`(new Date().getMinutes())`, TYPE_NUMBER);
case 'sensing.month':
return new TypedInput(`(new Date().getMonth() + 1)`, TYPE_NUMBER);
case 'sensing.of': {
const object = this.descendInput(node.object).asString();
const property = node.property;
if (node.object.kind === 'constant') {
const isStage = node.object.value === '_stage_';
// Note that if target isn't a stage, we can't assume it exists
const objectReference = isStage ? 'stage' : this.evaluateOnce(`runtime.getSpriteTargetByName(${object})`);
if (property === 'volume') {
return new TypedInput(`(${objectReference} ? ${objectReference}.volume : 0)`, TYPE_NUMBER);
}
if (isStage) {
switch (property) {
case 'background #':
// fallthrough for scratch 1.0 compatibility
case 'backdrop #':
return new TypedInput(`(${objectReference}.currentCostume + 1)`, TYPE_NUMBER);
case 'backdrop name':
return new TypedInput(`${objectReference}.getCostumes()[${objectReference}.currentCostume].name`, TYPE_STRING);
}
} else {
switch (property) {
case 'x position':
return new TypedInput(`(${objectReference} ? ${objectReference}.x : 0)`, TYPE_NUMBER);
case 'y position':
return new TypedInput(`(${objectReference} ? ${objectReference}.y : 0)`, TYPE_NUMBER);
case 'direction':
return new TypedInput(`(${objectReference} ? ${objectReference}.direction : 0)`, TYPE_NUMBER);
case 'costume #':
return new TypedInput(`(${objectReference} ? ${objectReference}.currentCostume + 1 : 0)`, TYPE_NUMBER);
case 'costume name':
return new TypedInput(`(${objectReference} ? ${objectReference}.getCostumes()[${objectReference}.currentCostume].name : 0)`, TYPE_UNKNOWN);
case 'size':
return new TypedInput(`(${objectReference} ? ${objectReference}.size : 0)`, TYPE_NUMBER);
}
}
const variableReference = this.evaluateOnce(`${objectReference} && ${objectReference}.lookupVariableByNameAndType("${sanitize(property)}", "", true)`);
return new TypedInput(`(${variableReference} ? ${variableReference}.value : 0)`, TYPE_UNKNOWN);
}
return new TypedInput(`runtime.ext_scratch3_sensing.getAttributeOf({OBJECT: ${object}, PROPERTY: "${sanitize(property)}" })`, TYPE_UNKNOWN);
}
case 'sensing.second':
return new TypedInput(`(new Date().getSeconds())`, TYPE_NUMBER);
case 'sensing.touching':
return new TypedInput(`target.isTouchingObject(${this.descendInput(node.object).asUnknown()})`, TYPE_BOOLEAN);
case 'sensing.touchingColor':
return new TypedInput(`target.isTouchingColor(colorToList(${this.descendInput(node.color).asColor()}))`, TYPE_BOOLEAN);
case 'sensing.username':
return new TypedInput('runtime.ioDevices.userData.getUsername()', TYPE_STRING);
case 'sensing.year':
return new TypedInput(`(new Date().getFullYear())`, TYPE_NUMBER);
case 'timer.get':
return new TypedInput('runtime.ioDevices.clock.projectTimer()', TYPE_NUMBER);
case 'tw.lastKeyPressed':
return new TypedInput('runtime.ioDevices.keyboard.getLastKeyPressed()', TYPE_STRING);
case 'var.get':
return this.descendVariable(node.variable);
default:
log.warn(`JS: Unknown input: ${node.kind}`, node);
throw new Error(`JS: Unknown input: ${node.kind}`);
}
}
/**
* @param {*} node Stacked node to compile.
*/
descendStackedBlock (node) {
switch (node.kind) {
case 'addons.call':
this.source += `${this.descendAddonCall(node)};\n`;
break;
case 'compat': {
// If the last command in a loop returns a promise, immediately continue to the next iteration.
// If you don't do this, the loop effectively yields twice per iteration and will run at half-speed.
const isLastInLoop = this.isLastBlockInLoop();
const blockType = node.blockType;
if (blockType === BlockType.COMMAND || blockType === BlockType.HAT) {
this.source += `${this.generateCompatibilityLayerCall(node, isLastInLoop)};\n`;
} else if (blockType === BlockType.CONDITIONAL || blockType === BlockType.LOOP || blockType === BlockType.INLINE) {
const branchVariable = this.localVariables.next();
this.source += `const ${branchVariable} = createBranchInfo(${blockType === BlockType.LOOP});\n`;
this.source += `while (${branchVariable}.branch = +(${this.generateCompatibilityLayerCall(node, false, branchVariable)})) {\n`;
this.source += `switch (${branchVariable}.branch) {\n`;
for (const index in node.substacks) {
this.source += `case ${+index}: {\n`;
this.descendStack(node.substacks[index], new Frame(false));
this.source += `break;\n`;
this.source += `}\n`; // close case
}
this.source += '}\n'; // close switch
this.source += `if (!${branchVariable}.isLoop) break;\n`;
this.yieldLoop();
this.source += '}\n'; // close while
} else {
throw new Error(`Unknown block type: ${blockType}`);
}
if (isLastInLoop) {
this.source += 'if (hasResumedFromPromise) {hasResumedFromPromise = false;continue;}\n';
}
break;
}
case 'control.createClone':
this.source += `runtime.ext_scratch3_control._createClone(${this.descendInput(node.target).asString()}, target);\n`;
break;
case 'control.deleteClone':
this.source += 'if (!target.isOriginal) {\n';
this.source += ' runtime.disposeTarget(target);\n';
this.source += ' runtime.stopForTarget(target);\n';
this.retire();
this.source += '}\n';
break;
case 'control.for': {
this.resetVariableInputs();
const index = this.localVariables.next();
this.source += `var ${index} = 0; `;
this.source += `while (${index} < ${this.descendInput(node.count).asNumber()}) { `;
this.source += `${index}++; `;
this.source += `${this.referenceVariable(node.variable)}.value = ${index};\n`;
this.descendStack(node.do, new Frame(true));
this.yieldLoop();
this.source += '}\n';
break;
}
case 'control.if':
this.source += `if (${this.descendInput(node.condition).asBoolean()}) {\n`;
this.descendStack(node.whenTrue, new Frame(false));
// only add the else branch if it won't be empty
// this makes scripts have a bit less useless noise in them
if (node.whenFalse.length) {
this.source += `} else {\n`;
this.descendStack(node.whenFalse, new Frame(false));
}
this.source += `}\n`;
break;
case 'control.repeat': {
const i = this.localVariables.next();
this.source += `for (var ${i} = ${this.descendInput(node.times).asNumber()}; ${i} >= 0.5; ${i}--) {\n`;
this.descendStack(node.do, new Frame(true));
this.yieldLoop();
this.source += `}\n`;
break;
}
case 'control.stopAll':
this.source += 'runtime.stopAll();\n';
this.retire();
break;
case 'control.stopOthers':
this.source += 'runtime.stopForTarget(target, thread);\n';
break;
case 'control.stopScript':
this.stopScript();
break;
case 'control.wait': {
const duration = this.localVariables.next();
this.source += `thread.timer = timer();\n`;
this.source += `var ${duration} = Math.max(0, 1000 * ${this.descendInput(node.seconds).asNumber()});\n`;
this.requestRedraw();
// always yield at least once, even on 0 second durations
this.yieldNotWarp();
this.source += `while (thread.timer.timeElapsed() < ${duration}) {\n`;
this.yieldStuckOrNotWarp();
this.source += '}\n';
this.source += 'thread.timer = null;\n';
break;
}
case 'control.waitUntil': {
this.resetVariableInputs();
this.source += `while (!${this.descendInput(node.condition).asBoolean()}) {\n`;
this.yieldStuckOrNotWarp();
this.source += `}\n`;
break;
}
case 'control.while':
this.resetVariableInputs();
this.source += `while (${this.descendInput(node.condition).asBoolean()}) {\n`;
this.descendStack(node.do, new Frame(true));
if (node.warpTimer) {
this.yieldStuckOrNotWarp();
} else {
this.yieldLoop();
}
this.source += `}\n`;
break;
case 'counter.clear':
this.source += 'runtime.ext_scratch3_control._counter = 0;\n';
break;
case 'counter.increment':
this.source += 'runtime.ext_scratch3_control._counter++;\n';
break;
case 'hat.edge':
this.isInHat = true;
this.source += '{\n';
// For exact Scratch parity, evaluate the input before checking old edge state.
// Can matter if the input is not instantly evaluated.
this.source += `const resolvedValue = ${this.descendInput(node.condition).asBoolean()};\n`;
this.source += `const id = "${sanitize(node.id)}";\n`;
this.source += 'const hasOldEdgeValue = target.hasEdgeActivatedValue(id);\n';
this.source += `const oldEdgeValue = target.updateEdgeActivatedValue(id, resolvedValue);\n`;
this.source += `const edgeWasActivated = hasOldEdgeValue ? (!oldEdgeValue && resolvedValue) : resolvedValue;\n`;
this.source += `if (!edgeWasActivated) {\n`;
this.retire();
this.source += '}\n';
this.source += 'yield;\n';
this.source += '}\n';
this.isInHat = false;
break;
case 'hat.predicate':
this.isInHat = true;
this.source += `if (!${this.descendInput(node.condition).asBoolean()}) {\n`;
this.retire();
this.source += '}\n';
this.source += 'yield;\n';
this.isInHat = false;
break;
case 'event.broadcast':
this.source += `startHats("event_whenbroadcastreceived", { BROADCAST_OPTION: ${this.descendInput(node.broadcast).asString()} });\n`;
this.resetVariableInputs();
break;
case 'event.broadcastAndWait':
this.source += `yield* waitThreads(startHats("event_whenbroadcastreceived", { BROADCAST_OPTION: ${this.descendInput(node.broadcast).asString()} }));\n`;
this.yielded();
break;
case 'list.add': {
const list = this.referenceVariable(node.list);
this.source += `${list}.value.push(${this.descendInput(node.item).asSafe()});\n`;
this.source += `${list}._monitorUpToDate = false;\n`;
break;
}
case 'list.delete': {
const list = this.referenceVariable(node.list);
const index = this.descendInput(node.index);
if (index instanceof ConstantInput) {
if (index.constantValue === 'last') {
this.source += `${list}.value.pop();\n`;
this.source += `${list}._monitorUpToDate = false;\n`;
break;
}
if (+index.constantValue === 1) {
this.source += `${list}.value.shift();\n`;
this.source += `${list}._monitorUpToDate = false;\n`;
break;
}
// do not need a special case for all as that is handled in IR generation (list.deleteAll)
}
this.source += `listDelete(${list}, ${index.asUnknown()});\n`;
break;
}
case 'list.deleteAll':
this.source += `${this.referenceVariable(node.list)}.value = [];\n`;
break;
case 'list.hide':
this.source += `runtime.monitorBlocks.changeBlock({ id: "${sanitize(node.list.id)}", element: "checkbox", value: false }, runtime);\n`;
break;
case 'list.insert': {
const list = this.referenceVariable(node.list);
const index = this.descendInput(node.index);
const item = this.descendInput(node.item);
if (index instanceof ConstantInput && +index.constantValue === 1) {
this.source += `${list}.value.unshift(${item.asSafe()});\n`;
this.source += `${list}._monitorUpToDate = false;\n`;
break;
}
this.source += `listInsert(${list}, ${index.asUnknown()}, ${item.asSafe()});\n`;
break;
}
case 'list.replace':
this.source += `listReplace(${this.referenceVariable(node.list)}, ${this.descendInput(node.index).asUnknown()}, ${this.descendInput(node.item).asSafe()});\n`;
break;
case 'list.show':
this.source += `runtime.monitorBlocks.changeBlock({ id: "${sanitize(node.list.id)}", element: "checkbox", value: true }, runtime);\n`;
break;
case 'looks.backwardLayers':
if (!this.target.isStage) {
this.source += `target.goBackwardLayers(${this.descendInput(node.layers).asNumber()});\n`;
}
break;
case 'looks.clearEffects':
this.source += 'target.clearEffects();\n';
break;
case 'looks.changeEffect':
if (Object.prototype.hasOwnProperty.call(this.target.effects, node.effect)) {