-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathservice.ts
1743 lines (1556 loc) · 64.3 KB
/
service.ts
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
/// <reference path="../localtypings/pxtarget.d.ts"/>
/// <reference path="../localtypings/pxtpackage.d.ts"/>
namespace ts.pxtc {
export const assert = Util.assert;
export const oops = Util.oops;
export import U = pxtc.Util;
export const ON_START_TYPE = "pxt-on-start";
export const ON_START_COMMENT = "on start"; // TODO: Localize? (adding lf doesn't work because this is run before translations are downloaded)
export const HANDLER_COMMENT = "code goes here"; // TODO: Localize? (adding lf doesn't work because this is run before translations are downloaded)
export const TS_STATEMENT_TYPE = "typescript_statement";
export const TS_DEBUGGER_TYPE = "debugger_keyword";
export const TS_BREAK_TYPE = "break_keyword";
export const TS_CONTINUE_TYPE = "continue_keyword";
export const TS_OUTPUT_TYPE = "typescript_expression";
export const TS_RETURN_STATEMENT_TYPE = "function_return";
export const PAUSE_UNTIL_TYPE = "pxt_pause_until";
export const COLLAPSED_BLOCK = "pxt_collapsed_block"
export const FUNCTION_DEFINITION_TYPE = "function_definition";
export const BINARY_JS = "binary.js";
export const BINARY_ASM = "binary.asm";
export const BINARY_HEX = "binary.hex";
export const BINARY_UF2 = "binary.uf2";
export const BINARY_ELF = "binary.elf";
export const BINARY_PXT64 = "binary.pxt64";
export const BINARY_ESP = "binary.bin";
export const BINARY_SRCMAP = "binary.srcmap";
export const NATIVE_TYPE_THUMB = "thumb";
export const NATIVE_TYPE_VM = "vm";
export interface BlocksInfo {
apis: ApisInfo;
blocks: SymbolInfo[];
blocksById: pxt.Map<SymbolInfo>;
enumsByName: pxt.Map<EnumInfo>;
kindsByName: pxt.Map<KindInfo>;
}
export interface EnumInfo {
name: string;
memberName: string;
blockId: string;
isBitMask: boolean;
isHash: boolean;
firstValue?: number;
initialMembers: string[];
promptHint: string;
}
export interface KindInfo {
name: string;
memberName: string;
createFunctionName: string;
blockId: string;
promptHint: string;
initialMembers: string[];
}
export interface CompletionEntry {
name: string;
kind: string;
qualifiedName: string;
}
export interface CompletionInfo {
entries: SymbolInfo[];
isMemberCompletion: boolean;
isNewIdentifierLocation: boolean;
isTypeLocation: boolean;
namespace: string[];
}
export interface LocationInfo {
fileName: string;
start: number;
length: number;
//derived
line?: number;
column?: number;
endLine?: number;
endColumn?: number;
}
export interface FunctionLocationInfo extends LocationInfo {
functionName: string;
argumentNames?: string[];
}
export interface KsDiagnostic extends LocationInfo {
code: number;
category: DiagnosticCategory;
messageText: string | DiagnosticMessageChain;
}
export interface ConfigEntry {
name: string;
key: number;
value: number;
}
export type CodeLang = "py" | "blocks" | "ts"
export type PosSpan = {
startPos: number;
endPos: number;
}
export interface SourceInterval {
ts: PosSpan;
py: PosSpan;
}
export type LineColToPos = (line: number, col: number) => number
export type PosToLineCol = (pos: number) => [number, number]
export interface SourceMapHelpers {
ts: {
posToLineCol: PosToLineCol,
lineColToPos: LineColToPos,
allOverlaps: (i: PosSpan) => SourceInterval[],
smallestOverlap: (i: PosSpan) => SourceInterval | undefined
locToLoc: (thisLoc: pxtc.LocationInfo) => pxtc.LocationInfo,
getText: (i: PosSpan) => string,
},
py: {
posToLineCol: PosToLineCol,
lineColToPos: LineColToPos,
allOverlaps: (i: PosSpan) => SourceInterval[],
smallestOverlap: (i: PosSpan) => SourceInterval | undefined,
locToLoc: (thisLoc: pxtc.LocationInfo) => pxtc.LocationInfo,
getText: (i: PosSpan) => string,
},
}
export function BuildSourceMapHelpers(sourceMap: SourceInterval[], tsFile: string, pyFile: string): SourceMapHelpers {
// Notes:
// lines are 0-indexed (Monaco they are 1-indexed)
// columns are 0-indexed (0th is first character)
// positions are 0-indexed, as if getting the index of a character in a file as a giant string (incl. new lines)
// line summation is the length of that line plus its newline plus all the lines before it; aka the position of the next line's first character
// end positions are zero-index but not inclusive, same behavior as substring
const makeLineColPosConverters = (file: string): { posToLineCol: PosToLineCol, lineColToPos: LineColToPos } => {
const lines = file.split("\n")
const lineLengths = lines
.map(l => l.length)
const lineLenSums = lineLengths
.reduce(({ lens, sum }, n) =>
({ lens: [...lens, sum + n + 1], sum: sum + n + 1 }),
{ lens: [] as number[], sum: 0 })
.lens
const lineColToPos = (line: number, col: number) => {
let pos = (lineLenSums[line - 1] || 0) + col
return pos
}
const posToLineCol = (pos: number) => {
const line = lineLenSums
.reduce((curr, nextLen, i) => pos < nextLen ? curr : i + 1, 0)
const col = lineLengths[line] - (lineLenSums[line] - pos) + 1
return [line, col] as [number, number]
}
return { posToLineCol, lineColToPos }
}
const lcp = {
ts: makeLineColPosConverters(tsFile),
py: makeLineColPosConverters(pyFile)
}
const intLen = (i: PosSpan) => i.endPos - i.startPos
const allOverlaps = (i: PosSpan, lang: "ts" | "py") => {
const { startPos, endPos } = i
return sourceMap
.filter(i => {
// O(n), can we and should we do better?
return i[lang].startPos <= startPos && endPos <= i[lang].endPos
})
}
const smallestOverlap = (i: PosSpan, lang: "ts" | "py"): SourceInterval | undefined => {
const overlaps = allOverlaps(i, lang)
return overlaps.reduce((p, n) => intLen(n[lang]) < intLen(p[lang]) ? n : p, overlaps[0])
}
const os = {
ts: {
allOverlaps: (i: PosSpan) => allOverlaps(i, "ts"),
smallestOverlap: (i: PosSpan) => smallestOverlap(i, "ts"),
},
py: {
allOverlaps: (i: PosSpan) => allOverlaps(i, "py"),
smallestOverlap: (i: PosSpan) => smallestOverlap(i, "py"),
}
}
const makeLocToLoc = (inLang: "ts" | "py", outLang: "ts" | "py") => {
const inLocToPosAndLen = (inLoc: pxtc.LocationInfo) => [lcp[inLang].lineColToPos(inLoc.line, inLoc.column), inLoc.length] as [number, number]
const locToLoc = (inLoc: pxtc.LocationInfo): pxtc.LocationInfo | undefined => {
const [inStartPos, inLen] = inLocToPosAndLen(inLoc)
const inEndPos = inStartPos + inLen
const bestOverlap = smallestOverlap({ startPos: inStartPos, endPos: inEndPos }, inLang)
if (!bestOverlap)
return undefined
const [outStartLine, outStartCol] = lcp[outLang].posToLineCol(bestOverlap[outLang].startPos)
const outLoc = {
fileName: `main.${outLang}`,
start: bestOverlap[outLang].startPos,
length: intLen(bestOverlap[outLang]),
line: outStartLine,
column: outStartCol
}
return outLoc
}
return locToLoc
}
const tsLocToPyLoc = makeLocToLoc("ts", "py")
const pyLocToTsLoc = makeLocToLoc("py", "ts")
const tsGetText = (i: PosSpan) => tsFile.substring(i.startPos, i.endPos)
const pyGetText = (i: PosSpan) => pyFile.substring(i.startPos, i.endPos)
return {
ts: {
...lcp.ts,
...os.ts,
locToLoc: tsLocToPyLoc,
getText: tsGetText
},
py: {
...lcp.py,
...os.py,
locToLoc: pyLocToTsLoc,
getText: pyGetText
},
}
}
export interface CompileResult {
outfiles: pxt.Map<string>;
diagnostics: KsDiagnostic[];
success: boolean;
times: pxt.Map<number>;
//ast?: Program; // Not needed, moved to pxtcompiler
breakpoints?: Breakpoint[];
procCallLocations?: pxtc.LocationInfo[];
procDebugInfo?: ProcDebugInfo[];
blocksInfo?: BlocksInfo;
blockSourceMap?: pxt.blocks.BlockSourceInterval[]; // mappings id,start,end
usedSymbols?: pxt.Map<SymbolInfo>; // q-names of symbols used
usedArguments?: pxt.Map<string[]>;
usedParts?: string[];
needsFullRecompile?: boolean;
// client options
saveOnly?: boolean;
userContextWindow?: Window;
downloadFileBaseName?: string;
headerId?: string;
confirmAsync?: (confirmOptions: {}) => Promise<number>;
configData?: ConfigEntry[];
sourceMap?: SourceInterval[];
globalNames?: pxt.Map<SymbolInfo>;
builtVariants?: string[];
fileSystem?: pxt.Map<string>;
}
export interface Breakpoint extends LocationInfo {
id: number;
isDebuggerStmt: boolean;
binAddr?: number;
}
export interface CellInfo {
name: string;
type: string;
index: number;
}
export interface ProcCallInfo {
procIndex: number;
callLabel: string;
addr: number;
stack: number;
}
export interface ProcDebugInfo {
name: string;
idx: number;
bkptLoc: number;
codeStartLoc: number;
codeEndLoc: number;
locals: CellInfo[];
args: CellInfo[];
localsMark: number;
calls: ProcCallInfo[];
size: number;
}
export const enum BitSize {
None,
Int8,
UInt8,
Int16,
UInt16,
Int32,
UInt32,
}
/* @internal */
const enum TokenKind {
SingleAsterisk = 1,
DoubleAsterisk = 1 << 1,
SingleUnderscore = 1 << 2,
DoubleUnderscore = 1 << 3,
Escape = 1 << 4,
Pipe = 1 << 5,
Parameter = 1 << 6,
Word = 1 << 7,
Image = 1 << 8,
TaggedText = 1 << 9,
ParamRef = 1 << 10,
TripleUnderscore = SingleUnderscore | DoubleUnderscore,
TripleAsterisk = SingleAsterisk | DoubleAsterisk,
StyleMarks = TripleAsterisk | TripleUnderscore,
Bold = DoubleUnderscore | DoubleAsterisk,
Italics = SingleUnderscore | SingleAsterisk,
Unstylable = Parameter | Pipe | ParamRef,
Text = Word | Escape
}
interface Token {
kind: TokenKind;
content?: string;
type?: string;
name?: string;
}
interface Label {
content: string;
styles: number;
endingToken?: string;
}
export function computeUsedParts(resp: CompileResult, filter?: "onlybuiltin" | "ignorebuiltin", force = false): string[] {
if (!resp.usedSymbols || !pxt.appTarget.simulator || (!force && !pxt.appTarget.simulator.parts))
return [];
const parseParts = (partsRaw: string, ps: string[]) => {
if (partsRaw) {
const partsSplit = partsRaw.split(/[ ,]+/g);
ps.push(...partsSplit.filter(p => !!p && ps.indexOf(p) < 0))
}
}
let parts: string[] = [];
let hiddenParts: string[] = [];
Object.keys(resp.usedSymbols).forEach(symbol => {
const info = resp.usedSymbols[symbol]
parseParts(info?.attributes.parts, parts)
parseParts(info?.attributes.hiddenParts, hiddenParts)
});
if (filter) {
const builtinParts = pxt.appTarget.simulator.boardDefinition.onboardComponents;
if (builtinParts) {
if (filter === "ignorebuiltin") {
parts = parts.filter(p => builtinParts.indexOf(p) === -1);
} else if (filter === "onlybuiltin") {
parts = parts.filter(p => builtinParts.indexOf(p) >= 0);
}
}
}
// apply hidden parts filter
parts = parts.filter(p => hiddenParts.indexOf(p) < 0)
//sort parts (so breadboarding layout is stable w.r.t. code ordering)
parts.sort();
parts = parts.reverse(); //not strictly necessary, but it's a little
// nicer for demos to have "ledmatrix"
// before "buttonpair"
return parts;
}
export function buildSimJsInfo(compileResult: pxtc.CompileResult): pxtc.BuiltSimJsInfo {
return {
js: compileResult.outfiles[pxtc.BINARY_JS],
targetVersion: pxt.appTarget.versions.target,
fnArgs: compileResult.usedArguments,
parts: pxtc.computeUsedParts(compileResult, "ignorebuiltin"),
usedBuiltinParts: pxtc.computeUsedParts(compileResult, "onlybuiltin"),
allParts: pxtc.computeUsedParts(compileResult, undefined, true),
breakpoints: compileResult.breakpoints?.map(bp => bp.id),
};
}
/**
* Unlocalized category name for a symbol
*/
export function blocksCategory(si: SymbolInfo): string {
const n = !si ? undefined : (si.attributes.blockNamespace || si.namespace);
return n ? Util.capitalize(n.split('.')[0]) : undefined;
}
export function getBlocksInfo(info: ApisInfo, categoryFilters?: string[]): BlocksInfo {
let blocks: SymbolInfo[] = []
const combinedSet: pxt.Map<SymbolInfo> = {}
const combinedGet: pxt.Map<SymbolInfo> = {}
const combinedChange: pxt.Map<SymbolInfo> = {}
const enumsByName: pxt.Map<EnumInfo> = {};
const kindsByName: pxt.Map<KindInfo> = {};
function addCombined(rtp: string, s: SymbolInfo) {
const isGet = rtp == "get"
const isSet = rtp == "set"
const isNumberType = s.retType == "number"
const m = isGet ? combinedGet : (isSet ? combinedSet : combinedChange)
const mkey = `${s.namespace}.${s.retType}`
let ex = U.lookup(m, mkey)
if (!ex) {
const tp = `@${rtp}@`
let paramNameShadow: string, paramValueShadow: string;
if (s.attributes.blockCombineShadow) {
// allowable %blockCombineShadow strings:-
// '{name shadow},' or '{value shadow}' or ',{value shadow}' or '{name shadow},{value shadow}'
const attribute = s.attributes.blockCombineShadow;
const match = attribute.match(/^([^,.]*),?([^,.]*)$/);
if (match && match.length == 3) {
paramNameShadow = match[1].trim();
paramValueShadow = match[2].trim();
if (paramValueShadow.length == 0 && !Util.endsWith(attribute, ",")) {
paramValueShadow = paramNameShadow;
paramNameShadow = "";
}
}
}
const varName = s.attributes.blockSetVariable || s.namespace.toLocaleLowerCase();
const paramName = `${varName}=${paramNameShadow || ""}`
const paramValue = `value=${paramValueShadow || ""}`;
ex = m[mkey] = {
attributes: {
blockId: `${isNumberType ? s.namespace : mkey}_blockCombine_${rtp}`,
callingConvention: ir.CallingConvention.Plain,
group: s.attributes.group, // first %blockCombine defines
paramDefl: {},
jsDoc: isGet
? U.lf("Read value of a property on an object")
: U.lf("Update value of property on an object")
},
name: tp,
namespace: s.namespace,
fileName: s.fileName,
qName: `${mkey}.${tp}`,
pkg: s.pkg,
kind: SymbolKind.Property,
parameters: [
{
name: "property",
description: isGet ?
U.lf("the name of the property to read") :
U.lf("the name of the property to change"),
isEnum: true,
type: "@combined@"
},
{
name: "value",
description: isSet ?
U.lf("the new value of the property") :
U.lf("the amount by which to change the property"),
type: s.retType,
}
].slice(0, isGet ? 1 : 2),
retType: isGet ? s.retType : "void",
combinedProperties: []
}
ex.attributes.block =
isGet ? `%${paramName} %property`:
isSet ? U.lf("set %{0} %property to %{1}", paramName, paramValue) :
U.lf("change %{0} %property by %{1}", paramName, paramValue)
updateBlockDef(ex.attributes)
if (pxt.Util.isTranslationMode()) {
ex.attributes.translationId = ex.attributes.block;
// This kicks off async work but doesn't wait; give untranslated values to start with
// to avoid a race causing a crash.
ex.attributes.block = isGet ? `%${paramName} %property` :
isSet ? `set %${paramName} %property to %${paramValue}` :
`change %${paramName} %property by %${paramValue}`;
updateBlockDef(ex.attributes);
pxt.crowdin.inContextLoadAsync(ex.attributes.translationId)
.then(r => {
ex.attributes.block = r;
updateBlockDef(ex.attributes);
});
}
blocks.push(ex)
}
ex.combinedProperties.push(s.qName)
}
for (let s of pxtc.Util.values(info.byQName)) {
if (s.attributes.shim === "ENUM_GET" && s.attributes.enumName && s.attributes.blockId) {
let didFail = false;
if (enumsByName[s.attributes.enumName]) {
pxt.warn(`Enum block ${s.attributes.blockId} trying to overwrite enum ${s.attributes.enumName}`);
didFail = true;
}
if (!s.attributes.enumMemberName) {
pxt.warn(`Enum block ${s.attributes.blockId} should specify enumMemberName`);
didFail = true;
}
if (!s.attributes.enumPromptHint) {
pxt.warn(`Enum block ${s.attributes.blockId} should specify enumPromptHint`);
didFail = true;
}
if (!s.attributes.enumInitialMembers || !s.attributes.enumInitialMembers.length) {
pxt.warn(`Enum block ${s.attributes.blockId} should specify enumInitialMembers`);
didFail = true;
}
if (didFail) {
continue;
}
const firstValue = parseInt(s.attributes.enumStartValue as any);
enumsByName[s.attributes.enumName] = {
blockId: s.attributes.blockId,
name: s.attributes.enumName,
memberName: s.attributes.enumMemberName,
firstValue: isNaN(firstValue) ? undefined : firstValue,
isBitMask: s.attributes.enumIsBitMask,
isHash: s.attributes.enumIsHash,
initialMembers: s.attributes.enumInitialMembers,
promptHint: s.attributes.enumPromptHint
};
}
if (s.attributes.shim === "KIND_GET" && s.attributes.blockId) {
const kindNamespace = s.attributes.kindNamespace || s.attributes.blockNamespace || s.namespace;
if (kindsByName[kindNamespace]) {
pxt.warn(`More than one block defined for kind ${kindNamespace}`);
continue;
}
const initialMembers: string[] = [];
if (info.byQName[kindNamespace]) {
for (const api of pxtc.Util.values(info.byQName)) {
if (api.namespace === kindNamespace && api.attributes.isKind) {
initialMembers.push(api.name);
}
}
}
kindsByName[kindNamespace] = {
blockId: s.attributes.blockId,
name: kindNamespace,
memberName: s.attributes.kindMemberName || kindNamespace,
initialMembers: initialMembers,
promptHint: s.attributes.enumPromptHint || Util.lf("Create a new kind..."),
createFunctionName: s.attributes.kindCreateFunction || "create"
};
}
if (s.attributes.blockCombine) {
if (!/@set/.test(s.name)) {
addCombined("get", s)
}
if (!s.isReadOnly) {
if (s.retType == 'number') {
addCombined("change", s)
}
addCombined("set", s)
}
} else if (!!s.attributes.block
&& !s.attributes.fixedInstance
&& s.kind != pxtc.SymbolKind.EnumMember
&& s.kind != pxtc.SymbolKind.Module
&& s.kind != pxtc.SymbolKind.Interface
&& s.kind != pxtc.SymbolKind.Class) {
if (!s.attributes.blockId)
s.attributes.blockId = s.qName.replace(/\./g, "_")
if (s.attributes.block == "true") {
let b = U.uncapitalize(s.name)
if (s.kind == SymbolKind.Method || s.kind == SymbolKind.Property) {
b += " %" + s.namespace.toLowerCase()
}
const params = s.parameters?.filter(pr => !parameterTypeIsArrowFunction(pr)) ?? [];
for (let p of params) {
b += " %" + p.name
}
s.attributes.block = b
updateBlockDef(s.attributes)
}
blocks.push(s)
}
}
// derive common block properties from namespace
for (let b of blocks) {
let parent = U.lookup(info.byQName, b.namespace)
if (!parent) continue
let pattr = parent.attributes as any
let battr = b.attributes as any
for (let n of ["blockNamespace", "color", "blockGap"]) {
if (battr[n] === undefined && pattr[n])
battr[n] = pattr[n]
}
}
if (categoryFilters)
filterCategories(categoryFilters);
return {
apis: info,
blocks,
blocksById: pxt.Util.toDictionary(blocks, b => b.attributes.blockId),
enumsByName,
kindsByName
}
function filterCategories(banned: string[]) {
if (banned.length) {
blocks = blocks.filter(b => {
let ns = (b.attributes.blockNamespace || b.namespace).split('.')[0];
return banned.indexOf(ns) === -1;
});
}
}
}
export function tsSnippetToPySnippet(param: string, symbol?: SymbolInfo): string {
const keywords: pxt.Map<string> = {
"true": "True",
"false": "False",
"null": "None"
}
const key = keywords[param];
if (key) {
return key
}
if ((symbol && symbol.kind == SymbolKind.Enum) || (!symbol && param.includes("."))) {
// Python enums are all caps
const dotIdx = param.lastIndexOf(".");
const left = param.substr(0, dotIdx)
let right = param.substr(dotIdx + 1)
right = U.snakify(right).toUpperCase();
if (left) {
return `${left}.${right}`
}
else {
return right;
}
}
return param;
}
export let apiLocalizationStrings: pxt.Map<string> = {};
export async function localizeApisAsync(apis: pxtc.ApisInfo, mainPkg: pxt.MainPackage): Promise<pxtc.ApisInfo> {
const lang = pxtc.Util.userLanguage();
if (lang == "en")
return Promise.resolve(cleanLocalizations(apis));
const langLower = lang.toLowerCase();
const attrJsLocsKey = langLower + "|jsdoc";
const attrBlockLocsKey = langLower + "|block";
const loc = await mainPkg.localizationStringsAsync(lang);
if (apiLocalizationStrings)
Util.jsonMergeFrom(loc, apiLocalizationStrings);
const toLocalize = Util.values(apis.byQName).filter(fn => fn.attributes._translatedLanguageCode !== lang);
await Util.promiseMapAll(toLocalize, async fn => {
const altLocSrc = fn.attributes.useLoc || fn.attributes.blockAliasFor;
const altLocSrcFn = altLocSrc && apis.byQName[altLocSrc];
if (fn.attributes._untranslatedJsDoc) fn.attributes.jsDoc = fn.attributes._untranslatedJsDoc;
if (fn.attributes._untranslatedBlock) fn.attributes.jsDoc = fn.attributes._untranslatedBlock;
const lookupLoc = (locSuff: string, attrKey: string) => {
return loc[fn.qName + locSuff] || fn.attributes.locs?.[attrKey]
|| (altLocSrcFn && (loc[altLocSrcFn.qName + locSuff] || altLocSrcFn.attributes.locs?.[attrKey]));
}
const locJsDoc = lookupLoc("", attrJsLocsKey);
if (locJsDoc) {
if (!fn.attributes._untranslatedJsDoc) {
fn.attributes._untranslatedJsDoc = fn.attributes.jsDoc;
}
fn.attributes.jsDoc = locJsDoc;
}
fn.parameters?.forEach(pi => {
const paramSuff = `|param|${pi.name}`;
const paramLocs = lookupLoc(paramSuff, langLower + paramSuff);
if (paramLocs) {
pi.description = paramLocs;
}
});
const nsDoc = loc['{id:category}' + Util.capitalize(fn.qName)];
let locBlock = loc[`${fn.qName}|block`] || fn.attributes.locs?.[attrBlockLocsKey];
if (!locBlock && altLocSrcFn) {
const otherTranslation = loc[`${altLocSrcFn.qName}|block`] || altLocSrcFn.attributes.locs?.[attrBlockLocsKey];
const isSameBlockDef = fn.attributes.block === (altLocSrcFn.attributes._untranslatedBlock || altLocSrcFn.attributes.block);
if (isSameBlockDef && !!otherTranslation) {
locBlock = otherTranslation;
}
}
if (locBlock && pxt.Util.isTranslationMode()) {
// in translation mode, crowdin sends translation identifiers which break the block parsing
// push identifier in DOM so that crowdin sends back the actual translation
fn.attributes.translationId = locBlock;
locBlock = await pxt.crowdin.inContextLoadAsync(locBlock);
}
if (nsDoc) {
// Check for "friendly namespace"
if (fn.attributes.block) {
fn.attributes.block = locBlock || fn.attributes.block;
} else {
fn.attributes.block = nsDoc;
}
updateBlockDef(fn.attributes);
} else if (fn.attributes.block && locBlock) {
const ps = pxt.blocks.compileInfo(fn);
const oldBlock = fn.attributes.block;
fn.attributes.block = pxt.blocks.normalizeBlock(locBlock, err => {
pxt.tickEvent("loc.normalized", {
block: fn.attributes.block,
lang: lang,
error: err,
});
});
if (!fn.attributes._untranslatedBlock) {
fn.attributes._untranslatedBlock = oldBlock;
}
if (oldBlock != fn.attributes.block) {
updateBlockDef(fn.attributes);
const locps = pxt.blocks.compileInfo(fn);
if (!hasEquivalentParameters(ps, locps)) {
pxt.reportError("loc.errors", "block has non matching arguments", {
block: fn.attributes.blockId,
lang: lang,
originalDefinition: oldBlock,
translatedBlock: fn.attributes.block,
});
pxt.tickEvent("loc.errors", {
block: fn.attributes.blockId,
lang: lang,
});
fn.attributes.block = oldBlock;
updateBlockDef(fn.attributes);
}
}
} else {
updateBlockDef(fn.attributes);
}
fn.attributes._translatedLanguageCode = lang;
});
return cleanLocalizations(apis);
}
function cleanLocalizations(apis: ApisInfo) {
Util.values(apis.byQName)
.filter(fb => fb.attributes.block && /^{[^:]+:[^}]+}/.test(fb.attributes.block))
.forEach(fn => { fn.attributes.block = fn.attributes.block.replace(/^{[^:]+:[^}]+}/, ''); });
return apis;
}
function hasEquivalentParameters(a: pxt.blocks.BlockCompileInfo, b: pxt.blocks.BlockCompileInfo) {
if (a.parameters.length != b.parameters.length) {
pxt.debug(`Localized block has extra or missing parameters`);
return false;
}
for (const aParam of a.parameters) {
const bParam = b.actualNameToParam[aParam.actualName];
if (!bParam
|| aParam.type != bParam.type
|| aParam.shadowBlockId != bParam.shadowBlockId
|| aParam.definitionName != bParam.definitionName) {
pxt.debug(`Parameter ${aParam.actualName} type, shadow block, or definition name does not match after localization`);
return false;
}
}
return true;
}
export function emptyExtInfo(): ExtensionInfo {
let cs = pxt.appTarget.compileService
if (!cs) cs = {} as any
const pio = !!cs.platformioIni;
const docker = cs.buildEngine == "dockermake" || cs.buildEngine == "dockercross" || cs.buildEngine == "dockerespidf";
const r: ExtensionInfo = {
functions: [],
generatedFiles: {},
extensionFiles: {},
sha: "",
compileData: "",
shimsDTS: "",
enumsDTS: "",
onlyPublic: true
}
if (pio) r.platformio = { dependencies: {} };
else if (docker) r.npmDependencies = {};
else r.yotta = { config: {}, dependencies: {} };
return r;
}
const numberAttributes = ["weight", "imageLiteral", "gridLiteral", "topblockWeight", "inlineInputModeLimit"]
const booleanAttributes = [
"advanced",
"handlerStatement",
"afterOnStart",
"optionalVariableArgs",
"blockHidden",
"constantShim",
"blockCombine",
"enumIsBitMask",
"enumIsHash",
"decompileIndirectFixedInstances",
"topblock",
"callInDebugger",
"duplicateShadowOnDrag",
"argsNullable",
"compileHiddenArguments"
];
export function parseCommentString(cmt: string): CommentAttrs {
let res: CommentAttrs = {
paramDefl: {},
callingConvention: ir.CallingConvention.Plain,
_source: cmt
}
let didSomething = true
while (didSomething) {
didSomething = false
cmt = cmt.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,
(f: string, n: string, d0: string, d1: string,
v0: string, v1: string, v2: string) => {
let v = v0 ? JSON.parse(v0) : (d0 ? (v0 || v1 || v2) : "true");
if (!v) v = "";
if (U.startsWith(n, "block.loc.")) {
if (!res.locs) res.locs = {};
res.locs[n.slice("block.loc.".length).toLowerCase() + "|block"] = v;
} else if (U.startsWith(n, "jsdoc.loc.")) {
if (!res.locs) res.locs = {};
res.locs[n.slice("jsdoc.loc.".length).toLowerCase() + "|jsdoc"] = v;
} else if (U.contains(n, ".loc.")) {
if (!res.locs) res.locs = {};
const p = n.slice(0, n.indexOf('.loc.'));
const l = n.slice(n.indexOf('.loc.') + '.loc.'.length);
res.locs[l + "|param|" + p] = v;
} else if (U.endsWith(n, ".defl")) {
if (v.indexOf(" ") > -1) {
res.paramDefl[n.slice(0, n.length - 5)] = `"${v}"`
} else {
res.paramDefl[n.slice(0, n.length - 5)] = v
}
if (!res.explicitDefaults) res.explicitDefaults = []
res.explicitDefaults.push(n.slice(0, n.length - 5))
} else if (U.endsWith(n, ".shadow")) {
if (!res._shadowOverrides) res._shadowOverrides = {};
res._shadowOverrides[n.slice(0, n.length - 7)] = v;
} else if (U.endsWith(n, ".snippet")) {
if (!res.paramSnippets) res.paramSnippets = {};
const paramName = n.slice(0, n.length - 8);
if (!res.paramSnippets[paramName]) res.paramSnippets[paramName] = {};
res.paramSnippets[paramName].ts = v;
} else if (U.endsWith(n, ".pySnippet")) {
if (!res.paramSnippets) res.paramSnippets = {};
const paramName = n.slice(0, n.length - 10);
if (!res.paramSnippets[paramName]) res.paramSnippets[paramName] = {};
res.paramSnippets[paramName].python = v;
} else if (U.endsWith(n, ".fieldEditor")) {
if (!res.paramFieldEditor) res.paramFieldEditor = {}
res.paramFieldEditor[n.slice(0, n.length - 12)] = v
} else if (U.contains(n, ".fieldOptions.")) {
if (!res.paramFieldEditorOptions) res.paramFieldEditorOptions = {}
const field = n.slice(0, n.indexOf('.fieldOptions.'));
const key = n.slice(n.indexOf('.fieldOptions.') + 14, n.length);
if (!res.paramFieldEditorOptions[field]) res.paramFieldEditorOptions[field] = {};
res.paramFieldEditorOptions[field][key] = v
} else if (U.contains(n, ".shadowOptions.")) {
if (!res.paramShadowOptions) res.paramShadowOptions = {}
const field = n.slice(0, n.indexOf('.shadowOptions.'));
const key = n.slice(n.indexOf('.shadowOptions.') + 15, n.length);
if (!res.paramShadowOptions[field]) res.paramShadowOptions[field] = {};
res.paramShadowOptions[field][key] = v
} else if (U.endsWith(n, ".min")) {
if (!res.paramMin) res.paramMin = {}
res.paramMin[n.slice(0, n.length - 4)] = v
} else if (U.endsWith(n, ".max")) {
if (!res.paramMax) res.paramMax = {}
res.paramMax[n.slice(0, n.length - 4)] = v
} else {
(<any>res)[n] = v;
}
didSomething = true
return "//% "
})
}
for (let n of numberAttributes) {
if (typeof (res as any)[n] == "string")
(res as any)[n] = parseInt((res as any)[n])
}
for (let n of booleanAttributes) {
if (typeof (res as any)[n] == "string")
(res as any)[n] = (res as any)[n] == 'true' || (res as any)[n] == '1' ? true : false;
}
if (res.trackArgs) {
res.trackArgs = ((res.trackArgs as any) as string).split(/[ ,]+/).map(s => parseInt(s) || 0)
}
if (res.enumInitialMembers) {
res.enumInitialMembers = ((res.enumInitialMembers as any) as string).split(/[ ,]+/);
}
if (res.blockExternalInputs && !res.inlineInputMode) {
res.inlineInputMode = "external";
}
res.paramHelp = {}
res.jsDoc = ""
cmt = cmt.replace(/\/\*\*([^]*?)\*\//g, (full: string, doccmt: string) => {
doccmt = doccmt.replace(/\n\s*(\*\s*)?/g, "\n")
doccmt = doccmt.replace(/^\s*@param\s+(\w+)\s+(.*)$/mg, (full: string, name: string, desc: string) => {
res.paramHelp[name] = desc
if (!res.paramDefl[name]) {
// these don't add to res.explicitDefaults
let m = /\beg\.?:\s*(.+)/.exec(desc);
if (m && m[1]) {
let defaultValue = /(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(m[1]);
if (defaultValue) {
let val = defaultValue[1] || defaultValue[2] || defaultValue[3];
if (!val) val = "";
// If there are spaces in the value, it means the value was surrounded with quotes, so add them back
if (val.indexOf(" ") > -1) {
res.paramDefl[name] = `"${val}"`;
}
else {
res.paramDefl[name] = val;
}
}
}
}
return ""
})
res.jsDoc += doccmt
return ""
})
res.jsDoc = res.jsDoc.trim()
if (res.async)
res.callingConvention = ir.CallingConvention.Async
if (res.promise)
res.callingConvention = ir.CallingConvention.Promise
if (res.jres)
res.whenUsed = true
if (res.subcategories) {
try {
res.subcategories = JSON.parse(res.subcategories as any);
}
catch (e) {
res.subcategories = undefined;
}
}
if (res.groups) {