forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp.ts
More file actions
1521 lines (1340 loc) · 53.2 KB
/
cpp.ts
File metadata and controls
1521 lines (1340 loc) · 53.2 KB
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"/>
namespace pxt {
declare var require: any;
function getLzmaAsync() {
if (U.isNodeJS) return Promise.resolve(require("lzma"));
else {
let lz = (<any>window).LZMA;
if (lz) return Promise.resolve(lz);
const monacoPaths: Map<string> = (window as any).MonacoPaths
return BrowserUtils.loadScriptAsync(monacoPaths['lzma/lzma_worker-min.js'])
.then(() => (<any>window).LZMA);
}
}
export function lzmaDecompressAsync(buf: Uint8Array): Promise<string> { // string
return getLzmaAsync()
.then(lzma => new Promise<string>((resolve, reject) => {
try {
lzma.decompress(buf, (res: string, error: any) => {
resolve(error ? undefined : res);
})
}
catch (e) {
resolve(undefined);
}
}));
}
export function lzmaCompressAsync(text: string): Promise<Uint8Array> {
return getLzmaAsync()
.then(lzma => new Promise<Uint8Array>((resolve, reject) => {
try {
lzma.compress(text, 7, (res: any, error: any) => {
resolve(error ? undefined : new Uint8Array(res));
})
}
catch (e) {
resolve(undefined);
}
}));
}
}
// preprocess C++ file to find functions exposed to pxt
namespace pxt.cpp {
import U = pxtc.Util;
let lf = U.lf;
function parseExpr(e: string): number {
e = e.trim()
e = e.replace(/^\(/, "")
e = e.replace(/\)$/, "")
e = e.trim();
if (/^-/.test(e) && parseExpr(e.slice(1)) != null)
return -parseExpr(e.slice(1))
if (/^0x[0-9a-f]+$/i.exec(e))
return parseInt(e.slice(2), 16)
if (/^0b[01]+$/i.exec(e))
return parseInt(e.slice(2), 2)
if (/^0\d+$/i.exec(e))
return parseInt(e, 8)
if (/^\d+$/i.exec(e))
return parseInt(e, 10)
return null;
}
export function nsWriter(nskw = "namespace") {
let text = ""
let currNs = ""
let setNs = (ns: string, over = "") => {
if (currNs == ns) return
if (currNs) text += "}\n"
if (ns)
text += over || (nskw + " " + ns + " {\n")
currNs = ns
}
let indent = " "
return {
setNs,
clear: () => {
text = ""
currNs = ""
},
write: (s: string) => {
if (!s.trim()) text += "\n"
else {
s = s.trim()
.replace(/^\s*/mg, indent)
.replace(/^(\s*)\*/mg, (f, s) => s + " *")
text += s + "\n"
}
},
incrIndent: () => {
indent += " "
},
decrIndent: () => {
indent = indent.slice(4)
},
finish: () => {
setNs("")
return text
}
}
}
export function parseCppInt(v: string): number {
if (!v) return null
v = v.trim()
let mm = /^\((.*)\)/.exec(v)
if (mm) v = mm[1]
if (/^-?(\d+|0[xX][0-9a-fA-F]+)$/.test(v))
return parseInt(v)
return null
}
let prevExtInfo: pxtc.ExtensionInfo;
let prevSnapshot: Map<string>;
export class PkgConflictError extends Error {
pkg0: Package;
pkg1: Package;
settingName: string;
isUserError: boolean;
isVersionConflict: boolean;
constructor(msg: string) {
super(msg)
this.isUserError = true
this.message = msg
}
}
export function getExtensionInfo(mainPkg: MainPackage): pxtc.ExtensionInfo {
let pkgSnapshot: Map<string> = {}
let constsName = "dal.d.ts"
let sourcePath = "/source/"
for (let pkg of mainPkg.sortedDeps()) {
pkg.addSnapshot(pkgSnapshot, [constsName, ".h", ".cpp"])
}
if (prevSnapshot && U.stringMapEq(pkgSnapshot, prevSnapshot)) {
pxt.debug("Using cached extinfo")
return prevExtInfo
}
pxt.debug("Generating new extinfo")
const res = pxtc.emptyExtInfo();
let compileService = appTarget.compileService;
if (!compileService)
compileService = {
gittag: "none",
serviceId: "nocompile"
}
let compile = appTarget.compile
if (!compile)
compile = {
isNative: false,
hasHex: false,
}
const isCSharp = compile.nativeType == pxtc.NATIVE_TYPE_CS
const isPlatformio = !!compileService.platformioIni;
const isCodal = compileService.buildEngine == "codal"
const isDockerMake = compileService.buildEngine == "dockermake"
const isYotta = !isCSharp && !isPlatformio && !isCodal && !isDockerMake
if (isPlatformio)
sourcePath = "/src/"
else if (isCodal || isDockerMake)
sourcePath = "/pxtapp/"
let pxtConfig = "// Configuration defines\n"
let pointersInc = "\nPXT_SHIMS_BEGIN\n"
let includesInc = `#include "pxt.h"\n`
let fullCS = ""
let thisErrors = ""
let dTsNamespace = ""
let err = (s: string) => thisErrors += ` ${fileName}(${lineNo}): ${s}\n`;
let lineNo = 0
let fileName = ""
let protos = nsWriter("namespace")
let shimsDTS = nsWriter("declare namespace")
let enumsDTS = nsWriter("declare namespace")
let allErrors = ""
let knownEnums: Map<boolean> = {}
const enumVals: Map<string> = {
"true": "1",
"false": "0",
"null": "0",
"NULL": "0",
}
// we sometimes append _ to C++ names to avoid name clashes
function toJs(name: string) {
return name.trim().replace(/[\_\*]$/, "")
}
let makefile = ""
for (const pkg of mainPkg.sortedDeps()) {
if (pkg.getFiles().indexOf(constsName) >= 0) {
const src = pkg.host().readFile(pkg, constsName)
Util.assert(!!src, `${constsName} not found in ${pkg.id}`)
src.split(/\r?\n/).forEach(ln => {
let m = /^\s*(\w+) = (.*),/.exec(ln)
if (m) {
enumVals[m[1]] = m[2]
}
})
}
if (!makefile && pkg.getFiles().indexOf("Makefile") >= 0) {
makefile = pkg.host().readFile(pkg, "Makefile")
}
}
function stripComments(ln: string) {
return ln.replace(/\/\/.*/, "").replace(/\/\*/, "")
}
let enumVal = 0
let inEnum = false
let currNs = ""
let currDocComment = ""
let currAttrs = ""
let inDocComment = false
let outp = ""
function handleComments(ln: string) {
if (inEnum) {
outp += ln + "\n"
return true
}
if (/^\s*\/\*\*/.test(ln)) {
inDocComment = true
currDocComment = ln + "\n"
if (/\*\//.test(ln)) inDocComment = false
outp += "//\n"
return true
}
if (inDocComment) {
currDocComment += ln + "\n"
if (/\*\//.test(ln)) {
inDocComment = false
}
outp += "//\n"
return true
}
if (/^\s*\/\/%/.test(ln)) {
currAttrs += ln + "\n"
outp += "//\n"
return true
}
outp += ln + "\n"
return false
}
function enterEnum(cpname: string, brace: string) {
inEnum = true
enumVal = -1
enumsDTS.write("")
enumsDTS.write("")
if (currAttrs || currDocComment) {
enumsDTS.write(currDocComment)
enumsDTS.write(currAttrs)
currAttrs = ""
currDocComment = ""
}
enumsDTS.write(`declare const enum ${toJs(cpname)} ${brace}`)
knownEnums[cpname] = true
}
function processEnumLine(ln: string) {
let lnNC = stripComments(ln)
if (inEnum && lnNC.indexOf("}") >= 0) {
inEnum = false
enumsDTS.write("}")
}
if (!inEnum)
return
// parse the enum case, with lots of optional stuff (?)
let mm = /^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(lnNC)
if (mm) {
let nm = mm[1]
let v = mm[3]
let opt = ""
if (v) {
// user-supplied value
v = v.trim()
let curr = U.lookup(enumVals, v)
if (curr != null) {
opt = " // " + v
v = curr
}
enumVal = parseCppInt(v)
if (enumVal == null)
err("cannot determine value of " + lnNC)
} else {
// no user-supplied value
enumVal++
v = enumVal + ""
}
enumsDTS.write(` ${toJs(nm)} = ${v},${opt}`)
} else {
enumsDTS.write(ln)
}
}
function finishNamespace() {
shimsDTS.setNs("");
shimsDTS.write("")
shimsDTS.write("")
if (currAttrs || currDocComment) {
shimsDTS.write(currDocComment)
shimsDTS.write(currAttrs)
currAttrs = ""
currDocComment = ""
}
}
function parseArg(parsedAttrs: pxtc.CommentAttrs, s: string) {
s = s.trim()
let m = /(.*)=\s*(-?\w+)$/.exec(s)
let defl = ""
let qm = ""
if (m) {
defl = m[2]
qm = "?"
s = m[1].trim()
}
m = /^(.*?)(\w+)$/.exec(s)
if (!m) {
err("invalid argument: " + s)
return {
name: "???",
type: "int"
}
}
let argName = m[2]
if (parsedAttrs.paramDefl[argName]) {
defl = parsedAttrs.paramDefl[argName]
qm = "?"
}
let numVal = defl ? U.lookup(enumVals, defl) : null
if (numVal != null)
defl = numVal
if (defl) {
if (parseCppInt(defl) == null)
err("Invalid default value (non-integer): " + defl)
currAttrs += ` ${argName}.defl=${defl}`
}
return {
name: argName + qm,
type: m[1]
}
}
function parseCpp(src: string, isHeader: boolean) {
currNs = ""
currDocComment = ""
currAttrs = ""
inDocComment = false
let indexedInstanceAttrs: pxtc.CommentAttrs
let indexedInstanceIdx = -1
// replace #if 0 .... #endif with newlines
src = src.replace(/^\s*#\s*if\s+0\s*$[^]*?^\s*#\s*endif\s*$/mg, f => f.replace(/[^\n]/g, ""))
// special handling of C++ namespace that ends with Methods (e.g. FooMethods)
// such a namespace will be converted into a TypeScript interface
// this enables simple objects with methods to be defined. See, for example:
// https://github.com/Microsoft/pxt-microbit/blob/master/libs/core/buffer.cpp
// within that namespace, the first parameter of each function should have
// the type Foo
function interfaceName() {
let n = currNs.replace(/Methods$/, "")
if (n == currNs) return null
return n
}
lineNo = 0
// the C++ types we can map to TypeScript
function mapType(tp: string) {
switch (tp.replace(/\s+/g, "")) {
case "void": return "void";
// TODO: need int16_t
case "int32_t":
case "int":
return "int32";
case "uint32_t":
case "unsigned":
return "uint32";
case "TNumber":
case "float":
case "double":
return "number";
case "uint16_t": return "uint16";
case "int16_t":
case "short": return "int16";
case "uint8_t":
case "byte": return "uint8";
case "int8_t":
case "sbyte": return "int8";
case "bool":
if (compile.shortPointers)
err("use 'boolean' not 'bool' on 8 bit targets")
return "boolean";
case "StringData*": return "string";
case "String": return "string";
case "ImageLiteral": return "string";
case "Action": return "() => void";
case "TValue": return "any";
default:
return toJs(tp);
//err("Don't know how to map type: " + tp)
//return "any"
}
}
function mapRunTimeType(tp: string) {
tp = tp.replace(/\s+/g, "")
switch (tp) {
case "int32_t":
case "uint32_t":
case "unsigned":
case "uint16_t":
case "int16_t":
case "short":
case "uint8_t":
case "byte":
case "int8_t":
case "sbyte":
case "int":
return "I";
case "void": return "V";
case "float": return "F";
case "TNumber": return "N";
case "TValue": return "T";
case "bool": return "B";
case "double": return "D"
default:
if (U.lookup(knownEnums, tp))
return "I"
return "_";
}
}
outp = ""
inEnum = false
enumVal = 0
enumsDTS.setNs("")
shimsDTS.setNs("")
src.split(/\r?\n/).forEach(ln => {
++lineNo
// remove comments (NC = no comments)
let lnNC = stripComments(ln)
processEnumLine(ln)
// "enum class" and "enum struct" is C++ syntax to force scoping of
// enum members
let enM = /^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(lnNC)
if (enM) {
enterEnum(enM[2], enM[3])
if (!isHeader) {
protos.setNs(currNs)
protos.write(`enum ${enM[2]} : int;`)
}
}
if (handleComments(ln))
return
if (/^typedef.*;\s*$/.test(ln)) {
protos.setNs(currNs);
protos.write(ln);
}
let m = /^\s*namespace\s+(\w+)/.exec(ln)
if (m) {
//if (currNs) err("more than one namespace declaration not supported")
currNs = m[1]
if (interfaceName()) {
finishNamespace()
let tpName = interfaceName()
shimsDTS.setNs(currNs, `declare interface ${tpName} {`)
} else if (currAttrs || currDocComment) {
finishNamespace()
shimsDTS.setNs(toJs(currNs))
enumsDTS.setNs(toJs(currNs))
}
return
}
// function definition
m = /^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(ln)
if (currAttrs && m) {
indexedInstanceAttrs = null
let parsedAttrs = pxtc.parseCommentString(currAttrs)
// top-level functions (outside of a namespace) are not permitted
if (!currNs) err("missing namespace declaration");
let retTp = (m[1] + m[2]).replace(/\s+/g, "")
let funName = m[3]
let origArgs = m[4]
currAttrs = currAttrs.trim().replace(/ \w+\.defl=\w+/g, "")
let argsFmt = mapRunTimeType(retTp)
let args = origArgs.split(/,/).filter(s => !!s).map(s => {
let r = parseArg(parsedAttrs, s)
argsFmt += mapRunTimeType(r.type)
return `${r.name}: ${mapType(r.type)}`
})
let numArgs = args.length
let fi: pxtc.FuncInfo = {
name: currNs + "::" + funName,
argsFmt,
value: null
}
//console.log(`${ln.trim()} : ${argsFmt}`)
if (currDocComment) {
shimsDTS.setNs(toJs(currNs))
shimsDTS.write("")
shimsDTS.write(currDocComment)
if (/ImageLiteral/.test(m[4]) && !/imageLiteral=/.test(currAttrs))
currAttrs += ` imageLiteral=1`
currAttrs += ` shim=${fi.name}`
shimsDTS.write(currAttrs)
funName = toJs(funName)
if (interfaceName()) {
let tp0 = (args[0] || "").replace(/^.*:\s*/, "").trim()
if (tp0.toLowerCase() != interfaceName().toLowerCase()) {
err(lf("Invalid first argument; should be of type '{0}', but is '{1}'", interfaceName(), tp0))
}
args.shift()
if (args.length == 0 && /\bproperty\b/.test(currAttrs))
shimsDTS.write(`${funName}: ${mapType(retTp)};`)
else
shimsDTS.write(`${funName}(${args.join(", ")}): ${mapType(retTp)};`)
} else {
shimsDTS.write(`function ${funName}(${args.join(", ")}): ${mapType(retTp)};`)
}
}
currDocComment = ""
currAttrs = ""
if (!isHeader) {
protos.setNs(currNs)
protos.write(`${retTp} ${funName}(${origArgs});`)
}
res.functions.push(fi)
if (isYotta)
pointersInc += "(uint32_t)(void*)::" + fi.name + ",\n"
else
pointersInc += "PXT_FNPTR(::" + fi.name + "),\n"
return;
}
m = /^\s*(\w+)\s+(\w+)\s*;/.exec(ln)
if (currAttrs && m) {
let parsedAttrs = pxtc.parseCommentString(currAttrs)
if (parsedAttrs.indexedInstanceNS) {
indexedInstanceAttrs = parsedAttrs
shimsDTS.setNs(parsedAttrs.indexedInstanceNS)
indexedInstanceIdx = 0
}
let tp = m[1]
let nm = m[2]
if (indexedInstanceAttrs) {
currAttrs = currAttrs.trim()
currAttrs += ` fixedInstance shim=${indexedInstanceAttrs.indexedInstanceShim}(${indexedInstanceIdx++})`
shimsDTS.write("")
shimsDTS.write(currDocComment)
shimsDTS.write(currAttrs)
shimsDTS.write(`const ${nm}: ${mapType(tp)};`)
currDocComment = ""
currAttrs = ""
return;
}
}
if (currAttrs && ln.trim()) {
err("declaration not understood: " + ln)
currAttrs = ""
currDocComment = ""
return;
}
})
return outp
}
function parseCs(src: string) {
currNs = ""
currDocComment = ""
currAttrs = ""
inDocComment = false
// replace #if false .... #endif with newlines
src = src.replace(/^\s*#\s*if\s+false\s*$[^]*?^\s*#\s*endif\s*$/mg, f => f.replace(/[^\n]/g, ""))
lineNo = 0
// the C# types we can map to TypeScript
function mapType(tp: string) {
switch (tp.replace(/\s+/g, "")) {
case "void": return "void";
case "int": return "int32";
case "uint": return "uint32";
case "float":
case "double": return "number";
case "ushort": return "uint16";
case "short": return "int16";
case "byte": return "uint8";
case "sbyte": return "int8";
case "bool": return "boolean";
case "string":
case "String": return "string";
case "Function": return "() => void";
case "object": return "any";
default:
return toJs(tp);
}
}
function isNumberType(tp: string) {
tp = tp.replace(/\s+/g, "")
if (U.lookup(knownEnums, tp))
return true
let mt = mapType(tp)
if (mt == "number" || /^u?int\d+$/.test(mt))
return true
return false
}
function mapRunTimeType(tp: string) {
tp = tp.replace(/\s+/g, "")
if (isNumberType(tp))
tp = "#" + tp
return tp + ";"
}
outp = "" // we don't really care about this one for C#
inEnum = false
enumVal = 0
enumsDTS.setNs("")
shimsDTS.setNs("")
src.split(/\r?\n/).forEach(ln => {
++lineNo
// remove comments (NC = no comments)
let lnNC = stripComments(ln)
processEnumLine(ln)
let enM = /^\s*(public) enum\s+(\w+)\s*({|$)/.exec(lnNC)
if (enM) {
enterEnum(enM[2], enM[3])
}
if (handleComments(ln))
return
let m = /^\s*public (static\s+|partial\s+)*class\s+(\w+)/.exec(ln)
if (m) {
currNs = m[2]
if (currAttrs || currDocComment) {
finishNamespace()
shimsDTS.setNs(toJs(currNs))
enumsDTS.setNs(toJs(currNs))
}
return
}
// function definition
m = /^\s*public static (async\s+)*([\w\[\]<>]+)\s+(\w+)\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(ln)
if (currAttrs && m) {
let parsedAttrs = pxtc.parseCommentString(currAttrs)
// top-level functions (outside of a namespace) are not permitted
if (!currNs) err("missing namespace declaration");
let retTp = m[2]
let funName = m[3]
let origArgs = m[4]
let isAsync = false
currAttrs = currAttrs.trim().replace(/ \w+\.defl=\w+/g, "")
if (retTp == "Task") {
retTp = "void"
isAsync = true
} else {
let mm = /^Task<(.*)>$/.exec(retTp)
if (mm) {
isAsync = true
retTp = mm[1]
}
}
let argsFmt = mapRunTimeType(retTp)
if (isAsync) {
argsFmt = "async;" + argsFmt
currAttrs += " async"
}
let args: string[] = []
for (let s of origArgs.split(/,/)) {
if (!s) continue
let r = parseArg(parsedAttrs, s)
let mapped = mapRunTimeType(r.type)
argsFmt += mapped
if (mapped != "CTX;")
args.push(`${r.name}: ${mapType(r.type)}`)
}
let fi: pxtc.FuncInfo = {
name: currNs + "::" + funName,
argsFmt,
value: null
}
//console.log(`${ln.trim()} : ${argsFmt}`)
if (currDocComment) {
shimsDTS.setNs(toJs(currNs))
shimsDTS.write("")
shimsDTS.write(currDocComment)
currAttrs += ` shim=${fi.name}`
shimsDTS.write(currAttrs)
funName = toJs(funName)
shimsDTS.write(`function ${funName}(${args.join(", ")}): ${mapType(retTp)};`)
}
currDocComment = ""
currAttrs = ""
res.functions.push(fi)
return;
}
if (currAttrs && ln.trim()) {
err("declaration not understood: " + ln)
currAttrs = ""
currDocComment = ""
return;
}
})
return outp
}
const currSettings: Map<any> = U.clone(compileService.yottaConfig || {})
const optSettings: Map<any> = {}
const settingSrc: Map<Package> = {}
function parseJson(pkg: Package) {
let j0 = pkg.config.platformio
if (j0 && j0.dependencies) {
U.jsonCopyFrom(res.platformio.dependencies, j0.dependencies)
}
if (res.npmDependencies && pkg.config.npmDependencies)
U.jsonCopyFrom(res.npmDependencies, pkg.config.npmDependencies)
let json = pkg.config.yotta
if (!json) return;
// TODO check for conflicts
if (json.dependencies) {
U.jsonCopyFrom(res.yotta.dependencies, json.dependencies)
}
if (json.config) {
const cfg = U.jsonFlatten(json.config)
for (const settingName of Object.keys(cfg)) {
const prev = U.lookup(settingSrc, settingName)
const settingValue = cfg[settingName]
if (!prev || prev.config.yotta.configIsJustDefaults) {
settingSrc[settingName] = pkg
currSettings[settingName] = settingValue
} else if (currSettings[settingName] === settingValue) {
// OK
} else if (!pkg.parent.config.yotta || !pkg.parent.config.yotta.ignoreConflicts) {
let err = new PkgConflictError(lf("conflict on yotta setting {0} between packages {1} and {2}",
settingName, pkg.id, prev.id))
err.pkg0 = prev
err.pkg1 = pkg
err.settingName = settingName
throw err;
}
}
}
if (json.optionalConfig) {
const cfg = U.jsonFlatten(json.optionalConfig)
for (const settingName of Object.keys(cfg)) {
const settingValue = cfg[settingName];
// last one wins
optSettings[settingName] = settingValue;
}
}
}
// This is overridden on the build server, but we need it for command line build
if (isYotta && compile.hasHex) {
let cs = compileService
U.assert(!!cs.yottaCorePackage);
U.assert(!!cs.githubCorePackage);
U.assert(!!cs.gittag);
let tagged = cs.githubCorePackage + "#" + compileService.gittag
res.yotta.dependencies[cs.yottaCorePackage] = tagged;
}
if (mainPkg) {
let seenMain = false
// TODO computeReachableNodes(pkg, true)
for (let pkg of mainPkg.sortedDeps()) {
thisErrors = ""
parseJson(pkg)
if (pkg == mainPkg) {
seenMain = true
// we only want the main package in generated .d.ts
shimsDTS.clear()
enumsDTS.clear()
} else {
U.assert(!seenMain)
}
let ext = isCSharp ? ".cs" : ".cpp"
for (let fn of pkg.getFiles()) {
let isHeader = !isCSharp && U.endsWith(fn, ".h")
if (isHeader || U.endsWith(fn, ext)) {
let fullName = pkg.config.name + "/" + fn
if ((pkg.config.name == "base" || pkg.config.name == "core") && isHeader)
fullName = fn
if (isHeader)
includesInc += `#include "${isYotta ? sourcePath.slice(1) : ""}${fullName}"\n`
let src = pkg.readFile(fn)
if (src == null)
U.userError(lf("C++ file {0} is missing in package {1}.", fn, pkg.config.name))
fileName = fullName
if (isCSharp) {
pxt.debug("Parse C#: " + fullName)
parseCs(src)
fullCS += `\n\n\n#line 1 "${fullName}"\n` + src
} else {
// parseCpp() will remove doc comments, to prevent excessive recompilation
pxt.debug("Parse C++: " + fullName)
src = parseCpp(src, isHeader)
res.extensionFiles[sourcePath + fullName] = src
}
if (pkg.level == 0)
res.onlyPublic = false
if (pkg.verProtocol() && pkg.verProtocol() != "pub" && pkg.verProtocol() != "embed")
res.onlyPublic = false
}
if (!isCSharp && (U.endsWith(fn, ".c") || U.endsWith(fn, ".S") || U.endsWith(fn, ".s"))) {
let src = pkg.readFile(fn)
res.extensionFiles[sourcePath + pkg.config.name + "/" + fn.replace(/\.S$/, ".s")] = src
}
}
if (thisErrors) {
allErrors += lf("Package {0}:\n", pkg.id) + thisErrors
}
}
}
if (allErrors)
U.userError(allErrors)
fullCS += "\n#line default\n"
// merge optional settings
U.jsonCopyFrom(optSettings, currSettings);
const configJson = U.jsonUnFlatten(optSettings)
if (isCSharp) {
res.extensionFiles["/lib.cs"] = fullCS
res.generatedFiles["/module.json"] = "{}"
} else if (isDockerMake) {
let packageJson = {
name: "pxt-app",
private: true,
dependencies: res.npmDependencies,
}
res.generatedFiles["/package.json"] = JSON.stringify(packageJson, null, 4) + "\n"
} else if (isCodal) {
let cs = compileService
let cfg = U.clone(cs.codalDefinitions) || {}
let trg = cs.codalTarget
if (typeof trg == "string") trg = trg + ".json"
let codalJson = {
"target": trg,
"definitions": cfg,
"config": cfg,
"application": "pxtapp",
"output_folder": "build",
// include these, because we use hash of this file to see if anything changed
"pxt_gitrepo": cs.githubCorePackage,
"pxt_gittag": cs.gittag,
}
U.iterMap(U.jsonFlatten(configJson), (k, v) => {
k = k.replace(/^codal\./, "device.").toUpperCase().replace(/\./g, "_")
cfg[k] = v
})
res.generatedFiles["/codal.json"] = JSON.stringify(codalJson, null, 4) + "\n"
} else if (isPlatformio) {
const iniLines = compileService.platformioIni.slice()
// TODO merge configjson
iniLines.push("lib_deps =")
U.iterMap(res.platformio.dependencies, (pkg, ver) => {
let pkgSpec = /[@#\/]/.test(ver) ? ver : pkg + "@" + ver
iniLines.push(" " + pkgSpec)
})
res.generatedFiles["/platformio.ini"] = iniLines.join("\n") + "\n"
} else {
res.yotta.config = configJson;
let name = "pxt-app"
if (compileService.yottaBinary)
name = compileService.yottaBinary.replace(/-combined/, "").replace(/\.hex$/, "")
let moduleJson = {
"name": name,
"version": "0.0.0",
"description": "Auto-generated. Do not edit.",
"license": "n/a",
"dependencies": res.yotta.dependencies,
"targetDependencies": {},
"bin": "./source"
}
res.generatedFiles["/module.json"] = JSON.stringify(moduleJson, null, 4) + "\n"
}
if (compile.boxDebug) {
pxtConfig += "#define PXT_BOX_DEBUG 1\n"
pxtConfig += "#define PXT_MEMLEAK_DEBUG 1\n"
}
if (compile.nativeType == pxtc.NATIVE_TYPE_AVRVM) {
pxtConfig += "#define PXT_VM 1\n"
} else {
pxtConfig += "#define PXT_VM 0\n"
}
if (!isCSharp) {
res.generatedFiles[sourcePath + "pointers.cpp"] = includesInc + protos.finish() + pointersInc + "\nPXT_SHIMS_END\n"
res.generatedFiles[sourcePath + "pxtconfig.h"] = pxtConfig
if (isYotta)
res.generatedFiles["/config.json"] = JSON.stringify(configJson, null, 4) + "\n"
res.generatedFiles[sourcePath + "main.cpp"] = `
#include "pxt.h"
#ifdef PXT_MAIN
PXT_MAIN
#else
int main() {
uBit.init();
pxt::start();
while (1) uBit.sleep(10000);
return 0;
}
#endif
`
}
if (makefile) {
let allfiles = Object.keys(res.extensionFiles).concat(Object.keys(res.generatedFiles))
let inc = ""
let objs: string[] = []
let add = (name: string, ext: string) => {