/
compiler.ts
1241 lines (1101 loc) Β· 50.4 KB
/
compiler.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 LLC 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 {ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecoratorHandler, NgModuleDecoratorHandler, NoopReferencesRegistry, PipeDecoratorHandler, ReferencesRegistry} from '../../annotations';
import {CycleAnalyzer, CycleHandlingStrategy, ImportGraph} from '../../cycles';
import {COMPILER_ERRORS_WITH_GUIDES, ERROR_DETAILS_PAGE_BASE_URL, ErrorCode, ngErrorCode} from '../../diagnostics';
import {checkForPrivateExports, ReferenceGraph} from '../../entry_point';
import {absoluteFromSourceFile, AbsoluteFsPath, LogicalFileSystem, resolve} from '../../file_system';
import {AbsoluteModuleStrategy, AliasingHost, AliasStrategy, DefaultImportTracker, ImportRewriter, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NoopImportRewriter, PrivateExportAliasingHost, R3SymbolsImportRewriter, Reference, ReferenceEmitStrategy, ReferenceEmitter, RelativePathStrategy, UnifiedModulesAliasingHost, UnifiedModulesStrategy} from '../../imports';
import {IncrementalBuildStrategy, IncrementalCompilation, IncrementalState} from '../../incremental';
import {SemanticSymbol} from '../../incremental/semantic_graph';
import {generateAnalysis, IndexedComponent, IndexingContext} from '../../indexer';
import {ComponentResources, CompoundMetadataReader, CompoundMetadataRegistry, DirectiveMeta, DtsMetadataReader, InjectableClassRegistry, LocalMetadataRegistry, MetadataReader, PipeMeta, ResourceRegistry} from '../../metadata';
import {PartialEvaluator} from '../../partial_evaluator';
import {ActivePerfRecorder, DelegatingPerfRecorder, PerfCheckpoint, PerfEvent, PerfPhase} from '../../perf';
import {FileUpdate, ProgramDriver, UpdateMode} from '../../program_driver';
import {DeclarationNode, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection';
import {AdapterResourceLoader} from '../../resource';
import {entryPointKeyFor, NgModuleRouteAnalyzer} from '../../routing';
import {ComponentScopeReader, LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver, TypeCheckScopeRegistry} from '../../scope';
import {generatedFactoryTransform} from '../../shims';
import {ivySwitchTransform} from '../../switch';
import {aliasTransformFactory, CompilationMode, declarationTransformFactory, DecoratorHandler, DtsTransformRegistry, ivyTransformFactory, TraitCompiler} from '../../transform';
import {TemplateTypeCheckerImpl} from '../../typecheck';
import {OptimizeFor, TemplateTypeChecker, TypeCheckingConfig} from '../../typecheck/api';
import {ExtendedTemplateCheckerImpl} from '../../typecheck/extended';
import {InvalidBananaInBoxCheck} from '../../typecheck/extended/src/template_checks/invalid_banana_in_box';
import {getSourceFileOrNull, isDtsPath, resolveModuleName, toUnredirectedSourceFile} from '../../util/src/typescript';
import {Xi18nContext} from '../../xi18n';
import {LazyRoute, NgCompilerAdapter, NgCompilerOptions} from '../api';
/**
* State information about a compilation which is only generated once some data is requested from
* the `NgCompiler` (for example, by calling `getDiagnostics`).
*/
interface LazyCompilationState {
isCore: boolean;
traitCompiler: TraitCompiler;
reflector: TypeScriptReflectionHost;
metaReader: MetadataReader;
scopeRegistry: LocalModuleScopeRegistry;
typeCheckScopeRegistry: TypeCheckScopeRegistry;
exportReferenceGraph: ReferenceGraph|null;
routeAnalyzer: NgModuleRouteAnalyzer;
dtsTransforms: DtsTransformRegistry;
aliasingHost: AliasingHost|null;
refEmitter: ReferenceEmitter;
templateTypeChecker: TemplateTypeChecker;
resourceRegistry: ResourceRegistry;
}
/**
* Discriminant type for a `CompilationTicket`.
*/
export enum CompilationTicketKind {
Fresh,
IncrementalTypeScript,
IncrementalResource,
}
/**
* Begin an Angular compilation operation from scratch.
*/
export interface FreshCompilationTicket {
kind: CompilationTicketKind.Fresh;
options: NgCompilerOptions;
incrementalBuildStrategy: IncrementalBuildStrategy;
programDriver: ProgramDriver;
enableTemplateTypeChecker: boolean;
usePoisonedData: boolean;
tsProgram: ts.Program;
perfRecorder: ActivePerfRecorder;
}
/**
* Begin an Angular compilation operation that incorporates changes to TypeScript code.
*/
export interface IncrementalTypeScriptCompilationTicket {
kind: CompilationTicketKind.IncrementalTypeScript;
options: NgCompilerOptions;
newProgram: ts.Program;
incrementalBuildStrategy: IncrementalBuildStrategy;
incrementalCompilation: IncrementalCompilation;
programDriver: ProgramDriver;
enableTemplateTypeChecker: boolean;
usePoisonedData: boolean;
perfRecorder: ActivePerfRecorder;
}
export interface IncrementalResourceCompilationTicket {
kind: CompilationTicketKind.IncrementalResource;
compiler: NgCompiler;
modifiedResourceFiles: Set<string>;
perfRecorder: ActivePerfRecorder;
}
/**
* A request to begin Angular compilation, either starting from scratch or from a known prior state.
*
* `CompilationTicket`s are used to initialize (or update) an `NgCompiler` instance, the core of the
* Angular compiler. They abstract the starting state of compilation and allow `NgCompiler` to be
* managed independently of any incremental compilation lifecycle.
*/
export type CompilationTicket = FreshCompilationTicket|IncrementalTypeScriptCompilationTicket|
IncrementalResourceCompilationTicket;
/**
* Create a `CompilationTicket` for a brand new compilation, using no prior state.
*/
export function freshCompilationTicket(
tsProgram: ts.Program, options: NgCompilerOptions,
incrementalBuildStrategy: IncrementalBuildStrategy, programDriver: ProgramDriver,
perfRecorder: ActivePerfRecorder|null, enableTemplateTypeChecker: boolean,
usePoisonedData: boolean): CompilationTicket {
return {
kind: CompilationTicketKind.Fresh,
tsProgram,
options,
incrementalBuildStrategy,
programDriver,
enableTemplateTypeChecker,
usePoisonedData,
perfRecorder: perfRecorder ?? ActivePerfRecorder.zeroedToNow(),
};
}
/**
* Create a `CompilationTicket` as efficiently as possible, based on a previous `NgCompiler`
* instance and a new `ts.Program`.
*/
export function incrementalFromCompilerTicket(
oldCompiler: NgCompiler, newProgram: ts.Program,
incrementalBuildStrategy: IncrementalBuildStrategy, programDriver: ProgramDriver,
modifiedResourceFiles: Set<AbsoluteFsPath>,
perfRecorder: ActivePerfRecorder|null): CompilationTicket {
const oldProgram = oldCompiler.getCurrentProgram();
const oldState = oldCompiler.incrementalStrategy.getIncrementalState(oldProgram);
if (oldState === null) {
// No incremental step is possible here, since no IncrementalDriver was found for the old
// program.
return freshCompilationTicket(
newProgram, oldCompiler.options, incrementalBuildStrategy, programDriver, perfRecorder,
oldCompiler.enableTemplateTypeChecker, oldCompiler.usePoisonedData);
}
if (perfRecorder === null) {
perfRecorder = ActivePerfRecorder.zeroedToNow();
}
const incrementalCompilation = IncrementalCompilation.incremental(
newProgram, versionMapFromProgram(newProgram, programDriver), oldProgram, oldState,
modifiedResourceFiles, perfRecorder);
return {
kind: CompilationTicketKind.IncrementalTypeScript,
enableTemplateTypeChecker: oldCompiler.enableTemplateTypeChecker,
usePoisonedData: oldCompiler.usePoisonedData,
options: oldCompiler.options,
incrementalBuildStrategy,
incrementalCompilation,
programDriver,
newProgram,
perfRecorder,
};
}
/**
* Create a `CompilationTicket` directly from an old `ts.Program` and associated Angular compilation
* state, along with a new `ts.Program`.
*/
export function incrementalFromStateTicket(
oldProgram: ts.Program, oldState: IncrementalState, newProgram: ts.Program,
options: NgCompilerOptions, incrementalBuildStrategy: IncrementalBuildStrategy,
programDriver: ProgramDriver, modifiedResourceFiles: Set<AbsoluteFsPath>,
perfRecorder: ActivePerfRecorder|null, enableTemplateTypeChecker: boolean,
usePoisonedData: boolean): CompilationTicket {
if (perfRecorder === null) {
perfRecorder = ActivePerfRecorder.zeroedToNow();
}
const incrementalCompilation = IncrementalCompilation.incremental(
newProgram, versionMapFromProgram(newProgram, programDriver), oldProgram, oldState,
modifiedResourceFiles, perfRecorder);
return {
kind: CompilationTicketKind.IncrementalTypeScript,
newProgram,
options,
incrementalBuildStrategy,
incrementalCompilation,
programDriver,
enableTemplateTypeChecker,
usePoisonedData,
perfRecorder,
};
}
export function resourceChangeTicket(compiler: NgCompiler, modifiedResourceFiles: Set<string>):
IncrementalResourceCompilationTicket {
return {
kind: CompilationTicketKind.IncrementalResource,
compiler,
modifiedResourceFiles,
perfRecorder: ActivePerfRecorder.zeroedToNow(),
};
}
/**
* The heart of the Angular Ivy compiler.
*
* The `NgCompiler` provides an API for performing Angular compilation within a custom TypeScript
* compiler. Each instance of `NgCompiler` supports a single compilation, which might be
* incremental.
*
* `NgCompiler` is lazy, and does not perform any of the work of the compilation until one of its
* output methods (e.g. `getDiagnostics`) is called.
*
* See the README.md for more information.
*/
export class NgCompiler {
/**
* Lazily evaluated state of the compilation.
*
* This is created on demand by calling `ensureAnalyzed`.
*/
private compilation: LazyCompilationState|null = null;
/**
* Any diagnostics related to the construction of the compilation.
*
* These are diagnostics which arose during setup of the host and/or program.
*/
private constructionDiagnostics: ts.Diagnostic[] = [];
/**
* Non-template diagnostics related to the program itself. Does not include template
* diagnostics because the template type checker memoizes them itself.
*
* This is set by (and memoizes) `getNonTemplateDiagnostics`.
*/
private nonTemplateDiagnostics: ts.Diagnostic[]|null = null;
private closureCompilerEnabled: boolean;
private currentProgram: ts.Program;
private entryPoint: ts.SourceFile|null;
private moduleResolver: ModuleResolver;
private resourceManager: AdapterResourceLoader;
private cycleAnalyzer: CycleAnalyzer;
readonly ignoreForDiagnostics: Set<ts.SourceFile>;
readonly ignoreForEmit: Set<ts.SourceFile>;
/**
* `NgCompiler` can be reused for multiple compilations (for resource-only changes), and each
* new compilation uses a fresh `PerfRecorder`. Thus, classes created with a lifespan of the
* `NgCompiler` use a `DelegatingPerfRecorder` so the `PerfRecorder` they write to can be updated
* with each fresh compilation.
*/
private delegatingPerfRecorder = new DelegatingPerfRecorder(this.perfRecorder);
/**
* Convert a `CompilationTicket` into an `NgCompiler` instance for the requested compilation.
*
* Depending on the nature of the compilation request, the `NgCompiler` instance may be reused
* from a previous compilation and updated with any changes, it may be a new instance which
* incrementally reuses state from a previous compilation, or it may represent a fresh
* compilation entirely.
*/
static fromTicket(ticket: CompilationTicket, adapter: NgCompilerAdapter) {
switch (ticket.kind) {
case CompilationTicketKind.Fresh:
return new NgCompiler(
adapter,
ticket.options,
ticket.tsProgram,
ticket.programDriver,
ticket.incrementalBuildStrategy,
IncrementalCompilation.fresh(
ticket.tsProgram, versionMapFromProgram(ticket.tsProgram, ticket.programDriver)),
ticket.enableTemplateTypeChecker,
ticket.usePoisonedData,
ticket.perfRecorder,
);
case CompilationTicketKind.IncrementalTypeScript:
return new NgCompiler(
adapter,
ticket.options,
ticket.newProgram,
ticket.programDriver,
ticket.incrementalBuildStrategy,
ticket.incrementalCompilation,
ticket.enableTemplateTypeChecker,
ticket.usePoisonedData,
ticket.perfRecorder,
);
case CompilationTicketKind.IncrementalResource:
const compiler = ticket.compiler;
compiler.updateWithChangedResources(ticket.modifiedResourceFiles, ticket.perfRecorder);
return compiler;
}
}
private constructor(
private adapter: NgCompilerAdapter,
readonly options: NgCompilerOptions,
private inputProgram: ts.Program,
readonly programDriver: ProgramDriver,
readonly incrementalStrategy: IncrementalBuildStrategy,
readonly incrementalCompilation: IncrementalCompilation,
readonly enableTemplateTypeChecker: boolean,
readonly usePoisonedData: boolean,
private livePerfRecorder: ActivePerfRecorder,
) {
if (this.options._extendedTemplateDiagnostics === true &&
this.options.strictTemplates === false) {
throw new Error(
'The \'_extendedTemplateDiagnostics\' option requires \'strictTemplates\' to also be enabled.');
}
this.constructionDiagnostics.push(...this.adapter.constructionDiagnostics);
const incompatibleTypeCheckOptionsDiagnostic = verifyCompatibleTypeCheckOptions(this.options);
if (incompatibleTypeCheckOptionsDiagnostic !== null) {
this.constructionDiagnostics.push(incompatibleTypeCheckOptionsDiagnostic);
}
this.currentProgram = inputProgram;
this.closureCompilerEnabled = !!this.options.annotateForClosureCompiler;
this.entryPoint =
adapter.entryPoint !== null ? getSourceFileOrNull(inputProgram, adapter.entryPoint) : null;
const moduleResolutionCache = ts.createModuleResolutionCache(
this.adapter.getCurrentDirectory(),
// doen't retain a reference to `this`, if other closures in the constructor here reference
// `this` internally then a closure created here would retain them. This can cause major
// memory leak issues since the `moduleResolutionCache` is a long-lived object and finds its
// way into all kinds of places inside TS internal objects.
this.adapter.getCanonicalFileName.bind(this.adapter));
this.moduleResolver =
new ModuleResolver(inputProgram, this.options, this.adapter, moduleResolutionCache);
this.resourceManager = new AdapterResourceLoader(adapter, this.options);
this.cycleAnalyzer = new CycleAnalyzer(
new ImportGraph(inputProgram.getTypeChecker(), this.delegatingPerfRecorder));
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, inputProgram);
this.ignoreForDiagnostics =
new Set(inputProgram.getSourceFiles().filter(sf => this.adapter.isShim(sf)));
this.ignoreForEmit = this.adapter.ignoreForEmit;
let dtsFileCount = 0;
let nonDtsFileCount = 0;
for (const sf of inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
dtsFileCount++;
} else {
nonDtsFileCount++;
}
}
livePerfRecorder.eventCount(PerfEvent.InputDtsFile, dtsFileCount);
livePerfRecorder.eventCount(PerfEvent.InputTsFile, nonDtsFileCount);
}
get perfRecorder(): ActivePerfRecorder {
return this.livePerfRecorder;
}
/**
* Exposes the `IncrementalCompilation` under an old property name that the CLI uses, avoiding a
* chicken-and-egg problem with the rename to `incrementalCompilation`.
*
* TODO(alxhub): remove when the CLI uses the new name.
*/
get incrementalDriver(): IncrementalCompilation {
return this.incrementalCompilation;
}
private updateWithChangedResources(
changedResources: Set<string>, perfRecorder: ActivePerfRecorder): void {
this.livePerfRecorder = perfRecorder;
this.delegatingPerfRecorder.target = perfRecorder;
perfRecorder.inPhase(PerfPhase.ResourceUpdate, () => {
if (this.compilation === null) {
// Analysis hasn't happened yet, so no update is necessary - any changes to resources will
// be captured by the inital analysis pass itself.
return;
}
this.resourceManager.invalidate();
const classesToUpdate = new Set<DeclarationNode>();
for (const resourceFile of changedResources) {
for (const templateClass of this.getComponentsWithTemplateFile(resourceFile)) {
classesToUpdate.add(templateClass);
}
for (const styleClass of this.getComponentsWithStyleFile(resourceFile)) {
classesToUpdate.add(styleClass);
}
}
for (const clazz of classesToUpdate) {
this.compilation.traitCompiler.updateResources(clazz);
if (!ts.isClassDeclaration(clazz)) {
continue;
}
this.compilation.templateTypeChecker.invalidateClass(clazz);
}
});
}
/**
* Get the resource dependencies of a file.
*
* If the file is not part of the compilation, an empty array will be returned.
*/
getResourceDependencies(file: ts.SourceFile): string[] {
this.ensureAnalyzed();
return this.incrementalCompilation.depGraph.getResourceDependencies(file);
}
/**
* Get all Angular-related diagnostics for this compilation.
*/
getDiagnostics(): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
diagnostics.push(...this.getNonTemplateDiagnostics(), ...this.getTemplateDiagnostics());
if (this.options._extendedTemplateDiagnostics) {
diagnostics.push(...this.getExtendedTemplateDiagnostics());
}
return this.addMessageTextDetails(diagnostics);
}
/**
* Get all Angular-related diagnostics for this compilation.
*
* If a `ts.SourceFile` is passed, only diagnostics related to that file are returned.
*/
getDiagnosticsForFile(file: ts.SourceFile, optimizeFor: OptimizeFor): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
diagnostics.push(
...this.getNonTemplateDiagnostics().filter(diag => diag.file === file),
...this.getTemplateDiagnosticsForFile(file, optimizeFor));
if (this.options._extendedTemplateDiagnostics) {
diagnostics.push(...this.getExtendedTemplateDiagnostics(file));
}
return this.addMessageTextDetails(diagnostics);
}
/**
* Add Angular.io error guide links to diagnostics for this compilation.
*/
private addMessageTextDetails(diagnostics: ts.Diagnostic[]): ts.Diagnostic[] {
return diagnostics.map(diag => {
if (diag.code && COMPILER_ERRORS_WITH_GUIDES.has(ngErrorCode(diag.code))) {
return {
...diag,
messageText: diag.messageText +
`. Find more at ${ERROR_DETAILS_PAGE_BASE_URL}/NG${ngErrorCode(diag.code)}`
};
}
return diag;
});
}
/**
* Get all setup-related diagnostics for this compilation.
*/
getOptionDiagnostics(): ts.Diagnostic[] {
return this.constructionDiagnostics;
}
/**
* Get the current `ts.Program` known to this `NgCompiler`.
*
* Compilation begins with an input `ts.Program`, and during template type-checking operations new
* `ts.Program`s may be produced using the `ProgramDriver`. The most recent such `ts.Program` to
* be produced is available here.
*
* This `ts.Program` serves two key purposes:
*
* * As an incremental starting point for creating the next `ts.Program` based on files that the
* user has changed (for clients using the TS compiler program APIs).
*
* * As the "before" point for an incremental compilation invocation, to determine what's changed
* between the old and new programs (for all compilations).
*/
getCurrentProgram(): ts.Program {
return this.currentProgram;
}
getTemplateTypeChecker(): TemplateTypeChecker {
if (!this.enableTemplateTypeChecker) {
throw new Error(
'The `TemplateTypeChecker` does not work without `enableTemplateTypeChecker`.');
}
return this.ensureAnalyzed().templateTypeChecker;
}
/**
* Retrieves the `ts.Declaration`s for any component(s) which use the given template file.
*/
getComponentsWithTemplateFile(templateFilePath: string): ReadonlySet<DeclarationNode> {
const {resourceRegistry} = this.ensureAnalyzed();
return resourceRegistry.getComponentsWithTemplate(resolve(templateFilePath));
}
/**
* Retrieves the `ts.Declaration`s for any component(s) which use the given template file.
*/
getComponentsWithStyleFile(styleFilePath: string): ReadonlySet<DeclarationNode> {
const {resourceRegistry} = this.ensureAnalyzed();
return resourceRegistry.getComponentsWithStyle(resolve(styleFilePath));
}
/**
* Retrieves external resources for the given component.
*/
getComponentResources(classDecl: DeclarationNode): ComponentResources|null {
if (!isNamedClassDeclaration(classDecl)) {
return null;
}
const {resourceRegistry} = this.ensureAnalyzed();
const styles = resourceRegistry.getStyles(classDecl);
const template = resourceRegistry.getTemplate(classDecl);
if (template === null) {
return null;
}
return {styles, template};
}
getMeta(classDecl: DeclarationNode): PipeMeta|DirectiveMeta|null {
if (!isNamedClassDeclaration(classDecl)) {
return null;
}
const ref = new Reference(classDecl);
const {metaReader} = this.ensureAnalyzed();
const meta = metaReader.getPipeMetadata(ref) ?? metaReader.getDirectiveMetadata(ref);
if (meta === null) {
return null;
}
return meta;
}
/**
* Perform Angular's analysis step (as a precursor to `getDiagnostics` or `prepareEmit`)
* asynchronously.
*
* Normally, this operation happens lazily whenever `getDiagnostics` or `prepareEmit` are called.
* However, certain consumers may wish to allow for an asynchronous phase of analysis, where
* resources such as `styleUrls` are resolved asynchonously. In these cases `analyzeAsync` must be
* called first, and its `Promise` awaited prior to calling any other APIs of `NgCompiler`.
*/
async analyzeAsync(): Promise<void> {
if (this.compilation !== null) {
return;
}
await this.perfRecorder.inPhase(PerfPhase.Analysis, async () => {
this.compilation = this.makeCompilation();
const promises: Promise<void>[] = [];
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
continue;
}
let analysisPromise = this.compilation.traitCompiler.analyzeAsync(sf);
if (analysisPromise !== undefined) {
promises.push(analysisPromise);
}
}
await Promise.all(promises);
this.perfRecorder.memory(PerfCheckpoint.Analysis);
this.resolveCompilation(this.compilation.traitCompiler);
});
}
/**
* List lazy routes detected during analysis.
*
* This can be called for one specific route, or to retrieve all top-level routes.
*/
listLazyRoutes(entryRoute?: string): LazyRoute[] {
if (entryRoute) {
// htts://github.com/angular/angular/blob/50732e156/packages/compiler-cli/src/transformers/compiler_host.ts#L175-L188).
//
// `@angular/cli` will always call this API with an absolute path, so the resolution step is
// not necessary, but keeping it backwards compatible in case someone else is using the API.
// Relative entry paths are disallowed.
if (entryRoute.startsWith('.')) {
throw new Error(`Failed to list lazy routes: Resolution of relative paths (${
entryRoute}) is not supported.`);
}
// Non-relative entry paths fall into one of the following categories:
// - Absolute system paths (e.g. `/foo/bar/my-project/my-module`), which are unaffected by the
// logic below.
// - Paths to enternal modules (e.g. `some-lib`).
// - Paths mapped to directories in `tsconfig.json` (e.g. `shared/my-module`).
// (See https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping.)
//
// In all cases above, the `containingFile` argument is ignored, so we can just take the first
// of the root files.
const containingFile = this.inputProgram.getRootFileNames()[0];
const [entryPath, moduleName] = entryRoute.split('#');
const resolvedModule =
resolveModuleName(entryPath, containingFile, this.options, this.adapter, null);
if (resolvedModule) {
entryRoute = entryPointKeyFor(resolvedModule.resolvedFileName, moduleName);
}
}
const compilation = this.ensureAnalyzed();
return compilation.routeAnalyzer.listLazyRoutes(entryRoute);
}
/**
* Fetch transformers and other information which is necessary for a consumer to `emit` the
* program with Angular-added definitions.
*/
prepareEmit(): {
transformers: ts.CustomTransformers,
} {
const compilation = this.ensureAnalyzed();
const coreImportsFrom = compilation.isCore ? getR3SymbolsFile(this.inputProgram) : null;
let importRewriter: ImportRewriter;
if (coreImportsFrom !== null) {
importRewriter = new R3SymbolsImportRewriter(coreImportsFrom.fileName);
} else {
importRewriter = new NoopImportRewriter();
}
const defaultImportTracker = new DefaultImportTracker();
const before = [
ivyTransformFactory(
compilation.traitCompiler, compilation.reflector, importRewriter, defaultImportTracker,
this.delegatingPerfRecorder, compilation.isCore, this.closureCompilerEnabled),
aliasTransformFactory(compilation.traitCompiler.exportStatements),
defaultImportTracker.importPreservingTransformer(),
];
const afterDeclarations: ts.TransformerFactory<ts.SourceFile>[] = [];
if (compilation.dtsTransforms !== null) {
afterDeclarations.push(
declarationTransformFactory(compilation.dtsTransforms, importRewriter));
}
// Only add aliasing re-exports to the .d.ts output if the `AliasingHost` requests it.
if (compilation.aliasingHost !== null && compilation.aliasingHost.aliasExportsInDts) {
afterDeclarations.push(aliasTransformFactory(compilation.traitCompiler.exportStatements));
}
if (this.adapter.factoryTracker !== null) {
before.push(
generatedFactoryTransform(this.adapter.factoryTracker.sourceInfo, importRewriter));
}
before.push(ivySwitchTransform);
return {transformers: {before, afterDeclarations} as ts.CustomTransformers};
}
/**
* Run the indexing process and return a `Map` of all indexed components.
*
* See the `indexing` package for more details.
*/
getIndexedComponents(): Map<DeclarationNode, IndexedComponent> {
const compilation = this.ensureAnalyzed();
const context = new IndexingContext();
compilation.traitCompiler.index(context);
return generateAnalysis(context);
}
/**
* Collect i18n messages into the `Xi18nContext`.
*/
xi18n(ctx: Xi18nContext): void {
// Note that the 'resolve' phase is not strictly necessary for xi18n, but this is not currently
// optimized.
const compilation = this.ensureAnalyzed();
compilation.traitCompiler.xi18n(ctx);
}
private ensureAnalyzed(this: NgCompiler): LazyCompilationState {
if (this.compilation === null) {
this.analyzeSync();
}
return this.compilation!;
}
private analyzeSync(): void {
this.perfRecorder.inPhase(PerfPhase.Analysis, () => {
this.compilation = this.makeCompilation();
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
continue;
}
this.compilation.traitCompiler.analyzeSync(sf);
}
this.perfRecorder.memory(PerfCheckpoint.Analysis);
this.resolveCompilation(this.compilation.traitCompiler);
});
}
private resolveCompilation(traitCompiler: TraitCompiler): void {
this.perfRecorder.inPhase(PerfPhase.Resolve, () => {
traitCompiler.resolve();
// At this point, analysis is complete and the compiler can now calculate which files need to
// be emitted, so do that.
this.incrementalCompilation.recordSuccessfulAnalysis(traitCompiler);
this.perfRecorder.memory(PerfCheckpoint.Resolve);
});
}
private get fullTemplateTypeCheck(): boolean {
// Determine the strictness level of type checking based on compiler options. As
// `strictTemplates` is a superset of `fullTemplateTypeCheck`, the former implies the latter.
// Also see `verifyCompatibleTypeCheckOptions` where it is verified that `fullTemplateTypeCheck`
// is not disabled when `strictTemplates` is enabled.
const strictTemplates = !!this.options.strictTemplates;
return strictTemplates || !!this.options.fullTemplateTypeCheck;
}
private getTypeCheckingConfig(): TypeCheckingConfig {
// Determine the strictness level of type checking based on compiler options. As
// `strictTemplates` is a superset of `fullTemplateTypeCheck`, the former implies the latter.
// Also see `verifyCompatibleTypeCheckOptions` where it is verified that `fullTemplateTypeCheck`
// is not disabled when `strictTemplates` is enabled.
const strictTemplates = !!this.options.strictTemplates;
const useInlineTypeConstructors = this.programDriver.supportsInlineOperations;
// First select a type-checking configuration, based on whether full template type-checking is
// requested.
let typeCheckingConfig: TypeCheckingConfig;
if (this.fullTemplateTypeCheck) {
typeCheckingConfig = {
applyTemplateContextGuards: strictTemplates,
checkQueries: false,
checkTemplateBodies: true,
alwaysCheckSchemaInTemplateBodies: true,
checkTypeOfInputBindings: strictTemplates,
honorAccessModifiersForInputBindings: false,
strictNullInputBindings: strictTemplates,
checkTypeOfAttributes: strictTemplates,
// Even in full template type-checking mode, DOM binding checks are not quite ready yet.
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: strictTemplates,
checkTypeOfAnimationEvents: strictTemplates,
// Checking of DOM events currently has an adverse effect on developer experience,
// e.g. for `<input (blur)="update($event.target.value)">` enabling this check results in:
// - error TS2531: Object is possibly 'null'.
// - error TS2339: Property 'value' does not exist on type 'EventTarget'.
checkTypeOfDomEvents: strictTemplates,
checkTypeOfDomReferences: strictTemplates,
// Non-DOM references have the correct type in View Engine so there is no strictness flag.
checkTypeOfNonDomReferences: true,
// Pipes are checked in View Engine so there is no strictness flag.
checkTypeOfPipes: true,
strictSafeNavigationTypes: strictTemplates,
useContextGenericType: strictTemplates,
strictLiteralTypes: true,
enableTemplateTypeChecker: this.enableTemplateTypeChecker,
useInlineTypeConstructors,
// Warnings for suboptimal type inference are only enabled if in Language Service mode
// (providing the full TemplateTypeChecker API) and if strict mode is not enabled. In strict
// mode, the user is in full control of type inference.
suggestionsForSuboptimalTypeInference: this.enableTemplateTypeChecker && !strictTemplates,
};
} else {
typeCheckingConfig = {
applyTemplateContextGuards: false,
checkQueries: false,
checkTemplateBodies: false,
// Enable deep schema checking in "basic" template type-checking mode only if Closure
// compilation is requested, which is a good proxy for "only in google3".
alwaysCheckSchemaInTemplateBodies: this.closureCompilerEnabled,
checkTypeOfInputBindings: false,
strictNullInputBindings: false,
honorAccessModifiersForInputBindings: false,
checkTypeOfAttributes: false,
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: false,
checkTypeOfAnimationEvents: false,
checkTypeOfDomEvents: false,
checkTypeOfDomReferences: false,
checkTypeOfNonDomReferences: false,
checkTypeOfPipes: false,
strictSafeNavigationTypes: false,
useContextGenericType: false,
strictLiteralTypes: false,
enableTemplateTypeChecker: this.enableTemplateTypeChecker,
useInlineTypeConstructors,
// In "basic" template type-checking mode, no warnings are produced since most things are
// not checked anyways.
suggestionsForSuboptimalTypeInference: false,
};
}
// Apply explicitly configured strictness flags on top of the default configuration
// based on "fullTemplateTypeCheck".
if (this.options.strictInputTypes !== undefined) {
typeCheckingConfig.checkTypeOfInputBindings = this.options.strictInputTypes;
typeCheckingConfig.applyTemplateContextGuards = this.options.strictInputTypes;
}
if (this.options.strictInputAccessModifiers !== undefined) {
typeCheckingConfig.honorAccessModifiersForInputBindings =
this.options.strictInputAccessModifiers;
}
if (this.options.strictNullInputTypes !== undefined) {
typeCheckingConfig.strictNullInputBindings = this.options.strictNullInputTypes;
}
if (this.options.strictOutputEventTypes !== undefined) {
typeCheckingConfig.checkTypeOfOutputEvents = this.options.strictOutputEventTypes;
typeCheckingConfig.checkTypeOfAnimationEvents = this.options.strictOutputEventTypes;
}
if (this.options.strictDomEventTypes !== undefined) {
typeCheckingConfig.checkTypeOfDomEvents = this.options.strictDomEventTypes;
}
if (this.options.strictSafeNavigationTypes !== undefined) {
typeCheckingConfig.strictSafeNavigationTypes = this.options.strictSafeNavigationTypes;
}
if (this.options.strictDomLocalRefTypes !== undefined) {
typeCheckingConfig.checkTypeOfDomReferences = this.options.strictDomLocalRefTypes;
}
if (this.options.strictAttributeTypes !== undefined) {
typeCheckingConfig.checkTypeOfAttributes = this.options.strictAttributeTypes;
}
if (this.options.strictContextGenerics !== undefined) {
typeCheckingConfig.useContextGenericType = this.options.strictContextGenerics;
}
if (this.options.strictLiteralTypes !== undefined) {
typeCheckingConfig.strictLiteralTypes = this.options.strictLiteralTypes;
}
return typeCheckingConfig;
}
private getTemplateDiagnostics(): ReadonlyArray<ts.Diagnostic> {
const compilation = this.ensureAnalyzed();
// Get the diagnostics.
const diagnostics: ts.Diagnostic[] = [];
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile || this.adapter.isShim(sf)) {
continue;
}
diagnostics.push(
...compilation.templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram));
}
const program = this.programDriver.getProgram();
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, program);
this.currentProgram = program;
return diagnostics;
}
private getTemplateDiagnosticsForFile(sf: ts.SourceFile, optimizeFor: OptimizeFor):
ReadonlyArray<ts.Diagnostic> {
const compilation = this.ensureAnalyzed();
// Get the diagnostics.
const diagnostics: ts.Diagnostic[] = [];
if (!sf.isDeclarationFile && !this.adapter.isShim(sf)) {
diagnostics.push(...compilation.templateTypeChecker.getDiagnosticsForFile(sf, optimizeFor));
}
const program = this.programDriver.getProgram();
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, program);
this.currentProgram = program;
return diagnostics;
}
private getNonTemplateDiagnostics(): ts.Diagnostic[] {
if (this.nonTemplateDiagnostics === null) {
const compilation = this.ensureAnalyzed();
this.nonTemplateDiagnostics = [...compilation.traitCompiler.diagnostics];
if (this.entryPoint !== null && compilation.exportReferenceGraph !== null) {
this.nonTemplateDiagnostics.push(...checkForPrivateExports(
this.entryPoint, this.inputProgram.getTypeChecker(), compilation.exportReferenceGraph));
}
}
return this.nonTemplateDiagnostics;
}
/**
* Calls the `extendedTemplateCheck` phase of the trait compiler
* @param sf optional parameter to get diagnostics for a certain file
* or all files in the program if `sf` is undefined
* @returns generated extended template diagnostics
*/
private getExtendedTemplateDiagnostics(sf?: ts.SourceFile): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
const compilation = this.ensureAnalyzed();
const typeChecker = this.inputProgram.getTypeChecker();
const templateChecks = [new InvalidBananaInBoxCheck()];
const extendedTemplateChecker = new ExtendedTemplateCheckerImpl(
compilation.templateTypeChecker, typeChecker, templateChecks);
if (sf !== undefined) {
return compilation.traitCompiler.extendedTemplateCheck(sf, extendedTemplateChecker);
}
for (const sf of this.inputProgram.getSourceFiles()) {
diagnostics.push(
...compilation.traitCompiler.extendedTemplateCheck(sf, extendedTemplateChecker));
}
return diagnostics;
}
private makeCompilation(): LazyCompilationState {
const checker = this.inputProgram.getTypeChecker();
const reflector = new TypeScriptReflectionHost(checker);
// Construct the ReferenceEmitter.
let refEmitter: ReferenceEmitter;
let aliasingHost: AliasingHost|null = null;
if (this.adapter.unifiedModulesHost === null || !this.options._useHostForImportGeneration) {
let localImportStrategy: ReferenceEmitStrategy;
// The strategy used for local, in-project imports depends on whether TS has been configured
// with rootDirs. If so, then multiple directories may be mapped in the same "module
// namespace" and the logic of `LogicalProjectStrategy` is required to generate correct
// imports which may cross these multiple directories. Otherwise, plain relative imports are
// sufficient.
if (this.options.rootDir !== undefined ||
(this.options.rootDirs !== undefined && this.options.rootDirs.length > 0)) {
// rootDirs logic is in effect - use the `LogicalProjectStrategy` for in-project relative
// imports.
localImportStrategy = new LogicalProjectStrategy(
reflector, new LogicalFileSystem([...this.adapter.rootDirs], this.adapter));
} else {
// Plain relative imports are all that's needed.
localImportStrategy = new RelativePathStrategy(reflector);
}
// The CompilerHost doesn't have fileNameToModuleName, so build an NPM-centric reference
// resolution strategy.
refEmitter = new ReferenceEmitter([
// First, try to use local identifiers if available.
new LocalIdentifierStrategy(),
// Next, attempt to use an absolute import.
new AbsoluteModuleStrategy(this.inputProgram, checker, this.moduleResolver, reflector),
// Finally, check if the reference is being written into a file within the project's .ts
// sources, and use a relative import if so. If this fails, ReferenceEmitter will throw
// an error.
localImportStrategy,
]);
// If an entrypoint is present, then all user imports should be directed through the
// entrypoint and private exports are not needed. The compiler will validate that all publicly
// visible directives/pipes are importable via this entrypoint.
if (this.entryPoint === null && this.options.generateDeepReexports === true) {
// No entrypoint is present and deep re-exports were requested, so configure the aliasing
// system to generate them.
aliasingHost = new PrivateExportAliasingHost(reflector);
}
} else {
// The CompilerHost supports fileNameToModuleName, so use that to emit imports.
refEmitter = new ReferenceEmitter([
// First, try to use local identifiers if available.
new LocalIdentifierStrategy(),
// Then use aliased references (this is a workaround to StrictDeps checks).
new AliasStrategy(),
// Then use fileNameToModuleName to emit imports.
new UnifiedModulesStrategy(reflector, this.adapter.unifiedModulesHost),
]);
aliasingHost = new UnifiedModulesAliasingHost(this.adapter.unifiedModulesHost);
}
const evaluator =
new PartialEvaluator(reflector, checker, this.incrementalCompilation.depGraph);
const dtsReader = new DtsMetadataReader(checker, reflector);
const localMetaRegistry = new LocalMetadataRegistry();
const localMetaReader: MetadataReader = localMetaRegistry;