-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeGenerator.mts
680 lines (553 loc) · 20 KB
/
CodeGenerator.mts
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
/**
* @module source/CodeGenerator.mjs
*/
/** @typedef {string} identifier */
import CollectionConfiguration from "./CollectionConfiguration.mjs";
import CompileTimeOptions from "./CompileTimeOptions.mjs";
import CollectionType from "./generatorTools/CollectionType.mjs";
import ConfigurationData from "./generatorTools/ConfigurationData.mjs";
import JSDocGenerator from "./generatorTools/JSDocGenerator.mjs";
import TemplateGenerators from "./generatorTools/TemplateGenerators.mjs";
import {
GeneratorPromiseSet,
CodeGeneratorBase,
generatorToPromiseSet,
} from "./generatorTools/GeneratorPromiseSet.mjs";
import { SingletonPromise } from "./utilities/PromiseTypes.mjs";
import fs from "fs/promises";
import path from "path";
import PreprocessorDefines from "./generatorTools/PreprocessorDefines.mjs";
type InternalFlags = Set<string>;
class TypeScriptDefs {
typeConstraint: string;
extendsConstraint: string;
constructor(typeConstraint: string, extendsConstraint: string) {
this.typeConstraint = typeConstraint;
this.extendsConstraint = extendsConstraint;
}
}
/** @package */
export default class CodeGenerator extends CodeGeneratorBase
{
// #region static private fields
/**
* Stringify a list of keys into an argument name list suitable for macros.
*
* @param {string[]} keys The key names.
* @returns {string} The serialized key names.
*/
static buildArgNameList(keys: string[]) : string {
return '[' + keys.map(key => `"${key}"`).join(", ") + ']'
}
/** @constant */
static #generatorToInternalFlags: Map<CodeGenerator, InternalFlags> = new Map;
/** @type {Map<string, string>} @constant */
static #mapOfStrongSetsTemplates: Map<string, string> = new Map([
/*
key:
S: strong
W: weak
/: before a slash is Map, after is Set
n: more than one
1: one
So:
"1W/nS" = one weak map key, multiple strong set keys
*/
["1S/nS", "Strong/OneMapOfStrongSets"],
["nS/1S", "Strong/MapOfOneStrongSet"],
["1S/1S", "Strong/OneMapOfOneStrongSet"],
["1W/nS", "Weak/OneMapOfStrongSets"],
["nW/1S", "Weak/MapOfOneStrongSet"],
["1W/1S", "Weak/OneMapOfOneStrongSet"],
]);
// #endregion static private fields
// #region private properties
/** @type {object} @constant */
#configurationData: ConfigurationData;
/** @type {string} @constant */
#targetPath: string;
/** @type {CompileTimeOptions} @constant */
#compileOptions: CompileTimeOptions;
#runPromise: SingletonPromise<string>;
/** @type {string} */
#status = "not started yet";
/** @type {Map<string, *>} @constant */
#defines: PreprocessorDefines = new PreprocessorDefines();
/** @type {JSDocGenerator[]} */
#docGenerators: JSDocGenerator[] = [];
/** @type {string} */
#generatedCode = "";
/** @type {Set<string>?} @constant */
#internalFlagSet: InternalFlags | undefined;
/** @type {CodeGenerator | null} */
#oneToOneSubGenerator: CodeGenerator | null = null;
// #endregion private properties
// #region public members
/**
* @param {CollectionConfiguration} configuration The configuration to use.
* @param {string} targetPath The directory to write the collection to.
* @param {CompileTimeOptions} compileOptions Flags from an owner which may override configurations.
*/
constructor(
configuration: CollectionConfiguration,
targetPath: string,
compileOptions: CompileTimeOptions | object = {}
)
{
super();
this.#compileOptions = (compileOptions instanceof CompileTimeOptions) ? compileOptions : new CompileTimeOptions({});
if (!(configuration instanceof CollectionConfiguration)) {
throw new Error("Configuration isn't a CollectionConfiguration");
}
if (typeof targetPath !== "string")
throw new Error("Target path should be a path to a file!");
configuration.lock(); // this may throw, but if so, it's good that it does so.
this.#configurationData = ConfigurationData.cloneData(configuration) as ConfigurationData;
this.#targetPath = targetPath;
const gpSet = new GeneratorPromiseSet(this, path.dirname(targetPath));
generatorToPromiseSet.set(this, gpSet);
this.#runPromise = new SingletonPromise(async () => await this.#run());
Object.seal(this);
}
/** @type {string} */
get status() : string {
return this.#status;
}
/**
* @public
* @type {string}
*
* The generated code at this point. Used in #buildOneToOneBase() by a parent CodeGenerator.
*/
get generatedCode() : string {
return this.#generatedCode;
}
get requiresDefaultMap() : boolean {
return this.#generatedCode?.includes(" new DefaultMap(") ||
this.#generatedCode?.includes(" new DefaultWeakMap(");
}
get requiresKeyHasher() : boolean {
return this.#generatedCode?.includes(" new KeyHasher(");
}
get requiresWeakKeyComposer() : boolean {
return this.#generatedCode?.includes(" new WeakKeyComposer(");
}
async run(): Promise<string> {
return await this.#runPromise.run();
}
/**
* @returns {Promise<identifier>} The class name.
*/
async #run() : Promise<string> {
{
const flags: InternalFlags | undefined = CodeGenerator.#generatorToInternalFlags.get(this);
if (flags)
this.#internalFlagSet = flags;
}
const gpSet = generatorToPromiseSet.getRequired(this);
const hasInitialTasks = gpSet.has(this.#targetPath);
const bp = gpSet.get(this.#targetPath);
if (!hasInitialTasks) {
bp.addTask(async () => {
try {
return await this.#buildCollection();
}
catch (ex) {
this.#status = "aborted";
throw ex;
}
});
}
if (gpSet.owner !== this)
return "";
if (!gpSet.generatorsTarget.deepTargets.includes(this.#targetPath))
gpSet.generatorsTarget.addSubtarget(this.#targetPath);
await gpSet.runMain();
return this.#configurationData.className;
}
// #endregion public members
// #region private methods
/**
* Generate the code!
*
* @returns {identifier} The class name.
* @see https://www.youtube.com/watch?v=nUCoYcxNMBE s/love/code/g
*/
async #buildCollection() : Promise<void>
{
this.#status = "in progress";
if (this.#configurationData.collectionTemplate === "OneToOne/Map") {
const base = this.#configurationData.oneToOneBase as CollectionConfiguration;
const data = ConfigurationData.cloneData(base) as ConfigurationData;
if (data.className !== "WeakMap") {
await this.#buildOneToOneBase(base);
}
this.#buildOneToOneDefines(base);
await this.#buildOneToOneDocGenerators(base);
}
else {
this.#buildDefines();
this.#buildDocGenerator();
}
this.#buildTypeScriptDefines();
this.#generateSource();
const gpSet = generatorToPromiseSet.getRequired(this);
if (this.requiresDefaultMap)
gpSet.requireDefaultMap();
if (this.requiresKeyHasher)
gpSet.requireKeyHasher();
if (this.requiresWeakKeyComposer)
gpSet.requireWeakKeyComposer();
if (!this.#internalFlagSet?.has("prevent export"))
await this.#writeSource(gpSet);
this.#status = "completed";
}
#filePrologue() : string
{
let fileOverview = "";
if (!this.#internalFlagSet?.has("no @file") && this.#configurationData.fileOverview) {
fileOverview = this.#configurationData.fileOverview;
fileOverview = fileOverview.split("\n").map(line => " *" + (line.trim() ? " " + line : "")).join("\n");
}
let lines = [
this.#compileOptions.licenseText ? this.#compileOptions.licenseText + "\n\n" : "",
`/**
* @file
* This is generated code. Do not edit.
*
* Generator: https://github.com/ajvincent/composite-collection/
* Template: ${this.#configurationData.collectionTemplate}
`.trim(),
this.#compileOptions.license ? ` * @license ${this.#compileOptions.license}` : "",
this.#compileOptions.author ? ` * @author ${this.#compileOptions.author}` : "",
this.#compileOptions.copyright ? ` * @copyright ${this.#compileOptions.copyright}` : "",
fileOverview,
" */"
];
lines = lines.filter(Boolean);
lines = lines.map(line => line === " * " ? " *" : line);
const generatedCodeNotice = lines.join("\n");
const prologue = [
generatedCodeNotice.trim(),
];
return prologue.filter(Boolean).join("\n\n");
}
#buildDefines() : void
{
const data = this.#configurationData;
const defines = this.#defines;
defines.className = data.className;
const mapKeys = data.weakMapKeys.concat(data.strongMapKeys);
const setKeys = data.weakSetElements.concat(data.strongSetElements);
defines.importLines = data.importLines;
{
const keys = Array.from(data.parameterToTypeMap.keys());
defines.argList = keys.join(", ");
}
{
const mapArgs: string[] = [], setArgs: string[] = [];
for (const [key, typeMap] of data.parameterToTypeMap) {
(typeMap.mapOrSetType.endsWith("Map") ? mapArgs : setArgs).push(key);
}
defines.mapArgList = mapArgs.join(", ");
defines.setArgList = setArgs.join(", ");
}
const paramsData = Array.from(data.parameterToTypeMap.values());
if (/Solo|Weak\/?Map/.test(data.collectionTemplate)) {
defines.weakMapKeys = data.weakMapKeys.slice();
defines.strongMapKeys = data.strongMapKeys.slice();
}
if (/Solo|Weak\/?Set/.test(data.collectionTemplate)) {
defines.weakSetElements = data.weakSetElements.slice();
defines.strongSetElements = data.strongSetElements.slice();
}
defines.mapKeys = mapKeys;
defines.setKeys = setKeys;
if (this.#defineValidatorCode(paramsData, "validateArguments", () => true))
defines.invokeValidate = true;
this.#defineValidatorCode(paramsData, "validateMapArguments", pd => mapKeys.includes(pd.argumentName));
this.#defineValidatorCode(paramsData, "validateSetArguments", pd => setKeys.includes(pd.argumentName));
if (mapKeys.length) {
const collection = data.parameterToTypeMap.getRequired(mapKeys[0])
defines.mapArgument0Type = collection.jsDocType;
}
if (setKeys.length) {
const collection = data.parameterToTypeMap.getRequired(setKeys[0]);
defines.setArgument0Type = collection.jsDocType;
}
if (data.valueType) {
const filter = (data.valueType.argumentValidator || "").trim();
if (filter)
defines.validateValue = filter + "\n ";
}
}
#buildTypeScriptDefines() : void
{
const defines = this.#defines;
const data = this.#configurationData;
let baseData = data;
if (data.collectionTemplate === "OneToOne/Map") {
const base = data.oneToOneBase;
if (base)
baseData = ConfigurationData.cloneData(base) || data;
if (baseData === data)
throw new Error("How'd we get here?");
}
const typeDefs: Map<string, TypeScriptDefs> = new Map;
let mapCount = 0, setCount = 0;
baseData.parameterToTypeMap.forEach((typeMap, arg) => {
let def, typeArray, keyArray;
if (typeMap.mapOrSetType.endsWith("Map")) {
def = `__MK${mapCount++}__`;
typeArray = defines.tsMapTypes;
keyArray = defines.tsMapKeys;
}
else {
def = `__SK${setCount++}__`;
typeArray = defines.tsSetTypes;
keyArray = defines.tsSetKeys;
}
typeArray.push(def);
keyArray.push(`${arg}: ${def}`)
typeDefs.set(arg, new TypeScriptDefs(def, typeMap.tsType));
});
if (data.collectionTemplate === "OneToOne/Map") {
const oneToOneKeyDefs = typeDefs.get(data.oneToOneKeyName);
if (oneToOneKeyDefs) {
defines.tsOneToOneKeyType = oneToOneKeyDefs.typeConstraint;
typeDefs.delete(data.oneToOneKeyName);
}
typeDefs.set("value", new TypeScriptDefs(
"__V__",
data.valueType?.tsType || "object"
));
defines.tsValueKey = "value: __V__";
}
else if (data.collectionTemplate.endsWith("Map")) {
typeDefs.set("value", new TypeScriptDefs(
"__V__",
data.valueType?.tsType || "unknown"
));
defines.tsValueKey = "value: __V__";
}
defines.tsGenericFull = `<\n ${
Array.from(
typeDefs.values()
).map(
def => `${def.typeConstraint}${
def.extendsConstraint === "unknown" || def.typeConstraint === "any" ?
"" :
" extends " + def.extendsConstraint
}`
).join(",\n ")
}\n>`.trim();
}
#defineValidatorCode(
paramsData: CollectionType[],
defineName: "validateArguments" | "validateMapArguments" | "validateSetArguments",
filter: (value: CollectionType) => boolean
) : boolean
{
const validatorCode = paramsData.filter(filter).map(pd => {
return pd.argumentValidator || "";
}).filter(Boolean).join("\n\n").trim();
if (validatorCode) {
this.#defines[defineName] = validatorCode;
}
return Boolean(validatorCode);
}
#buildOneToOneDefines(
base: CollectionConfiguration | symbol
) : void
{
const data = this.#configurationData;
const baseData = ConfigurationData.cloneData(base) as ConfigurationData;
const defines = this.#defines;
defines.className = data.className;
defines.baseClassName = baseData.className;
defines.importLines = data.importLines;
const weakKeyName = data.oneToOneKeyName;
defines.weakKeyName = weakKeyName;
// bindOneToOne arguments
const keys = Array.from(baseData.parameterToTypeMap.keys());
defines.baseArgList = keys.slice();
keys.splice(keys.indexOf(weakKeyName), 1);
defines.bindArgList = keys;
const wrapBaseClass = baseData.weakMapKeys.length + baseData.strongMapKeys.length >= 2;
defines.wrapBaseClass = wrapBaseClass;
const parameters = Array.from(baseData.parameterToTypeMap.values());
defines.baseClassValidatesKey = parameters.some(param => param.argumentValidator);
defines.baseClassValidatesValue = Boolean(baseData.valueType?.argumentValidator);
}
#buildDocGenerator() : void
{
const generator = new JSDocGenerator(
this.#configurationData.className,
!this.#configurationData.collectionTemplate.endsWith("Map")
);
this.#configurationData.parameterToTypeMap.forEach(typeData => {
generator.addParameter(typeData);
});
if (this.#configurationData.valueType && !this.#configurationData.parameterToTypeMap.has("value")) {
generator.addParameter(this.#configurationData.valueType);
}
this.#docGenerators.push(generator);
}
async #buildOneToOneDocGenerators(
base: CollectionConfiguration | symbol
) : Promise<void>
{
const baseData = ConfigurationData.cloneData(base) as ConfigurationData;
// For the solo doc generator, the value argument comes first.
let generator = await this.#createOneToOneGenerator("oneToOneSoloArg");
generator.addParameter(
baseData.valueType ||
new CollectionType("value", "Map", "object", "object", "The value.", "")
);
this.#appendTypesToDocGenerator(base, generator, "", false);
// For the duo doc generator, there are two of each argument, and two values.
generator = await this.#createOneToOneGenerator("oneToOneDuoArg");
this.#appendTypesToDocGenerator(base, generator, "_1", true);
this.#appendTypesToDocGenerator(base, generator, "_2", true);
}
async #createOneToOneGenerator(moduleName: string) : Promise<JSDocGenerator>
{
const generator = new JSDocGenerator(
this.#configurationData.className,
false
);
await generator.setMethodParametersByModule(moduleName);
this.#docGenerators.push(generator);
return generator;
}
#appendTypesToDocGenerator(
base: CollectionConfiguration | symbol,
generator: JSDocGenerator,
typeSuffix: string,
addValue: boolean
) : void
{
const baseData = ConfigurationData.cloneData(base) as ConfigurationData;
baseData.parameterToTypeMap.delete(this.#configurationData.oneToOneKeyName);
baseData.parameterToTypeMap.forEach(typeData => {
generator.addParameter(new CollectionType(
typeData.argumentName + typeSuffix,
typeData.mapOrSetType,
typeData.jsDocType,
typeData.tsType,
typeData.description,
typeData.argumentValidator
));
});
if (addValue) {
const {
mapOrSetType = "Map",
jsDocType = baseData.valueType?.jsDocType || "object",
tsType = baseData.valueType?.tsType || "object",
description = "The value.",
argumentValidator = ""
} = baseData.valueType || {};
let {
argumentName = "value",
} = baseData.valueType || {};
argumentName += typeSuffix;
generator.addParameter(new CollectionType(
argumentName,
mapOrSetType,
jsDocType,
tsType,
description,
argumentValidator
));
}
}
#generateSource() : void
{
this.#configurationData.collectionTemplate = this.#chooseCollectionTemplate();
const generator = TemplateGenerators.getRequired(this.#configurationData.collectionTemplate);
let codeSegments = [
this.#generatedCode,
generator(this.#defines, ...this.#docGenerators),
];
if (!this.#internalFlagSet?.has("prevent export")) {
codeSegments = [
this.#filePrologue(),
...codeSegments,
`export default ${this.#configurationData.className};`
];
}
this.#generatedCode = codeSegments.flat(Infinity).filter(Boolean).join("\n\n") + "\n";
this.#generatedCode = this.#generatedCode.replace(/\n{3,}/g, "\n\n");
}
#chooseCollectionTemplate() : string
{
const startTemplate = this.#configurationData.collectionTemplate;
const weakMapCount = this.#configurationData.weakMapKeys?.length || 0,
strongMapCount = this.#configurationData.strongMapKeys?.length || 0,
weakSetCount = this.#configurationData.weakSetElements?.length || 0,
strongSetCount = this.#configurationData.strongSetElements?.length || 0;
const mapCount = weakMapCount + strongMapCount,
setCount = weakSetCount + strongSetCount;
if (mapCount && setCount && !this.#compileOptions.disableKeyOptimization) {
// Map of Sets, maybe optimized
const shortKey = [
mapCount > 1 ? "n" : "1",
weakMapCount ? "W" : "S",
"/",
setCount > 1 ? "n" : "1",
weakSetCount ? "W" : "S"
].join("");
// console.log(`\n\n${shortKey} ${Array.from(this.#defines.keys()).join(", ")}\n\n`);
return CodeGenerator.#mapOfStrongSetsTemplates.get(shortKey) || startTemplate;
}
return startTemplate;
}
/**
* @param {GeneratorPromiseSet} gpSet The current promise set.
* @returns {Promise<void>}
*/
async #writeSource(gpSet: GeneratorPromiseSet) : Promise<void>
{
const targetPath = this.#targetPath.replace(/\.mjs$/, ".mts");
gpSet.scheduleTSC(targetPath);
await fs.writeFile(
targetPath,
this.#generatedCode,
{ encoding: "utf-8" }
);
}
async #buildOneToOneBase(
base: CollectionConfiguration | symbol
) : Promise<void>
{
const baseData = ConfigurationData.cloneData(base) as ConfigurationData;
if (baseData.className === "WeakMap")
return;
if (typeof base === "symbol")
throw new Error("assertion: unreachable");
if (this.#configurationData.oneToOneOptions?.pathToBaseModule) {
this.#generatedCode += `import ${baseData.className} from "${
this.#configurationData.oneToOneOptions.pathToBaseModule
}"\n\n`;
this.#generatedCode += baseData.importLines;
this.#generatedCode += "\n";
return;
}
const internalFlags: InternalFlags = new Set([
"prevent export",
"configuration ok",
"no @file",
]);
this.#oneToOneSubGenerator = new CodeGenerator(
base,
this.#targetPath,
{ ...this.#compileOptions }
);
CodeGenerator.#generatorToInternalFlags.set(this.#oneToOneSubGenerator, internalFlags);
await this.#oneToOneSubGenerator.run();
this.#generatedCode += this.#oneToOneSubGenerator.generatedCode + "\n";
}
// #endregion private methods
}
Object.freeze(CodeGenerator);
Object.freeze(CodeGenerator.prototype);