-
Notifications
You must be signed in to change notification settings - Fork 242
/
assembler.ts
1638 lines (1417 loc) · 61.3 KB
/
assembler.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
import * as colors from 'colors/safe';
import * as crypto from 'crypto';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import deepEqual = require('deep-equal');
import * as fs from 'fs-extra';
import * as spec from '@jsii/spec';
import * as log4js from 'log4js';
import * as path from 'path';
import * as ts from 'typescript';
import { JSII_DIAGNOSTICS_CODE } from './compiler';
import { getReferencedDocParams, parseSymbolDocumentation } from './docs';
import { Diagnostic, EmitResult, Emitter } from './emitter';
import * as literate from './literate';
import { ProjectInfo } from './project-info';
import { isReservedName } from './reserved-words';
import { Validator } from './validator';
import { SHORT_VERSION, VERSION } from './version';
import { enabledWarnings } from './warnings';
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
const sortJson = require('sort-json');
const LOG = log4js.getLogger('jsii/assembler');
/**
* The JSII Assembler consumes a ``ts.Program`` instance and emits a JSII assembly.
*/
export class Assembler implements Emitter {
private _diagnostics = new Array<Diagnostic>();
private _deferred = new Array<DeferredRecord>();
private _types: { [fqn: string]: spec.Type } = {};
/**
* @param projectInfo information about the package being assembled
* @param program the TypeScript program to be assembled from
* @param stdlib the directory where the TypeScript stdlib is rooted
*/
public constructor(
public readonly projectInfo: ProjectInfo,
public readonly program: ts.Program,
public readonly stdlib: string) { }
private get _typeChecker(): ts.TypeChecker {
return this.program.getTypeChecker();
}
/**
* Attempt emitting the JSII assembly for the program.
*
* @return the result of the assembly emission.
*/
public async emit(): Promise<EmitResult> {
this._diagnostics = [];
if (!this.projectInfo.description) {
this._diagnostic(null,
ts.DiagnosticCategory.Suggestion,
'A "description" field should be specified in "package.json"');
}
if (!this.projectInfo.homepage) {
this._diagnostic(null,
ts.DiagnosticCategory.Suggestion,
'A "homepage" field should be specified in "package.json"');
}
const readme = await _loadReadme.call(this);
if (readme == null) {
this._diagnostic(null,
ts.DiagnosticCategory.Suggestion,
'There is no "README.md" file. It is recommended to have one.');
}
const docs = _loadDocs.call(this);
this._types = {};
this._deferred = [];
const mainFile = path.resolve(this.projectInfo.projectRoot, this.projectInfo.types.replace(/\.d\.ts(x?)$/, '.ts$1'));
const visitPromises = new Array<Promise<any>>();
for (const sourceFile of this.program.getSourceFiles().filter(f => !f.isDeclarationFile)) {
if (sourceFile.fileName !== mainFile) { continue; }
if (LOG.isTraceEnabled()) {
LOG.trace(`Processing source file: ${colors.blue(path.relative(this.projectInfo.projectRoot, sourceFile.fileName))}`);
}
const symbol = this._typeChecker.getSymbolAtLocation(sourceFile);
if (!symbol) { continue; }
for (const node of this._typeChecker.getExportsOfModule(symbol)) {
visitPromises.push(this._visitNode(node.declarations[0], new EmitContext([], this.projectInfo.stability)));
}
}
await Promise.all(visitPromises);
this.callDeferredsInOrder();
// Skip emitting if any diagnostic message is an error
if (this._diagnostics.find(diag => diag.category === ts.DiagnosticCategory.Error) != null) {
LOG.debug('Skipping emit due to errors.');
// Clearing ``this._types`` to allow contents to be garbage-collected.
delete this._types;
try {
return { diagnostics: this._diagnostics, emitSkipped: true };
} finally {
// Clearing ``this._diagnostics`` to allow contents to be garbage-collected.
delete this._diagnostics;
}
}
const jsiiVersion = this.projectInfo.jsiiVersionFormat === 'short' ? SHORT_VERSION : VERSION;
const assembly: spec.Assembly = {
schema: spec.SchemaVersion.LATEST,
name: this.projectInfo.name,
version: this.projectInfo.version,
description: this.projectInfo.description || this.projectInfo.name,
license: this.projectInfo.license,
keywords: this.projectInfo.keywords,
homepage: this.projectInfo.homepage || this.projectInfo.repository.url,
author: this.projectInfo.author,
contributors: this.projectInfo.contributors && [...this.projectInfo.contributors],
repository: this.projectInfo.repository,
dependencies: noEmptyDict({ ...this.projectInfo.dependencies, ...this.projectInfo.peerDependencies }),
dependencyClosure: noEmptyDict(toDependencyClosure(this.projectInfo.dependencyClosure)),
bundled: this.projectInfo.bundleDependencies,
types: this._types,
targets: this.projectInfo.targets,
metadata: this.projectInfo.metadata,
docs,
readme,
jsiiVersion,
fingerprint: '<TBD>',
};
const validator = new Validator(this.projectInfo, assembly);
const validationResult = await validator.emit();
if (!validationResult.emitSkipped) {
const assemblyPath = path.join(this.projectInfo.projectRoot, '.jsii');
LOG.trace(`Emitting assembly: ${colors.blue(assemblyPath)}`);
await fs.writeJson(assemblyPath, _fingerprint(assembly), { encoding: 'utf8', spaces: 2 });
}
try {
return {
diagnostics: [...this._diagnostics, ...validationResult.diagnostics],
emitSkipped: validationResult.emitSkipped
};
} finally {
// Clearing ``this._types`` to allow contents to be garbage-collected.
delete this._types;
// Clearing ``this._diagnostics`` to allow contents to be garbage-collected.
delete this._diagnostics;
}
async function _loadReadme(this: Assembler) {
const readmePath = path.join(this.projectInfo.projectRoot, 'README.md');
if (!await fs.pathExists(readmePath)) { return undefined; }
const renderedLines = await literate.includeAndRenderExamples(
await literate.loadFromFile(readmePath),
literate.fileSystemLoader(this.projectInfo.projectRoot)
);
return { markdown: renderedLines.join('\n') };
}
function _loadDocs(this: Assembler): spec.Docs | undefined {
if (!this.projectInfo.stability && !this.projectInfo.deprecated) {
return undefined;
}
const deprecated = this.projectInfo.deprecated;
const stability = this.projectInfo.stability;
return { deprecated, stability };
}
}
/**
* Defer a callback until a (set of) types are available
*
* This is a helper function around _defer() which encapsulates the _dereference
* action (which is basically the majority use case for _defer anyway).
*
* Will not invoke the function with any 'undefined's; an error will already have been emitted in
* that case anyway.
*
* @param fqn FQN of the current type (the type that has a dependency on baseTypes)
* @param baseTypes Array of type references to be looked up
* @param referencingNode Node to report a diagnostic on if we fail to look up a t ype
* @param cb Callback to be invoked with the Types corresponding to the TypeReferences in baseTypes
*/
private _deferUntilTypesAvailable(
fqn: string, baseTypes: Array<string | spec.NamedTypeReference>,
referencingNode: ts.Node, cb: (...xs: spec.Type[]) => void
) {
// We can do this one eagerly
if (baseTypes.length === 0) {
cb();
return;
}
const baseFqns = baseTypes.map(bt => typeof bt === 'string' ? bt : bt.fqn);
this._defer(fqn, baseFqns, () => {
const resolved = baseFqns.map(x => this._dereference(x, referencingNode)).filter(x => x !== undefined);
if (resolved.length > 0) {
cb(...resolved as spec.Type[]);
}
});
}
/**
* Defer checks for after the program has been entirely processed; useful for verifying type references that may not
* have been discovered yet, and verifying properties about them.
*
* The callback is guaranteed to be executed only after all deferreds for all types in 'dependedFqns' have
* been executed.
*
* @param fqn FQN of the current type.
* @param dependedFqns List of FQNs of types this callback depends on. All deferreds for all
* @param cb the function to be called in a deferred way. It will be bound with ``this``, so it can depend on using
* ``this``.
*/
private _defer(fqn: string, dependedFqns: string[], cb: () => void) {
this._deferred.push({ fqn, dependedFqns, cb: cb.bind(this) });
}
/**
* Obtains the ``spec.Type`` for a given ``spec.NamedTypeReference``.
*
* @param ref the type reference to be de-referenced
*
* @returns the de-referenced type, if it was found, otherwise ``undefined``.
*/
private _dereference(ref: string | spec.NamedTypeReference, referencingNode: ts.Node | null): spec.Type | undefined {
if (typeof ref !== 'string') {
ref = ref.fqn;
}
const [assm,] = ref.split('.');
let type;
if (assm === this.projectInfo.name) {
type = this._types[ref];
} else {
const assembly = this.projectInfo.dependencyClosure.find(dep => dep.name === assm);
type = assembly?.types?.[ref];
// since we are exposing a type of this assembly in this module's public API,
// we expect it to appear as a peer dependency instead of a normal dependency.
if (assembly) {
if (!(assembly.name in this.projectInfo.peerDependencies)) {
this._diagnostic(referencingNode, ts.DiagnosticCategory.Warning,
`The type '${ref}' is exposed in the public API of this module. ` +
`Therefore, the module '${assembly.name}' must also be defined under "peerDependencies". ` +
'This will be auto-corrected unless --no-fix-peer-dependencies was specified.');
}
}
}
if (!type) {
this._diagnostic(referencingNode, ts.DiagnosticCategory.Error,
`Unable to resolve referenced type '${ref}'. Type may be @internal or unexported`);
}
return type;
}
private _diagnostic(node: ts.Node | null, category: ts.DiagnosticCategory, messageText: string) {
this._diagnostics.push({
domain: 'JSII',
category,
code: JSII_DIAGNOSTICS_CODE,
messageText: `JSII: ${messageText}`,
file: node != null ? node.getSourceFile() : undefined,
start: node != null ? node.getStart() : undefined,
length: node != null ? node.getEnd() - node.getStart() : undefined,
});
}
/**
* Compute the JSII fully qualified name corresponding to a ``ts.Type`` instance. If for any reason a name cannot be
* computed for the type, a marker is returned instead, and an ``ts.DiagnosticCategory.Error`` diagnostic is
* inserted in the assembler context.
*
* @param type the type for which a JSII fully qualified name is neede.
*
* @returns the FQN of the type, or some "unknown" marker.
*/
private async _getFQN(type: ts.Type): Promise<string> {
const tsName = this._typeChecker.getFullyQualifiedName(type.symbol);
const groups = /^"([^"]+)"\.(.*)$/.exec(tsName);
let node = type.symbol.valueDeclaration;
if (!node && type.symbol.declarations.length > 0) { node = type.symbol.declarations[0]; }
if (!groups) {
this._diagnostic(node, ts.DiagnosticCategory.Error, `Cannot use private type ${tsName} in exported declarations`);
return tsName;
}
const [, modulePath, typeName,] = groups;
const pkg = await _findPackageInfo(modulePath);
if (!pkg) {
this._diagnostic(node, ts.DiagnosticCategory.Error, `Could not find module for ${modulePath}`);
return `unknown.${typeName}`;
}
const fqn = `${pkg.name}.${typeName}`;
if (pkg.name !== this.projectInfo.name && !this._dereference({ fqn }, type.symbol.valueDeclaration)) {
this._diagnostic(node,
ts.DiagnosticCategory.Error,
`Use of foreign type not present in the ${pkg.name}'s assembly: ${fqn}`);
}
return fqn;
async function _findPackageInfo(fromDir: string): Promise<any> {
const filePath = path.join(fromDir, 'package.json');
if (await fs.pathExists(filePath)) {
return fs.readJson(filePath);
}
const parent = path.dirname(fromDir);
if (parent === fromDir) { return undefined; }
return _findPackageInfo(parent);
}
}
/**
* Register exported types in ``this.types``.
*
* @param node a node found in a module
* @param namePrefix the prefix for the types' namespaces
*/
private async _visitNode(node: ts.Declaration, context: EmitContext): Promise<spec.Type[]> {
if ((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) === 0) { return []; }
let jsiiType: spec.Type | undefined;
if (ts.isClassDeclaration(node) && _isExported(node)) {
jsiiType = await this._visitClass(this._typeChecker.getTypeAtLocation(node), context);
} else if (ts.isInterfaceDeclaration(node) && _isExported(node)) {
jsiiType = await this._visitInterface(this._typeChecker.getTypeAtLocation(node), context);
} else if (ts.isEnumDeclaration(node) && _isExported(node)) {
jsiiType = await this._visitEnum(this._typeChecker.getTypeAtLocation(node), context);
} else if (ts.isModuleDeclaration(node)) {
const name = node.name.getText();
const symbol = (node as any).symbol;
if (LOG.isTraceEnabled()) { LOG.trace(`Entering namespace: ${colors.cyan([...context.namespace, name].join('.'))}`); }
const allTypesPromises = new Array<Promise<spec.Type[]>>();
for (const prop of this._typeChecker.getExportsOfModule(symbol)) {
allTypesPromises.push(this._visitNode(prop.declarations[0], context.appendNamespace(node.name.getText())));
}
const allTypes = await flattenPromises(allTypesPromises);
if (LOG.isTraceEnabled()) { LOG.trace(`Leaving namespace: ${colors.cyan([...context.namespace, name].join('.'))}`); }
return allTypes;
} else {
this._diagnostic(node, ts.DiagnosticCategory.Message, `Skipping ${ts.SyntaxKind[node.kind]} node`);
}
if (!jsiiType) { return []; }
if (LOG.isInfoEnabled()) {
LOG.info(`Registering JSII ${colors.magenta(jsiiType.kind)}: ${colors.green(jsiiType.fqn)}`);
}
this._types[jsiiType.fqn] = jsiiType;
jsiiType.locationInModule = this.declarationLocation(node);
const type = this._typeChecker.getTypeAtLocation(node);
if (type.symbol.exports) {
const nestedContext = context.appendNamespace(type.symbol.name);
const visitedNodes = this._typeChecker.getExportsOfModule(type.symbol).filter(s => s.declarations)
.map(exportedNode => this._visitNode(exportedNode.declarations[0], nestedContext));
for (const nestedTypes of await Promise.all(visitedNodes)) {
for (const nestedType of nestedTypes) {
if (nestedType.namespace !== nestedContext.namespace.join('.')) {
this._diagnostic(node,
ts.DiagnosticCategory.Error,
`All child names of a type '${jsiiType.fqn}' must point to concrete types, but '${nestedType.namespace}' is a namespaces, and this structure cannot be supported in all languages (e.g. Java)`);
}
}
}
}
return [jsiiType];
}
private declarationLocation(node: ts.Declaration): spec.SourceLocation {
const file = node.getSourceFile();
const line = ts.getLineAndCharacterOfPosition(file, node.getStart()).line;
return {
filename: path.relative(this.projectInfo.projectRoot, file.fileName),
line: line + 1,
};
}
private async _processBaseInterfaces(fqn: string, baseTypes?: ts.Type[]) {
const erasedBases = new Array<ts.Type>();
if (!baseTypes) {
return { erasedBases };
}
const result = new Array<spec.NamedTypeReference>();
const baseInterfaces = new Set<ts.Type>();
const processBaseTypes = (types: ts.Type[]) => {
for (const iface of types) {
// base is private/internal, so we continue recursively with it's own bases
if (this._isPrivateOrInternal(iface.symbol)) {
erasedBases.push(iface);
const bases = iface.getBaseTypes();
if (bases) {
processBaseTypes(bases);
}
continue;
}
baseInterfaces.add(iface);
}
};
processBaseTypes(baseTypes);
const typeRefs = Array.from(baseInterfaces).map(async iface => {
const decl = iface.symbol.valueDeclaration;
const typeRef = await this._typeReference(iface, decl);
return { decl, typeRef };
});
for (const { decl, typeRef } of await Promise.all(typeRefs)) {
if (!spec.isNamedTypeReference(typeRef)) {
this._diagnostic(decl,
ts.DiagnosticCategory.Error,
`Interface of ${fqn} is not a named type (${spec.describeTypeReference(typeRef)})`);
continue;
}
this._deferUntilTypesAvailable(fqn, [typeRef], decl, (deref) => {
if (!spec.isInterfaceType(deref)) {
this._diagnostic(decl,
ts.DiagnosticCategory.Error,
`Inheritance clause of ${fqn} uses ${spec.describeTypeReference(typeRef)} as an interface`);
}
});
result.push(typeRef);
}
return { interfaces: result.length === 0 ? undefined : result, erasedBases };
}
private async _visitClass(type: ts.Type, ctx: EmitContext): Promise<spec.ClassType | undefined> {
if (LOG.isTraceEnabled()) {
LOG.trace(`Processing class: ${colors.gray(ctx.namespace.join('.'))}.${colors.cyan(type.symbol.name)}`);
}
if (_hasInternalJsDocTag(type.symbol)) {
return undefined;
}
this._warnAboutReservedWords(type.symbol);
const fqn = `${[this.projectInfo.name, ...ctx.namespace].join('.')}.${type.symbol.name}`;
const jsiiType: spec.ClassType = {
assembly: this.projectInfo.name,
fqn,
kind: spec.TypeKind.Class,
name: type.symbol.name,
namespace: ctx.namespace.length > 0 ? ctx.namespace.join('.') : undefined,
docs: this._visitDocumentation(type.symbol, ctx),
};
if (_isAbstract(type.symbol, jsiiType)) {
jsiiType.abstract = true;
}
const erasedBases = new Array<ts.BaseType>();
for (let base of type.getBaseTypes() ?? []) {
if (jsiiType.base) {
this._diagnostic(base.symbol.valueDeclaration, ts.DiagnosticCategory.Error, `Found multiple base types for ${jsiiType.fqn}`);
continue;
}
//
// base classes ("extends foo")
// Crawl up the inheritance tree if the current base type is not exported, so we identify the type(s) to be
// erased, and identify the closest exported base class, should there be one.
while (base && this._isPrivateOrInternal(base.symbol)) {
LOG.debug(`Base class of ${colors.green(jsiiType.fqn)} named ${colors.green(base.symbol.name)} is not exported, erasing it...`);
erasedBases.push(base);
base = (base.getBaseTypes() ?? [])[0];
}
if (!base) {
// There is no exported base class to be found, pretend this class has no base class.
continue;
}
// eslint-disable-next-line no-await-in-loop
const ref = await this._typeReference(base, type.symbol.valueDeclaration);
if (!spec.isNamedTypeReference(ref)) {
this._diagnostic(base.symbol.valueDeclaration,
ts.DiagnosticCategory.Error,
`Base type of ${jsiiType.fqn} is not a named type (${spec.describeTypeReference(ref)})`);
continue;
}
this._deferUntilTypesAvailable(fqn, [ref], base.symbol.valueDeclaration, (deref) => {
if (!spec.isClassType(deref)) {
this._diagnostic(base.symbol.valueDeclaration,
ts.DiagnosticCategory.Error,
`Base type of ${jsiiType.fqn} is not a class (${spec.describeTypeReference(ref)})`);
}
});
jsiiType.base = ref.fqn;
}
//
// base interfaces ("implements foo")
// collect all "implements" declarations from the current type and all
// erased base types (because otherwise we lose them, see jsii#487)
const implementsClauses = new Array<ts.HeritageClause>();
for (const heritage of [type, ...erasedBases].map(t => (t.symbol.valueDeclaration as ts.ClassDeclaration).heritageClauses ?? [])) {
for (const clause of heritage) {
if (clause.token === ts.SyntaxKind.ExtendsKeyword) {
// Handled by `getBaseTypes`
continue;
} else if (clause.token !== ts.SyntaxKind.ImplementsKeyword) {
this._diagnostic(clause, ts.DiagnosticCategory.Error, `Ignoring ${ts.SyntaxKind[clause.token]} heritage clause`);
continue;
}
implementsClauses.push(clause);
}
}
// process all "implements" clauses
const allInterfaces = new Set<string>();
const baseInterfaces = implementsClauses.map(clause => this._processBaseInterfaces(fqn, clause.types.map(t => this._getTypeFromTypeNode(t))));
for (const { interfaces } of await Promise.all(baseInterfaces)) {
for (const ifc of interfaces ?? []) {
allInterfaces.add(ifc.fqn);
}
if (interfaces) {
this._deferUntilTypesAvailable(jsiiType.fqn, interfaces, type.symbol.valueDeclaration, (...ifaces) => {
for (const iface of ifaces) {
if (spec.isInterfaceType(iface) && iface.datatype) {
this._diagnostic(type.symbol.valueDeclaration,
ts.DiagnosticCategory.Error,
`Attempted to implement struct ${iface.fqn} from class ${jsiiType.fqn}`);
}
}
});
}
}
if (allInterfaces.size > 0) {
jsiiType.interfaces = Array.from(allInterfaces);
}
if (!type.isClass()) {
throw new Error('Oh no');
}
const allDeclarations: Array<{ decl: ts.Declaration, type: ts.InterfaceType | ts.BaseType }>
= type.symbol.declarations.map(decl => ({ decl, type }));
// Considering erased bases' declarations, too, so they are "blended in"
for (const base of erasedBases) {
allDeclarations.push(...base.symbol.declarations.map(decl => ({ decl, type: base })));
}
for (const { decl, type: declaringType } of allDeclarations) {
const classDecl = decl as ts.ClassDeclaration | ts.InterfaceDeclaration;
if (!classDecl.members) { continue; }
for (const memberDecl of classDecl.members) {
const member: ts.Symbol = (memberDecl as any).symbol;
if (!(declaringType.symbol.getDeclarations() ?? []).find(d => d === memberDecl.parent)) {
continue;
}
if (this._isPrivateOrInternal(member, memberDecl)) {
continue;
}
// constructors are handled later
if (ts.isConstructorDeclaration(memberDecl)) {
continue;
}
// eslint-disable-next-line no-await-in-loop
if (ts.isMethodDeclaration(memberDecl) || ts.isMethodSignature(memberDecl)) {
await this._visitMethod(member, jsiiType, ctx.replaceStability(jsiiType.docs?.stability));
} else if (ts.isPropertyDeclaration(memberDecl)
|| ts.isPropertySignature(memberDecl)
|| ts.isAccessor(memberDecl)) {
await this._visitProperty(member, jsiiType, ctx.replaceStability(jsiiType.docs?.stability));
} else {
this._diagnostic(memberDecl,
ts.DiagnosticCategory.Warning,
`Ignoring un-handled ${ts.SyntaxKind[memberDecl.kind]} member`);
}
/* eslint-enable no-await-in-loop */
}
}
const memberEmitContext = ctx.replaceStability(jsiiType.docs && jsiiType.docs.stability);
// Find the first defined constructor in this class, or it's erased bases
const constructor = [type, ...erasedBases].map(getConstructor).find(ctor => ctor != null);
const ctorDeclaration = constructor && (constructor.declarations[0] as ts.ConstructorDeclaration);
if (constructor && ctorDeclaration) {
const signature = this._typeChecker.getSignatureFromDeclaration(ctorDeclaration);
if ((ts.getCombinedModifierFlags(ctorDeclaration) & ts.ModifierFlags.Private) === 0) {
jsiiType.initializer = {};
if (signature) {
for (const param of signature.getParameters()) {
jsiiType.initializer.parameters = jsiiType.initializer.parameters ?? [];
// eslint-disable-next-line no-await-in-loop
jsiiType.initializer.parameters.push(await this._toParameter(param, ctx.replaceStability(jsiiType.docs?.stability)));
jsiiType.initializer.variadic = jsiiType.initializer?.parameters?.some(p => !!p.variadic) || undefined;
jsiiType.initializer.protected = (ts.getCombinedModifierFlags(ctorDeclaration) & ts.ModifierFlags.Protected) !== 0
|| undefined;
}
}
this._verifyConsecutiveOptionals(ctorDeclaration, jsiiType.initializer.parameters);
jsiiType.initializer.docs = this._visitDocumentation(constructor, memberEmitContext);
}
// Process constructor-based property declarations even if constructor is private
if (signature) {
for (const param of signature.getParameters()) {
if (ts.isParameterPropertyDeclaration(param.valueDeclaration, param.valueDeclaration.parent) && !this._isPrivateOrInternal(param)) {
// eslint-disable-next-line no-await-in-loop
await this._visitProperty(param, jsiiType, memberEmitContext);
}
}
}
} else if (jsiiType.base) {
this._deferUntilTypesAvailable(fqn, [jsiiType.base], type.symbol.valueDeclaration, (baseType) => {
if (spec.isClassType(baseType)) {
jsiiType.initializer = baseType.initializer;
} else {
this._diagnostic(type.symbol.valueDeclaration,
ts.DiagnosticCategory.Error,
`Base type of ${jsiiType.fqn} (${jsiiType.base}) is not a class`);
}
});
} else {
jsiiType.initializer = {};
}
this._verifyNoStaticMixing(jsiiType, type.symbol.valueDeclaration);
return _sortMembers(jsiiType);
}
/**
* Use the TypeChecker's getTypeFromTypeNode, but throw a descriptive error if it fails
*/
private _getTypeFromTypeNode(t: ts.TypeNode) {
const type = this._typeChecker.getTypeFromTypeNode(t);
if (isErrorType(type)) {
throw new Error(`Unable to resolve type: ${t.getFullText()}. This typically happens if something is wrong with your dependency closure.`);
}
return type;
}
/**
* Check that this class doesn't declare any members that are of different staticness in itself or any of its bases
*/
private _verifyNoStaticMixing(klass: spec.ClassType, decl: ts.Declaration) {
function stat(s?: boolean) {
return s ? 'static' : 'non-static';
}
// Check class itself--may have two methods/props with the same name, so check the arrays
const statics = new Set((klass.methods ?? []).concat(klass.properties ?? []).filter(x => x.static).map(x => x.name));
const nonStatics = new Set((klass.methods ?? []).concat(klass.properties ?? []).filter(x => !x.static).map(x => x.name));
// Intersect
for (const member of intersect(statics, nonStatics)) {
this._diagnostic(decl, ts.DiagnosticCategory.Error,
`member '${member}' of class '${klass.name}' cannot be declared both statically and non-statically`);
}
// Check against base classes. They will not contain duplicate member names so we can load
// the members into a map.
const classMembers = typeMembers(klass);
this._withBaseClass(klass, decl, (base, recurse) => {
for (const [name, baseMember] of Object.entries(typeMembers(base))) {
const member = classMembers[name];
if (!member) { continue; }
if (!!baseMember.static !== !!member.static) {
this._diagnostic(decl, ts.DiagnosticCategory.Error,
`${stat(member.static)} member '${name}' of class '${klass.name}' conflicts with ${stat(baseMember.static)} member in ancestor '${base.name}'`);
}
}
recurse();
});
}
/**
* Wrapper around _deferUntilTypesAvailable, invoke the callback with the given classes' base type
*
* Does nothing if the given class doesn't have a base class.
*
* The second argument will be a `recurse` function for easy recursion up the inheritance tree
* (no messing around with binding 'self' and 'this' and doing multiple calls to _withBaseClass.)
*/
private _withBaseClass(klass: spec.ClassType, decl: ts.Declaration, cb: (base: spec.ClassType, recurse: () => void) => void) {
if (klass.base) {
this._deferUntilTypesAvailable(klass.fqn, [klass.base], decl, (base) => {
if (!spec.isClassType(base)) { throw new Error('Oh no'); }
cb(base, () => this._withBaseClass(base, decl, cb));
});
}
}
/**
* @returns true if this member is internal and should be omitted from the type manifest
*/
private _isPrivateOrInternal(symbol: ts.Symbol, validateDeclaration?: ts.Declaration): boolean {
const hasInternalJsDocTag = _hasInternalJsDocTag(symbol);
const hasUnderscorePrefix = symbol.name !== '__constructor' && symbol.name.startsWith('_');
if (_isPrivate(symbol)) {
LOG.trace(`${colors.cyan(symbol.name)} is marked "private", or is an unexported type declaration`);
return true;
}
if (!hasInternalJsDocTag && !hasUnderscorePrefix) {
return false;
}
// we only validate if we have a declaration
if (validateDeclaration) {
if (!hasUnderscorePrefix) {
this._diagnostic(validateDeclaration, ts.DiagnosticCategory.Error,
`${colors.cyan(symbol.name)}: the name of members marked as @internal must begin with an underscore`);
}
if (!hasInternalJsDocTag) {
this._diagnostic(validateDeclaration, ts.DiagnosticCategory.Error,
`${colors.cyan(symbol.name)}: members with names that begin with an underscore must be marked as @internal via a JSDoc tag`);
}
}
return true;
}
private async _visitEnum(type: ts.Type, ctx: EmitContext): Promise<spec.EnumType | undefined> {
if (LOG.isTraceEnabled()) {
LOG.trace(`Processing enum: ${colors.gray(ctx.namespace.join('.'))}.${colors.cyan(type.symbol.name)}`);
}
// Forcefully resolving to the EnumDeclaration symbol for single-valued enums
const symbol: ts.Symbol = type.isLiteral() ? (type.symbol as any).parent : type.symbol;
if (!symbol) {
throw new Error(`Unable to resolve enum declaration for ${type.symbol.name}!`);
}
if (_hasInternalJsDocTag(symbol)) {
return Promise.resolve(undefined);
}
this._warnAboutReservedWords(type.symbol);
const decl = symbol.valueDeclaration;
const flags = ts.getCombinedModifierFlags(decl);
if (flags & ts.ModifierFlags.Const) {
this._diagnostic(decl,
ts.DiagnosticCategory.Error,
"Exported enum cannot be declared 'const'");
}
const docs = this._visitDocumentation(symbol, ctx);
const typeContext = ctx.replaceStability(docs?.stability);
const members = type.isUnion() ? type.types : [type];
const jsiiType: spec.EnumType = {
assembly: this.projectInfo.name,
fqn: `${[this.projectInfo.name, ...ctx.namespace].join('.')}.${symbol.name}`,
kind: spec.TypeKind.Enum,
members: members.map(m => ({
name: m.symbol.name,
docs: this._visitDocumentation(m.symbol, typeContext),
})),
name: symbol.name,
namespace: ctx.namespace.length > 0 ? ctx.namespace.join('.') : undefined,
docs
};
return Promise.resolve(jsiiType);
}
/**
* Return docs for a symbol
*/
private _visitDocumentation(sym: ts.Symbol, context: EmitContext): spec.Docs | undefined {
const result = parseSymbolDocumentation(sym, this._typeChecker);
for (const diag of result.diagnostics ?? []) {
this._diagnostic(sym.declarations[0],
ts.DiagnosticCategory.Error,
diag
);
}
// Apply the current context's stability if none was specified locally.
if (result.docs.stability == null) {
result.docs.stability = context.stability;
}
const allUndefined = Object.values(result.docs).every(v => v === undefined);
return !allUndefined ? result.docs : undefined;
}
/**
* Check that all parameters the doc block refers to with a @param declaration actually exist
*/
private _validateReferencedDocParams(method: spec.Method, methodSym: ts.Symbol) {
const params = getReferencedDocParams(methodSym);
const actualNames = new Set((method.parameters ?? []).map(p => p.name));
for (const param of params) {
if (!actualNames.has(param)) {
this._diagnostic(methodSym.valueDeclaration, ts.DiagnosticCategory.Warning,
`In doc block of '${method.name}', '@param ${param}' refers to a nonexistent parameter.`);
}
}
}
private async _visitInterface(type: ts.Type, ctx: EmitContext): Promise<spec.InterfaceType | undefined> {
if (LOG.isTraceEnabled()) {
LOG.trace(`Processing interface: ${colors.gray(ctx.namespace.join('.'))}.${colors.cyan(type.symbol.name)}`);
}
if (_hasInternalJsDocTag(type.symbol)) {
return undefined;
}
this._warnAboutReservedWords(type.symbol);
const fqn = `${[this.projectInfo.name, ...ctx.namespace].join('.')}.${type.symbol.name}`;
const jsiiType: spec.InterfaceType = {
assembly: this.projectInfo.name,
fqn,
kind: spec.TypeKind.Interface,
name: type.symbol.name,
namespace: ctx.namespace.length > 0 ? ctx.namespace.join('.') : undefined,
docs: this._visitDocumentation(type.symbol, ctx),
};
const { interfaces, erasedBases } = await this._processBaseInterfaces(fqn, type.getBaseTypes());
jsiiType.interfaces = apply(interfaces, arr => arr.map(i => i.fqn));
for (const declaringType of [type, ...erasedBases]) {
for (const member of declaringType.getProperties()) {
if (!(declaringType.symbol.getDeclarations() ?? []).find(decl => decl === member.valueDeclaration.parent)) { continue; }
if (this._isPrivateOrInternal(member, member.valueDeclaration)) {
continue;
}
if (ts.isMethodDeclaration(member.valueDeclaration) || ts.isMethodSignature(member.valueDeclaration)) {
// eslint-disable-next-line no-await-in-loop
await this._visitMethod(member, jsiiType, ctx.replaceStability(jsiiType.docs?.stability));
} else if (ts.isPropertyDeclaration(member.valueDeclaration)
|| ts.isPropertySignature(member.valueDeclaration)
|| ts.isAccessor(member.valueDeclaration)) {
// eslint-disable-next-line no-await-in-loop
await this._visitProperty(member, jsiiType, ctx.replaceStability(jsiiType.docs?.stability));
} else {
this._diagnostic(member.valueDeclaration,
ts.DiagnosticCategory.Warning,
`Ignoring un-handled ${ts.SyntaxKind[member.valueDeclaration.kind]} member`);
}
}
}
// Calculate datatype based on the datatypeness of this interface and all of its parents
// To keep the spec minimal the actual values of the attribute are "true" or "undefined" (to represent "false").
this._deferUntilTypesAvailable(fqn, jsiiType.interfaces ?? [], type.symbol.valueDeclaration, (...bases: spec.Type[]) => {
if ((jsiiType.methods ?? []).length === 0) {
jsiiType.datatype = true;
}
for (const base of bases) {
if (spec.isInterfaceType(base) && !base.datatype) {
jsiiType.datatype = undefined;
}
}
const interfaceName = isInterfaceName(jsiiType.name);
// If it's not a datatype the name must start with an "I".
if (!jsiiType.datatype && !interfaceName) {
this._diagnostic(type.symbol.declarations[0],
ts.DiagnosticCategory.Error,
`Interface contains behavior: name should be "I${jsiiType.name}"`);
}
// If the name starts with an "I" it is not intended as a datatype, so switch that off.
if (jsiiType.datatype && interfaceName) {
jsiiType.datatype = undefined;
}
// Okay, this is a data type, check that all properties are readonly
if (jsiiType.datatype) {
for (const prop of jsiiType.properties ?? []) {
if (!prop.immutable) {
const p = type.getProperty(prop.name)!;
this._diagnostic(p.valueDeclaration,
ts.DiagnosticCategory.Error,
`The property '${prop.name}' in data type '${jsiiType.name}' must be 'readonly' since data is passed by-value`);
// force property to be "readonly" since jsii languages will pass this by-value
prop.immutable = true;
}
}
} else {
// This is *NOT* a data type, so it may not extend something that is one.
for (const base of bases) {
if (!spec.isInterfaceType(base)) {
// Invalid type we already warned about earlier, just ignoring it here...
continue;
}
if (base.datatype) {
this._diagnostic(type.symbol.valueDeclaration,
ts.DiagnosticCategory.Error,
`Attempted to extend struct ${base.fqn} from regular interface ${jsiiType.fqn}`);
}
}
}
});
// Check that no interface declares a member that's already declared
// in a base type (not allowed in C#).
const names = memberNames(jsiiType);
const checkNoIntersection = (...bases: spec.Type[]) => {
for (const base of bases) {
if (!spec.isInterfaceType(base)) { continue; }
const baseMembers = memberNames(base);
for (const memberName of names) {
if (baseMembers.includes(memberName)) {
this._diagnostic(type.symbol.declarations[0],
ts.DiagnosticCategory.Error,
`Interface declares same member as inherited interface: ${memberName}`);
}
}
// Recurse upwards
this._deferUntilTypesAvailable(fqn, base.interfaces ?? [], type.symbol.valueDeclaration, checkNoIntersection);
}
};
this._deferUntilTypesAvailable(fqn, jsiiType.interfaces ?? [], type.symbol.valueDeclaration, checkNoIntersection);
return _sortMembers(jsiiType);
}
private async _visitMethod(symbol: ts.Symbol, type: spec.ClassType | spec.InterfaceType, ctx: EmitContext) {
if (LOG.isTraceEnabled()) {
LOG.trace(`Processing method: ${colors.green(type.fqn)}#${colors.cyan(symbol.name)}`);
}
const declaration = symbol.valueDeclaration as (ts.MethodDeclaration | ts.MethodSignature);
const signature = this._typeChecker.getSignatureFromDeclaration(declaration);
if (!signature) {
this._diagnostic(declaration, ts.DiagnosticCategory.Error, `Unable to compute signature for ${type.fqn}#${symbol.name}`);
return;
}
if (isProhibitedMemberName(symbol.name)) {
this._diagnostic(declaration, ts.DiagnosticCategory.Error, `Prohibited member name: ${symbol.name}`);
return;
}
this._warnAboutReservedWords(symbol);
const parameters = await Promise.all(signature.getParameters().map(p => this._toParameter(p, ctx)));
const returnType = signature.getReturnType();
const method: spec.Method = {
abstract: _isAbstract(symbol, type) || undefined,
name: symbol.name,
parameters: parameters.length > 0 ? parameters : undefined,
protected: _isProtected(symbol) || undefined,
returns: _isVoid(returnType) ? undefined : await this._optionalValue(returnType, declaration),
async: _isPromise(returnType) || undefined,
static: _isStatic(symbol) || undefined,
locationInModule: this.declarationLocation(declaration),
};
method.variadic = method.parameters?.some(p => !!p.variadic) || undefined;
this._verifyConsecutiveOptionals(declaration, method.parameters);
method.docs = this._visitDocumentation(symbol, ctx);
// If the last parameter is a datatype, verify that it does not share any field names with
// other function arguments, so that it can be turned into keyword arguments by jsii frontends
// that support such.
const lastParamTypeRef = apply(last(parameters), x => x.type);
const lastParamSymbol = last(signature.getParameters());
if (lastParamTypeRef && spec.isNamedTypeReference(lastParamTypeRef)) {
this._deferUntilTypesAvailable(symbol.name, [lastParamTypeRef], lastParamSymbol!.declarations[0], (lastParamType) => {
if (!spec.isInterfaceType(lastParamType) || !lastParamType.datatype) { return; }