-
Notifications
You must be signed in to change notification settings - Fork 1
/
pxtpy.js
6112 lines (6112 loc) · 247 KB
/
pxtpy.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 __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
/// <reference path='../built/pxtlib.d.ts' />
/// <reference path='../built/pxtcompiler.d.ts' />
var pxt;
(function (pxt) {
var py;
(function (py) {
var VarModifier;
(function (VarModifier) {
VarModifier[VarModifier["NonLocal"] = 0] = "NonLocal";
VarModifier[VarModifier["Global"] = 1] = "Global";
})(VarModifier = py.VarModifier || (py.VarModifier = {}));
})(py = pxt.py || (pxt.py = {}));
})(pxt || (pxt = {}));
var pxt;
(function (pxt) {
var py;
(function (py_1) {
var B = pxt.blocks;
// global state
var externalApis; // slurped from libraries
var internalApis; // defined in Python
var ctx;
var currIteration = 0;
var typeId = 0;
// this measures if we gained additional information about type state
// we run conversion several times, until we have all information possible
var numUnifies = 0;
var autoImport = true;
var currErrorCtx = "???";
var verboseTypes = false;
var lastAST = undefined;
var lastFile;
var diagnostics;
var compileOptions;
var syntaxInfo;
var infoNode = undefined;
var infoScope;
// TODO: move to utils
function isFalsy(t) {
return t === null || t === undefined;
}
function isTruthy(t) {
return t !== null && t !== undefined;
}
function stmtTODO(v) {
pxt.tickEvent("python.todo", { kind: v.kind });
return B.mkStmt(B.mkText("TODO: " + v.kind));
}
function exprTODO(v) {
pxt.tickEvent("python.todo", { kind: v.kind });
return B.mkText(" {TODO: " + v.kind + "} ");
}
function docComment(cmt) {
if (cmt.trim().split(/\n/).length <= 1)
cmt = cmt.trim();
else
cmt = cmt + "\n";
return B.mkStmt(B.mkText("/** " + cmt + " */"));
}
function defName(n, tp) {
return {
kind: "Name",
id: n,
isdef: true,
ctx: "Store",
tsType: tp
};
}
var tpString = mkType({ primType: "string" });
var tpNumber = mkType({ primType: "number" });
var tpBoolean = mkType({ primType: "boolean" });
var tpVoid = mkType({ primType: "void" });
var tpAny = mkType({ primType: "any" });
var tpBuffer = undefined;
var builtInTypes = {
"string": tpString,
"number": tpNumber,
"boolean": tpBoolean,
"void": tpVoid,
"any": tpAny,
};
function ts2PyType(syntaxKind) {
switch (syntaxKind) {
case ts.SyntaxKind.StringKeyword:
return tpString;
case ts.SyntaxKind.NumberKeyword:
return tpNumber;
case ts.SyntaxKind.BooleanKeyword:
return tpBoolean;
case ts.SyntaxKind.VoidKeyword:
return tpVoid;
case ts.SyntaxKind.AnyKeyword:
return tpAny;
default: {
// TODO: this could be null
return tpBuffer;
}
}
}
function cleanSymbol(s) {
var r = pxt.U.flatClone(s);
delete r.pyAST;
delete r.pyInstanceType;
delete r.pyRetType;
delete r.pySymbolType;
delete r.moduleTypeMarker;
delete r.declared;
if (r.parameters)
r.parameters = r.parameters.map(function (p) {
p = pxt.U.flatClone(p);
delete p.pyType;
return p;
});
return r;
}
function mapTsType(tp) {
// TODO handle specifc generic types like: SparseArray<number[]>
// TODO handle union types like: Sprite | particles.ParticleAnchor
// wrapped in (...)
if (tp[0] == "(" && pxt.U.endsWith(tp, ")")) {
return mapTsType(tp.slice(1, -1));
}
// lambda (...) => ...
var arrowIdx = tp.indexOf(" => ");
if (arrowIdx > 0) {
var retTypeStr = tp.slice(arrowIdx + 4);
if (retTypeStr.indexOf(")[]") == -1) {
var retType = mapTsType(retTypeStr);
var argsStr = tp.slice(1, arrowIdx - 1);
var argsWords = argsStr ? argsStr.split(/, /) : [];
var argTypes = argsWords.map(function (a) { return mapTsType(a.replace(/\w+\??: /, "")); });
return mkFunType(retType, argTypes);
}
}
// array ...[]
if (pxt.U.endsWith(tp, "[]")) {
return mkArrayType(mapTsType(tp.slice(0, -2)));
}
if (tp === "_py.Array") {
return mkArrayType(tpAny);
}
// builtin
var t = pxt.U.lookup(builtInTypes, tp);
if (t)
return t;
// handle number litterals like "-20" (b/c TS loves to give specific types to const's)
var isNum = !!tp && !isNaN(tp); // https://stackoverflow.com/questions/175739
if (isNum)
return tpNumber;
// generic
if (tp == "T" || tp == "U") // TODO hack!
return mkType({ primType: "'" + tp });
// defined by a symbol,
// either in external (non-py) APIs (like default/common packages)
// or in internal (py) APIs (probably main.py)
var sym = lookupApi(tp + "@type") || lookupApi(tp);
if (!sym) {
error(null, 9501, pxt.U.lf("unknown type '{0}' near '{1}'", tp, currErrorCtx || "???"));
return mkType({ primType: tp });
}
if (sym.kind == 7 /* EnumMember */)
return tpNumber;
// sym.pyInstanceType might not be initialized yet and we don't want to call symbolType() here to avoid infinite recursion
if (sym.kind == 8 /* Class */ || sym.kind == 9 /* Interface */)
return sym.pyInstanceType || mkType({ classType: sym });
if (sym.kind == 6 /* Enum */)
return tpNumber;
error(null, 9502, pxt.U.lf("'{0}' is not a type near '{1}'", tp, currErrorCtx || "???"));
return mkType({ primType: tp });
}
// img/hex literal
function isTaggedTemplate(sym) {
return sym.attributes.shim && sym.attributes.shim[0] == "@";
}
function getOrSetSymbolType(sym) {
if (!sym.pySymbolType) {
currErrorCtx = sym.pyQName;
if (sym.parameters) {
if (isTaggedTemplate(sym)) {
sym.parameters = [{
"name": "literal",
"description": "",
"type": "string",
"options": {}
}];
}
for (var _i = 0, _a = sym.parameters; _i < _a.length; _i++) {
var p = _a[_i];
if (!p.pyType)
p.pyType = mapTsType(p.type);
}
}
var prevRetType = sym.pyRetType;
if (isModule(sym)) {
sym.pyRetType = mkType({ moduleType: sym });
}
else {
if (sym.retType)
sym.pyRetType = mapTsType(sym.retType);
else if (sym.pyRetType) {
// nothing to do
}
else {
pxt.U.oops("no type for: " + sym.pyQName);
sym.pyRetType = mkType({});
}
}
if (prevRetType) {
unify(sym.pyAST, prevRetType, sym.pyRetType);
}
if (sym.kind == 3 /* Function */ || sym.kind == 1 /* Method */) {
var paramTypes = sym.parameters.map(function (p) { return p.pyType; });
if (paramTypes.some(isFalsy)) {
error(null, 9526, pxt.U.lf("function symbol is missing parameter types near '{1}'", currErrorCtx || "???"));
return mkType({});
}
sym.pySymbolType = mkFunType(sym.pyRetType, paramTypes.filter(isTruthy));
}
else
sym.pySymbolType = sym.pyRetType;
if (sym.kind == 8 /* Class */ || sym.kind == 9 /* Interface */) {
sym.pyInstanceType = mkType({ classType: sym });
}
currErrorCtx = undefined;
}
return sym.pySymbolType;
}
function lookupApi(name) {
return pxt.U.lookup(internalApis, name) || pxt.U.lookup(externalApis, name);
}
function lookupGlobalSymbol(name) {
if (!name)
return undefined;
var sym = lookupApi(name);
if (sym)
getOrSetSymbolType(sym);
return sym;
}
function initApis(apisInfo, tsShadowFiles) {
internalApis = {};
externalApis = {};
var tsShadowFilesSet = pxt.U.toDictionary(tsShadowFiles, function (t) { return t; });
var _loop_1 = function (sym) {
if (tsShadowFilesSet.hasOwnProperty(sym.fileName)) {
return "continue";
}
var sym2 = sym;
if (sym2.extendsTypes)
sym2.extendsTypes = sym2.extendsTypes.filter(function (e) { return e != sym2.qName; });
if (!sym2.pyQName || !sym2.qName) {
error(null, 9526, pxt.U.lf("Symbol '{0}' is missing qName for '{1}'", sym2.name, !sym2.pyQName ? "py" : "ts"));
}
externalApis[sym2.pyQName] = sym2;
externalApis[sym2.qName] = sym2;
};
for (var _i = 0, _a = pxt.U.values(apisInfo.byQName); _i < _a.length; _i++) {
var sym = _a[_i];
_loop_1(sym);
}
// TODO this is for testing mostly; we can do this lazily
// for (let sym of U.values(externalApis)) {
// if (sym)
// getOrSetSymbolType(sym)
// }
tpBuffer = mapTsType("Buffer");
}
function mkType(o) {
if (o === void 0) { o = {}; }
var r = pxt.U.flatClone(o);
r.tid = ++typeId;
return r;
}
function mkArrayType(eltTp) {
return mkType({ primType: "@array", typeArgs: [eltTp] });
}
function mkFunType(retTp, argTypes) {
return mkType({ primType: "@fn" + argTypes.length, typeArgs: [retTp].concat(argTypes) });
}
function instanceType(sym) {
getOrSetSymbolType(sym);
if (!sym.pyInstanceType)
error(null, 9527, pxt.U.lf("Instance type symbol '{0}' is missing pyInstanceType", sym));
return sym.pyInstanceType;
}
function currentScope() {
return ctx.currFun || ctx.currClass || ctx.currModule;
}
function topScope() {
var current = currentScope();
while (current && current.parent) {
current = current.parent;
}
return current;
}
function isTopLevel() {
return ctx.currModule.name == "main" && !ctx.currFun && !ctx.currClass;
}
function addImport(a, name, scope) {
var sym = lookupGlobalSymbol(name);
if (!sym)
error(a, 9503, pxt.U.lf("No module named '{0}'", name));
return sym;
}
function defvar(n, opts, scope) {
if (!scope)
scope = currentScope();
var v = scope.vars[n];
if (!v) {
var pref = getFullName(scope);
if (pref)
pref += ".";
var qn = pref + n;
if (isLocalScope(scope))
v = mkSymbol(4 /* Variable */, n);
else
v = addSymbol(4 /* Variable */, qn);
scope.vars[n] = v;
}
for (var _i = 0, _a = Object.keys(opts); _i < _a.length; _i++) {
var k = _a[_i];
v[k] = opts[k];
}
return v;
}
function find(t) {
if (t.union) {
t.union = find(t.union);
return t.union;
}
return t;
}
// TODO cache it?
function getFullName(n) {
var s = n;
var pref = "";
if (s.parent && s.parent.kind !== "FunctionDef" && s.parent.kind !== "AsyncFunctionDef") {
pref = getFullName(s.parent);
if (!pref)
pref = "";
else
pref += ".";
}
var nn = n;
if (n.kind == "Module" && nn.name == "main")
return "";
if (nn.name)
return pref + nn.name;
else
return pref + "?" + n.kind;
}
function applyTypeMap(s) {
var over = pxt.U.lookup(typeMap, s);
if (over)
return over;
for (var _i = 0, _a = pxt.U.values(ctx.currModule.vars); _i < _a.length; _i++) {
var v = _a[_i];
if (!v.isImport)
continue;
if (v.expandsTo == s) {
if (!v.pyName)
error(null, 9553, lf("missing pyName"));
return v.pyName;
}
if (v.isImport && pxt.U.startsWith(s, (v.expandsTo || "") + ".")) {
return v.pyName + s.slice(v.expandsTo.length);
}
}
return s;
}
function t2s(t) {
t = find(t);
var suff = function (s) { return verboseTypes ? s : ""; };
if (t.primType) {
if (t.typeArgs && t.primType == "@array") {
return t2s(t.typeArgs[0]) + "[]";
}
if (pxt.U.startsWith(t.primType, "@fn") && t.typeArgs)
return "(" + t.typeArgs.slice(1).map(function (t) { return "_: " + t2s(t); }).join(", ") + ") => " + t2s(t.typeArgs[0]);
return t.primType + suff("/P");
}
if (t.classType && t.classType.pyQName)
return applyTypeMap(t.classType.pyQName) + suff("/C");
else if (t.moduleType && t.moduleType.pyQName)
return applyTypeMap(t.moduleType.pyQName) + suff("/M");
else
return "?" + t.tid;
}
function mkDiag(astNode, category, code, messageText) {
if (!astNode)
astNode = lastAST;
if (!astNode || !ctx || !ctx.currModule) {
return {
fileName: lastFile,
start: 0,
length: 0,
line: undefined,
column: undefined,
code: code,
category: category,
messageText: messageText,
};
}
else {
return {
fileName: lastFile,
start: astNode.startPos,
length: astNode.endPos - astNode.startPos,
line: undefined,
column: undefined,
code: code,
category: category,
messageText: messageText,
};
}
}
// next free error 9572; 9550-9599 reserved for parser
function error(astNode, code, msg) {
diagnostics.push(mkDiag(astNode, pxtc.DiagnosticCategory.Error, code, msg));
//const pos = position(astNode ? astNode.startPos || 0 : 0, mod.source)
//currErrs += U.lf("{0} near {1}{2}", msg, mod.tsFilename.replace(/\.ts/, ".py"), pos) + "\n"
}
function typeError(a, t0, t1) {
error(a, 9500, pxt.U.lf("types not compatible: {0} and {1}", t2s(t0), t2s(t1)));
}
function typeCtor(t) {
if (t.primType)
return t.primType;
else if (t.classType)
return t.classType;
else if (t.moduleType) {
// a class SymbolInfo can be used as both classType and moduleType
// but these are different constructors (one is instance, one is class itself)
if (!t.moduleType.moduleTypeMarker)
t.moduleType.moduleTypeMarker = {};
return t.moduleType.moduleTypeMarker;
}
return null;
}
function isFree(t) {
return !typeCtor(find(t));
}
function canUnify(t0, t1) {
t0 = find(t0);
t1 = find(t1);
if (t0 === t1)
return true;
var c0 = typeCtor(t0);
var c1 = typeCtor(t1);
if (!c0 || !c1)
return true;
if (c0 !== c1)
return false;
if (t0.typeArgs && t1.typeArgs) {
for (var i = 0; i < Math.min(t0.typeArgs.length, t1.typeArgs.length); ++i)
if (!canUnify(t0.typeArgs[i], t1.typeArgs[i]))
return false;
}
return true;
}
function unifyClass(a, t, cd) {
t = find(t);
if (t.classType == cd)
return;
if (isFree(t)) {
t.classType = cd;
return;
}
unify(a, t, instanceType(cd));
}
function unifyTypeOf(e, t1) {
unify(e, typeOf(e), t1);
}
function unify(a, t0, t1) {
if (t0 === t1)
return;
t0 = find(t0);
t1 = find(t1);
if (t0 === t1)
return;
if (t0.primType === "any") {
t0.union = t1;
return;
}
var c0 = typeCtor(t0);
var c1 = typeCtor(t1);
if (c0 && c1) {
if (c0 === c1) {
t0.union = t1; // no type-state change here - actual change would be in arguments only
if (t0.typeArgs && t1.typeArgs) {
for (var i = 0; i < Math.min(t0.typeArgs.length, t1.typeArgs.length); ++i)
unify(a, t0.typeArgs[i], t1.typeArgs[i]);
}
t0.union = t1;
}
else {
typeError(a, t0, t1);
}
}
else if (c0 && !c1) {
unify(a, t1, t0);
}
else {
// the type state actually changes here
numUnifies++;
t0.union = t1;
// detect late unifications
// if (currIteration > 2) error(a, `unify ${t2s(t0)} ${t2s(t1)}`)
}
}
function mkSymbol(kind, qname) {
var m = /(.*)\.(.*)/.exec(qname);
var name = m ? m[2] : qname;
var ns = m ? m[1] : "";
return {
kind: kind,
name: name,
pyName: name,
qName: qname,
pyQName: qname,
namespace: ns,
attributes: {},
pyRetType: mkType()
};
}
function addSymbol(kind, qname) {
var sym = internalApis[qname];
if (sym) {
sym.kind = kind;
return sym;
}
sym = mkSymbol(kind, qname);
if (!sym.pyQName)
error(null, 9527, pxt.U.lf("Symbol '{0}' is missing pyQName", qname));
internalApis[sym.pyQName] = sym;
return sym;
}
function isLocalScope(scope) {
var s = scope;
while (s) {
if (s.kind == "FunctionDef")
return true;
s = s.parent;
}
return false;
}
function addSymbolFor(k, n, scope) {
if (!n.symInfo) {
var qn = getFullName(n);
if (pxt.U.endsWith(qn, ".__init__"))
qn = qn.slice(0, -9) + ".__constructor";
scope = scope || currentScope();
if (isLocalScope(scope))
n.symInfo = mkSymbol(k, qn);
else
n.symInfo = addSymbol(k, qn);
var sym = n.symInfo;
sym.pyAST = n;
if (!sym.pyName)
error(null, 9528, pxt.U.lf("Symbol '{0}' is missing pyName", sym.qName || sym.name));
scope.vars[sym.pyName] = sym;
}
return n.symInfo;
}
// TODO optimize ?
function listClassFields(cd) {
var qn = cd.symInfo.qName;
return pxt.U.values(internalApis).filter(function (e) { return e.namespace == qn && e.kind == 2 /* Property */; });
}
function getClassField(ct, n, checkOnly, skipBases) {
if (checkOnly === void 0) { checkOnly = false; }
if (skipBases === void 0) { skipBases = false; }
var qid = ct.pyQName + "." + n;
var f = lookupGlobalSymbol(qid);
if (f)
return f;
if (!skipBases) {
for (var _i = 0, _a = ct.extendsTypes || []; _i < _a.length; _i++) {
var b = _a[_i];
var sym = lookupGlobalSymbol(b);
if (sym) {
if (sym == ct)
pxt.U.userError("field lookup loop on: " + sym.qName + " / " + n);
var classF = getClassField(sym, n, true);
if (classF)
return classF;
}
}
}
if (!checkOnly && ct.pyAST && ct.pyAST.kind == "ClassDef") {
var sym = addSymbol(2 /* Property */, qid);
sym.isInstance = true;
return sym;
}
return null;
}
function getTypesForFieldLookup(recvType) {
var t = find(recvType);
return __spreadArrays([
t.classType
], resolvePrimTypes(t.primType), [
t.moduleType
]).filter(isTruthy);
}
function getTypeField(recv, n, checkOnly) {
if (checkOnly === void 0) { checkOnly = false; }
var recvType = typeOf(recv);
var constructorTypes = getTypesForFieldLookup(recvType);
for (var _i = 0, constructorTypes_1 = constructorTypes; _i < constructorTypes_1.length; _i++) {
var ct = constructorTypes_1[_i];
var f = getClassField(ct, n, checkOnly);
if (f) {
var isModule_1 = !!ct.moduleTypeMarker;
if (isModule_1) {
if (f.isInstance)
error(null, 9505, pxt.U.lf("the field '{0}' of '{1}' is not static", n, ct.pyQName));
}
else {
if (!f.isInstance)
error(null, 9504, pxt.U.lf("the field '{0}' of '{1}' is static", n, ct.pyQName));
if (isSuper(recv))
f.isProtected = true;
else if (isThis(recv)) {
if (!ctx.currClass)
error(null, 9529, pxt.U.lf("no class context found for {0}", f.pyQName));
if (f.namespace != ctx.currClass.symInfo.qName) {
f.isProtected = true;
}
}
}
return f;
}
}
return null;
}
function resolvePrimTypes(primType) {
var res = [];
if (primType == "@array") {
res = [lookupApi("_py.Array"), lookupApi("Array")];
}
else if (primType == "string") {
// we need to check both the special "_py" namespace and the typescript "String"
// class because for example ".length" is only defined in the latter
res = [lookupApi("_py.String"), lookupApi("String")];
}
return res.filter(function (a) { return !!a; });
}
function lookupVar(n) {
var s = currentScope();
var v = pxt.U.lookup(s.vars, n);
if (v)
return v;
// while (s) {
// let v = U.lookup(s.vars, n)
// if (v) return v
// // go to parent, excluding class scopes
// do {
// s = s.parent
// } while (s && s.kind == "ClassDef")
// }
//if (autoImport && lookupGlobalSymbol(n)) {
// return addImport(currentScope(), n, ctx.currModule)
//}
return null;
}
function lookupSymbol(n) {
if (!n)
return null;
var firstDot = n.indexOf(".");
if (firstDot > 0) {
var v = lookupVar(n.slice(0, firstDot));
// expand name if needed
if (v && v.pyQName != v.pyName)
n = v.pyQName + n.slice(firstDot);
}
else {
var v = lookupVar(n);
if (v)
return v;
}
return lookupGlobalSymbol(n);
}
function getClassDef(e) {
var n = getName(e);
var s = lookupSymbol(n);
if (s && s.pyAST && s.pyAST.kind == "ClassDef")
return s.pyAST;
return null;
}
function typeOf(e) {
if (e.tsType) {
return find(e.tsType);
}
else {
e.tsType = mkType();
return e.tsType;
}
}
function isOfType(e, name) {
var t = typeOf(e);
if (t.classType && t.classType.pyQName == name)
return true;
if (t2s(t) == name)
return true;
return false;
}
function resetCtx(m) {
ctx = {
currClass: undefined,
currFun: undefined,
currModule: m,
blockDepth: 0
};
lastFile = m.tsFilename.replace(/\.ts$/, ".py");
}
function isModule(s) {
if (!s)
return false;
switch (s.kind) {
case 5 /* Module */:
case 9 /* Interface */:
case 8 /* Class */:
case 6 /* Enum */:
return true;
default:
return false;
}
}
function scope(f) {
var prevCtx = pxt.U.flatClone(ctx);
var r;
try {
r = f();
}
finally {
ctx = prevCtx;
}
return r;
}
function todoExpr(name, e) {
if (!e)
return B.mkText("");
return B.mkGroup([B.mkText("/* TODO: " + name + " "), e, B.mkText(" */")]);
}
function todoComment(name, n) {
if (n.length == 0)
return B.mkText("");
return B.mkGroup([B.mkText("/* TODO: " + name + " "), B.mkGroup(n), B.mkText(" */"), B.mkNewLine()]);
}
function doKeyword(k) {
var t = expr(k.value);
if (k.arg)
return B.mkInfix(B.mkText(k.arg), "=", t);
else
return B.mkGroup([B.mkText("**"), t]);
}
function compileType(e) {
if (!e)
return mkType();
var tpName = tryGetName(e);
if (tpName) {
var sym = lookupApi(tpName + "@type") || lookupApi(tpName);
if (sym) {
getOrSetSymbolType(sym);
if (sym.kind == 6 /* Enum */)
return tpNumber;
if (sym.pyInstanceType)
return sym.pyInstanceType;
}
else if (builtInTypes[tpName])
return builtInTypes[tpName];
error(e, 9506, pxt.U.lf("cannot find type '{0}'", tpName));
}
error(e, 9507, pxt.U.lf("invalid type syntax"));
return mkType({});
}
function doArgs(n, isMethod) {
var args = n.args;
if (args.kwonlyargs.length)
error(n, 9517, pxt.U.lf("keyword-only arguments not supported yet"));
var nargs = args.args.slice();
if (isMethod) {
if (nargs[0].arg != "self")
error(n, 9518, pxt.U.lf("first argument of method has to be called 'self'"));
nargs.shift();
}
else {
if (nargs.some(function (a) { return a.arg == "self"; }))
error(n, 9519, pxt.U.lf("non-methods cannot have an argument called 'self'"));
}
if (!n.symInfo.parameters) {
var didx_1 = args.defaults.length - nargs.length;
n.symInfo.parameters = nargs.map(function (a) {
if (!a.annotation)
error(n, 9519, pxt.U.lf("Arg '{0}' missing annotation", a.arg));
var tp = compileType(a.annotation);
var defl = "";
if (didx_1 >= 0) {
defl = B.flattenNode([expr(args.defaults[didx_1])]).output;
unify(a, tp, typeOf(args.defaults[didx_1]));
}
didx_1++;
return {
name: a.arg,
description: "",
type: "",
initializer: defl,
default: defl,
pyType: tp
};
});
}
var lst = n.symInfo.parameters.map(function (p) {
var v = defvar(p.name, { isParam: true });
if (!p.pyType)
error(n, 9530, pxt.U.lf("parameter '{0}' missing pyType", p.name));
unify(n, getOrSetSymbolType(v), p.pyType);
var res = [quote(p.name), typeAnnot(p.pyType, true)];
if (p.default) {
res.push(B.mkText(" = " + p.default));
}
return B.mkGroup(res);
});
if (args.vararg)
lst.push(B.mkText("TODO *" + args.vararg.arg));
if (args.kwarg)
lst.push(B.mkText("TODO **" + args.kwarg.arg));
return B.H.mkParenthesizedExpression(B.mkCommaSep(lst));
}
function accessAnnot(f) {
if (!f.pyName || f.pyName[0] != "_")
return B.mkText("");
return f.isProtected ? B.mkText("protected ") : B.mkText("private ");
}
var numOps = {
Sub: 1,
Div: 1,
Pow: 1,
LShift: 1,
RShift: 1,
BitOr: 1,
BitXor: 1,
BitAnd: 1,
FloorDiv: 1,
Mult: 1,
};
var opMapping = {
Add: "+",
Sub: "-",
Mult: "*",
MatMult: "Math.matrixMult",
Div: "/",
Mod: "%",
Pow: "**",
LShift: "<<",
RShift: ">>",
BitOr: "|",
BitXor: "^",
BitAnd: "&",
FloorDiv: "Math.idiv",
And: "&&",
Or: "||",
Eq: "==",
NotEq: "!=",
Lt: "<",
LtE: "<=",
Gt: ">",
GtE: ">=",
Is: "===",
IsNot: "!==",
In: "py.In",
NotIn: "py.NotIn",
};
var prefixOps = {
Invert: "~",
Not: "!",
UAdd: "P+",
USub: "P-",
};
var typeMap = {
"adafruit_bus_device.i2c_device.I2CDevice": "pins.I2CDevice"
};
function stmts(ss) {
ctx.blockDepth++;
var res = B.mkBlock(ss.map(stmt));
ctx.blockDepth--;
return res;
}
function exprs0(ee) {
ee = ee.filter(function (e) { return !!e; });
return ee.map(expr);
}
function setupScope(n) {
if (!n.vars) {
n.vars = {};
n.parent = currentScope();
n.blockDepth = ctx.blockDepth;
}
}
function typeAnnot(t, defaultToAny) {
if (defaultToAny === void 0) { defaultToAny = false; }
var s = t2s(t);
if (s[0] == "?") {
// TODO:
// example from minecraft doc snippet:
// player.onChat("while",function(num1){while(num1<10){}})
// -> py -> ts ->
// player.onChat("while",function(num1:any;/**TODO:type**/){while(num1<10){;}})
// work around using any:
// return B.mkText(": any /** TODO: type **/")
// but for now we can just omit the type and most of the type it'll be inferable
return defaultToAny ? B.mkText(": any") : B.mkText("");
}
return B.mkText(": " + t2s(t));
}
function guardedScope(v, f) {
try {
return scope(f);
}
catch (e) {
console.log(e);
return B.mkStmt(todoComment("conversion failed for " + (v.name || v.kind), []));
}
}
function shouldInlineFunction(si) {
if (!si || !si.pyAST)
return false;
if (si.pyAST.kind != "FunctionDef")
return false;
var fn = si.pyAST;
if (!fn.callers || fn.callers.length != 1)
return false;
if (fn.callers[0].inCalledPosition)
return false;
return true;
}
function emitFunctionDef(n, inline) {
if (inline === void 0) { inline = false; }
return guardedScope(n, function () {
var isMethod = !!ctx.currClass && !ctx.currFun;
var topLev = isTopLevel();
var nested = !!ctx.currFun;
setupScope(n);
var existing = lookupSymbol(getFullName(n));
var sym = addSymbolFor(isMethod ? 1 /* Method */ : 3 /* Function */, n);
if (!inline) {
if (existing && existing.declared === currIteration) {
error(n, 9520, lf("Duplicate function declaration"));
}
sym.declared = currIteration;
if (shouldInlineFunction(sym)) {
return B.mkText("");
}
}
if (isMethod)
sym.isInstance = true;
ctx.currFun = n;
var prefix = "";
var funname = n.name;
var remainingDecorators = n.decorator_list.filter(function (d) {
if (tryGetName(d) == "property") {
prefix = "get";
return false;
}
if (d.kind == "Attribute" && d.attr == "setter" &&
d.value.kind == "Name") {
funname = d.value.id;
prefix = "set";
return false;
}
return true;
});
var nodes = [
todoComment("decorators", remainingDecorators.map(expr))
];
if (n.body.length >= 1 && n.body[0].kind == "Raise")
n.alwaysThrows = true;
if (isMethod) {
if (!ctx.currClass)
error(n, 9531, lf("method '{0}' is missing current class context", sym.pyQName));
if (!sym.pyRetType)
error(n, 9532, lf("method '{0}' is missing a return type", sym.pyQName));
if (n.name == "__init__") {
nodes.push(B.mkText("constructor"));
unifyClass(n, sym.pyRetType, ctx.currClass.symInfo);
}
else {
if (funname == "__get__" || funname == "__set__") {
var vv = n.vars["value"];
if (funname == "__set__" && vv) {
var cf = getClassField(ctx.currClass.symInfo, "__get__");
if (cf && cf.pyAST && cf.pyAST.kind == "FunctionDef")
unify(n, vv.pyRetType, cf.pyRetType);
}