-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
builder.ts
2480 lines (2340 loc) · 114 KB
/
builder.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 {
addRange,
AffectedFileResult,
append,
arrayFrom,
arrayToMap,
BuilderProgram,
BuilderProgramHost,
BuilderState,
BuildInfo,
BuildInfoFileVersionMap,
CancellationToken,
CommandLineOption,
compareStringsCaseSensitive,
compareValues,
CompilerHost,
CompilerOptions,
compilerOptionsAffectDeclarationPath,
compilerOptionsAffectEmit,
compilerOptionsAffectSemanticDiagnostics,
CompilerOptionsValue,
concatenate,
convertToOptionsWithAbsolutePaths,
createGetCanonicalFileName,
createModeMismatchDetails,
createModuleNotFoundChain,
createProgram,
CustomTransformers,
Debug,
Diagnostic,
DiagnosticCategory,
DiagnosticMessageChain,
DiagnosticRelatedInformation,
DiagnosticWithLocation,
EmitAndSemanticDiagnosticsBuilderProgram,
EmitOnly,
EmitResult,
emitSkippedWithNoDiagnostics,
emptyArray,
ensurePathIsNonModuleName,
FileIncludeKind,
filterSemanticDiagnostics,
forEach,
forEachEntry,
forEachKey,
generateDjb2Hash,
getDirectoryPath,
getEmitDeclarations,
getIsolatedModules,
getNormalizedAbsolutePath,
getOptionsNameMap,
getOwnKeys,
getRelativePathFromDirectory,
getSourceFileOfNode,
getTsBuildInfoEmitOutputFilePath,
handleNoEmitOptions,
HostForComputeHash,
isArray,
isDeclarationFileName,
isIncrementalCompilation,
isJsonSourceFile,
isNumber,
isString,
map,
mapDefinedIterator,
maybeBind,
noop,
notImplemented,
Path,
Program,
ProjectReference,
ReadBuildProgramHost,
ReadonlyCollection,
RepopulateDiagnosticChainInfo,
returnFalse,
returnUndefined,
sameMap,
SemanticDiagnosticsBuilderProgram,
SignatureInfo,
skipAlias,
skipTypeCheckingIgnoringNoCheck,
some,
SourceFile,
sourceFileMayBeEmitted,
SourceMapEmitResult,
SymbolFlags,
toPath,
tryAddToSet,
version,
WriteFileCallback,
WriteFileCallbackData,
} from "./_namespaces/ts.js";
/** @internal */
export interface ReusableDiagnostic extends ReusableDiagnosticRelatedInformation {
/** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
reportsUnnecessary?: {};
reportDeprecated?: {};
source?: string;
relatedInformation?: ReusableDiagnosticRelatedInformation[];
skippedOn?: keyof CompilerOptions;
}
/** @internal */
export interface ReusableDiagnosticRelatedInformation {
category: DiagnosticCategory;
code: number;
file: string | undefined | false;
start: number | undefined;
length: number | undefined;
messageText: string | ReusableDiagnosticMessageChain;
}
/** @internal */
export interface ReusableRepopulateInfoChain {
info: RepopulateDiagnosticChainInfo;
next?: ReusableDiagnosticMessageChain[];
}
/** @internal */
export type SerializedDiagnosticMessageChain = Omit<DiagnosticMessageChain, "next" | "repopulateInfo"> & {
next?: ReusableDiagnosticMessageChain[];
};
/** @internal */
export type ReusableDiagnosticMessageChain = SerializedDiagnosticMessageChain | ReusableRepopulateInfoChain;
/**
* Signature (Hash of d.ts emitted), is string if it was emitted using same d.ts.map option as what compilerOptions indicate, otherwise tuple of string
*
* @internal
*/
export type EmitSignature = string | [signature: string];
/** @internal */
export interface ReusableBuilderProgramState extends BuilderState {
/**
* Cache of bind and check diagnostics for files with their Path being the key
*/
semanticDiagnosticsPerFile: Map<Path, readonly ReusableDiagnostic[] | readonly Diagnostic[]>;
/** Cache of dts emit diagnostics for files with their Path being the key */
emitDiagnosticsPerFile?: Map<Path, readonly ReusableDiagnostic[] | readonly Diagnostic[]> | undefined;
/**
* The map has key by source file's path that has been changed
*/
changedFilesSet?: Set<Path>;
/**
* program corresponding to this state
*/
program?: Program | undefined;
/**
* compilerOptions for the program
*/
compilerOptions: CompilerOptions;
/**
* Files pending to be emitted
*/
affectedFilesPendingEmit?: ReadonlyMap<Path, BuilderFileEmit>;
/**
* emitKind pending for a program with --out
*/
programEmitPending?: BuilderFileEmit;
/** If semantic diagnsotic check is pending */
checkPending?: true;
/*
* true if semantic diagnostics are ReusableDiagnostic instead of Diagnostic
*/
hasReusableDiagnostic?: true;
/**
* Hash of d.ts emitted for the file, use to track when emit of d.ts changes
*/
emitSignatures?: Map<Path, EmitSignature>;
/**
* Hash of d.ts emit with --out
*/
outSignature?: EmitSignature;
/**
* Name of the file whose dts was the latest to change
*/
latestChangedDtsFile: string | undefined;
/** Recorded if program had errors */
hasErrors?: boolean;
}
// dprint-ignore
/** @internal */
export const enum BuilderFileEmit {
None = 0,
Js = 1 << 0, // emit js file
JsMap = 1 << 1, // emit js.map file
JsInlineMap = 1 << 2, // emit inline source map in js file
DtsErrors = 1 << 3, // emit dts errors
DtsEmit = 1 << 4, // emit d.ts file
DtsMap = 1 << 5, // emit d.ts.map file
Dts = DtsErrors | DtsEmit,
AllJs = Js | JsMap | JsInlineMap,
AllDtsEmit = DtsEmit | DtsMap,
AllDts = Dts | DtsMap,
All = AllJs | AllDts,
}
/**
* State to store the changed files, affected files and cache semantic diagnostics
*
* @internal
*/
// TODO: GH#18217 Properties of this interface are frequently asserted to be defined.
export interface BuilderProgramState extends BuilderState, ReusableBuilderProgramState {
/**
* Cache of bind and check diagnostics for files with their Path being the key
*/
semanticDiagnosticsPerFile: Map<Path, readonly Diagnostic[]>;
/** Cache of dts emit diagnostics for files with their Path being the key */
emitDiagnosticsPerFile?: Map<Path, readonly Diagnostic[]> | undefined;
/**
* The map has key by source file's path that has been changed
*/
changedFilesSet: Set<Path>;
/**
* Set of affected files being iterated
*/
affectedFiles?: readonly SourceFile[] | undefined;
/**
* Current index to retrieve affected file from
*/
affectedFilesIndex: number | undefined;
/**
* Current changed file for iterating over affected files
*/
currentChangedFilePath?: Path | undefined;
/**
* Already seen affected files
*/
seenAffectedFiles: Set<Path> | undefined;
/**
* whether this program has cleaned semantic diagnostics cache for lib files
*/
cleanedDiagnosticsOfLibFiles?: boolean;
/**
* True if the semantic diagnostics were copied from the old state
*/
semanticDiagnosticsFromOldState?: Set<Path>;
/**
* Records if change in dts emit was detected
*/
hasChangedEmitSignature?: boolean;
/**
* Files pending to be emitted
*/
affectedFilesPendingEmit?: Map<Path, BuilderFileEmit>;
/**
* true if build info is emitted
*/
buildInfoEmitPending: boolean;
/**
* Already seen emitted files
*/
seenEmittedFiles: Map<Path, BuilderFileEmit> | undefined;
/** Already seen program emit */
seenProgramEmit: BuilderFileEmit | undefined;
hasErrorsFromOldState?: boolean;
}
interface BuilderProgramStateWithDefinedProgram extends BuilderProgramState {
program: Program;
}
function isBuilderProgramStateWithDefinedProgram(state: ReusableBuilderProgramState): state is BuilderProgramStateWithDefinedProgram {
return state.program !== undefined;
}
function toBuilderProgramStateWithDefinedProgram(state: ReusableBuilderProgramState): BuilderProgramStateWithDefinedProgram {
Debug.assert(isBuilderProgramStateWithDefinedProgram(state));
return state;
}
/**
* Get flags determining what all needs to be emitted
*
* @internal
*/
export function getBuilderFileEmit(options: CompilerOptions): BuilderFileEmit {
let result = BuilderFileEmit.Js;
if (options.sourceMap) result = result | BuilderFileEmit.JsMap;
if (options.inlineSourceMap) result = result | BuilderFileEmit.JsInlineMap;
if (getEmitDeclarations(options)) result = result | BuilderFileEmit.Dts;
if (options.declarationMap) result = result | BuilderFileEmit.DtsMap;
if (options.emitDeclarationOnly) result = result & BuilderFileEmit.AllDts;
return result;
}
function getPendingEmitKind(
optionsOrEmitKind: CompilerOptions | BuilderFileEmit,
oldOptionsOrEmitKind: CompilerOptions | BuilderFileEmit | undefined,
): BuilderFileEmit {
const oldEmitKind = oldOptionsOrEmitKind && (isNumber(oldOptionsOrEmitKind) ? oldOptionsOrEmitKind : getBuilderFileEmit(oldOptionsOrEmitKind));
const emitKind = isNumber(optionsOrEmitKind) ? optionsOrEmitKind : getBuilderFileEmit(optionsOrEmitKind);
if (oldEmitKind === emitKind) return BuilderFileEmit.None;
if (!oldEmitKind || !emitKind) return emitKind;
const diff = oldEmitKind ^ emitKind;
let result = BuilderFileEmit.None;
// If there is diff in Js emit, pending emit is js emit flags
if (diff & BuilderFileEmit.AllJs) result = emitKind & BuilderFileEmit.AllJs;
// If dts errors pending, add dts errors flag
if (diff & BuilderFileEmit.DtsErrors) result = result | (emitKind & BuilderFileEmit.DtsErrors);
// If there is diff in Dts emit, pending emit is dts emit flags
if (diff & BuilderFileEmit.AllDtsEmit) result = result | (emitKind & BuilderFileEmit.AllDtsEmit);
return result;
}
function hasSameKeys(
map1: ReadonlyCollection<string> | undefined,
map2: ReadonlyCollection<string> | undefined,
): boolean {
// Has same size and every key is present in both maps
return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !forEachKey(map1, key => !map2.has(key));
}
/**
* Create the state so that we can iterate on changedFiles/affected files
*/
function createBuilderProgramState(
newProgram: Program,
oldState: Readonly<ReusableBuilderProgramState> | undefined,
): BuilderProgramState {
const state = BuilderState.create(newProgram, oldState, /*disableUseFileVersionAsSignature*/ false) as BuilderProgramState;
state.program = newProgram;
const compilerOptions = newProgram.getCompilerOptions();
state.compilerOptions = compilerOptions;
const outFilePath = compilerOptions.outFile;
state.semanticDiagnosticsPerFile = new Map();
if (outFilePath && compilerOptions.composite && oldState?.outSignature && outFilePath === oldState.compilerOptions.outFile) {
state.outSignature = oldState.outSignature && getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldState.outSignature);
}
state.changedFilesSet = new Set();
state.latestChangedDtsFile = compilerOptions.composite ? oldState?.latestChangedDtsFile : undefined;
state.checkPending = state.compilerOptions.noCheck ? true : undefined;
const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState);
const oldCompilerOptions = useOldState ? oldState!.compilerOptions : undefined;
let canCopySemanticDiagnostics = useOldState &&
!compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions!);
// We can only reuse emit signatures (i.e. .d.ts signatures) if the .d.ts file is unchanged,
// which will eg be depedent on change in options like declarationDir and outDir options are unchanged.
// We need to look in oldState.compilerOptions, rather than oldCompilerOptions (i.e.we need to disregard useOldState) because
// oldCompilerOptions can be undefined if there was change in say module from None to some other option
// which would make useOldState as false since we can now use reference maps that are needed to track what to emit, what to check etc
// but that option change does not affect d.ts file name so emitSignatures should still be reused.
const canCopyEmitSignatures = compilerOptions.composite &&
oldState?.emitSignatures &&
!outFilePath &&
!compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions);
let canCopyEmitDiagnostics = true;
if (useOldState) {
// Copy old state's changed files set
oldState!.changedFilesSet?.forEach(value => state.changedFilesSet.add(value));
if (!outFilePath && oldState!.affectedFilesPendingEmit?.size) {
state.affectedFilesPendingEmit = new Map(oldState!.affectedFilesPendingEmit);
state.seenAffectedFiles = new Set();
}
state.programEmitPending = oldState!.programEmitPending;
// If there is changeSet with --outFile, cannot copy semantic diagnsotics or emitDiagnostics
// as they all need to be calculated again all together since we dont know whats the affected file set because of the way d.ts works
if (outFilePath && state.changedFilesSet.size) {
canCopySemanticDiagnostics = false;
canCopyEmitDiagnostics = false;
}
state.hasErrorsFromOldState = oldState!.hasErrors;
}
else {
// We arent using old state, so atleast emit buildInfo with current information
state.buildInfoEmitPending = isIncrementalCompilation(compilerOptions);
}
// Update changed files and copy semantic diagnostics if we can
const referencedMap = state.referencedMap;
const oldReferencedMap = useOldState ? oldState!.referencedMap : undefined;
const copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions!.skipLibCheck;
const copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions!.skipDefaultLibCheck;
state.fileInfos.forEach((info, sourceFilePath) => {
let oldInfo: Readonly<BuilderState.FileInfo> | undefined;
let newReferences: ReadonlySet<Path> | undefined;
// if not using old state, every file is changed
if (
!useOldState ||
// File wasn't present in old state
!(oldInfo = oldState!.fileInfos.get(sourceFilePath)) ||
// versions dont match
oldInfo.version !== info.version ||
// Implied formats dont match
oldInfo.impliedFormat !== info.impliedFormat ||
// Referenced files changed
!hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) ||
// Referenced file was deleted in the new program
newReferences && forEachKey(newReferences, path => !state.fileInfos.has(path) && oldState!.fileInfos.has(path))
) {
// Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
addFileToChangeSet(sourceFilePath);
}
else {
const sourceFile = newProgram.getSourceFileByPath(sourceFilePath)!;
const emitDiagnostics = canCopyEmitDiagnostics ?
oldState!.emitDiagnosticsPerFile?.get(sourceFilePath) : undefined;
if (emitDiagnostics) {
(state.emitDiagnosticsPerFile ??= new Map()).set(
sourceFilePath,
oldState!.hasReusableDiagnostic ?
convertToDiagnostics(emitDiagnostics as readonly ReusableDiagnostic[], sourceFilePath, newProgram) :
repopulateDiagnostics(emitDiagnostics as readonly Diagnostic[], newProgram),
);
}
if (canCopySemanticDiagnostics) {
if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) return;
if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) return;
// Unchanged file copy diagnostics
const diagnostics = oldState!.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
state.semanticDiagnosticsPerFile.set(
sourceFilePath,
oldState!.hasReusableDiagnostic ?
convertToDiagnostics(diagnostics as readonly ReusableDiagnostic[], sourceFilePath, newProgram) :
repopulateDiagnostics(diagnostics as readonly Diagnostic[], newProgram),
);
(state.semanticDiagnosticsFromOldState ??= new Set()).add(sourceFilePath);
}
}
}
if (canCopyEmitSignatures) {
const oldEmitSignature = oldState.emitSignatures.get(sourceFilePath);
if (oldEmitSignature) {
(state.emitSignatures ??= new Map()).set(sourceFilePath, getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldEmitSignature));
}
}
});
// If the global file is removed, add all files as changed
if (
useOldState && forEachEntry(oldState!.fileInfos, (info, sourceFilePath) => {
if (state.fileInfos.has(sourceFilePath)) return false;
if (info.affectsGlobalScope) return true;
// if file is deleted we need to write buildInfo again
state.buildInfoEmitPending = true;
return !!outFilePath;
})
) {
BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
.forEach(file => addFileToChangeSet(file.resolvedPath));
}
else if (oldCompilerOptions) {
// If options affect emit, then we need to do complete emit per compiler options
// otherwise only the js or dts that needs to emitted because its different from previously emitted options
const pendingEmitKind = compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions) ?
getBuilderFileEmit(compilerOptions) :
getPendingEmitKind(compilerOptions, oldCompilerOptions);
if (pendingEmitKind !== BuilderFileEmit.None) {
if (!outFilePath) {
// Add all files to affectedFilesPendingEmit since emit changed
newProgram.getSourceFiles().forEach(f => {
// Add to affectedFilesPending emit only if not changed since any changed file will do full emit
if (!state.changedFilesSet.has(f.resolvedPath)) {
addToAffectedFilesPendingEmit(
state,
f.resolvedPath,
pendingEmitKind,
);
}
});
Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
state.seenAffectedFiles = state.seenAffectedFiles || new Set();
}
else if (!state.changedFilesSet.size) {
state.programEmitPending = state.programEmitPending ?
state.programEmitPending | pendingEmitKind :
pendingEmitKind;
}
state.buildInfoEmitPending = true;
}
}
if (
useOldState &&
state.semanticDiagnosticsPerFile.size !== state.fileInfos.size &&
oldState!.checkPending !== state.checkPending
) state.buildInfoEmitPending = true;
return state;
function addFileToChangeSet(path: Path) {
state.changedFilesSet.add(path);
if (outFilePath) {
// If there is changeSet with --outFile, cannot copy semantic diagnsotics or emitDiagnostics
// as they all need to be calculated again all together since we dont know whats the affected file set because of the way d.ts works
canCopySemanticDiagnostics = false;
canCopyEmitDiagnostics = false;
state.semanticDiagnosticsFromOldState = undefined;
state.semanticDiagnosticsPerFile.clear();
state.emitDiagnosticsPerFile = undefined;
}
state.buildInfoEmitPending = true;
// Setting this to undefined as changed files means full emit so no need to track emit explicitly
state.programEmitPending = undefined;
}
}
/**
* Covert to Emit signature based on oldOptions and EmitSignature format
* If d.ts map options differ then swap the format, otherwise use as is
*/
function getEmitSignatureFromOldSignature(
options: CompilerOptions,
oldOptions: CompilerOptions,
oldEmitSignature: EmitSignature,
): EmitSignature {
return !!options.declarationMap === !!oldOptions.declarationMap ?
// Use same format of signature
oldEmitSignature :
// Convert to different format
isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0];
}
function repopulateDiagnostics(
diagnostics: readonly Diagnostic[],
newProgram: Program,
): readonly Diagnostic[] {
if (!diagnostics.length) return diagnostics;
return sameMap(diagnostics, diag => {
if (isString(diag.messageText)) return diag;
const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag.messageText, diag.file, newProgram, chain => chain.repopulateInfo?.());
return repopulatedChain === diag.messageText ?
diag :
{ ...diag, messageText: repopulatedChain };
});
}
function convertOrRepopulateDiagnosticMessageChain<T extends DiagnosticMessageChain | ReusableDiagnosticMessageChain>(
chain: T,
sourceFile: SourceFile | undefined,
newProgram: Program,
repopulateInfo: (chain: T) => RepopulateDiagnosticChainInfo | undefined,
): DiagnosticMessageChain {
const info = repopulateInfo(chain);
if (info === true) {
return {
...createModeMismatchDetails(sourceFile!),
next: convertOrRepopulateDiagnosticMessageChainArray(chain.next as T[], sourceFile, newProgram, repopulateInfo),
};
}
else if (info) {
return {
...createModuleNotFoundChain(sourceFile!, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference),
next: convertOrRepopulateDiagnosticMessageChainArray(chain.next as T[], sourceFile, newProgram, repopulateInfo),
};
}
const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next as T[], sourceFile, newProgram, repopulateInfo);
return next === chain.next ? chain as DiagnosticMessageChain : { ...chain as DiagnosticMessageChain, next };
}
function convertOrRepopulateDiagnosticMessageChainArray<T extends DiagnosticMessageChain | ReusableDiagnosticMessageChain>(
array: T[] | undefined,
sourceFile: SourceFile | undefined,
newProgram: Program,
repopulateInfo: (chain: T) => RepopulateDiagnosticChainInfo | undefined,
): DiagnosticMessageChain[] | undefined {
return sameMap(array, chain => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo));
}
function convertToDiagnostics(
diagnostics: readonly ReusableDiagnostic[],
diagnosticFilePath: Path,
newProgram: Program,
): readonly Diagnostic[] {
if (!diagnostics.length) return emptyArray;
let buildInfoDirectory: string | undefined;
return diagnostics.map(diagnostic => {
const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, diagnosticFilePath, newProgram, toPathInBuildInfoDirectory);
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
result.reportsDeprecated = diagnostic.reportDeprecated;
result.source = diagnostic.source;
result.skippedOn = diagnostic.skippedOn;
const { relatedInformation } = diagnostic;
result.relatedInformation = relatedInformation ?
relatedInformation.length ?
relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, diagnosticFilePath, newProgram, toPathInBuildInfoDirectory)) :
[] :
undefined;
return result;
});
function toPathInBuildInfoDirectory(path: string) {
buildInfoDirectory ??= getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions())!, newProgram.getCurrentDirectory()));
return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName);
}
}
function convertToDiagnosticRelatedInformation(
diagnostic: ReusableDiagnosticRelatedInformation,
diagnosticFilePath: Path,
newProgram: Program,
toPath: (path: string) => Path,
): DiagnosticRelatedInformation {
const { file } = diagnostic;
const sourceFile = file !== false ?
newProgram.getSourceFileByPath(file ? toPath(file) : diagnosticFilePath) :
undefined;
return {
...diagnostic,
file: sourceFile,
messageText: isString(diagnostic.messageText) ?
diagnostic.messageText :
convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, chain => (chain as ReusableRepopulateInfoChain).info),
};
}
/**
* Releases program and other related not needed properties
*/
function releaseCache(state: BuilderProgramState) {
BuilderState.releaseCache(state);
state.program = undefined;
}
/**
* Verifies that source file is ok to be used in calls that arent handled by next
*/
function assertSourceFileOkWithoutNextAffectedCall(state: BuilderProgramState, sourceFile: SourceFile | undefined) {
Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex! - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
}
/**
* This function returns the next affected file to be processed.
* Note that until doneAffected is called it would keep reporting same result
* This is to allow the callers to be able to actually remove affected file only when the operation is complete
* eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
*/
function getNextAffectedFile(
state: BuilderProgramStateWithDefinedProgram,
cancellationToken: CancellationToken | undefined,
host: BuilderProgramHost,
): SourceFile | Program | undefined {
while (true) {
const { affectedFiles } = state;
if (affectedFiles) {
const seenAffectedFiles = state.seenAffectedFiles!;
let affectedFilesIndex = state.affectedFilesIndex!; // TODO: GH#18217
while (affectedFilesIndex < affectedFiles.length) {
const affectedFile = affectedFiles[affectedFilesIndex];
if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
// Set the next affected file as seen and remove the cached semantic diagnostics
state.affectedFilesIndex = affectedFilesIndex;
addToAffectedFilesPendingEmit(
state,
affectedFile.resolvedPath,
getBuilderFileEmit(state.compilerOptions),
);
handleDtsMayChangeOfAffectedFile(
state,
affectedFile,
cancellationToken,
host,
);
return affectedFile;
}
affectedFilesIndex++;
}
// Remove the changed file from the change set
state.changedFilesSet.delete(state.currentChangedFilePath!);
state.currentChangedFilePath = undefined;
// Commit the changes in file signature
state.oldSignatures?.clear();
state.affectedFiles = undefined;
}
// Get next changed file
const nextKey = state.changedFilesSet.keys().next();
if (nextKey.done) {
// Done
return undefined;
}
// With --out or --outFile all outputs go into single file
// so operations are performed directly on program, return program
const compilerOptions = state.program.getCompilerOptions();
if (compilerOptions.outFile) return state.program;
// Get next batch of affected files
state.affectedFiles = BuilderState.getFilesAffectedByWithOldState(
state,
state.program,
nextKey.value,
cancellationToken,
host,
);
state.currentChangedFilePath = nextKey.value;
state.affectedFilesIndex = 0;
if (!state.seenAffectedFiles) state.seenAffectedFiles = new Set();
}
}
function clearAffectedFilesPendingEmit(
state: BuilderProgramState,
emitOnlyDtsFiles: boolean | undefined,
isForDtsErrors: boolean,
) {
if (!state.affectedFilesPendingEmit?.size && !state.programEmitPending) return;
if (!emitOnlyDtsFiles && !isForDtsErrors) {
state.affectedFilesPendingEmit = undefined;
state.programEmitPending = undefined;
}
state.affectedFilesPendingEmit?.forEach((emitKind, path) => {
// Mark the files as pending only if they are pending on js files, remove the dts emit pending flag
const pending = !isForDtsErrors ?
emitKind & BuilderFileEmit.AllJs :
emitKind & (BuilderFileEmit.AllJs | BuilderFileEmit.AllDtsEmit);
if (!pending) state.affectedFilesPendingEmit!.delete(path);
else state.affectedFilesPendingEmit!.set(path, pending);
});
// Mark the program as pending only if its pending on js files, remove the dts emit pending flag
if (state.programEmitPending) {
const pending = !isForDtsErrors ?
state.programEmitPending & BuilderFileEmit.AllJs :
state.programEmitPending & (BuilderFileEmit.AllJs | BuilderFileEmit.AllDtsEmit);
if (!pending) state.programEmitPending = undefined;
else state.programEmitPending = pending;
}
}
/**
* Determining what all is pending to be emitted based on previous options or previous file emit flags
* @internal
*/
export function getPendingEmitKindWithSeen(
optionsOrEmitKind: CompilerOptions | BuilderFileEmit,
seenOldOptionsOrEmitKind: CompilerOptions | BuilderFileEmit | undefined,
emitOnlyDtsFiles: boolean | undefined,
isForDtsErrors: boolean,
): BuilderFileEmit {
let pendingKind = getPendingEmitKind(optionsOrEmitKind, seenOldOptionsOrEmitKind);
if (emitOnlyDtsFiles) pendingKind = pendingKind & BuilderFileEmit.AllDts;
if (isForDtsErrors) pendingKind = pendingKind & BuilderFileEmit.DtsErrors;
return pendingKind;
}
function getBuilderFileEmitAllDts(isForDtsErrors: boolean) {
return !isForDtsErrors ? BuilderFileEmit.AllDts : BuilderFileEmit.DtsErrors;
}
/**
* Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
*/
function getNextAffectedFilePendingEmit(
state: BuilderProgramStateWithDefinedProgram,
emitOnlyDtsFiles: boolean | undefined,
isForDtsErrors: boolean,
) {
if (!state.affectedFilesPendingEmit?.size) return undefined;
return forEachEntry(state.affectedFilesPendingEmit, (emitKind, path) => {
const affectedFile = state.program.getSourceFileByPath(path);
if (!affectedFile || !sourceFileMayBeEmitted(affectedFile, state.program)) {
state.affectedFilesPendingEmit!.delete(path);
return undefined;
}
const seenKind = state.seenEmittedFiles?.get(affectedFile.resolvedPath);
const pendingKind = getPendingEmitKindWithSeen(
emitKind,
seenKind,
emitOnlyDtsFiles,
isForDtsErrors,
);
if (pendingKind) return { affectedFile, emitKind: pendingKind };
});
}
function getNextPendingEmitDiagnosticsFile(
state: BuilderProgramStateWithDefinedProgram,
isForDtsErrors: boolean,
) {
if (!state.emitDiagnosticsPerFile?.size) return undefined;
return forEachEntry(state.emitDiagnosticsPerFile, (diagnostics, path) => {
const affectedFile = state.program.getSourceFileByPath(path);
if (!affectedFile || !sourceFileMayBeEmitted(affectedFile, state.program)) {
state.emitDiagnosticsPerFile!.delete(path);
return undefined;
}
const seenKind = state.seenEmittedFiles?.get(affectedFile.resolvedPath) || BuilderFileEmit.None;
if (!(seenKind & getBuilderFileEmitAllDts(isForDtsErrors))) return { affectedFile, diagnostics, seenKind };
});
}
function removeDiagnosticsOfLibraryFiles(state: BuilderProgramStateWithDefinedProgram) {
if (!state.cleanedDiagnosticsOfLibFiles) {
state.cleanedDiagnosticsOfLibFiles = true;
const options = state.program.getCompilerOptions();
forEach(state.program.getSourceFiles(), f =>
state.program.isSourceFileDefaultLibrary(f) &&
!skipTypeCheckingIgnoringNoCheck(f, options, state.program) &&
removeSemanticDiagnosticsOf(state, f.resolvedPath));
}
}
/**
* Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
* This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
*/
function handleDtsMayChangeOfAffectedFile(
state: BuilderProgramStateWithDefinedProgram,
affectedFile: SourceFile,
cancellationToken: CancellationToken | undefined,
host: BuilderProgramHost,
) {
removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
// If affected files is everything except default library, then nothing more to do
if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
removeDiagnosticsOfLibraryFiles(state);
// When a change affects the global scope, all files are considered to be affected without updating their signature
// That means when affected file is handled, its signature can be out of date
// To avoid this, ensure that we update the signature for any affected file in this scenario.
BuilderState.updateShapeSignature(
state,
state.program,
affectedFile,
cancellationToken,
host,
);
return;
}
if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return;
handleDtsMayChangeOfReferencingExportOfAffectedFile(
state,
affectedFile,
cancellationToken,
host,
);
}
/**
* Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
* Also we need to make sure signature is updated for these files
*/
function handleDtsMayChangeOf(
state: BuilderProgramStateWithDefinedProgram,
path: Path,
invalidateJsFiles: boolean,
cancellationToken: CancellationToken | undefined,
host: BuilderProgramHost,
): void {
removeSemanticDiagnosticsOf(state, path);
if (!state.changedFilesSet.has(path)) {
const sourceFile = state.program.getSourceFileByPath(path);
if (sourceFile) {
// Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
// we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
// This ensures that we dont later during incremental builds considering wrong signature.
// Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
// But we avoid expensive full shape computation, as using file version as shape is enough for correctness.
BuilderState.updateShapeSignature(
state,
state.program,
sourceFile,
cancellationToken,
host,
/*useFileVersionAsSignature*/ true,
);
// If not dts emit, nothing more to do
if (invalidateJsFiles) {
addToAffectedFilesPendingEmit(
state,
path,
getBuilderFileEmit(state.compilerOptions),
);
}
else if (getEmitDeclarations(state.compilerOptions)) {
addToAffectedFilesPendingEmit(
state,
path,
state.compilerOptions.declarationMap ? BuilderFileEmit.AllDts : BuilderFileEmit.Dts,
);
}
}
}
}
/**
* Removes semantic diagnostics for path and
* returns true if there are no more semantic diagnostics from the old state
*/
function removeSemanticDiagnosticsOf(state: BuilderProgramState, path: Path) {
if (!state.semanticDiagnosticsFromOldState) {
return true;
}
state.semanticDiagnosticsFromOldState.delete(path);
state.semanticDiagnosticsPerFile.delete(path);
return !state.semanticDiagnosticsFromOldState.size;
}
function isChangedSignature(state: BuilderProgramState, path: Path) {
const oldSignature = Debug.checkDefined(state.oldSignatures).get(path) || undefined;
const newSignature = Debug.checkDefined(state.fileInfos.get(path)).signature;
return newSignature !== oldSignature;
}
function handleDtsMayChangeOfGlobalScope(
state: BuilderProgramStateWithDefinedProgram,
filePath: Path,
invalidateJsFiles: boolean,
cancellationToken: CancellationToken | undefined,
host: BuilderProgramHost,
): boolean {
if (!state.fileInfos.get(filePath)?.affectsGlobalScope) return false;
// Every file needs to be handled
BuilderState.getAllFilesExcludingDefaultLibraryFile(
state,
state.program,
/*firstSourceFile*/ undefined,
).forEach(file =>
handleDtsMayChangeOf(
state,
file.resolvedPath,
invalidateJsFiles,
cancellationToken,
host,
)
);
removeDiagnosticsOfLibraryFiles(state);
return true;
}
/**
* Iterate on referencing modules that export entities from affected file and delete diagnostics and add pending emit
*/
function handleDtsMayChangeOfReferencingExportOfAffectedFile(
state: BuilderProgramStateWithDefinedProgram,
affectedFile: SourceFile,
cancellationToken: CancellationToken | undefined,
host: BuilderProgramHost,
) {
// If there was change in signature (dts output) for the changed file,
// then only we need to handle pending file emit
if (!state.referencedMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) return;
if (!isChangedSignature(state, affectedFile.resolvedPath)) return;
// Since isolated modules dont change js files, files affected by change in signature is itself
// But we need to cleanup semantic diagnostics and queue dts emit for affected files
if (getIsolatedModules(state.compilerOptions)) {
const seenFileNamesMap = new Map<Path, true>();
seenFileNamesMap.set(affectedFile.resolvedPath, true);
const queue = BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
while (queue.length > 0) {
const currentPath = queue.pop()!;
if (!seenFileNamesMap.has(currentPath)) {
seenFileNamesMap.set(currentPath, true);
if (
handleDtsMayChangeOfGlobalScope(
state,
currentPath,
/*invalidateJsFiles*/ false,
cancellationToken,
host,
)
) return;
handleDtsMayChangeOf(state, currentPath, /*invalidateJsFiles*/ false, cancellationToken, host);
if (isChangedSignature(state, currentPath)) {
const currentSourceFile = state.program.getSourceFileByPath(currentPath)!;
queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
}
}
}
}
const seenFileAndExportsOfFile = new Set<string>();
// If exported const enum, we need to ensure that js files are emitted as well since the const enum value changed
const invalidateJsFiles = !!affectedFile.symbol?.exports && !!forEachEntry(
affectedFile.symbol.exports,
exported => {
if ((exported.flags & SymbolFlags.ConstEnum) !== 0) return true;
const aliased = skipAlias(exported, state.program.getTypeChecker());
if (aliased === exported) return false;
return (aliased.flags & SymbolFlags.ConstEnum) !== 0 &&
some(aliased.declarations, d => getSourceFileOfNode(d) === affectedFile);
},
);
// Go through files that reference affected file and handle dts emit and semantic diagnostics for them and their references
state.referencedMap.getKeys(affectedFile.resolvedPath)?.forEach(exportedFromPath => {
if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, invalidateJsFiles, cancellationToken, host)) return true;
const references = state.referencedMap!.getKeys(exportedFromPath);
return references && forEachKey(references, filePath =>
handleDtsMayChangeOfFileAndExportsOfFile(
state,
filePath,
invalidateJsFiles,
seenFileAndExportsOfFile,
cancellationToken,
host,
));
});
}
/**