@needle-tools/needle-component-compiler 2.4.1-pre → 3.0.0-68ab237

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,699 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.run = exports.compile = void 0;
4
- var fs_1 = require("fs");
5
- var ts = require("typescript");
6
- var fs = require("fs");
7
- var path = require("path");
8
- var types = require("./types");
9
- var dict = types.dict;
10
- // add either of these two comments above a class to enforce code gen or disable it for the next class
11
- var exportNextClassCommand = "@generate-component";
12
- var dontExportNextClassCommand = "@dont-generate-component";
13
- // add above field to add [SerializeField] attribute
14
- var serializeCommand = "@serializeField";
15
- var dontSerializeCommand = "@nonSerialized";
16
- // https://regex101.com/r/ltpcKT/2
17
- var typePattern = new RegExp("@type ?(?<type>.+)");
18
- var ifdefPattern = new RegExp("@ifdef ?(?<ifdef>.+)");
19
- var CODEGEN_MARKER_START = "// NEEDLE_CODEGEN_START";
20
- var CODEGEN_MARKER_END = "// NEEDLE_CODEGEN_END";
21
- var allowDebugLogs = true;
22
- // will be set to true when e.g. a comment for export is found
23
- var exportNextClass = false;
24
- var dontExportNextClass = false;
25
- var serializeField = false;
26
- var dontSerialize = false;
27
- var typesFileContent = undefined;
28
- // const exportDir = "../dist";
29
- var commentStarts = [];
30
- var contexts = [];
31
- var lastTypeFound = null;
32
- var ifdefSections = [];
33
- function resetAllState() {
34
- exportNextClass = false;
35
- dontExportNextClass = false;
36
- serializeField = false;
37
- dontSerialize = false;
38
- typesFileContent = undefined;
39
- commentStarts.length = 0;
40
- contexts.length = 0;
41
- lastTypeFound = null;
42
- ifdefSections.length = 0;
43
- }
44
- function resetExportNextClass() {
45
- dontExportNextClass = false;
46
- exportNextClass = false;
47
- }
48
- function tryGetKnownType(str) {
49
- if (typesFileContent === undefined) {
50
- typesFileContent = null;
51
- var filePath = path.dirname(__dirname) + "/src/types.json";
52
- if (fs.existsSync(filePath)) {
53
- if (allowDebugLogs)
54
- console.log("Reading types file");
55
- var content = fs.readFileSync(filePath, "utf8");
56
- typesFileContent = JSON.parse(content);
57
- }
58
- }
59
- if (typesFileContent) {
60
- var fullType = typesFileContent[str];
61
- if (fullType && allowDebugLogs)
62
- console.log(fullType);
63
- return fullType;
64
- }
65
- return null;
66
- }
67
- // https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API
68
- var ExportContext = /** @class */ (function () {
69
- function ExportContext(outputDir, fileName) {
70
- this.classEnd = -1;
71
- this.indentLevel = 0;
72
- this.emitMethodContextMenu = null;
73
- this.outputDir = outputDir;
74
- this.fileName = fileName;
75
- this.reset();
76
- }
77
- ExportContext.prototype.onBeforeMethod = function (name) {
78
- if (this.emitMethodContextMenu !== undefined) {
79
- var contextMenuText = this.emitMethodContextMenu === null ? name : this.emitMethodContextMenu;
80
- this.appendLine("[UnityEngine.ContextMenu(\"" + contextMenuText + "\")]");
81
- }
82
- };
83
- ExportContext.prototype.append = function (text) {
84
- for (var i = 0; i < this.indentLevel; i++)
85
- text = "\t" + text;
86
- this.textBuffer += text;
87
- this.emitMethodContextMenu = undefined;
88
- };
89
- ExportContext.prototype.appendLine = function (text) {
90
- this.append(text + "\n");
91
- };
92
- ExportContext.prototype.flush = function () {
93
- if (this.textBuffer.length <= 0)
94
- return;
95
- this.textBuffer = CODEGEN_MARKER_START + "\n" + this.textBuffer + "\n" + CODEGEN_MARKER_END;
96
- var code = this.textBuffer;
97
- if (this.outputDir !== null) {
98
- var dir = this.outputDir + "/";
99
- var path_1 = dir + this.fileName;
100
- this.replaceGeneratedCodeSection(path_1);
101
- if (allowDebugLogs)
102
- console.log("Write to " + path_1);
103
- fs.writeFileSync(path_1, code);
104
- }
105
- this.reset();
106
- return code;
107
- };
108
- ExportContext.prototype.reset = function () {
109
- this.textBuffer = "";
110
- this.classEnd = -1;
111
- };
112
- ExportContext.prototype.replaceGeneratedCodeSection = function (path) {
113
- if (fs.existsSync(path)) {
114
- var existing = fs.readFileSync(path, "utf8");
115
- var regex = new RegExp("(?<before>.*?)\/\/ ?NEEDLE_CODEGEN_START.+\/\/ ?NEEDLE_CODEGEN_END(?<after>.*)", "s");
116
- var matches = regex.exec(existing);
117
- if (matches === null || matches === void 0 ? void 0 : matches.groups) {
118
- if (allowDebugLogs)
119
- console.log("Found codegen sections");
120
- var before_1 = matches.groups.before;
121
- var after_1 = matches.groups.after;
122
- this.textBuffer = before_1 + this.textBuffer + after_1;
123
- }
124
- }
125
- };
126
- return ExportContext;
127
- }());
128
- function compile(code, fileName, outputDir, debugLogs) {
129
- if (debugLogs === void 0) { debugLogs = true; }
130
- resetAllState();
131
- allowDebugLogs = debugLogs;
132
- // Parse a file
133
- var sourceFile = ts.createSourceFile(fileName, code, ts.ScriptTarget.ES2015, true);
134
- var prog = ts.createProgram([fileName], {});
135
- // delint it
136
- return run(prog, outputDir, sourceFile);
137
- }
138
- exports.compile = compile;
139
- function run(program, outputDir, sourceFile) {
140
- if (outputDir !== null && !fs.existsSync(outputDir)) {
141
- console.error("Output directory does not exist: \"" + outputDir + "\"");
142
- return;
143
- }
144
- var results = [];
145
- traverseFile(sourceFile);
146
- function traverseFile(node) {
147
- visit(node);
148
- ts.forEachChild(node, traverseFile);
149
- }
150
- return results;
151
- function visit(node) {
152
- var _a, _b, _c, _d, _e, _f;
153
- var context = contexts.length > 0 ? contexts[contexts.length - 1] : null;
154
- if (context) {
155
- if ((context === null || context === void 0 ? void 0 : context.classEnd) > 0 && node.pos >= (context === null || context === void 0 ? void 0 : context.classEnd)) {
156
- while (context.indentLevel > 0) {
157
- context.indentLevel -= 1;
158
- context.append("}\n");
159
- }
160
- var code = context.flush();
161
- results.push(code);
162
- context = null;
163
- contexts.pop();
164
- }
165
- }
166
- if (allowDebugLogs)
167
- console.log("\t", ts.SyntaxKind[node.kind]);
168
- var commentRanges = ts.getLeadingCommentRanges(sourceFile.getFullText(), node.getFullStart());
169
- if (commentRanges === null || commentRanges === void 0 ? void 0 : commentRanges.length) {
170
- for (var _i = 0, commentRanges_1 = commentRanges; _i < commentRanges_1.length; _i++) {
171
- var r = commentRanges_1[_i];
172
- // avoid emitting comments multiple times
173
- if (commentStarts.includes(r.pos))
174
- continue;
175
- commentStarts.push(r.pos);
176
- var comment = node.getSourceFile().getFullText().slice(r.pos, r.end);
177
- if (context) {
178
- // https://regex101.com/r/ud4oev/1
179
- var emitContextMenu = comment.match("(\/{2,}|\/\*)\s*@contextmenu {0,}(?<text>[a-zA-Z 0-9]+)?");
180
- if (emitContextMenu) {
181
- context.emitMethodContextMenu = (_b = (_a = emitContextMenu.groups) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : null;
182
- }
183
- else if (comment.includes(serializeCommand))
184
- serializeField = true;
185
- else if (comment.includes(dontSerializeCommand))
186
- dontSerialize = true;
187
- }
188
- if (comment.includes(exportNextClassCommand))
189
- exportNextClass = true;
190
- if (comment.includes(dontExportNextClassCommand))
191
- dontExportNextClass = true;
192
- var typeMatch = typePattern.exec(comment);
193
- if (typeMatch && typeMatch.groups) {
194
- // for some reason our regex does also match surrounding ( ) even tho: https://regex101.com/r/PoWK6V/1
195
- // so we remove them
196
- var type = typeMatch.groups["type"];
197
- type = type.replace(/\(/, "").replace(/\)/, "");
198
- if (allowDebugLogs)
199
- console.log("Found type: ", type);
200
- lastTypeFound = type;
201
- }
202
- var ifdefMatch = ifdefPattern.exec(comment);
203
- if (ifdefMatch && ifdefMatch.groups) {
204
- var ifdef = ifdefMatch.groups["ifdef"];
205
- if (ifdef)
206
- ifdefSections.push(ifdef);
207
- }
208
- }
209
- }
210
- var skip = dontSerialize;
211
- switch (node.kind) {
212
- // Namespace
213
- // case ts.SyntaxKind.ModuleDeclaration:
214
- // const mod = node as ts.ModuleDeclaration;
215
- // console.log(ts.SyntaxKind[mod.getChildAt(1).kind])
216
- // const type = mod.getChildAt(1) as ts.Identifier;
217
- // console.log("MODULE", type.text)
218
- // break;
219
- // case ts.SyntaxKind.Identifier:
220
- // break;
221
- // case ts.SyntaxKind.ClassDeclaration:
222
- // case ts.SyntaxKind.SingleLineCommentTrivia:
223
- // console.log("comment: " + node.getText())
224
- // break;
225
- case ts.SyntaxKind.Decorator:
226
- break;
227
- case ts.SyntaxKind.MethodDeclaration:
228
- lastTypeFound = null;
229
- serializeField = false;
230
- dontSerialize = false;
231
- resetExportNextClass();
232
- if (!context)
233
- break;
234
- // TODO: always emit at least OnEnable method per class so generated components have toggle in editor
235
- var meth = node;
236
- // const isCoroutine = func.asteriskToken;
237
- if (!skip && meth.name) {
238
- var pub_1 = isPublic(meth);
239
- if (!pub_1)
240
- return;
241
- var paramsStr = "";
242
- for (var _g = 0, _h = meth.parameters; _g < _h.length; _g++) {
243
- var param = _h[_g];
244
- if (!param || !param.name)
245
- continue;
246
- if (paramsStr.length > 0)
247
- paramsStr += ", ";
248
- var type = tryResolveTypeRecursive(param);
249
- if (type === undefined)
250
- type = "object";
251
- paramsStr += type + " @" + param.name.getText();
252
- }
253
- var methodName = meth.name.getText();
254
- switch (methodName) {
255
- case "onEnable":
256
- methodName = "OnEnable";
257
- break;
258
- case "onDisable":
259
- methodName = "OnDisable";
260
- break;
261
- }
262
- context.onBeforeMethod(methodName);
263
- // let visibility = pub ? "public" : "private";
264
- context.append("public void " + methodName + "(" + paramsStr + "){}\n");
265
- }
266
- break;
267
- case ts.SyntaxKind.SetAccessor:
268
- case ts.SyntaxKind.PropertyDeclaration:
269
- resetExportNextClass();
270
- if (!context)
271
- break;
272
- if (allowDebugLogs)
273
- console.log("Found variable", node.getText());
274
- var vardec = node;
275
- var varName = "@" + vardec.name.getText();
276
- var pub = isPublic(vardec);
277
- var visibility = pub ? "public" : "private";
278
- var isAccessible = pub;
279
- dontSerialize = false;
280
- if (serializeField) {
281
- if (allowDebugLogs)
282
- console.log("[SerializeField]");
283
- context.appendLine("[UnityEngine.SerializeField]");
284
- isAccessible = true;
285
- }
286
- else if (skip)
287
- isAccessible = false;
288
- if (!isAccessible) {
289
- if (allowDebugLogs)
290
- console.log("Skip because not public or serializeable");
291
- break;
292
- }
293
- var name_1 = vardec.name.getText();
294
- if (allowDebugLogs)
295
- console.log("Variable:", name_1);
296
- if (name_1.startsWith("\"@") || name_1.startsWith("\"$") || name_1.startsWith("$"))
297
- break;
298
- var typeString = lastTypeFound !== null && lastTypeFound !== void 0 ? lastTypeFound : tryResolveTypeRecursive(node);
299
- var postFix = "";
300
- var typeName = (_c = vardec.type) === null || _c === void 0 ? void 0 : _c.getText();
301
- var shouldCommentTheLine = typeString === undefined;
302
- if (typeString === undefined) {
303
- postFix = " → Could not resolve C# type";
304
- }
305
- var assignment = "";
306
- if (typeString !== undefined) {
307
- for (var _j = 0, _k = node.getChildren(); _j < _k.length; _j++) {
308
- var ch = _k[_j];
309
- switch (ch.kind) {
310
- default:
311
- // console.log("Unknown assignment:", ts.SyntaxKind[ch.kind]);
312
- break;
313
- case ts.SyntaxKind.NewExpression:
314
- assignment = " = " + getTypeForAssignment(ch);
315
- break;
316
- case ts.SyntaxKind.FalseKeyword:
317
- case ts.SyntaxKind.TrueKeyword:
318
- assignment = " = " + ch.getText();
319
- break;
320
- case ts.SyntaxKind.StringLiteral:
321
- var str = ch;
322
- assignment = " = \"" + str.text + "\"";
323
- break;
324
- case ts.SyntaxKind.FirstLiteralToken:
325
- var lit = ch;
326
- assignment = " = " + lit.text;
327
- if (ts.isNumericLiteral(lit))
328
- assignment += "f";
329
- break;
330
- case ts.SyntaxKind.ArrayLiteralExpression:
331
- var arr = ch;
332
- assignment = " = new " + typeString;
333
- // if (arr.elements.length > 0) {
334
- assignment += "{" + arr.elements.map(function (e) { return " " + getTypeForAssignment(e); }) + " }";
335
- // }
336
- break;
337
- }
338
- }
339
- }
340
- var requireEndIf = false;
341
- if (ifdefSections.length > 0) {
342
- requireEndIf = true;
343
- context.appendLine("#ifdef " + ifdefSections.pop());
344
- }
345
- if (typeString === undefined)
346
- typeString = typeName;
347
- if (typeString === "[]") {
348
- if (allowDebugLogs)
349
- console.log("Unknown array type for \"" + varName + " " + typeName + "\" - your type is probably not known (did you just create it this session?) and you might need to regenerate the Typemap in Unity. Go to \"Needle Engine/Internal/Generate Type Map for component compiler");
350
- // typeString = "object[]";
351
- // assignment = " = new object[0]";
352
- shouldCommentTheLine = true;
353
- }
354
- if (allowDebugLogs)
355
- console.log("EMIT member: \"" + typeString + "\" " + varName, assignment, "Last type found:", lastTypeFound);
356
- var prefix = shouldCommentTheLine ? "// " : "";
357
- context.append(prefix + visibility + " " + typeString + " " + varName + assignment + ";" + postFix + "\n");
358
- lastTypeFound = null;
359
- if (requireEndIf) {
360
- context.appendLine("#endif");
361
- }
362
- break;
363
- case ts.SyntaxKind.ClassDeclaration:
364
- serializeField = false;
365
- var dec = node;
366
- // a class must inherit a component
367
- var inheritsComponent = testInheritsComponent(node);
368
- if (!dontExportNextClass && (lastTypeFound || exportNextClass || inheritsComponent)) {
369
- resetExportNextClass();
370
- var name_2 = (_d = dec.name) === null || _d === void 0 ? void 0 : _d.escapedText;
371
- if (allowDebugLogs)
372
- console.log("Found class: ", name_2);
373
- var namespace = (_e = tryParseNamespace(node)) !== null && _e !== void 0 ? _e : "Needle.Typescript.GeneratedComponents";
374
- if (allowDebugLogs)
375
- console.log("NAMESPACE", namespace);
376
- var newContext = new ExportContext(outputDir, name_2 + ".cs");
377
- newContext.appendLine("// auto generated code - do not edit directly");
378
- newContext.appendLine("");
379
- newContext.appendLine("#pragma warning disable");
380
- newContext.appendLine("");
381
- newContext.appendLine("namespace " + namespace);
382
- newContext.appendLine("{");
383
- newContext.indentLevel += 1;
384
- // newContext.appendLine("// source: " + path.resolve(sourceFile.fileName));
385
- var typeName_1 = "UnityEngine.MonoBehaviour";
386
- if (typeof inheritsComponent === "string")
387
- typeName_1 = inheritsComponent;
388
- if (lastTypeFound)
389
- typeName_1 = lastTypeFound;
390
- if (allowDebugLogs)
391
- console.log(name_2 + " inherits " + typeName_1);
392
- var modifiers = "";
393
- if (dec.modifiers) {
394
- for (var _l = 0, _m = dec.modifiers; _l < _m.length; _l++) {
395
- var mod = _m[_l];
396
- switch (mod.getText()) {
397
- case "abstract":
398
- modifiers += " abstract";
399
- if (allowDebugLogs)
400
- console.log(name_2 + " is abstract");
401
- break;
402
- }
403
- }
404
- }
405
- modifiers += " partial";
406
- newContext.appendLine("public " + modifiers.trim() + " class " + name_2 + " : " + typeName_1);
407
- newContext.appendLine("{");
408
- newContext.indentLevel += 1;
409
- newContext.classEnd = dec.end;
410
- contexts.push(newContext);
411
- }
412
- else {
413
- if (allowDebugLogs)
414
- console.log("Class type is unknown and will not generate a component: ", (_f = dec.name) === null || _f === void 0 ? void 0 : _f.escapedText);
415
- }
416
- lastTypeFound = null;
417
- break;
418
- }
419
- function testInheritsComponent(node) {
420
- switch (node.kind) {
421
- case ts.SyntaxKind.ClassDeclaration:
422
- var dec = node;
423
- if (dec.heritageClauses) {
424
- for (var _i = 0, _a = dec.heritageClauses; _i < _a.length; _i++) {
425
- var h = _a[_i];
426
- if (h.types.length <= 0)
427
- continue;
428
- for (var _b = 0, _c = h.types; _b < _c.length; _b++) {
429
- var type = _c[_b];
430
- // const symbol = program.getTypeChecker().getSymbolAtLocation(type.expression);
431
- // console.log(symbol);
432
- var text = type.expression.getText();
433
- if (text === "Component")
434
- return true;
435
- if (text === "Behaviour")
436
- return true;
437
- var known = tryGetKnownType(text);
438
- if (known)
439
- return known;
440
- }
441
- }
442
- }
443
- return false;
444
- }
445
- return false;
446
- }
447
- function getTypeForAssignment(node) {
448
- // console.log("-------------------\nAssign", ts.SyntaxKind[node.kind]);
449
- switch (node.kind) {
450
- case ts.SyntaxKind.FirstLiteralToken:
451
- return node.getText();
452
- case ts.SyntaxKind.NewExpression:
453
- var type = undefined;
454
- var args = undefined;
455
- for (var _i = 0, _a = node.getChildren(); _i < _a.length; _i++) {
456
- var ch = _a[_i];
457
- var text = ch.getText();
458
- // console.log("child", ts.SyntaxKind[ch.kind], text);
459
- switch (ch.kind) {
460
- case ts.SyntaxKind.Identifier:
461
- case ts.SyntaxKind.PropertyAccessExpression:
462
- type = tryGetTypeFromText(text);
463
- break;
464
- case ts.SyntaxKind.SyntaxList:
465
- for (var _b = 0, _c = ch.getChildren(); _b < _c.length; _b++) {
466
- var arg = _c[_b];
467
- if (args === undefined)
468
- args = "";
469
- var res = getTypeForAssignment(arg);
470
- // handle floats being assigned with "f" suffix
471
- if (Number.parseFloat(res) >= 0) {
472
- args += res + "f";
473
- }
474
- else {
475
- args += res;
476
- if (res === ",")
477
- args += " ";
478
- }
479
- }
480
- break;
481
- }
482
- }
483
- if (!args)
484
- args = "";
485
- if (type) {
486
- console.log(type, args);
487
- return "new " + type + "(" + args + ")";
488
- }
489
- // const expType = node.getChildren().find(c => c.kind === ts.SyntaxKind.Identifier);
490
- break;
491
- }
492
- var str = node.getText();
493
- if (allowDebugLogs)
494
- console.log("Unknown assignment:", str, ts.SyntaxKind[node.kind]);
495
- return str;
496
- }
497
- function isPublic(node) {
498
- if (node.kind === ts.SyntaxKind.PublicKeyword) {
499
- return true;
500
- }
501
- else if (node.kind === ts.SyntaxKind.PrivateKeyword || node.kind === ts.SyntaxKind.ProtectedKeyword) {
502
- return false;
503
- }
504
- for (var _i = 0, _a = node.getChildren(); _i < _a.length; _i++) {
505
- var ch = _a[_i];
506
- if (!isPublic(ch))
507
- return false;
508
- }
509
- return true;
510
- }
511
- function tryParseNamespace(node, namespace) {
512
- // console.log("TRAVERSE - " + ts.SyntaxKind[node.kind]);
513
- switch (node.kind) {
514
- case ts.SyntaxKind.ModuleDeclaration:
515
- for (var _i = 0, _a = node.getChildren(); _i < _a.length; _i++) {
516
- var ch = _a[_i];
517
- // console.log("-- TRAVERSE - " + ts.SyntaxKind[ch.kind]);
518
- switch (ch.kind) {
519
- case ts.SyntaxKind.Identifier:
520
- var id = ch;
521
- if (id.text) {
522
- if (!namespace)
523
- namespace = "";
524
- namespace = id.text + (namespace ? "." : "") + namespace;
525
- }
526
- break;
527
- }
528
- }
529
- break;
530
- }
531
- if (node.parent) {
532
- return tryParseNamespace(node.parent, namespace);
533
- }
534
- return namespace;
535
- }
536
- function tryGetTypeFromText(typeName) {
537
- // if a type is imported via some namespace e.g. THREE.AnimationClip
538
- // we want to remove that namespace / import name
539
- var separatorIndex = typeName.lastIndexOf(".");
540
- if (separatorIndex > 0) {
541
- var newName = typeName.substring(separatorIndex + 1);
542
- if (allowDebugLogs)
543
- console.log("Remove import name from type: \"" + typeName + "\" → \"" + newName + "\"");
544
- typeName = newName;
545
- }
546
- var res = dict[typeName];
547
- if (res === undefined) {
548
- switch (typeName) {
549
- case "Array":
550
- break;
551
- default:
552
- var knownType = tryGetKnownType(typeName);
553
- res = knownType !== null && knownType !== void 0 ? knownType : undefined;
554
- break;
555
- }
556
- }
557
- // console.log(typeName, res);
558
- return res;
559
- }
560
- function tryResolveTypeRecursive(node) {
561
- if (!node)
562
- return undefined;
563
- // skip decorators (e.g. @serializable() may break array generation)
564
- if (node.kind === ts.SyntaxKind.Decorator)
565
- return undefined;
566
- var typeName = node === null || node === void 0 ? void 0 : node.getText();
567
- var varDec = node;
568
- if (varDec.type) {
569
- typeName = varDec.type.getText();
570
- }
571
- var res = undefined;
572
- // console.log("Unknown type: " + typeName);
573
- switch (node.kind) {
574
- // case ts.SyntaxKind.SyntaxList:
575
- // const list = node as ts.SyntaxList;
576
- // for (const ch of list._children) {
577
- // res = tryResolveTypeRecursive(ch);
578
- // }
579
- // break;
580
- case ts.SyntaxKind.UnionType:
581
- var union = node;
582
- for (var _i = 0, _a = union.types; _i < _a.length; _i++) {
583
- var t = _a[_i];
584
- res = tryResolveTypeRecursive(t);
585
- if (res !== undefined)
586
- return res;
587
- }
588
- break;
589
- case ts.SyntaxKind.ArrayType:
590
- res = "[]";
591
- break;
592
- case ts.SyntaxKind.TypeReference:
593
- var typeRef = node;
594
- var typeName_2 = typeRef.typeName.getText();
595
- if (allowDebugLogs)
596
- console.log("TypeReference:", typeName_2);
597
- switch (typeName_2) {
598
- case "Array":
599
- break;
600
- default:
601
- return tryGetTypeFromText(typeName_2);
602
- }
603
- // return res;
604
- break;
605
- case ts.SyntaxKind.BooleanKeyword:
606
- case ts.SyntaxKind.NumberKeyword:
607
- case ts.SyntaxKind.StringKeyword:
608
- case ts.SyntaxKind.ObjectKeyword:
609
- var keyword = node.getText();
610
- // the basic keywords are declared in the static dictionary
611
- // no need for a complex lookup
612
- res = dict[keyword];
613
- break;
614
- case ts.SyntaxKind.Identifier:
615
- var id = node;
616
- switch (id.text) {
617
- // if we have an array we dont want to use the System.Array as a type but just make it to the array syntax
618
- case "Array":
619
- res = "[]";
620
- break;
621
- default:
622
- // console.log(id.text);
623
- // res = tryGetTypeFromText(id.text);
624
- break;
625
- }
626
- break;
627
- }
628
- var isInGenericDeclaration = false;
629
- for (var _b = 0, _c = node.getChildren(); _b < _c.length; _b++) {
630
- var child = _c[_b];
631
- // if (res !== undefined) break;
632
- // console.log("Child type: " + ts.SyntaxKind[child.kind]);
633
- var isGenericStart = false;
634
- var isAssignment = false;
635
- switch (child.kind) {
636
- case ts.SyntaxKind.FirstAssignment:
637
- isAssignment = true;
638
- break;
639
- case ts.SyntaxKind.FirstBinaryOperator:
640
- // console.log("Generic start: " + child.getText());
641
- isInGenericDeclaration = true;
642
- isGenericStart = true;
643
- break;
644
- case ts.SyntaxKind.GreaterThanGreaterThanToken:
645
- isInGenericDeclaration = false;
646
- // console.log("Generic end: " + child.getText());
647
- break;
648
- }
649
- // if (isAssignment) break;
650
- var childResult = tryResolveTypeRecursive(child);
651
- if (childResult !== undefined) {
652
- if (res === undefined)
653
- res = "";
654
- if (allowDebugLogs)
655
- console.log("Child: " + ts.SyntaxKind[child.kind] + " → " + childResult);
656
- // if the thing is a generic return as generic result
657
- if (isInGenericDeclaration && !res.includes("[]")) {
658
- res = "<" + childResult + ">";
659
- }
660
- // we got a generic result, these need to be appended
661
- else if (childResult.startsWith("<")) {
662
- res += childResult;
663
- }
664
- // concat default
665
- else
666
- res = childResult + res;
667
- }
668
- }
669
- // if (ts.isTypeReferenceNode(node)) {
670
- // const typeRef = node as ts.TypeReferenceNode;
671
- // const typeName = typeRef.typeName.getText();
672
- // switch (typeName) {
673
- // case "Array":
674
- // res += "[]";
675
- // return res;
676
- // }
677
- // }
678
- return res;
679
- }
680
- }
681
- }
682
- exports.run = run;
683
- if (process) {
684
- if (process.argv.length < 4) {
685
- console.error("Missing args, call with: <output_dir> <input_files>");
686
- }
687
- else {
688
- var outputDir_1 = process.argv[2];
689
- var fileNames = process.argv.slice(3);
690
- fileNames.forEach(function (fileName) {
691
- if (!fs.existsSync(fileName)) {
692
- }
693
- else {
694
- var code = (0, fs_1.readFileSync)(fileName).toString();
695
- compile(code, fileName, outputDir_1);
696
- }
697
- });
698
- }
699
- }