-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpxtblocks.js
12575 lines (12575 loc) · 597 KB
/
pxtblocks.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
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
///<reference path='../localtypings/pxtblockly.d.ts'/>
/// <reference path="../built/pxtlib.d.ts" />
var iface;
var pxt;
(function (pxt) {
var blocks;
(function (blocks_1) {
function workerOpAsync(op, arg) {
return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(op, arg);
}
blocks_1.workerOpAsync = workerOpAsync;
var placeholders = {};
var MAX_COMMENT_LINE_LENGTH = 50;
///////////////////////////////////////////////////////////////////////////////
// Miscellaneous utility functions
///////////////////////////////////////////////////////////////////////////////
// Mutate [a1] in place and append to it the elements from [a2].
function append(a1, a2) {
a1.push.apply(a1, a2);
}
// A few wrappers for basic Block operations that throw errors when compilation
// is not possible. (The outer code catches these and highlights the relevant
// block.)
// Internal error (in our code). Compilation shouldn't proceed.
function assert(x) {
if (!x)
throw new Error("Assertion failure");
}
function throwBlockError(msg, block) {
var e = new Error(msg);
e.block = block;
throw e;
}
///////////////////////////////////////////////////////////////////////////////
// Types
//
// We slap a very simple type system on top of Blockly. This is needed to ensure
// we generate valid TouchDevelop code (otherwise compilation from TD to C++
// would not work).
///////////////////////////////////////////////////////////////////////////////
// There are several layers of abstraction for the type system.
// - Block are annotated with a string return type, and a string type for their
// input blocks (see blocks-custom.js). We use that as the reference semantics
// for the blocks.
// - In this "type system", we use the enum Type. Using an enum rules out more
// mistakes.
// - When emitting code, we target the "TouchDevelop types".
//
// Type inference / checking is done as follows. First, we try to assign a type
// to all variables. We do this by examining all variable assignments and
// figuring out the type from the right-hand side. There's a fixpoint computation
// (see [mkEnv]). Then, we propagate down the expected type when doing code
// generation; when generating code for a variable dereference, if the expected
// type doesn't match the inferred type, it's an error. If the type was
// undetermined as of yet, the type of the variable becomes the expected type.
var Point = /** @class */ (function () {
function Point(link, type, parentType, childType, isArrayType) {
this.link = link;
this.type = type;
this.parentType = parentType;
this.childType = childType;
this.isArrayType = isArrayType;
}
return Point;
}());
blocks_1.Point = Point;
var BlockDeclarationType;
(function (BlockDeclarationType) {
BlockDeclarationType[BlockDeclarationType["None"] = 0] = "None";
BlockDeclarationType[BlockDeclarationType["Argument"] = 1] = "Argument";
BlockDeclarationType[BlockDeclarationType["Assigned"] = 2] = "Assigned";
BlockDeclarationType[BlockDeclarationType["Implicit"] = 3] = "Implicit";
})(BlockDeclarationType = blocks_1.BlockDeclarationType || (blocks_1.BlockDeclarationType = {}));
function find(p) {
if (p.link)
return find(p.link);
return p;
}
function union(p1, p2) {
var _p1 = find(p1);
var _p2 = find(p2);
assert(_p1.link == null && _p2.link == null);
if (_p1 == _p2)
return;
if (_p1.childType && _p2.childType) {
var ct = _p1.childType;
_p1.childType = null;
union(ct, _p2.childType);
}
else if (_p1.childType && !_p2.childType) {
_p2.childType = _p1.childType;
}
if (_p1.parentType && _p2.parentType) {
var pt = _p1.parentType;
_p1.parentType = null;
union(pt, _p2.parentType);
}
else if (_p1.parentType && !_p2.parentType && !_p2.type) {
_p2.parentType = _p1.parentType;
}
var t = unify(_p1.type, _p2.type);
p1.link = _p2;
_p1.link = _p2;
_p1.isArrayType = _p2.isArrayType;
p1.type = null;
p2.type = t;
}
// Ground types.
function mkPoint(t, isArrayType) {
if (isArrayType === void 0) { isArrayType = false; }
return new Point(null, t, null, null, isArrayType);
}
var pNumber = mkPoint("number");
var pBoolean = mkPoint("boolean");
var pString = mkPoint("string");
var pUnit = mkPoint("void");
function ground(t) {
if (!t)
return mkPoint(t);
switch (t.toLowerCase()) {
case "number": return pNumber;
case "boolean": return pBoolean;
case "string": return pString;
case "void": return pUnit;
default:
// Unification variable.
return mkPoint(t);
}
}
///////////////////////////////////////////////////////////////////////////////
// Type inference
//
// Expressions are now directly compiled as a tree. This requires knowing, for
// each property ref, the right value for its [parent] property.
///////////////////////////////////////////////////////////////////////////////
// Infers the expected type of an expression by looking at the untranslated
// block and figuring out, from the look of it, what type of expression it
// holds.
function returnType(e, b) {
assert(b != null);
if (isPlaceholderBlock(b)) {
if (!b.p)
b.p = mkPoint(null);
return find(b.p);
}
if (b.type == "variables_get")
return find(lookup(e, b, b.getField("VAR").getText()).type);
if (b.type == "function_call_output") {
return getReturnTypeOfFunctionCall(e, b);
}
if (!b.outputConnection) {
return ground(pUnit.type);
}
var check = b.outputConnection.check_ && b.outputConnection.check_.length ? b.outputConnection.check_[0] : "T";
if (check === "Array") {
if (b.outputConnection.check_.length > 1) {
// HACK: The real type is stored as the second check
return ground(b.outputConnection.check_[1]);
}
// The only block that hits this case should be lists_create_with, so we
// can safely infer the type from the first input that has a return type
var tp = void 0;
if (b.inputList && b.inputList.length) {
for (var _i = 0, _a = b.inputList; _i < _a.length; _i++) {
var input = _a[_i];
if (input.connection && input.connection.targetBlock()) {
var t = find(returnType(e, input.connection.targetBlock()));
if (t) {
if (t.parentType) {
return t.parentType;
}
tp = ground(t.type + "[]");
genericLink(tp, t);
break;
}
}
}
}
if (tp)
tp.isArrayType = true;
return tp || mkPoint(null, true);
}
else if (check === "T") {
var func_1 = e.stdCallTable[b.type];
var isArrayGet = b.type === "lists_index_get";
if (isArrayGet || func_1 && func_1.comp.thisParameter) {
var parentInput = void 0;
if (isArrayGet) {
parentInput = b.inputList.find(function (i) { return i.name === "LIST"; });
}
else {
parentInput = b.inputList.find(function (i) { return i.name === func_1.comp.thisParameter.definitionName; });
}
if (parentInput.connection && parentInput.connection.targetBlock()) {
var parentType = returnType(e, parentInput.connection.targetBlock());
if (parentType.childType) {
return parentType.childType;
}
var p = isArrayType(parentType.type) ? mkPoint(parentType.type.substr(0, parentType.type.length - 2)) : mkPoint(null);
genericLink(parentType, p);
return p;
}
}
return mkPoint(null);
}
return ground(check);
}
function getReturnTypeOfFunction(e, name) {
if (!e.userFunctionReturnValues[name]) {
var definition = Blockly.Functions.getDefinition(name, e.workspace);
var res = mkPoint("void");
if (isFunctionRecursive(definition, true)) {
res = mkPoint("any");
}
else {
var returnTypes = [];
for (var _i = 0, _a = definition.getDescendants(false); _i < _a.length; _i++) {
var child = _a[_i];
if (child.type === "function_return") {
attachPlaceholderIf(e, child, "RETURN_VALUE");
returnTypes.push(returnType(e, getInputTargetBlock(child, "RETURN_VALUE")));
}
}
if (returnTypes.length) {
try {
var unified = mkPoint(null);
for (var _b = 0, returnTypes_1 = returnTypes; _b < returnTypes_1.length; _b++) {
var point = returnTypes_1[_b];
union(unified, point);
}
res = unified;
}
catch (err) {
e.diagnostics.push({
blockId: definition.id,
message: pxt.Util.lf("Function '{0}' has an invalid return type", name)
});
res = mkPoint("any");
}
}
}
e.userFunctionReturnValues[name] = res;
}
return e.userFunctionReturnValues[name];
}
function getReturnTypeOfFunctionCall(e, call) {
var name = call.getField("function_name").getText();
return getReturnTypeOfFunction(e, name);
}
// Basic type unification routine; easy, because there's no structural types.
// FIXME: Generics are not supported
function unify(t1, t2) {
if (t1 == null || t1 === "Array" && isArrayType(t2))
return t2;
else if (t2 == null || t2 === "Array" && isArrayType(t1))
return t1;
else if (t1 == t2)
return t1;
else
throw new Error("cannot mix " + t1 + " with " + t2);
}
function isArrayType(type) {
return type && type.indexOf("[]") !== -1;
}
function mkPlaceholderBlock(e, parent, type) {
// XXX define a proper placeholder block type
return {
type: "placeholder",
p: mkPoint(type || null),
workspace: e.workspace,
parentBlock_: parent
};
}
function attachPlaceholderIf(e, b, n, type) {
// Ugly hack to keep track of the type we want there.
var target = b.getInputTargetBlock(n);
if (!target) {
if (!placeholders[b.id]) {
placeholders[b.id] = {};
}
if (!placeholders[b.id][n]) {
placeholders[b.id][n] = mkPlaceholderBlock(e, b, type);
}
}
else if (target.type === pxtc.TS_OUTPUT_TYPE && !(target.p)) {
target.p = mkPoint(null);
}
}
function getLoopVariableField(b) {
return (b.type == "pxt_controls_for" || b.type == "pxt_controls_for_of") ?
getInputTargetBlock(b, "VAR") : b;
}
function getInputTargetBlock(b, n) {
var res = b.getInputTargetBlock(n);
if (!res) {
return placeholders[b.id] && placeholders[b.id][n];
}
else {
return res;
}
}
function removeAllPlaceholders() {
placeholders = {};
}
// Unify the *return* type of the parameter [n] of block [b] with point [p].
function unionParam(e, b, n, p) {
attachPlaceholderIf(e, b, n);
try {
union(returnType(e, getInputTargetBlock(b, n)), p);
}
catch (e) {
// TypeScript should catch this error and bubble it up
}
}
function infer(allBlocks, e, w) {
if (allBlocks)
allBlocks.filter(function (b) { return b.isEnabled(); }).forEach(function (b) {
try {
switch (b.type) {
case "math_op2":
unionParam(e, b, "x", ground(pNumber.type));
unionParam(e, b, "y", ground(pNumber.type));
break;
case "math_op3":
unionParam(e, b, "x", ground(pNumber.type));
break;
case "math_arithmetic":
case "logic_compare":
switch (b.getFieldValue("OP")) {
case "ADD":
case "MINUS":
case "MULTIPLY":
case "DIVIDE":
case "LT":
case "LTE":
case "GT":
case "GTE":
case "POWER":
unionParam(e, b, "A", ground(pNumber.type));
unionParam(e, b, "B", ground(pNumber.type));
break;
case "AND":
case "OR":
attachPlaceholderIf(e, b, "A", pBoolean.type);
attachPlaceholderIf(e, b, "B", pBoolean.type);
break;
case "EQ":
case "NEQ":
attachPlaceholderIf(e, b, "A");
attachPlaceholderIf(e, b, "B");
var p1_1 = returnType(e, getInputTargetBlock(b, "A"));
var p2 = returnType(e, getInputTargetBlock(b, "B"));
try {
union(p1_1, p2);
}
catch (e) {
// TypeScript should catch this error and bubble it up
}
break;
}
break;
case "logic_operation":
attachPlaceholderIf(e, b, "A", pBoolean.type);
attachPlaceholderIf(e, b, "B", pBoolean.type);
break;
case "logic_negate":
attachPlaceholderIf(e, b, "BOOL", pBoolean.type);
break;
case "controls_if":
for (var i = 0; i <= b.elseifCount_; ++i)
attachPlaceholderIf(e, b, "IF" + i, pBoolean.type);
break;
case "pxt_controls_for":
case "controls_simple_for":
unionParam(e, b, "TO", ground(pNumber.type));
break;
case "pxt_controls_for_of":
case "controls_for_of":
var listTp = returnType(e, getInputTargetBlock(b, "LIST"));
var elementTp = lookup(e, b, getLoopVariableField(b).getField("VAR").getText()).type;
genericLink(listTp, elementTp);
break;
case "variables_set":
case "variables_change":
var p1 = lookup(e, b, b.getField("VAR").getText()).type;
attachPlaceholderIf(e, b, "VALUE");
var rhs = getInputTargetBlock(b, "VALUE");
if (rhs) {
var tr = returnType(e, rhs);
try {
union(p1, tr);
}
catch (e) {
// TypeScript should catch this error and bubble it up
}
}
break;
case "controls_repeat_ext":
unionParam(e, b, "TIMES", ground(pNumber.type));
break;
case "device_while":
attachPlaceholderIf(e, b, "COND", pBoolean.type);
break;
case "lists_index_get":
unionParam(e, b, "LIST", ground("Array"));
unionParam(e, b, "INDEX", ground(pNumber.type));
var listType = returnType(e, getInputTargetBlock(b, "LIST"));
var ret = returnType(e, b);
genericLink(listType, ret);
break;
case "lists_index_set":
unionParam(e, b, "LIST", ground("Array"));
attachPlaceholderIf(e, b, "VALUE");
handleGenericType(b, "LIST");
unionParam(e, b, "INDEX", ground(pNumber.type));
break;
case 'function_definition':
getReturnTypeOfFunction(e, b.getField("function_name").getText());
break;
case 'function_call':
case 'function_call_output':
b.getArguments().forEach(function (arg) {
unionParam(e, b, arg.id, ground(arg.type));
});
break;
case pxtc.TS_RETURN_STATEMENT_TYPE:
attachPlaceholderIf(e, b, "RETURN_VALUE");
break;
case pxtc.PAUSE_UNTIL_TYPE:
unionParam(e, b, "PREDICATE", pBoolean);
break;
default:
if (b.type in e.stdCallTable) {
var call_1 = e.stdCallTable[b.type];
if (call_1.attrs.shim === "ENUM_GET" || call_1.attrs.shim === "KIND_GET")
return;
visibleParams(call_1, countOptionals(b)).forEach(function (p, i) {
var isInstance = call_1.isExtensionMethod && i === 0;
if (p.definitionName && !b.getFieldValue(p.definitionName)) {
var i_1 = b.inputList.find(function (i) { return i.name == p.definitionName; });
if (i_1 && i_1.connection && i_1.connection.check_) {
if (isInstance && connectionCheck(i_1) === "Array") {
var gen = handleGenericType(b, p.definitionName);
if (gen) {
return;
}
}
// All of our injected blocks have single output checks, but the builtin
// blockly ones like string.length and array.length might have multiple
for (var j = 0; j < i_1.connection.check_.length; j++) {
try {
var t = i_1.connection.check_[j];
unionParam(e, b, p.definitionName, ground(t));
break;
}
catch (e) {
// Ignore type checking errors in the blocks...
}
}
}
}
});
}
}
}
catch (err) {
var be = err.block || b;
be.setWarningText(err + "");
e.errors.push(be);
}
});
// Last pass: if some variable has no type (because it was never used or
// assigned to), just unify it with int...
e.allVariables.forEach(function (v) {
if (getConcreteType(v.type).type == null)
union(v.type, ground(v.type.isArrayType ? "number[]" : pNumber.type));
});
function connectionCheck(i) {
return i.name ? i.connection && i.connection.check_ && i.connection.check_.length ? i.connection.check_[0] : "T" : undefined;
}
function handleGenericType(b, name) {
var genericArgs = b.inputList.filter(function (input) { return connectionCheck(input) === "T"; });
if (genericArgs.length) {
var gen = getInputTargetBlock(b, genericArgs[0].name);
if (gen) {
var arg = returnType(e, gen);
var arrayType = arg.type ? ground(returnType(e, gen).type + "[]") : ground(null);
genericLink(arrayType, arg);
unionParam(e, b, name, arrayType);
return true;
}
}
return false;
}
}
function genericLink(parent, child) {
var p = find(parent);
var c = find(child);
if (p.childType) {
union(p.childType, c);
}
else if (!p.type) {
p.childType = c;
}
if (c.parentType) {
union(c.parentType, p);
}
else if (!c.type) {
c.parentType = p;
}
if (isArrayType(p.type))
p.isArrayType = true;
}
function getConcreteType(point, found) {
if (found === void 0) { found = []; }
var t = find(point);
if (found.indexOf(t) === -1) {
found.push(t);
if (!t.type || t.type === "Array") {
if (t.parentType) {
var parent_1 = getConcreteType(t.parentType, found);
if (parent_1.type && parent_1.type !== "Array") {
if (isArrayType(parent_1.type)) {
t.type = parent_1.type.substr(0, parent_1.type.length - 2);
}
else {
t.type = parent_1.type;
}
return t;
}
}
if (t.childType) {
var child = getConcreteType(t.childType, found);
if (child.type) {
t.type = child.type + "[]";
return t;
}
}
}
}
return t;
}
///////////////////////////////////////////////////////////////////////////////
// Expressions
//
// Expressions are now directly compiled as a tree. This requires knowing, for
// each property ref, the right value for its [parent] property.
///////////////////////////////////////////////////////////////////////////////
function extractNumber(b) {
var v = b.getFieldValue(b.type === "math_number_minmax" ? "SLIDER" : "NUM");
var parsed = parseFloat(v);
checkNumber(parsed, b);
return parsed;
}
function checkNumber(n, b) {
if (!isFinite(n) || isNaN(n)) {
throwBlockError(lf("Number entered is either too large or too small"), b);
}
}
function extractTsExpression(e, b, comments) {
return blocks_1.mkText(b.getFieldValue("EXPRESSION").trim());
}
function compileNumber(e, b, comments) {
return blocks_1.H.mkNumberLiteral(extractNumber(b));
}
var opToTok = {
// POWER gets a special treatment because there's no operator for it in
// TouchDevelop
"ADD": "+",
"MINUS": "-",
"MULTIPLY": "*",
"DIVIDE": "/",
"LT": "<",
"LTE": "<=",
"GT": ">",
"GTE": ">=",
"AND": "&&",
"OR": "||",
"EQ": "==",
"NEQ": "!=",
"POWER": "**"
};
function compileArithmetic(e, b, comments) {
var bOp = b.getFieldValue("OP");
var left = getInputTargetBlock(b, "A");
var right = getInputTargetBlock(b, "B");
var args = [compileExpression(e, left, comments), compileExpression(e, right, comments)];
var t = returnType(e, left).type;
if (t == pString.type) {
if (bOp == "EQ")
return blocks_1.H.mkSimpleCall("==", args);
else if (bOp == "NEQ")
return blocks_1.H.mkSimpleCall("!=", args);
}
else if (t == pBoolean.type)
return blocks_1.H.mkSimpleCall(opToTok[bOp], args);
// Compilation of math operators.
assert(bOp in opToTok);
return blocks_1.H.mkSimpleCall(opToTok[bOp], args);
}
function compileModulo(e, b, comments) {
var left = getInputTargetBlock(b, "DIVIDEND");
var right = getInputTargetBlock(b, "DIVISOR");
var args = [compileExpression(e, left, comments), compileExpression(e, right, comments)];
return blocks_1.H.mkSimpleCall("%", args);
}
function compileMathOp2(e, b, comments) {
var op = b.getFieldValue("op");
var x = compileExpression(e, getInputTargetBlock(b, "x"), comments);
var y = compileExpression(e, getInputTargetBlock(b, "y"), comments);
return blocks_1.H.mathCall(op, [x, y]);
}
function compileMathOp3(e, b, comments) {
var x = compileExpression(e, getInputTargetBlock(b, "x"), comments);
return blocks_1.H.mathCall("abs", [x]);
}
function compileText(e, b, comments) {
return blocks_1.H.mkStringLiteral(b.getFieldValue("TEXT"));
}
function compileTextJoin(e, b, comments) {
var last;
var i = 0;
while (true) {
var val = getInputTargetBlock(b, "ADD" + i);
i++;
if (!val) {
if (i < b.inputList.length) {
continue;
}
else {
break;
}
}
var compiled = compileExpression(e, val, comments);
if (!last) {
if (val.type.indexOf("text") === 0) {
last = compiled;
}
else {
// If we don't start with a string, then the TS won't match
// the implied semantics of the blocks
last = blocks_1.H.mkSimpleCall("+", [blocks_1.H.mkStringLiteral(""), compiled]);
}
}
else {
last = blocks_1.H.mkSimpleCall("+", [last, compiled]);
}
}
if (!last) {
return blocks_1.H.mkStringLiteral("");
}
return last;
}
function compileBoolean(e, b, comments) {
return blocks_1.H.mkBooleanLiteral(b.getFieldValue("BOOL") == "TRUE");
}
function compileNot(e, b, comments) {
var expr = compileExpression(e, getInputTargetBlock(b, "BOOL"), comments);
return blocks_1.mkPrefix("!", [blocks_1.H.mkParenthesizedExpression(expr)]);
}
function compileCreateList(e, b, comments) {
// collect argument
var args = b.inputList.map(function (input) { return input.connection && input.connection.targetBlock() ? compileExpression(e, input.connection.targetBlock(), comments) : undefined; })
.filter(function (e) { return !!e; });
return blocks_1.H.mkArrayLiteral(args);
}
function compileListGet(e, b, comments) {
var listBlock = getInputTargetBlock(b, "LIST");
var listExpr = compileExpression(e, listBlock, comments);
var index = compileExpression(e, getInputTargetBlock(b, "INDEX"), comments);
var res = blocks_1.mkGroup([listExpr, blocks_1.mkText("["), index, blocks_1.mkText("]")]);
return res;
}
function compileListSet(e, b, comments) {
var listBlock = getInputTargetBlock(b, "LIST");
var listExpr = compileExpression(e, listBlock, comments);
var index = compileExpression(e, getInputTargetBlock(b, "INDEX"), comments);
var value = compileExpression(e, getInputTargetBlock(b, "VALUE"), comments);
var res = blocks_1.mkGroup([listExpr, blocks_1.mkText("["), index, blocks_1.mkText("] = "), value]);
return listBlock.type === "lists_create_with" ? prefixWithSemicolon(res) : res;
}
function compileMathJsOp(e, b, comments) {
var op = b.getFieldValue("OP");
var args = [compileExpression(e, getInputTargetBlock(b, "ARG0"), comments)];
if (b.getInput("ARG1")) {
args.push(compileExpression(e, getInputTargetBlock(b, "ARG1"), comments));
}
return blocks_1.H.mathCall(op, args);
}
function compileFunctionDefinition(e, b, comments) {
var name = escapeVarName(b.getField("function_name").getText(), e, true);
var stmts = getInputTargetBlock(b, "STACK");
var argsDeclaration = b.getArguments().map(function (a) {
return escapeVarName(a.name, e) + ": " + a.type;
});
var isRecursive = isFunctionRecursive(b, false);
return [
blocks_1.mkText("function " + name + " (" + argsDeclaration.join(", ") + ")" + (isRecursive ? ": any" : "")),
compileStatements(e, stmts)
];
}
function compileProcedure(e, b, comments) {
var name = escapeVarName(b.getFieldValue("NAME"), e, true);
var stmts = getInputTargetBlock(b, "STACK");
return [
blocks_1.mkText("function " + name + "() "),
compileStatements(e, stmts)
];
}
function compileProcedureCall(e, b, comments) {
var name = escapeVarName(b.getFieldValue("NAME"), e, true);
return blocks_1.mkStmt(blocks_1.mkText(name + "()"));
}
function compileFunctionCall(e, b, comments, statement) {
var name = escapeVarName(b.getField("function_name").getText(), e, true);
var externalInputs = !b.getInputsInline();
var args = b.getArguments().map(function (a) {
return {
actualName: a.name,
definitionName: a.id
};
});
var compiledArgs = args.map(function (a) { return compileArgument(e, b, a, comments); });
var res = blocks_1.H.stdCall(name, compiledArgs, externalInputs);
if (statement) {
return blocks_1.mkStmt(res);
}
return res;
}
function compileReturnStatement(e, b, comments) {
var expression = getInputTargetBlock(b, "RETURN_VALUE");
if (expression && expression.type != "placeholder") {
return blocks_1.mkStmt(blocks_1.mkText("return "), compileExpression(e, expression, comments));
}
else {
return blocks_1.mkStmt(blocks_1.mkText("return"));
}
}
function compileArgumentReporter(e, b, comments) {
var name = escapeVarName(b.getFieldValue("VALUE"), e);
return blocks_1.mkText(name);
}
function compileWorkspaceComment(c) {
var content = c.getContent();
return blocks_1.Helpers.mkMultiComment(content.trim());
}
function defaultValueForType(t) {
if (t.type == null) {
union(t, ground(pNumber.type));
t = find(t);
}
if (isArrayType(t.type) || t.isArrayType) {
return blocks_1.mkText("[]");
}
switch (t.type) {
case "boolean":
return blocks_1.H.mkBooleanLiteral(false);
case "number":
return blocks_1.H.mkNumberLiteral(0);
case "string":
return blocks_1.H.mkStringLiteral("");
default:
return blocks_1.mkText("null");
}
}
// [t] is the expected type; we assume that we never null block children
// (because placeholder blocks have been inserted by the type-checking phase
// whenever a block was actually missing).
function compileExpression(e, b, comments) {
assert(b != null);
e.stats[b.type] = (e.stats[b.type] || 0) + 1;
maybeAddComment(b, comments);
var expr;
if (b.type == "placeholder" || !(b.isEnabled && b.isEnabled())) {
var ret = find(returnType(e, b));
if (ret.type === "Array") {
// FIXME: Can't use default type here because TS complains about
// the array having an implicit any type. However, forcing this
// to be a number array may cause type issues. Also, potential semicolon
// issues if we ever have a block where the array is not the first argument...
var isExpression = b.parentBlock_.type === "lists_index_get";
if (!isExpression) {
var call = e.stdCallTable[b.parentBlock_.type];
isExpression = call && call.isExpression;
}
var arrayNode = blocks_1.mkText("[0]");
expr = isExpression ? arrayNode : prefixWithSemicolon(arrayNode);
}
else {
expr = defaultValueForType(returnType(e, b));
}
}
else
switch (b.type) {
case "math_number":
case "math_integer":
case "math_whole_number":
expr = compileNumber(e, b, comments);
break;
case "math_number_minmax":
expr = compileNumber(e, b, comments);
break;
case "math_op2":
expr = compileMathOp2(e, b, comments);
break;
case "math_op3":
expr = compileMathOp3(e, b, comments);
break;
case "math_arithmetic":
case "logic_compare":
case "logic_operation":
expr = compileArithmetic(e, b, comments);
break;
case "math_modulo":
expr = compileModulo(e, b, comments);
break;
case "logic_boolean":
expr = compileBoolean(e, b, comments);
break;
case "logic_negate":
expr = compileNot(e, b, comments);
break;
case "variables_get":
expr = compileVariableGet(e, b);
break;
case "text":
expr = compileText(e, b, comments);
break;
case "text_join":
expr = compileTextJoin(e, b, comments);
break;
case "lists_create_with":
expr = compileCreateList(e, b, comments);
break;
case "lists_index_get":
expr = compileListGet(e, b, comments);
break;
case "lists_index_set":
expr = compileListSet(e, b, comments);
break;
case "math_js_op":
case "math_js_round":
expr = compileMathJsOp(e, b, comments);
break;
case pxtc.TS_OUTPUT_TYPE:
expr = extractTsExpression(e, b, comments);
break;
case "argument_reporter_boolean":
case "argument_reporter_number":
case "argument_reporter_string":
case "argument_reporter_custom":
expr = compileArgumentReporter(e, b, comments);
break;
case "function_call_output":
expr = compileFunctionCall(e, b, comments, false);
break;
default:
var call = e.stdCallTable[b.type];
if (call) {
if (call.imageLiteral)
expr = compileImage(e, b, call.imageLiteral, call.imageLiteralColumns, call.imageLiteralRows, call.namespace, call.f, visibleParams(call, countOptionals(b)).map(function (ar) { return compileArgument(e, b, ar, comments); }));
else
expr = compileStdCall(e, b, call, comments);
}
else {
pxt.reportError("blocks", "unable to compile expression", { "details": b.type });
expr = defaultValueForType(returnType(e, b));
}
break;
}
expr.id = b.id;
return expr;
}
blocks_1.compileExpression = compileExpression;
function lookup(e, b, name) {
return getVarInfo(name, e.idToScope[b.id]);
}
function emptyEnv(w) {
return {
workspace: w,
stdCallTable: {},
userFunctionReturnValues: {},
diagnostics: [],
errors: [],
renames: {
oldToNew: {},
takenNames: {},
oldToNewFunctions: {}
},
stats: {},
enums: [],
kinds: [],
idToScope: {},
allVariables: [],
blocksInfo: null,
generatedVarDeclarations: {}
};
}
;
///////////////////////////////////////////////////////////////////////////////
// Statements
///////////////////////////////////////////////////////////////////////////////
function compileControlsIf(e, b, comments) {
var stmts = [];
// Notice the <= (if there's no else-if, we still compile the primary if).
for (var i = 0; i <= b.elseifCount_; ++i) {
var cond = compileExpression(e, getInputTargetBlock(b, "IF" + i), comments);
var thenBranch = compileStatements(e, getInputTargetBlock(b, "DO" + i));
var startNode = blocks_1.mkText("if (");
if (i > 0) {
startNode = blocks_1.mkText("else if (");
startNode.glueToBlock = blocks_1.GlueMode.WithSpace;
}
append(stmts, [
startNode,
cond,
blocks_1.mkText(")"),
thenBranch
]);
}
if (b.elseCount_) {
var elseNode = blocks_1.mkText("else");
elseNode.glueToBlock = blocks_1.GlueMode.WithSpace;
append(stmts, [
elseNode,
compileStatements(e, getInputTargetBlock(b, "ELSE"))
]);
}
return stmts;
}
function compileControlsFor(e, b, comments) {
var bTo = getInputTargetBlock(b, "TO");
var bDo = getInputTargetBlock(b, "DO");
var bBy = getInputTargetBlock(b, "BY");
var bFrom = getInputTargetBlock(b, "FROM");
var incOne = !bBy || (bBy.type.match(/^math_number/) && extractNumber(bBy) == 1);
var binding = lookup(e, b, getLoopVariableField(b).getField("VAR").getText());
return [
blocks_1.mkText("for (let " + binding.escapedName + " = "),
bFrom ? compileExpression(e, bFrom, comments) : blocks_1.mkText("0"),
blocks_1.mkText("; "),
blocks_1.mkInfix(blocks_1.mkText(binding.escapedName), "<=", compileExpression(e, bTo, comments)),
blocks_1.mkText("; "),
incOne ? blocks_1.mkText(binding.escapedName + "++") : blocks_1.mkInfix(blocks_1.mkText(binding.escapedName), "+=", compileExpression(e, bBy, comments)),
blocks_1.mkText(")"),
compileStatements(e, bDo)
];
}
function compileControlsRepeat(e, b, comments) {
var bound = compileExpression(e, getInputTargetBlock(b, "TIMES"), comments);
var body = compileStatements(e, getInputTargetBlock(b, "DO"));
var valid = function (x) { return e.idToScope[b.id].variables[x] === undefined; };
var name = "index";
// Start at 2 because index0 and index1 are bad names
for (var i = 2; !valid(name); i++)
name = "index" + i;
return [
blocks_1.mkText("for (let " + name + " = 0; "),
blocks_1.mkInfix(blocks_1.mkText(name), "<", bound),
blocks_1.mkText("; " + name + "++)"),
body
];
}
function compileWhile(e, b, comments) {
var cond = compileExpression(e, getInputTargetBlock(b, "COND"), comments);
var body = compileStatements(e, getInputTargetBlock(b, "DO"));
return [
blocks_1.mkText("while ("),
cond,
blocks_1.mkText(")"),
body
];
}
function compileControlsForOf(e, b, comments) {
var bOf = getInputTargetBlock(b, "LIST");
var bDo = getInputTargetBlock(b, "DO");
var binding = lookup(e, b, getLoopVariableField(b).getField("VAR").getText());
return [
blocks_1.mkText("for (let " + binding.escapedName + " of "),
compileExpression(e, bOf, comments),
blocks_1.mkText(")"),
compileStatements(e, bDo)
];
}
function compileForever(e, b) {
var bBody = getInputTargetBlock(b, "HANDLER");
var body = compileStatements(e, bBody);