forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditorServices.ts
2283 lines (2058 loc) · 94.2 KB
/
editorServices.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
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="session.ts" />
namespace ts.server {
export interface Logger {
close(): void;
isVerbose(): boolean;
loggingEnabled(): boolean;
perftrc(s: string): void;
info(s: string): void;
startGroup(): void;
endGroup(): void;
msg(s: string, type?: string): void;
}
const lineCollectionCapacity = 4;
function mergeFormatOptions(formatCodeOptions: FormatCodeOptions, formatOptions: protocol.FormatOptions): void {
const hasOwnProperty = Object.prototype.hasOwnProperty;
Object.keys(formatOptions).forEach((key) => {
const codeKey = key.charAt(0).toUpperCase() + key.substring(1);
if (hasOwnProperty.call(formatCodeOptions, codeKey)) {
formatCodeOptions[codeKey] = formatOptions[key];
}
});
}
export class ScriptInfo {
svc: ScriptVersionCache;
children: ScriptInfo[] = []; // files referenced by this file
defaultProject: Project; // project to use by default for file
fileWatcher: FileWatcher;
formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions);
path: Path;
constructor(private host: ServerHost, public fileName: string, public content: string, public isOpen = false) {
this.path = toPath(fileName, host.getCurrentDirectory(), createGetCanonicalFileName(host.useCaseSensitiveFileNames));
this.svc = ScriptVersionCache.fromString(host, content);
}
setFormatOptions(formatOptions: protocol.FormatOptions): void {
if (formatOptions) {
mergeFormatOptions(this.formatCodeOptions, formatOptions);
}
}
close() {
this.isOpen = false;
}
addChild(childInfo: ScriptInfo) {
this.children.push(childInfo);
}
snap() {
return this.svc.getSnapshot();
}
getText() {
const snap = this.snap();
return snap.getText(0, snap.getLength());
}
getLineInfo(line: number) {
const snap = this.snap();
return snap.index.lineNumberToInfo(line);
}
editContent(start: number, end: number, newText: string): void {
this.svc.edit(start, end - start, newText);
}
getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange {
return this.svc.getTextChangesBetweenVersions(startVersion, endVersion);
}
getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange {
return this.snap().getChangeRange(oldSnapshot);
}
}
interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations {
lastCheckTime: number;
}
export class LSHost implements ts.LanguageServiceHost {
ls: ts.LanguageService;
compilationSettings: ts.CompilerOptions;
filenameToScript: ts.FileMap<ScriptInfo>;
roots: ScriptInfo[] = [];
private resolvedModuleNames: ts.FileMap<Map<TimestampedResolvedModule>>;
private moduleResolutionHost: ts.ModuleResolutionHost;
private getCanonicalFileName: (fileName: string) => string;
constructor(public host: ServerHost, public project: Project) {
this.getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
this.resolvedModuleNames = createFileMap<Map<TimestampedResolvedModule>>();
this.filenameToScript = createFileMap<ScriptInfo>();
this.moduleResolutionHost = {
fileExists: fileName => this.fileExists(fileName),
readFile: fileName => this.host.readFile(fileName),
directoryExists: directoryName => this.host.directoryExists(directoryName)
};
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const currentResolutionsInFile = this.resolvedModuleNames.get(path);
const newResolutions: Map<TimestampedResolvedModule> = {};
const resolvedModules: ResolvedModule[] = [];
const compilerOptions = this.getCompilationSettings();
for (const moduleName of moduleNames) {
// check if this is a duplicate entry in the list
let resolution = lookUp(newResolutions, moduleName);
if (!resolution) {
const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName);
if (moduleResolutionIsValid(existingResolution)) {
// ok, it is safe to use existing module resolution results
resolution = existingResolution;
}
else {
resolution = <TimestampedResolvedModule>resolveModuleName(moduleName, containingFile, compilerOptions, this.moduleResolutionHost);
resolution.lastCheckTime = Date.now();
newResolutions[moduleName] = resolution;
}
}
ts.Debug.assert(resolution !== undefined);
resolvedModules.push(resolution.resolvedModule);
}
// replace old results with a new one
this.resolvedModuleNames.set(path, newResolutions);
return resolvedModules;
function moduleResolutionIsValid(resolution: TimestampedResolvedModule): boolean {
if (!resolution) {
return false;
}
if (resolution.resolvedModule) {
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
return true;
}
// consider situation if we have no candidate locations as valid resolution.
// after all there is no point to invalidate it if we have no idea where to look for the module.
return resolution.failedLookupLocations.length === 0;
}
}
getDefaultLibFileName() {
const nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
}
getScriptSnapshot(filename: string): ts.IScriptSnapshot {
const scriptInfo = this.getScriptInfo(filename);
if (scriptInfo) {
return scriptInfo.snap();
}
}
setCompilationSettings(opt: ts.CompilerOptions) {
this.compilationSettings = opt;
// conservatively assume that changing compiler options might affect module resolution strategy
this.resolvedModuleNames.clear();
}
lineAffectsRefs(filename: string, line: number) {
const info = this.getScriptInfo(filename);
const lineInfo = info.getLineInfo(line);
if (lineInfo && lineInfo.text) {
const regex = /reference|import|\/\*|\*\//;
return regex.test(lineInfo.text);
}
}
getCompilationSettings() {
// change this to return active project settings for file
return this.compilationSettings;
}
getScriptFileNames() {
return this.roots.map(root => root.fileName);
}
getScriptVersion(filename: string) {
return this.getScriptInfo(filename).svc.latestVersion().toString();
}
getCurrentDirectory(): string {
return "";
}
getScriptIsOpen(filename: string) {
return this.getScriptInfo(filename).isOpen;
}
removeReferencedFile(info: ScriptInfo) {
if (!info.isOpen) {
this.filenameToScript.remove(info.path);
this.resolvedModuleNames.remove(info.path);
}
}
getScriptInfo(filename: string): ScriptInfo {
const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
let scriptInfo = this.filenameToScript.get(path);
if (!scriptInfo) {
scriptInfo = this.project.openReferencedFile(filename);
if (scriptInfo) {
this.filenameToScript.set(path, scriptInfo);
}
}
return scriptInfo;
}
addRoot(info: ScriptInfo) {
if (!this.filenameToScript.contains(info.path)) {
this.filenameToScript.set(info.path, info);
this.roots.push(info);
}
}
removeRoot(info: ScriptInfo) {
if (!this.filenameToScript.contains(info.path)) {
this.filenameToScript.remove(info.path);
this.roots = copyListRemovingItem(info, this.roots);
this.resolvedModuleNames.remove(info.path);
}
}
saveTo(filename: string, tmpfilename: string) {
const script = this.getScriptInfo(filename);
if (script) {
const snap = script.snap();
this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength()));
}
}
reloadScript(filename: string, tmpfilename: string, cb: () => any) {
const script = this.getScriptInfo(filename);
if (script) {
script.svc.reloadFromFile(tmpfilename, cb);
}
}
editScript(filename: string, start: number, end: number, newText: string) {
const script = this.getScriptInfo(filename);
if (script) {
script.editContent(start, end, newText);
return;
}
throw new Error("No script with name '" + filename + "'");
}
resolvePath(path: string): string {
const result = this.host.resolvePath(path);
return result;
}
fileExists(path: string): boolean {
const result = this.host.fileExists(path);
return result;
}
directoryExists(path: string): boolean {
return this.host.directoryExists(path);
}
/**
* @param line 1 based index
*/
lineToTextSpan(filename: string, line: number): ts.TextSpan {
const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const script: ScriptInfo = this.filenameToScript.get(path);
const index = script.snap().index;
const lineInfo = index.lineNumberToInfo(line + 1);
let len: number;
if (lineInfo.leaf) {
len = lineInfo.leaf.text.length;
}
else {
const nextLineInfo = index.lineNumberToInfo(line + 2);
len = nextLineInfo.offset - lineInfo.offset;
}
return ts.createTextSpan(lineInfo.offset, len);
}
/**
* @param line 1 based index
* @param offset 1 based index
*/
lineOffsetToPosition(filename: string, line: number, offset: number): number {
const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const script: ScriptInfo = this.filenameToScript.get(path);
const index = script.snap().index;
const lineInfo = index.lineNumberToInfo(line);
// TODO: assert this offset is actually on the line
return (lineInfo.offset + offset - 1);
}
/**
* @param line 1-based index
* @param offset 1-based index
*/
positionToLineOffset(filename: string, position: number): ILineInfo {
const path = toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const script: ScriptInfo = this.filenameToScript.get(path);
const index = script.snap().index;
const lineOffset = index.charOffsetToLineNumberAndPos(position);
return { line: lineOffset.line, offset: lineOffset.offset + 1 };
}
}
export interface ProjectOptions {
// these fields can be present in the project file
files?: string[];
compilerOptions?: ts.CompilerOptions;
}
export class Project {
compilerService: CompilerService;
projectFilename: string;
projectFileWatcher: FileWatcher;
directoryWatcher: FileWatcher;
// Used to keep track of what directories are watched for this project
directoriesWatchedForTsconfig: string[] = [];
program: ts.Program;
filenameToSourceFile: ts.Map<ts.SourceFile> = {};
updateGraphSeq = 0;
/** Used for configured projects which may have multiple open roots */
openRefCount = 0;
constructor(public projectService: ProjectService, public projectOptions?: ProjectOptions) {
if (projectOptions && projectOptions.files) {
// If files are listed explicitly, allow all extensions
projectOptions.compilerOptions.allowNonTsExtensions = true;
}
this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions);
}
addOpenRef() {
this.openRefCount++;
}
deleteOpenRef() {
this.openRefCount--;
return this.openRefCount;
}
openReferencedFile(filename: string) {
return this.projectService.openFile(filename, /*openedByClient*/ false);
}
getRootFiles() {
return this.compilerService.host.roots.map(info => info.fileName);
}
getFileNames() {
const sourceFiles = this.program.getSourceFiles();
return sourceFiles.map(sourceFile => sourceFile.fileName);
}
getSourceFile(info: ScriptInfo) {
return this.filenameToSourceFile[info.fileName];
}
getSourceFileFromName(filename: string, requireOpen?: boolean) {
const info = this.projectService.getScriptInfo(filename);
if (info) {
if ((!requireOpen) || info.isOpen) {
return this.getSourceFile(info);
}
}
}
isRoot(info: ScriptInfo) {
return this.compilerService.host.roots.some(root => root === info);
}
removeReferencedFile(info: ScriptInfo) {
this.compilerService.host.removeReferencedFile(info);
this.updateGraph();
}
updateFileMap() {
this.filenameToSourceFile = {};
const sourceFiles = this.program.getSourceFiles();
for (let i = 0, len = sourceFiles.length; i < len; i++) {
const normFilename = ts.normalizePath(sourceFiles[i].fileName);
this.filenameToSourceFile[normFilename] = sourceFiles[i];
}
}
finishGraph() {
this.updateGraph();
this.compilerService.languageService.getNavigateToItems(".*");
}
updateGraph() {
this.program = this.compilerService.languageService.getProgram();
this.updateFileMap();
}
isConfiguredProject() {
return this.projectFilename;
}
// add a root file to project
addRoot(info: ScriptInfo) {
this.compilerService.host.addRoot(info);
}
// remove a root file from project
removeRoot(info: ScriptInfo) {
this.compilerService.host.removeRoot(info);
}
filesToString() {
let strBuilder = "";
ts.forEachValue(this.filenameToSourceFile,
sourceFile => { strBuilder += sourceFile.fileName + "\n"; });
return strBuilder;
}
setProjectOptions(projectOptions: ProjectOptions) {
this.projectOptions = projectOptions;
if (projectOptions.compilerOptions) {
projectOptions.compilerOptions.allowNonTsExtensions = true;
this.compilerService.setCompilerOptions(projectOptions.compilerOptions);
}
}
}
export interface ProjectOpenResult {
success?: boolean;
errorMsg?: string;
project?: Project;
}
function copyListRemovingItem<T>(item: T, list: T[]) {
const copiedList: T[] = [];
for (let i = 0, len = list.length; i < len; i++) {
if (list[i] != item) {
copiedList.push(list[i]);
}
}
return copiedList;
}
export interface ProjectServiceEventHandler {
(eventName: string, project: Project, fileName: string): void;
}
export interface HostConfiguration {
formatCodeOptions: ts.FormatCodeOptions;
hostInfo: string;
}
export class ProjectService {
filenameToScriptInfo: ts.Map<ScriptInfo> = {};
// open, non-configured root files
openFileRoots: ScriptInfo[] = [];
// projects built from openFileRoots
inferredProjects: Project[] = [];
// projects specified by a tsconfig.json file
configuredProjects: Project[] = [];
// open files referenced by a project
openFilesReferenced: ScriptInfo[] = [];
// open files that are roots of a configured project
openFileRootsConfigured: ScriptInfo[] = [];
// a path to directory watcher map that detects added tsconfig files
directoryWatchersForTsconfig: ts.Map<FileWatcher> = {};
// count of how many projects are using the directory watcher. If the
// number becomes 0 for a watcher, then we should close it.
directoryWatchersRefCount: ts.Map<number> = {};
hostConfiguration: HostConfiguration;
timerForDetectingProjectFileListChanges: Map<NodeJS.Timer> = {};
constructor(public host: ServerHost, public psLogger: Logger, public eventHandler?: ProjectServiceEventHandler) {
// ts.disableIncrementalParsing = true;
this.addDefaultHostConfiguration();
}
addDefaultHostConfiguration() {
this.hostConfiguration = {
formatCodeOptions: ts.clone(CompilerService.defaultFormatCodeOptions),
hostInfo: "Unknown host"
};
}
getFormatCodeOptions(file?: string) {
if (file) {
const info = this.filenameToScriptInfo[file];
if (info) {
return info.formatCodeOptions;
}
}
return this.hostConfiguration.formatCodeOptions;
}
watchedFileChanged(fileName: string) {
const info = this.filenameToScriptInfo[fileName];
if (!info) {
this.psLogger.info("Error: got watch notification for unknown file: " + fileName);
}
if (!this.host.fileExists(fileName)) {
// File was deleted
this.fileDeletedInFilesystem(info);
}
else {
if (info && (!info.isOpen)) {
info.svc.reloadFromFile(info.fileName);
}
}
}
/**
* This is the callback function when a watched directory has added or removed source code files.
* @param project the project that associates with this directory watcher
* @param fileName the absolute file name that changed in watched directory
*/
directoryWatchedForSourceFilesChanged(project: Project, fileName: string) {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) {
return;
}
this.log("Detected source file changes: " + fileName);
this.startTimerForDetectingProjectFileListChanges(project);
}
startTimerForDetectingProjectFileListChanges(project: Project) {
if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) {
clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]);
}
this.timerForDetectingProjectFileListChanges[project.projectFilename] = setTimeout(
() => this.handleProjectFileListChanges(project),
250
);
}
handleProjectFileListChanges(project: Project) {
const { projectOptions } = this.configFileToProjectOptions(project.projectFilename);
const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f)));
const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f)));
// We check if the project file list has changed. If so, we update the project.
if (!arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) {
// For configured projects, the change is made outside the tsconfig file, and
// it is not likely to affect the project for other files opened by the client. We can
// just update the current project.
this.updateConfiguredProject(project);
// Call updateProjectStructure to clean up inferred projects we may have
// created for the new files
this.updateProjectStructure();
}
}
/**
* This is the callback function when a watched directory has an added tsconfig file.
*/
directoryWatchedForTsconfigChanged(fileName: string) {
if (ts.getBaseFileName(fileName) != "tsconfig.json") {
this.log(fileName + " is not tsconfig.json");
return;
}
this.log("Detected newly added tsconfig file: " + fileName);
const { projectOptions } = this.configFileToProjectOptions(fileName);
const rootFilesInTsconfig = projectOptions.files.map(f => this.getCanonicalFileName(f));
const openFileRoots = this.openFileRoots.map(s => this.getCanonicalFileName(s.fileName));
// We should only care about the new tsconfig file if it contains any
// opened root files of existing inferred projects
for (const openFileRoot of openFileRoots) {
if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) {
this.reloadProjects();
return;
}
}
}
getCanonicalFileName(fileName: string) {
const name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
return ts.normalizePath(name);
}
watchedProjectConfigFileChanged(project: Project) {
this.log("Config file changed: " + project.projectFilename);
this.updateConfiguredProject(project);
this.updateProjectStructure();
}
log(msg: string, type = "Err") {
this.psLogger.msg(msg, type);
}
setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments) {
if (args.file) {
const info = this.filenameToScriptInfo[args.file];
if (info) {
info.setFormatOptions(args.formatOptions);
this.log("Host configuration update for file " + args.file, "Info");
}
}
else {
if (args.hostInfo !== undefined) {
this.hostConfiguration.hostInfo = args.hostInfo;
this.log("Host information " + args.hostInfo, "Info");
}
if (args.formatOptions) {
mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions);
this.log("Format host information updated", "Info");
}
}
}
closeLog() {
this.psLogger.close();
}
createInferredProject(root: ScriptInfo) {
const project = new Project(this);
project.addRoot(root);
let currentPath = ts.getDirectoryPath(root.fileName);
let parentPath = ts.getDirectoryPath(currentPath);
while (currentPath != parentPath) {
if (!project.projectService.directoryWatchersForTsconfig[currentPath]) {
this.log("Add watcher for: " + currentPath);
project.projectService.directoryWatchersForTsconfig[currentPath] =
this.host.watchDirectory(currentPath, fileName => this.directoryWatchedForTsconfigChanged(fileName));
project.projectService.directoryWatchersRefCount[currentPath] = 1;
}
else {
project.projectService.directoryWatchersRefCount[currentPath] += 1;
}
project.directoriesWatchedForTsconfig.push(currentPath);
currentPath = parentPath;
parentPath = ts.getDirectoryPath(parentPath);
}
project.finishGraph();
this.inferredProjects.push(project);
return project;
}
fileDeletedInFilesystem(info: ScriptInfo) {
this.psLogger.info(info.fileName + " deleted");
if (info.fileWatcher) {
info.fileWatcher.close();
info.fileWatcher = undefined;
}
if (!info.isOpen) {
this.filenameToScriptInfo[info.fileName] = undefined;
const referencingProjects = this.findReferencingProjects(info);
if (info.defaultProject) {
info.defaultProject.removeRoot(info);
}
for (let i = 0, len = referencingProjects.length; i < len; i++) {
referencingProjects[i].removeReferencedFile(info);
}
for (let j = 0, flen = this.openFileRoots.length; j < flen; j++) {
const openFile = this.openFileRoots[j];
if (this.eventHandler) {
this.eventHandler("context", openFile.defaultProject, openFile.fileName);
}
}
for (let j = 0, flen = this.openFilesReferenced.length; j < flen; j++) {
const openFile = this.openFilesReferenced[j];
if (this.eventHandler) {
this.eventHandler("context", openFile.defaultProject, openFile.fileName);
}
}
}
this.printProjects();
}
updateConfiguredProjectList() {
const configuredProjects: Project[] = [];
for (let i = 0, len = this.configuredProjects.length; i < len; i++) {
if (this.configuredProjects[i].openRefCount > 0) {
configuredProjects.push(this.configuredProjects[i]);
}
}
this.configuredProjects = configuredProjects;
}
removeProject(project: Project) {
this.log("remove project: " + project.getRootFiles().toString());
if (project.isConfiguredProject()) {
project.projectFileWatcher.close();
project.directoryWatcher.close();
this.configuredProjects = copyListRemovingItem(project, this.configuredProjects);
}
else {
for (const directory of project.directoriesWatchedForTsconfig) {
// if the ref count for this directory watcher drops to 0, it's time to close it
project.projectService.directoryWatchersRefCount[directory]--;
if (!project.projectService.directoryWatchersRefCount[directory]) {
this.log("Close directory watcher for: " + directory);
project.projectService.directoryWatchersForTsconfig[directory].close();
delete project.projectService.directoryWatchersForTsconfig[directory];
}
}
this.inferredProjects = copyListRemovingItem(project, this.inferredProjects);
}
const fileNames = project.getFileNames();
for (const fileName of fileNames) {
const info = this.getScriptInfo(fileName);
if (info.defaultProject == project) {
info.defaultProject = undefined;
}
}
}
setConfiguredProjectRoot(info: ScriptInfo) {
for (let i = 0, len = this.configuredProjects.length; i < len; i++) {
const configuredProject = this.configuredProjects[i];
if (configuredProject.isRoot(info)) {
info.defaultProject = configuredProject;
configuredProject.addOpenRef();
return true;
}
}
return false;
}
addOpenFile(info: ScriptInfo) {
if (this.setConfiguredProjectRoot(info)) {
this.openFileRootsConfigured.push(info);
}
else {
this.findReferencingProjects(info);
if (info.defaultProject) {
this.openFilesReferenced.push(info);
}
else {
// create new inferred project p with the newly opened file as root
info.defaultProject = this.createInferredProject(info);
const openFileRoots: ScriptInfo[] = [];
// for each inferred project root r
for (let i = 0, len = this.openFileRoots.length; i < len; i++) {
const r = this.openFileRoots[i];
// if r referenced by the new project
if (info.defaultProject.getSourceFile(r)) {
// remove project rooted at r
this.removeProject(r.defaultProject);
// put r in referenced open file list
this.openFilesReferenced.push(r);
// set default project of r to the new project
r.defaultProject = info.defaultProject;
}
else {
// otherwise, keep r as root of inferred project
openFileRoots.push(r);
}
}
this.openFileRoots = openFileRoots;
this.openFileRoots.push(info);
}
}
this.updateConfiguredProjectList();
}
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
*/
closeOpenFile(info: ScriptInfo) {
// Closing file should trigger re-reading the file content from disk. This is
// because the user may chose to discard the buffer content before saving
// to the disk, and the server's version of the file can be out of sync.
info.svc.reloadFromFile(info.fileName);
const openFileRoots: ScriptInfo[] = [];
let removedProject: Project;
for (let i = 0, len = this.openFileRoots.length; i < len; i++) {
// if closed file is root of project
if (info === this.openFileRoots[i]) {
// remove that project and remember it
removedProject = info.defaultProject;
}
else {
openFileRoots.push(this.openFileRoots[i]);
}
}
this.openFileRoots = openFileRoots;
if (!removedProject) {
const openFileRootsConfigured: ScriptInfo[] = [];
for (let i = 0, len = this.openFileRootsConfigured.length; i < len; i++) {
if (info === this.openFileRootsConfigured[i]) {
if (info.defaultProject.deleteOpenRef() === 0) {
removedProject = info.defaultProject;
}
}
else {
openFileRootsConfigured.push(this.openFileRootsConfigured[i]);
}
}
this.openFileRootsConfigured = openFileRootsConfigured;
}
if (removedProject) {
this.removeProject(removedProject);
const openFilesReferenced: ScriptInfo[] = [];
const orphanFiles: ScriptInfo[] = [];
// for all open, referenced files f
for (let i = 0, len = this.openFilesReferenced.length; i < len; i++) {
const f = this.openFilesReferenced[i];
// if f was referenced by the removed project, remember it
if (f.defaultProject === removedProject || !f.defaultProject) {
f.defaultProject = undefined;
orphanFiles.push(f);
}
else {
// otherwise add it back to the list of referenced files
openFilesReferenced.push(f);
}
}
this.openFilesReferenced = openFilesReferenced;
// treat orphaned files as newly opened
for (let i = 0, len = orphanFiles.length; i < len; i++) {
this.addOpenFile(orphanFiles[i]);
}
}
else {
this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced);
}
info.close();
}
findReferencingProjects(info: ScriptInfo, excludedProject?: Project) {
const referencingProjects: Project[] = [];
info.defaultProject = undefined;
for (let i = 0, len = this.inferredProjects.length; i < len; i++) {
const inferredProject = this.inferredProjects[i];
inferredProject.updateGraph();
if (inferredProject !== excludedProject) {
if (inferredProject.getSourceFile(info)) {
info.defaultProject = inferredProject;
referencingProjects.push(inferredProject);
}
}
}
for (let i = 0, len = this.configuredProjects.length; i < len; i++) {
const configuredProject = this.configuredProjects[i];
configuredProject.updateGraph();
if (configuredProject.getSourceFile(info)) {
info.defaultProject = configuredProject;
}
}
return referencingProjects;
}
/**
* This function rebuilds the project for every file opened by the client
*/
reloadProjects() {
this.log("reload projects.");
// First check if there is new tsconfig file added for inferred project roots
for (const info of this.openFileRoots) {
this.openOrUpdateConfiguredProjectForFile(info.fileName);
}
this.updateProjectStructure();
}
/**
* This function is to update the project structure for every projects.
* It is called on the premise that all the configured projects are
* up to date.
*/
updateProjectStructure() {
this.log("updating project structure from ...", "Info");
this.printProjects();
const unattachedOpenFiles: ScriptInfo[] = [];
const openFileRootsConfigured: ScriptInfo[] = [];
for (const info of this.openFileRootsConfigured) {
const project = info.defaultProject;
if (!project || !(project.getSourceFile(info))) {
info.defaultProject = undefined;
unattachedOpenFiles.push(info);
}
else {
openFileRootsConfigured.push(info);
}
}
this.openFileRootsConfigured = openFileRootsConfigured;
// First loop through all open files that are referenced by projects but are not
// project roots. For each referenced file, see if the default project still
// references that file. If so, then just keep the file in the referenced list.
// If not, add the file to an unattached list, to be rechecked later.
const openFilesReferenced: ScriptInfo[] = [];
for (let i = 0, len = this.openFilesReferenced.length; i < len; i++) {
const referencedFile = this.openFilesReferenced[i];
referencedFile.defaultProject.updateGraph();
const sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile);
if (sourceFile) {
openFilesReferenced.push(referencedFile);
}
else {
unattachedOpenFiles.push(referencedFile);
}
}
this.openFilesReferenced = openFilesReferenced;
// Then, loop through all of the open files that are project roots.
// For each root file, note the project that it roots. Then see if
// any other projects newly reference the file. If zero projects
// newly reference the file, keep it as a root. If one or more
// projects newly references the file, remove its project from the
// inferred projects list (since it is no longer a root) and add
// the file to the open, referenced file list.
const openFileRoots: ScriptInfo[] = [];
for (let i = 0, len = this.openFileRoots.length; i < len; i++) {
const rootFile = this.openFileRoots[i];
const rootedProject = rootFile.defaultProject;
const referencingProjects = this.findReferencingProjects(rootFile, rootedProject);
if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) {
// If the root file has already been added into a configured project,
// meaning the original inferred project is gone already.
if (!rootedProject.isConfiguredProject()) {
this.removeProject(rootedProject);
}
this.openFileRootsConfigured.push(rootFile);
}
else {
if (referencingProjects.length === 0) {
rootFile.defaultProject = rootedProject;
openFileRoots.push(rootFile);
}
else {
// remove project from inferred projects list because root captured
this.removeProject(rootedProject);
this.openFilesReferenced.push(rootFile);
}
}
}
this.openFileRoots = openFileRoots;
// Finally, if we found any open, referenced files that are no longer
// referenced by their default project, treat them as newly opened
// by the editor.
for (let i = 0, len = unattachedOpenFiles.length; i < len; i++) {
this.addOpenFile(unattachedOpenFiles[i]);
}
this.printProjects();
}
getScriptInfo(filename: string) {
filename = ts.normalizePath(filename);
return ts.lookUp(this.filenameToScriptInfo, filename);
}
/**
* @param filename is absolute pathname
* @param fileContent is a known version of the file content that is more up to date than the one on disk
*/
openFile(fileName: string, openedByClient: boolean, fileContent?: string) {
fileName = ts.normalizePath(fileName);
let info = ts.lookUp(this.filenameToScriptInfo, fileName);
if (!info) {
let content: string;
if (this.host.fileExists(fileName)) {
content = fileContent || this.host.readFile(fileName);
}
if (!content) {
if (openedByClient) {
content = "";
}
}
if (content !== undefined) {