forked from angular/angular
/
esm2015_host.ts
1890 lines (1716 loc) · 72.7 KB
/
esm2015_host.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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {AbsoluteFsPath} from '../../../src/ngtsc/file_system';
import {ClassDeclaration, ClassMember, ClassMemberKind, ConcreteDeclaration, CtorParameter, Declaration, Decorator, TypeScriptReflectionHost, isDecoratorIdentifier, reflectObjectLiteral} from '../../../src/ngtsc/reflection';
import {isWithinPackage} from '../analysis/util';
import {Logger} from '../logging/logger';
import {BundleProgram} from '../packages/bundle_program';
import {findAll, getNameText, hasNameIdentifier, isDefined, stripDollarSuffix} from '../utils';
import {ClassSymbol, ModuleWithProvidersFunction, NgccClassSymbol, NgccReflectionHost, PRE_R3_MARKER, SwitchableVariableDeclaration, isSwitchableVariableDeclaration} from './ngcc_host';
export const DECORATORS = 'decorators' as ts.__String;
export const PROP_DECORATORS = 'propDecorators' as ts.__String;
export const CONSTRUCTOR = '__constructor' as ts.__String;
export const CONSTRUCTOR_PARAMS = 'ctorParameters' as ts.__String;
/**
* Esm2015 packages contain ECMAScript 2015 classes, etc.
* Decorators are defined via static properties on the class. For example:
*
* ```
* class SomeDirective {
* }
* SomeDirective.decorators = [
* { type: Directive, args: [{ selector: '[someDirective]' },] }
* ];
* SomeDirective.ctorParameters = () => [
* { type: ViewContainerRef, },
* { type: TemplateRef, },
* { type: undefined, decorators: [{ type: Inject, args: [INJECTED_TOKEN,] },] },
* ];
* SomeDirective.propDecorators = {
* "input1": [{ type: Input },],
* "input2": [{ type: Input },],
* };
* ```
*
* * Classes are decorated if they have a static property called `decorators`.
* * Members are decorated if there is a matching key on a static property
* called `propDecorators`.
* * Constructor parameters decorators are found on an object returned from
* a static method called `ctorParameters`.
*/
export class Esm2015ReflectionHost extends TypeScriptReflectionHost implements NgccReflectionHost {
protected dtsDeclarationMap: Map<string, ts.Declaration>|null;
/**
* The set of source files that have already been preprocessed.
*/
protected preprocessedSourceFiles = new Set<ts.SourceFile>();
/**
* In ES2015, class declarations may have been down-leveled into variable declarations,
* initialized using a class expression. In certain scenarios, an additional variable
* is introduced that represents the class so that results in code such as:
*
* ```
* let MyClass_1; let MyClass = MyClass_1 = class MyClass {};
* ```
*
* This map tracks those aliased variables to their original identifier, i.e. the key
* corresponds with the declaration of `MyClass_1` and its value becomes the `MyClass` identifier
* of the variable declaration.
*
* This map is populated during the preprocessing of each source file.
*/
protected aliasedClassDeclarations = new Map<ts.Declaration, ts.Identifier>();
/**
* Caches the information of the decorators on a class, as the work involved with extracting
* decorators is complex and frequently used.
*
* This map is lazily populated during the first call to `acquireDecoratorInfo` for a given class.
*/
protected decoratorCache = new Map<ClassDeclaration, DecoratorInfo>();
constructor(
protected logger: Logger, protected isCore: boolean, checker: ts.TypeChecker,
dts?: BundleProgram|null) {
super(checker);
this.dtsDeclarationMap =
dts && this.computeDtsDeclarationMap(dts.path, dts.program, dts.package) || null;
}
/**
* Find a symbol for a node that we think is a class.
* Classes should have a `name` identifier, because they may need to be referenced in other parts
* of the program.
*
* In ES2015, a class may be declared using a variable declaration of the following structure:
*
* ```
* var MyClass = MyClass_1 = class MyClass {};
* ```
*
* Here, the intermediate `MyClass_1` assignment is optional. In the above example, the
* `class MyClass {}` node is returned as declaration of `MyClass`.
*
* @param declaration the declaration node whose symbol we are finding.
* @returns the symbol for the node or `undefined` if it is not a "class" or has no symbol.
*/
getClassSymbol(declaration: ts.Node): NgccClassSymbol|undefined {
const symbol = this.getClassSymbolFromOuterDeclaration(declaration);
if (symbol !== undefined) {
return symbol;
}
return this.getClassSymbolFromInnerDeclaration(declaration);
}
/**
* In ES2015, a class may be declared using a variable declaration of the following structure:
*
* ```
* var MyClass = MyClass_1 = class MyClass {};
* ```
*
* This method extracts the `NgccClassSymbol` for `MyClass` when provided with the `var MyClass`
* declaration node. When the `class MyClass {}` node or any other node is given, this method will
* return undefined instead.
*
* @param declaration the declaration whose symbol we are finding.
* @returns the symbol for the node or `undefined` if it does not represent an outer declaration
* of a class.
*/
protected getClassSymbolFromOuterDeclaration(declaration: ts.Node): NgccClassSymbol|undefined {
// Create a symbol without inner declaration if the declaration is a regular class declaration.
if (ts.isClassDeclaration(declaration) && hasNameIdentifier(declaration)) {
return this.createClassSymbol(declaration, null);
}
// Otherwise, the declaration may be a variable declaration, in which case it must be
// initialized using a class expression as inner declaration.
if (ts.isVariableDeclaration(declaration) && hasNameIdentifier(declaration)) {
const innerDeclaration = getInnerClassDeclaration(declaration);
if (innerDeclaration !== null) {
return this.createClassSymbol(declaration, innerDeclaration);
}
}
return undefined;
}
/**
* In ES2015, a class may be declared using a variable declaration of the following structure:
*
* ```
* var MyClass = MyClass_1 = class MyClass {};
* ```
*
* This method extracts the `NgccClassSymbol` for `MyClass` when provided with the
* `class MyClass {}` declaration node. When the `var MyClass` node or any other node is given,
* this method will return undefined instead.
*
* @param declaration the declaration whose symbol we are finding.
* @returns the symbol for the node or `undefined` if it does not represent an inner declaration
* of a class.
*/
protected getClassSymbolFromInnerDeclaration(declaration: ts.Node): NgccClassSymbol|undefined {
if (!ts.isClassExpression(declaration) || !hasNameIdentifier(declaration)) {
return undefined;
}
const outerDeclaration = getVariableDeclarationOfDeclaration(declaration);
if (outerDeclaration === undefined || !hasNameIdentifier(outerDeclaration)) {
return undefined;
}
return this.createClassSymbol(outerDeclaration, declaration);
}
/**
* Creates an `NgccClassSymbol` from an outer and inner declaration. If a class only has an outer
* declaration, the "implementation" symbol of the created `NgccClassSymbol` will be set equal to
* the "declaration" symbol.
*
* @param outerDeclaration The outer declaration node of the class.
* @param innerDeclaration The inner declaration node of the class, or undefined if no inner
* declaration is present.
* @returns the `NgccClassSymbol` representing the class, or undefined if a `ts.Symbol` for any of
* the declarations could not be resolved.
*/
protected createClassSymbol(
outerDeclaration: ClassDeclaration, innerDeclaration: ClassDeclaration|null): NgccClassSymbol
|undefined {
const declarationSymbol =
this.checker.getSymbolAtLocation(outerDeclaration.name) as ClassSymbol | undefined;
if (declarationSymbol === undefined) {
return undefined;
}
const implementationSymbol = innerDeclaration !== null ?
this.checker.getSymbolAtLocation(innerDeclaration.name) :
declarationSymbol;
if (implementationSymbol === undefined) {
return undefined;
}
return {
name: declarationSymbol.name,
declaration: declarationSymbol,
implementation: implementationSymbol,
};
}
/**
* Examine a declaration (for example, of a class or function) and return metadata about any
* decorators present on the declaration.
*
* @param declaration a TypeScript `ts.Declaration` node representing the class or function over
* which to reflect. For example, if the intent is to reflect the decorators of a class and the
* source is in ES6 format, this will be a `ts.ClassDeclaration` node. If the source is in ES5
* format, this might be a `ts.VariableDeclaration` as classes in ES5 are represented as the
* result of an IIFE execution.
*
* @returns an array of `Decorator` metadata if decorators are present on the declaration, or
* `null` if either no decorators were present or if the declaration is not of a decoratable type.
*/
getDecoratorsOfDeclaration(declaration: ts.Declaration): Decorator[]|null {
const symbol = this.getClassSymbol(declaration);
if (!symbol) {
return null;
}
return this.getDecoratorsOfSymbol(symbol);
}
/**
* Examine a declaration which should be of a class, and return metadata about the members of the
* class.
*
* @param clazz a `ClassDeclaration` representing the class over which to reflect.
*
* @returns an array of `ClassMember` metadata representing the members of the class.
*
* @throws if `declaration` does not resolve to a class declaration.
*/
getMembersOfClass(clazz: ClassDeclaration): ClassMember[] {
const classSymbol = this.getClassSymbol(clazz);
if (!classSymbol) {
throw new Error(`Attempted to get members of a non-class: "${clazz.getText()}"`);
}
return this.getMembersOfSymbol(classSymbol);
}
/**
* Reflect over the constructor of a class and return metadata about its parameters.
*
* This method only looks at the constructor of a class directly and not at any inherited
* constructors.
*
* @param clazz a `ClassDeclaration` representing the class over which to reflect.
*
* @returns an array of `Parameter` metadata representing the parameters of the constructor, if
* a constructor exists. If the constructor exists and has 0 parameters, this array will be empty.
* If the class has no constructor, this method returns `null`.
*
* @throws if `declaration` does not resolve to a class declaration.
*/
getConstructorParameters(clazz: ClassDeclaration): CtorParameter[]|null {
const classSymbol = this.getClassSymbol(clazz);
if (!classSymbol) {
throw new Error(
`Attempted to get constructor parameters of a non-class: "${clazz.getText()}"`);
}
const parameterNodes = this.getConstructorParameterDeclarations(classSymbol);
if (parameterNodes) {
return this.getConstructorParamInfo(classSymbol, parameterNodes);
}
return null;
}
hasBaseClass(clazz: ClassDeclaration): boolean {
const superHasBaseClass = super.hasBaseClass(clazz);
if (superHasBaseClass) {
return superHasBaseClass;
}
const innerClassDeclaration = getInnerClassDeclaration(clazz);
if (innerClassDeclaration === null) {
return false;
}
return super.hasBaseClass(innerClassDeclaration);
}
getBaseClassExpression(clazz: ClassDeclaration): ts.Expression|null {
// First try getting the base class from the "outer" declaration
const superBaseClassIdentifier = super.getBaseClassExpression(clazz);
if (superBaseClassIdentifier) {
return superBaseClassIdentifier;
}
// That didn't work so now try getting it from the "inner" declaration.
const innerClassDeclaration = getInnerClassDeclaration(clazz);
if (innerClassDeclaration === null) {
return null;
}
return super.getBaseClassExpression(innerClassDeclaration);
}
/**
* Check whether the given node actually represents a class.
*/
isClass(node: ts.Node): node is ClassDeclaration {
return super.isClass(node) || this.getClassSymbol(node) !== undefined;
}
/**
* Trace an identifier to its declaration, if possible.
*
* This method attempts to resolve the declaration of the given identifier, tracing back through
* imports and re-exports until the original declaration statement is found. A `Declaration`
* object is returned if the original declaration is found, or `null` is returned otherwise.
*
* In ES2015, we need to account for identifiers that refer to aliased class declarations such as
* `MyClass_1`. Since such declarations are only available within the module itself, we need to
* find the original class declaration, e.g. `MyClass`, that is associated with the aliased one.
*
* @param id a TypeScript `ts.Identifier` to trace back to a declaration.
*
* @returns metadata about the `Declaration` if the original declaration is found, or `null`
* otherwise.
*/
getDeclarationOfIdentifier(id: ts.Identifier): Declaration|null {
const superDeclaration = super.getDeclarationOfIdentifier(id);
// The identifier may have been of an additional class assignment such as `MyClass_1` that was
// present as alias for `MyClass`. If so, resolve such aliases to their original declaration.
if (superDeclaration !== null && superDeclaration.node !== null) {
const aliasedIdentifier = this.resolveAliasedClassIdentifier(superDeclaration.node);
if (aliasedIdentifier !== null) {
return this.getDeclarationOfIdentifier(aliasedIdentifier);
}
}
return superDeclaration;
}
/**
* Gets all decorators of the given class symbol. Any decorator that have been synthetically
* injected by a migration will not be present in the returned collection.
*/
getDecoratorsOfSymbol(symbol: NgccClassSymbol): Decorator[]|null {
const {classDecorators} = this.acquireDecoratorInfo(symbol);
if (classDecorators === null) {
return null;
}
// Return a clone of the array to prevent consumers from mutating the cache.
return Array.from(classDecorators);
}
/**
* Search the given module for variable declarations in which the initializer
* is an identifier marked with the `PRE_R3_MARKER`.
* @param module the module in which to search for switchable declarations.
* @returns an array of variable declarations that match.
*/
getSwitchableDeclarations(module: ts.Node): SwitchableVariableDeclaration[] {
// Don't bother to walk the AST if the marker is not found in the text
return module.getText().indexOf(PRE_R3_MARKER) >= 0 ?
findAll(module, isSwitchableVariableDeclaration) :
[];
}
getVariableValue(declaration: ts.VariableDeclaration): ts.Expression|null {
const value = super.getVariableValue(declaration);
if (value) {
return value;
}
// We have a variable declaration that has no initializer. For example:
//
// ```
// var HttpClientXsrfModule_1;
// ```
//
// So look for the special scenario where the variable is being assigned in
// a nearby statement to the return value of a call to `__decorate`.
// Then find the 2nd argument of that call, the "target", which will be the
// actual class identifier. For example:
//
// ```
// HttpClientXsrfModule = HttpClientXsrfModule_1 = tslib_1.__decorate([
// NgModule({
// providers: [],
// })
// ], HttpClientXsrfModule);
// ```
//
// And finally, find the declaration of the identifier in that argument.
// Note also that the assignment can occur within another assignment.
//
const block = declaration.parent.parent.parent;
const symbol = this.checker.getSymbolAtLocation(declaration.name);
if (symbol && (ts.isBlock(block) || ts.isSourceFile(block))) {
const decorateCall = this.findDecoratedVariableValue(block, symbol);
const target = decorateCall && decorateCall.arguments[1];
if (target && ts.isIdentifier(target)) {
const targetSymbol = this.checker.getSymbolAtLocation(target);
const targetDeclaration = targetSymbol && targetSymbol.valueDeclaration;
if (targetDeclaration) {
if (ts.isClassDeclaration(targetDeclaration) ||
ts.isFunctionDeclaration(targetDeclaration)) {
// The target is just a function or class declaration
// so return its identifier as the variable value.
return targetDeclaration.name || null;
} else if (ts.isVariableDeclaration(targetDeclaration)) {
// The target is a variable declaration, so find the far right expression,
// in the case of multiple assignments (e.g. `var1 = var2 = value`).
let targetValue = targetDeclaration.initializer;
while (targetValue && isAssignment(targetValue)) {
targetValue = targetValue.right;
}
if (targetValue) {
return targetValue;
}
}
}
}
}
return null;
}
/**
* Find all top-level class symbols in the given file.
* @param sourceFile The source file to search for classes.
* @returns An array of class symbols.
*/
findClassSymbols(sourceFile: ts.SourceFile): NgccClassSymbol[] {
const classes: NgccClassSymbol[] = [];
this.getModuleStatements(sourceFile).forEach(statement => {
if (ts.isVariableStatement(statement)) {
statement.declarationList.declarations.forEach(declaration => {
const classSymbol = this.getClassSymbol(declaration);
if (classSymbol) {
classes.push(classSymbol);
}
});
} else if (ts.isClassDeclaration(statement)) {
const classSymbol = this.getClassSymbol(statement);
if (classSymbol) {
classes.push(classSymbol);
}
}
});
return classes;
}
/**
* Get the number of generic type parameters of a given class.
*
* @param clazz a `ClassDeclaration` representing the class over which to reflect.
*
* @returns the number of type parameters of the class, if known, or `null` if the declaration
* is not a class or has an unknown number of type parameters.
*/
getGenericArityOfClass(clazz: ClassDeclaration): number|null {
const dtsDeclaration = this.getDtsDeclaration(clazz);
if (dtsDeclaration && ts.isClassDeclaration(dtsDeclaration)) {
return dtsDeclaration.typeParameters ? dtsDeclaration.typeParameters.length : 0;
}
return null;
}
/**
* Take an exported declaration of a class (maybe down-leveled to a variable) and look up the
* declaration of its type in a separate .d.ts tree.
*
* This function is allowed to return `null` if the current compilation unit does not have a
* separate .d.ts tree. When compiling TypeScript code this is always the case, since .d.ts files
* are produced only during the emit of such a compilation. When compiling .js code, however,
* there is frequently a parallel .d.ts tree which this method exposes.
*
* Note that the `ts.ClassDeclaration` returned from this function may not be from the same
* `ts.Program` as the input declaration.
*/
getDtsDeclaration(declaration: ts.Declaration): ts.Declaration|null {
if (!this.dtsDeclarationMap) {
return null;
}
if (!isNamedDeclaration(declaration)) {
throw new Error(
`Cannot get the dts file for a declaration that has no name: ${declaration.getText()} in ${declaration.getSourceFile().fileName}`);
}
return this.dtsDeclarationMap.has(declaration.name.text) ?
this.dtsDeclarationMap.get(declaration.name.text) ! :
null;
}
/**
* Search the given source file for exported functions and static class methods that return
* ModuleWithProviders objects.
* @param f The source file to search for these functions
* @returns An array of function declarations that look like they return ModuleWithProviders
* objects.
*/
getModuleWithProvidersFunctions(f: ts.SourceFile): ModuleWithProvidersFunction[] {
const exports = this.getExportsOfModule(f);
if (!exports) return [];
const infos: ModuleWithProvidersFunction[] = [];
exports.forEach((declaration, name) => {
if (declaration.node === null) {
return;
}
if (this.isClass(declaration.node)) {
this.getMembersOfClass(declaration.node).forEach(member => {
if (member.isStatic) {
const info = this.parseForModuleWithProviders(
member.name, member.node, member.implementation, declaration.node);
if (info) {
infos.push(info);
}
}
});
} else {
if (isNamedDeclaration(declaration.node)) {
const info =
this.parseForModuleWithProviders(declaration.node.name.text, declaration.node);
if (info) {
infos.push(info);
}
}
}
});
return infos;
}
///////////// Protected Helpers /////////////
/**
* Finds the identifier of the actual class declaration for a potentially aliased declaration of a
* class.
*
* If the given declaration is for an alias of a class, this function will determine an identifier
* to the original declaration that represents this class.
*
* @param declaration The declaration to resolve.
* @returns The original identifier that the given class declaration resolves to, or `undefined`
* if the declaration does not represent an aliased class.
*/
protected resolveAliasedClassIdentifier(declaration: ts.Declaration): ts.Identifier|null {
this.ensurePreprocessed(declaration.getSourceFile());
return this.aliasedClassDeclarations.has(declaration) ?
this.aliasedClassDeclarations.get(declaration) ! :
null;
}
/**
* Ensures that the source file that `node` is part of has been preprocessed.
*
* During preprocessing, all statements in the source file will be visited such that certain
* processing steps can be done up-front and cached for subsequent usages.
*
* @param sourceFile The source file that needs to have gone through preprocessing.
*/
protected ensurePreprocessed(sourceFile: ts.SourceFile): void {
if (!this.preprocessedSourceFiles.has(sourceFile)) {
this.preprocessedSourceFiles.add(sourceFile);
for (const statement of sourceFile.statements) {
this.preprocessStatement(statement);
}
}
}
/**
* Analyzes the given statement to see if it corresponds with a variable declaration like
* `let MyClass = MyClass_1 = class MyClass {};`. If so, the declaration of `MyClass_1`
* is associated with the `MyClass` identifier.
*
* @param statement The statement that needs to be preprocessed.
*/
protected preprocessStatement(statement: ts.Statement): void {
if (!ts.isVariableStatement(statement)) {
return;
}
const declarations = statement.declarationList.declarations;
if (declarations.length !== 1) {
return;
}
const declaration = declarations[0];
const initializer = declaration.initializer;
if (!ts.isIdentifier(declaration.name) || !initializer || !isAssignment(initializer) ||
!ts.isIdentifier(initializer.left) || !ts.isClassExpression(initializer.right)) {
return;
}
const aliasedIdentifier = initializer.left;
const aliasedDeclaration = this.getDeclarationOfIdentifier(aliasedIdentifier);
if (aliasedDeclaration === null || aliasedDeclaration.node === null) {
throw new Error(
`Unable to locate declaration of ${aliasedIdentifier.text} in "${statement.getText()}"`);
}
this.aliasedClassDeclarations.set(aliasedDeclaration.node, declaration.name);
}
/** Get the top level statements for a module.
*
* In ES5 and ES2015 this is just the top level statements of the file.
* @param sourceFile The module whose statements we want.
* @returns An array of top level statements for the given module.
*/
protected getModuleStatements(sourceFile: ts.SourceFile): ts.Statement[] {
return Array.from(sourceFile.statements);
}
/**
* Walk the AST looking for an assignment to the specified symbol.
* @param node The current node we are searching.
* @returns an expression that represents the value of the variable, or undefined if none can be
* found.
*/
protected findDecoratedVariableValue(node: ts.Node|undefined, symbol: ts.Symbol):
ts.CallExpression|null {
if (!node) {
return null;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
const left = node.left;
const right = node.right;
if (ts.isIdentifier(left) && this.checker.getSymbolAtLocation(left) === symbol) {
return (ts.isCallExpression(right) && getCalleeName(right) === '__decorate') ? right : null;
}
return this.findDecoratedVariableValue(right, symbol);
}
return node.forEachChild(node => this.findDecoratedVariableValue(node, symbol)) || null;
}
/**
* Try to retrieve the symbol of a static property on a class.
* @param symbol the class whose property we are interested in.
* @param propertyName the name of static property.
* @returns the symbol if it is found or `undefined` if not.
*/
protected getStaticProperty(symbol: NgccClassSymbol, propertyName: ts.__String): ts.Symbol
|undefined {
return symbol.declaration.exports && symbol.declaration.exports.get(propertyName);
}
/**
* This is the main entry-point for obtaining information on the decorators of a given class. This
* information is computed either from static properties if present, or using `tslib.__decorate`
* helper calls otherwise. The computed result is cached per class.
*
* @param classSymbol the class for which decorators should be acquired.
* @returns all information of the decorators on the class.
*/
protected acquireDecoratorInfo(classSymbol: NgccClassSymbol): DecoratorInfo {
const decl = classSymbol.declaration.valueDeclaration;
if (this.decoratorCache.has(decl)) {
return this.decoratorCache.get(decl) !;
}
// Extract decorators from static properties and `__decorate` helper calls, then merge them
// together where the information from the static properties is preferred.
const staticProps = this.computeDecoratorInfoFromStaticProperties(classSymbol);
const helperCalls = this.computeDecoratorInfoFromHelperCalls(classSymbol);
const decoratorInfo: DecoratorInfo = {
classDecorators: staticProps.classDecorators || helperCalls.classDecorators,
memberDecorators: staticProps.memberDecorators || helperCalls.memberDecorators,
constructorParamInfo: staticProps.constructorParamInfo || helperCalls.constructorParamInfo,
};
this.decoratorCache.set(decl, decoratorInfo);
return decoratorInfo;
}
/**
* Attempts to compute decorator information from static properties "decorators", "propDecorators"
* and "ctorParameters" on the class. If neither of these static properties is present the
* library is likely not compiled using tsickle for usage with Closure compiler, in which case
* `null` is returned.
*
* @param classSymbol The class symbol to compute the decorators information for.
* @returns All information on the decorators as extracted from static properties, or `null` if
* none of the static properties exist.
*/
protected computeDecoratorInfoFromStaticProperties(classSymbol: NgccClassSymbol): {
classDecorators: Decorator[] | null; memberDecorators: Map<string, Decorator[]>| null;
constructorParamInfo: ParamInfo[] | null;
} {
let classDecorators: Decorator[]|null = null;
let memberDecorators: Map<string, Decorator[]>|null = null;
let constructorParamInfo: ParamInfo[]|null = null;
const decoratorsProperty = this.getStaticProperty(classSymbol, DECORATORS);
if (decoratorsProperty !== undefined) {
classDecorators = this.getClassDecoratorsFromStaticProperty(decoratorsProperty);
}
const propDecoratorsProperty = this.getStaticProperty(classSymbol, PROP_DECORATORS);
if (propDecoratorsProperty !== undefined) {
memberDecorators = this.getMemberDecoratorsFromStaticProperty(propDecoratorsProperty);
}
const constructorParamsProperty = this.getStaticProperty(classSymbol, CONSTRUCTOR_PARAMS);
if (constructorParamsProperty !== undefined) {
constructorParamInfo = this.getParamInfoFromStaticProperty(constructorParamsProperty);
}
return {classDecorators, memberDecorators, constructorParamInfo};
}
/**
* Get all class decorators for the given class, where the decorators are declared
* via a static property. For example:
*
* ```
* class SomeDirective {}
* SomeDirective.decorators = [
* { type: Directive, args: [{ selector: '[someDirective]' },] }
* ];
* ```
*
* @param decoratorsSymbol the property containing the decorators we want to get.
* @returns an array of decorators or null if none where found.
*/
protected getClassDecoratorsFromStaticProperty(decoratorsSymbol: ts.Symbol): Decorator[]|null {
const decoratorsIdentifier = decoratorsSymbol.valueDeclaration;
if (decoratorsIdentifier && decoratorsIdentifier.parent) {
if (ts.isBinaryExpression(decoratorsIdentifier.parent) &&
decoratorsIdentifier.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
// AST of the array of decorator values
const decoratorsArray = decoratorsIdentifier.parent.right;
return this.reflectDecorators(decoratorsArray)
.filter(decorator => this.isFromCore(decorator));
}
}
return null;
}
/**
* Examine a symbol which should be of a class, and return metadata about its members.
*
* @param symbol the `ClassSymbol` representing the class over which to reflect.
* @returns an array of `ClassMember` metadata representing the members of the class.
*/
protected getMembersOfSymbol(symbol: NgccClassSymbol): ClassMember[] {
const members: ClassMember[] = [];
// The decorators map contains all the properties that are decorated
const {memberDecorators} = this.acquireDecoratorInfo(symbol);
// Make a copy of the decorators as successfully reflected members delete themselves from the
// map, so that any leftovers can be easily dealt with.
const decoratorsMap = new Map(memberDecorators);
// The member map contains all the method (instance and static); and any instance properties
// that are initialized in the class.
if (symbol.implementation.members) {
symbol.implementation.members.forEach((value, key) => {
const decorators = decoratorsMap.get(key as string);
const reflectedMembers = this.reflectMembers(value, decorators);
if (reflectedMembers) {
decoratorsMap.delete(key as string);
members.push(...reflectedMembers);
}
});
}
// The static property map contains all the static properties
if (symbol.implementation.exports) {
symbol.implementation.exports.forEach((value, key) => {
const decorators = decoratorsMap.get(key as string);
const reflectedMembers = this.reflectMembers(value, decorators, true);
if (reflectedMembers) {
decoratorsMap.delete(key as string);
members.push(...reflectedMembers);
}
});
}
// If this class was declared as a VariableDeclaration then it may have static properties
// attached to the variable rather than the class itself
// For example:
// ```
// let MyClass = class MyClass {
// // no static properties here!
// }
// MyClass.staticProperty = ...;
// ```
if (ts.isVariableDeclaration(symbol.declaration.valueDeclaration)) {
if (symbol.declaration.exports) {
symbol.declaration.exports.forEach((value, key) => {
const decorators = decoratorsMap.get(key as string);
const reflectedMembers = this.reflectMembers(value, decorators, true);
if (reflectedMembers) {
decoratorsMap.delete(key as string);
members.push(...reflectedMembers);
}
});
}
}
// Deal with any decorated properties that were not initialized in the class
decoratorsMap.forEach((value, key) => {
members.push({
implementation: null,
decorators: value,
isStatic: false,
kind: ClassMemberKind.Property,
name: key,
nameNode: null,
node: null,
type: null,
value: null
});
});
return members;
}
/**
* Member decorators may be declared as static properties of the class:
*
* ```
* SomeDirective.propDecorators = {
* "ngForOf": [{ type: Input },],
* "ngForTrackBy": [{ type: Input },],
* "ngForTemplate": [{ type: Input },],
* };
* ```
*
* @param decoratorsProperty the class whose member decorators we are interested in.
* @returns a map whose keys are the name of the members and whose values are collections of
* decorators for the given member.
*/
protected getMemberDecoratorsFromStaticProperty(decoratorsProperty: ts.Symbol):
Map<string, Decorator[]> {
const memberDecorators = new Map<string, Decorator[]>();
// Symbol of the identifier for `SomeDirective.propDecorators`.
const propDecoratorsMap = getPropertyValueFromSymbol(decoratorsProperty);
if (propDecoratorsMap && ts.isObjectLiteralExpression(propDecoratorsMap)) {
const propertiesMap = reflectObjectLiteral(propDecoratorsMap);
propertiesMap.forEach((value, name) => {
const decorators =
this.reflectDecorators(value).filter(decorator => this.isFromCore(decorator));
if (decorators.length) {
memberDecorators.set(name, decorators);
}
});
}
return memberDecorators;
}
/**
* For a given class symbol, collects all decorator information from tslib helper methods, as
* generated by TypeScript into emitted JavaScript files.
*
* Class decorators are extracted from calls to `tslib.__decorate` that look as follows:
*
* ```
* let SomeDirective = class SomeDirective {}
* SomeDirective = __decorate([
* Directive({ selector: '[someDirective]' }),
* ], SomeDirective);
* ```
*
* The extraction of member decorators is similar, with the distinction that its 2nd and 3rd
* argument correspond with a "prototype" target and the name of the member to which the
* decorators apply.
*
* ```
* __decorate([
* Input(),
* __metadata("design:type", String)
* ], SomeDirective.prototype, "input1", void 0);
* ```
*
* @param classSymbol The class symbol for which decorators should be extracted.
* @returns All information on the decorators of the class.
*/
protected computeDecoratorInfoFromHelperCalls(classSymbol: NgccClassSymbol): DecoratorInfo {
let classDecorators: Decorator[]|null = null;
const memberDecorators = new Map<string, Decorator[]>();
const constructorParamInfo: ParamInfo[] = [];
const getConstructorParamInfo = (index: number) => {
let param = constructorParamInfo[index];
if (param === undefined) {
param = constructorParamInfo[index] = {decorators: null, typeExpression: null};
}
return param;
};
// All relevant information can be extracted from calls to `__decorate`, obtain these first.
// Note that although the helper calls are retrieved using the class symbol, the result may
// contain helper calls corresponding with unrelated classes. Therefore, each helper call still
// has to be checked to actually correspond with the class symbol.
const helperCalls = this.getHelperCallsForClass(classSymbol, '__decorate');
for (const helperCall of helperCalls) {
if (isClassDecorateCall(helperCall, classSymbol.name)) {
// This `__decorate` call is targeting the class itself.
const helperArgs = helperCall.arguments[0];
for (const element of helperArgs.elements) {
const entry = this.reflectDecorateHelperEntry(element);
if (entry === null) {
continue;
}
if (entry.type === 'decorator') {
// The helper arg was reflected to represent an actual decorator
if (this.isFromCore(entry.decorator)) {
(classDecorators || (classDecorators = [])).push(entry.decorator);
}
} else if (entry.type === 'param:decorators') {
// The helper arg represents a decorator for a parameter. Since it's applied to the
// class, it corresponds with a constructor parameter of the class.
const param = getConstructorParamInfo(entry.index);
(param.decorators || (param.decorators = [])).push(entry.decorator);
} else if (entry.type === 'params') {
// The helper arg represents the types of the parameters. Since it's applied to the
// class, it corresponds with the constructor parameters of the class.
entry.types.forEach(
(type, index) => getConstructorParamInfo(index).typeExpression = type);
}
}
} else if (isMemberDecorateCall(helperCall, classSymbol.name)) {
// The `__decorate` call is targeting a member of the class
const helperArgs = helperCall.arguments[0];
const memberName = helperCall.arguments[2].text;
for (const element of helperArgs.elements) {
const entry = this.reflectDecorateHelperEntry(element);
if (entry === null) {
continue;
}
if (entry.type === 'decorator') {
// The helper arg was reflected to represent an actual decorator.
if (this.isFromCore(entry.decorator)) {
const decorators =
memberDecorators.has(memberName) ? memberDecorators.get(memberName) ! : [];
decorators.push(entry.decorator);
memberDecorators.set(memberName, decorators);
}
} else {
// Information on decorated parameters is not interesting for ngcc, so it's ignored.
}
}
}
}
return {classDecorators, memberDecorators, constructorParamInfo};
}
/**
* Extract the details of an entry within a `__decorate` helper call. For example, given the
* following code:
*
* ```
* __decorate([
* Directive({ selector: '[someDirective]' }),
* tslib_1.__param(2, Inject(INJECTED_TOKEN)),
* tslib_1.__metadata("design:paramtypes", [ViewContainerRef, TemplateRef, String])
* ], SomeDirective);
* ```
*
* it can be seen that there are calls to regular decorators (the `Directive`) and calls into
* `tslib` functions which have been inserted by TypeScript. Therefore, this function classifies
* a call to correspond with
* 1. a real decorator like `Directive` above, or
* 2. a decorated parameter, corresponding with `__param` calls from `tslib`, or
* 3. the type information of parameters, corresponding with `__metadata` call from `tslib`
*
* @param expression the expression that needs to be reflected into a `DecorateHelperEntry`
* @returns an object that indicates which of the three categories the call represents, together
* with the reflected information of the call, or null if the call is not a valid decorate call.
*/
protected reflectDecorateHelperEntry(expression: ts.Expression): DecorateHelperEntry|null {
// We only care about those elements that are actual calls
if (!ts.isCallExpression(expression)) {
return null;
}
const call = expression;
const helperName = getCalleeName(call);
if (helperName === '__metadata') {
// This is a `tslib.__metadata` call, reflect to arguments into a `ParameterTypes` object
// if the metadata key is "design:paramtypes".
const key = call.arguments[0];
if (key === undefined || !ts.isStringLiteral(key) || key.text !== 'design:paramtypes') {
return null;
}