-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
session.ts
4076 lines (3685 loc) · 197 KB
/
session.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 {
arrayFrom,
arrayReverseIterator,
BufferEncoding,
CallHierarchyIncomingCall,
CallHierarchyItem,
CallHierarchyOutgoingCall,
cast,
CodeAction,
CodeActionCommand,
CodeFixAction,
CombinedCodeActions,
CompilerOptions,
CompletionEntry,
CompletionEntryData,
CompletionEntryDetails,
CompletionInfo,
computeLineAndCharacterOfPosition,
computeLineStarts,
concatenate,
createQueue,
createSet,
createTextSpan,
createTextSpanFromBounds,
Debug,
decodedTextSpanIntersectsWith,
deduplicate,
DefinitionInfo,
DefinitionInfoAndBoundSpan,
Diagnostic,
diagnosticCategoryName,
DiagnosticRelatedInformation,
displayPartsToString,
DocumentHighlights,
DocumentPosition,
DocumentSpan,
documentSpansEqual,
EmitOutput,
equateValues,
FileTextChanges,
filter,
find,
FindAllReferences,
first,
firstIterator,
firstOrUndefined,
flatMap,
flatMapToMutable,
flattenDiagnosticMessageText,
forEachNameInAccessChainWalkingLeft,
FormatCodeSettings,
formatting,
getDeclarationFromName,
getDeclarationOfKind,
getDocumentSpansEqualityComparer,
getEmitDeclarations,
getEntrypointsFromPackageJsonInfo,
getLineAndCharacterOfPosition,
getMappedContextSpan,
getMappedDocumentSpan,
getMappedLocation,
getNodeModulePathParts,
getNormalizedAbsolutePath,
getPackageNameFromTypesPackageName,
getPackageScopeForPath,
getSnapshotText,
getSupportedCodeFixes,
getTemporaryModuleResolutionState,
getTextOfIdentifierOrLiteral,
getTouchingPropertyName,
GoToDefinition,
HostCancellationToken,
identity,
ImplementationLocation,
ImportSpecifier,
isAccessExpression,
isArray,
isDeclarationFileName,
isIdentifier,
isString,
isStringLiteralLike,
JSDocLinkDisplayPart,
JSDocTagInfo,
LanguageServiceMode,
LineAndCharacter,
LinkedEditingInfo,
map,
mapDefined,
mapDefinedIterator,
mapIterator,
mapOneOrMany,
memoize,
ModuleResolutionKind,
MultiMap,
NavigateToItem,
NavigationBarItem,
NavigationTree,
nodeModulesPathPart,
normalizePath,
OperationCanceledException,
OrganizeImportsMode,
OutliningSpan,
PasteEdits,
Path,
PerformanceEvent,
PossibleProgramFileInfo,
Program,
QuickInfo,
RefactorEditInfo,
ReferencedSymbol,
ReferencedSymbolDefinitionInfo,
ReferencedSymbolEntry,
ReferenceEntry,
removeFileExtension,
RenameInfo,
RenameLocation,
ScriptKind,
SelectionRange,
SemanticClassificationFormat,
SignatureHelpItem,
SignatureHelpItems,
singleIterator,
some,
SourceFile,
startsWith,
SymbolDisplayPart,
SyntaxKind,
TextChange,
TextInsertion,
TextRange,
TextSpan,
textSpanEnd,
timestamp,
toArray,
toFileNameLowerCase,
tracing,
unmangleScopedPackageName,
version,
WithMetadata,
} from "./_namespaces/ts.js";
import {
AuxiliaryProject,
CloseFileWatcherEvent,
ConfigFileDiagEvent,
ConfiguredProject,
ConfiguredProjectLoadKind,
convertFormatOptions,
convertScriptKindName,
convertUserPreferences,
CreateDirectoryWatcherEvent,
CreateFileWatcherEvent,
EmitResult,
emptyArray,
Errors,
GcTimer,
indent,
isConfigFile,
isConfiguredProject,
isDynamicFileName,
isExternalProject,
isInferredProject,
ITypingsInstaller,
LargeFileReferencedEvent,
Logger,
LogLevel,
Msg,
NormalizedPath,
nullTypingsInstaller,
Project,
ProjectInfoTelemetryEvent,
ProjectKind,
ProjectLanguageServiceStateEvent,
ProjectLoadingFinishEvent,
ProjectLoadingStartEvent,
ProjectService,
ProjectServiceEvent,
ProjectServiceEventHandler,
ProjectServiceOptions,
ProjectsUpdatedInBackgroundEvent,
ScriptInfo,
ScriptInfoOrConfig,
ServerHost,
stringifyIndented,
toNormalizedPath,
updateProjectIfDirty,
} from "./_namespaces/ts.server.js";
import * as protocol from "./protocol.js";
interface StackTraceError extends Error {
stack?: string;
}
export interface ServerCancellationToken extends HostCancellationToken {
setRequest(requestId: number): void;
resetRequest(requestId: number): void;
}
export const nullCancellationToken: ServerCancellationToken = {
isCancellationRequested: () => false,
setRequest: () => void 0,
resetRequest: () => void 0,
};
function hrTimeToMilliseconds(time: [number, number]): number {
const seconds = time[0];
const nanoseconds = time[1];
return ((1e9 * seconds) + nanoseconds) / 1000000.0;
}
function isDeclarationFileInJSOnlyNonConfiguredProject(project: Project, file: NormalizedPath) {
// Checking for semantic diagnostics is an expensive process. We want to avoid it if we
// know for sure it is not needed.
// For instance, .d.ts files injected by ATA automatically do not produce any relevant
// errors to a JS- only project.
//
// Note that configured projects can set skipLibCheck (on by default in jsconfig.json) to
// disable checking for declaration files. We only need to verify for inferred projects (e.g.
// miscellaneous context in VS) and external projects(e.g.VS.csproj project) with only JS
// files.
//
// We still want to check .js files in a JS-only inferred or external project (e.g. if the
// file has '// @ts-check').
if (
(isInferredProject(project) || isExternalProject(project)) &&
project.isJsOnlyProject()
) {
const scriptInfo = project.getScriptInfoForNormalizedPath(file);
return scriptInfo && !scriptInfo.isJavaScript();
}
return false;
}
function dtsChangeCanAffectEmit(compilationSettings: CompilerOptions) {
return getEmitDeclarations(compilationSettings) || !!compilationSettings.emitDecoratorMetadata;
}
function formatDiag(fileName: NormalizedPath, project: Project, diag: Diagnostic): protocol.Diagnostic {
const scriptInfo = project.getScriptInfoForNormalizedPath(fileName)!; // TODO: GH#18217
return {
start: scriptInfo.positionToLineOffset(diag.start!),
end: scriptInfo.positionToLineOffset(diag.start! + diag.length!), // TODO: GH#18217
text: flattenDiagnosticMessageText(diag.messageText, "\n"),
code: diag.code,
category: diagnosticCategoryName(diag),
reportsUnnecessary: diag.reportsUnnecessary,
reportsDeprecated: diag.reportsDeprecated,
source: diag.source,
relatedInformation: map(diag.relatedInformation, formatRelatedInformation),
};
}
function formatRelatedInformation(info: DiagnosticRelatedInformation): protocol.DiagnosticRelatedInformation {
if (!info.file) {
return {
message: flattenDiagnosticMessageText(info.messageText, "\n"),
category: diagnosticCategoryName(info),
code: info.code,
};
}
return {
span: {
start: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start!)),
end: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start! + info.length!)), // TODO: GH#18217
file: info.file.fileName,
},
message: flattenDiagnosticMessageText(info.messageText, "\n"),
category: diagnosticCategoryName(info),
code: info.code,
};
}
function convertToLocation(lineAndCharacter: LineAndCharacter): protocol.Location {
return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 };
}
/** @internal */
export function formatDiagnosticToProtocol(diag: Diagnostic, includeFileName: true): protocol.DiagnosticWithFileName;
/** @internal */
export function formatDiagnosticToProtocol(diag: Diagnostic, includeFileName: false): protocol.Diagnostic;
/** @internal */
export function formatDiagnosticToProtocol(diag: Diagnostic, includeFileName: boolean): protocol.Diagnostic | protocol.DiagnosticWithFileName {
const start = (diag.file && convertToLocation(getLineAndCharacterOfPosition(diag.file, diag.start!)))!; // TODO: GH#18217
const end = (diag.file && convertToLocation(getLineAndCharacterOfPosition(diag.file, diag.start! + diag.length!)))!; // TODO: GH#18217
const text = flattenDiagnosticMessageText(diag.messageText, "\n");
const { code, source } = diag;
const category = diagnosticCategoryName(diag);
const common = {
start,
end,
text,
code,
category,
reportsUnnecessary: diag.reportsUnnecessary,
reportsDeprecated: diag.reportsDeprecated,
source,
relatedInformation: map(diag.relatedInformation, formatRelatedInformation),
};
return includeFileName
? { ...common, fileName: diag.file && diag.file.fileName }
: common;
}
interface PendingErrorCheck {
fileName: NormalizedPath;
project: Project;
}
function allEditsBeforePos(edits: readonly TextChange[], pos: number): boolean {
return edits.every(edit => textSpanEnd(edit.span) < pos);
}
// CommandNames used to be exposed before TS 2.4 as a namespace
// In TS 2.4 we switched to an enum, keep this for backward compatibility
// The var assignment ensures that even though CommandTypes are a const enum
// we want to ensure the value is maintained in the out since the file is
// built using --preseveConstEnum.
/** @deprecated use ts.server.protocol.CommandTypes */
export type CommandNames = protocol.CommandTypes;
/** @deprecated use ts.server.protocol.CommandTypes */
export const CommandNames: any = (protocol as any).CommandTypes;
export function formatMessage<T extends protocol.Message>(msg: T, logger: Logger, byteLength: (s: string, encoding: BufferEncoding) => number, newLine: string): string {
const verboseLogging = logger.hasLevel(LogLevel.verbose);
const json = JSON.stringify(msg);
if (verboseLogging) {
logger.info(`${msg.type}:${stringifyIndented(msg)}`);
}
const len = byteLength(json, "utf8");
return `Content-Length: ${1 + len}\r\n\r\n${json}${newLine}`;
}
/**
* Allows to schedule next step in multistep operation
*/
interface NextStep {
immediate(actionType: string, action: () => void): void;
delay(actionType: string, ms: number, action: () => void): void;
}
/** @internal */
export type PerformanceData =
& Omit<protocol.PerformanceData, "diagnosticsDuration">
& { diagnosticsDuration?: Map<NormalizedPath, protocol.DiagnosticPerformanceData>; };
/**
* External capabilities used by multistep operation
*/
interface MultistepOperationHost {
getCurrentRequestId(): number;
getPerformanceData(): PerformanceData | undefined;
sendRequestCompletedEvent(requestId: number, performanceData: PerformanceData | undefined): void;
getServerHost(): ServerHost;
isCancellationRequested(): boolean;
executeWithRequestId(requestId: number, action: () => void, performanceData: PerformanceData | undefined): void;
logError(error: Error, message: string): void;
}
/**
* Represents operation that can schedule its next step to be executed later.
* Scheduling is done via instance of NextStep. If on current step subsequent step was not scheduled - operation is assumed to be completed.
*/
class MultistepOperation implements NextStep {
private requestId: number | undefined;
private performanceData: PerformanceData | undefined;
private timerHandle: any;
private immediateId: number | undefined;
constructor(private readonly operationHost: MultistepOperationHost) {}
public startNew(action: (next: NextStep) => void) {
this.complete();
this.requestId = this.operationHost.getCurrentRequestId();
this.executeAction(action);
}
private complete() {
if (this.requestId !== undefined) {
this.operationHost.sendRequestCompletedEvent(this.requestId, this.performanceData);
this.requestId = undefined;
}
this.setTimerHandle(undefined);
this.setImmediateId(undefined);
this.performanceData = undefined;
}
public immediate(actionType: string, action: () => void) {
const requestId = this.requestId!;
Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id");
this.setImmediateId(
this.operationHost.getServerHost().setImmediate(() => {
this.immediateId = undefined;
this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action), this.performanceData);
}, actionType),
);
}
public delay(actionType: string, ms: number, action: () => void) {
const requestId = this.requestId!;
Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id");
this.setTimerHandle(
this.operationHost.getServerHost().setTimeout(
() => {
this.timerHandle = undefined;
this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action), this.performanceData);
},
ms,
actionType,
),
);
}
private executeAction(action: (next: NextStep) => void) {
let stop = false;
try {
if (this.operationHost.isCancellationRequested()) {
stop = true;
tracing?.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId, early: true });
}
else {
tracing?.push(tracing.Phase.Session, "stepAction", { seq: this.requestId });
action(this);
tracing?.pop();
}
}
catch (e) {
// Cancellation or an error may have left incomplete events on the tracing stack.
tracing?.popAll();
stop = true;
// ignore cancellation request
if (e instanceof OperationCanceledException) {
tracing?.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId });
}
else {
tracing?.instant(tracing.Phase.Session, "stepError", { seq: this.requestId, message: (e as Error).message });
this.operationHost.logError(e, `delayed processing of request ${this.requestId}`);
}
}
this.performanceData = this.operationHost.getPerformanceData();
if (stop || !this.hasPendingWork()) {
this.complete();
}
}
private setTimerHandle(timerHandle: any) {
if (this.timerHandle !== undefined) {
this.operationHost.getServerHost().clearTimeout(this.timerHandle);
}
this.timerHandle = timerHandle;
}
private setImmediateId(immediateId: number | undefined) {
if (this.immediateId !== undefined) {
this.operationHost.getServerHost().clearImmediate(this.immediateId);
}
this.immediateId = immediateId;
}
private hasPendingWork() {
return !!this.timerHandle || !!this.immediateId;
}
}
export type Event = <T extends object>(body: T, eventName: string) => void;
export interface EventSender {
event: Event;
}
/** @internal */
export function toEvent(eventName: string, body: object): protocol.Event {
return {
seq: 0,
type: "event",
event: eventName,
body,
};
}
type Projects = readonly Project[] | {
readonly projects: readonly Project[];
readonly symLinkedProjects: MultiMap<Path, Project>;
};
/**
* This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project.
*/
function combineProjectOutput<T, U extends {}>(
defaultValue: T,
getValue: (path: Path) => T,
projects: Projects,
action: (project: Project, value: T) => readonly U[] | U | undefined,
): U[] {
const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue));
if (!isArray(projects) && projects.symLinkedProjects) {
projects.symLinkedProjects.forEach((projects, path) => {
const value = getValue(path);
outputs.push(...flatMap(projects, project => action(project, value)));
});
}
return deduplicate(outputs, equateValues);
}
interface ProjectNavigateToItems {
project: Project;
navigateToItems: readonly NavigateToItem[];
}
function createDocumentSpanSet(useCaseSensitiveFileNames: boolean): Set<DocumentSpan> {
return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, getDocumentSpansEqualityComparer(useCaseSensitiveFileNames));
}
function getRenameLocationsWorker(
projects: Projects,
defaultProject: Project,
initialLocation: DocumentPosition,
findInStrings: boolean,
findInComments: boolean,
preferences: protocol.UserPreferences,
useCaseSensitiveFileNames: boolean,
): readonly RenameLocation[] {
const perProjectResults = getPerProjectReferences(
projects,
defaultProject,
initialLocation,
getDefinitionLocation(defaultProject, initialLocation, /*isForRename*/ true),
mapDefinitionInProject,
(project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences),
(renameLocation, cb) => cb(documentSpanLocation(renameLocation)),
);
// No filtering or dedup'ing is required if there's exactly one project
if (isArray(perProjectResults)) {
return perProjectResults;
}
const results: RenameLocation[] = [];
const seen = createDocumentSpanSet(useCaseSensitiveFileNames);
perProjectResults.forEach((projectResults, project) => {
for (const result of projectResults) {
// If there's a mapped location, it'll appear in the results for another project
if (!seen.has(result) && !getMappedLocationForProject(documentSpanLocation(result), project)) {
results.push(result);
seen.add(result);
}
}
});
return results;
}
function getDefinitionLocation(defaultProject: Project, initialLocation: DocumentPosition, isForRename: boolean): DocumentPosition | undefined {
const infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos, /*searchOtherFilesOnly*/ false, /*stopAtAlias*/ isForRename);
const info = infos && firstOrUndefined(infos);
// Note that the value of `isLocal` may depend on whether or not the checker has run on the containing file
// (implying that FAR cascading behavior may depend on request order)
return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : undefined;
}
function getReferencesWorker(
projects: Projects,
defaultProject: Project,
initialLocation: DocumentPosition,
useCaseSensitiveFileNames: boolean,
logger: Logger,
): readonly ReferencedSymbol[] {
const perProjectResults = getPerProjectReferences(
projects,
defaultProject,
initialLocation,
getDefinitionLocation(defaultProject, initialLocation, /*isForRename*/ false),
mapDefinitionInProject,
(project, position) => {
logger.info(`Finding references to ${position.fileName} position ${position.pos} in project ${project.getProjectName()}`);
return project.getLanguageService().findReferences(position.fileName, position.pos);
},
(referencedSymbol, cb) => {
cb(documentSpanLocation(referencedSymbol.definition));
for (const ref of referencedSymbol.references) {
cb(documentSpanLocation(ref));
}
},
);
// No re-mapping or isDefinition updatses are required if there's exactly one project
if (isArray(perProjectResults)) {
return perProjectResults;
}
// `isDefinition` is only (definitely) correct in `defaultProject` because we might
// have started the other project searches from related symbols. Propagate the
// correct results to all other projects.
const defaultProjectResults = perProjectResults.get(defaultProject);
if (defaultProjectResults?.[0]?.references[0]?.isDefinition === undefined) {
// Clear all isDefinition properties
perProjectResults.forEach(projectResults => {
for (const referencedSymbol of projectResults) {
for (const ref of referencedSymbol.references) {
delete ref.isDefinition;
}
}
});
}
else {
// Correct isDefinition properties from projects other than defaultProject
const knownSymbolSpans = createDocumentSpanSet(useCaseSensitiveFileNames);
for (const referencedSymbol of defaultProjectResults) {
for (const ref of referencedSymbol.references) {
if (ref.isDefinition) {
knownSymbolSpans.add(ref);
// One is enough - updateIsDefinitionOfReferencedSymbols will fill out the set based on symbols
break;
}
}
}
const updatedProjects = new Set<Project>();
while (true) {
let progress = false;
perProjectResults.forEach((referencedSymbols, project) => {
if (updatedProjects.has(project)) return;
const updated = project.getLanguageService().updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans);
if (updated) {
updatedProjects.add(project);
progress = true;
}
});
if (!progress) break;
}
perProjectResults.forEach((referencedSymbols, project) => {
if (updatedProjects.has(project)) return;
for (const referencedSymbol of referencedSymbols) {
for (const ref of referencedSymbol.references) {
ref.isDefinition = false;
}
}
});
}
// We need to de-duplicate and aggregate the results by choosing an authoritative version
// of each definition and merging references from all the projects where they appear.
const results: ReferencedSymbol[] = [];
const seenRefs = createDocumentSpanSet(useCaseSensitiveFileNames); // It doesn't make sense to have a reference in two definition lists, so we de-dup globally
// TODO: We might end up with a more logical allocation of refs to defs if we pre-sorted the defs by descending ref-count.
// Otherwise, it just ends up attached to the first corresponding def we happen to process. The others may or may not be
// dropped later when we check for defs with ref-count 0.
perProjectResults.forEach((projectResults, project) => {
for (const referencedSymbol of projectResults) {
const mappedDefinitionFile = getMappedLocationForProject(documentSpanLocation(referencedSymbol.definition), project);
const definition: ReferencedSymbolDefinitionInfo = mappedDefinitionFile === undefined ?
referencedSymbol.definition :
{
...referencedSymbol.definition,
textSpan: createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length), // Why would the length be the same in the original?
fileName: mappedDefinitionFile.fileName,
contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project),
};
let symbolToAddTo = find(results, o => documentSpansEqual(o.definition, definition, useCaseSensitiveFileNames));
if (!symbolToAddTo) {
symbolToAddTo = { definition, references: [] };
results.push(symbolToAddTo);
}
for (const ref of referencedSymbol.references) {
if (!seenRefs.has(ref) && !getMappedLocationForProject(documentSpanLocation(ref), project)) {
seenRefs.add(ref);
symbolToAddTo.references.push(ref);
}
}
}
});
return results.filter(o => o.references.length !== 0);
}
interface ProjectAndLocation {
readonly project: Project;
readonly location: DocumentPosition;
}
function forEachProjectInProjects(projects: Projects, path: string | undefined, cb: (project: Project, path: string | undefined) => void): void {
for (const project of isArray(projects) ? projects : projects.projects) {
cb(project, path);
}
if (!isArray(projects) && projects.symLinkedProjects) {
projects.symLinkedProjects.forEach((symlinkedProjects, symlinkedPath) => {
for (const project of symlinkedProjects) {
cb(project, symlinkedPath);
}
});
}
}
/**
* @param projects Projects initially known to contain {@link initialLocation}
* @param defaultProject The default project containing {@link initialLocation}
* @param initialLocation Where the search operation was triggered
* @param getResultsForPosition This is where you plug in `findReferences`, `renameLocation`, etc
* @param forPositionInResult Given an item returned by {@link getResultsForPosition} enumerate the positions referred to by that result
* @returns In the common case where there's only one project, returns an array of results from {@link getResultsForPosition}.
* If multiple projects were searched - even if they didn't return results - the result will be a map from project to per-project results.
*/
function getPerProjectReferences<TResult>(
projects: Projects,
defaultProject: Project,
initialLocation: DocumentPosition,
defaultDefinition: DocumentPosition | undefined,
mapDefinitionInProject: (
definition: DocumentPosition,
project: Project,
getGeneratedDefinition: () => DocumentPosition | undefined,
getSourceDefinition: () => DocumentPosition | undefined,
) => DocumentPosition | undefined,
getResultsForPosition: (project: Project, location: DocumentPosition) => readonly TResult[] | undefined,
forPositionInResult?: (result: TResult, cb: (location: DocumentPosition) => void) => void,
): readonly TResult[] | Map<Project, readonly TResult[]> {
// If `getResultsForPosition` returns results for a project, they go in here
const resultsMap = new Map<Project, readonly TResult[]>();
const queue = createQueue<ProjectAndLocation>();
// In order to get accurate isDefinition values for `defaultProject`,
// we need to ensure that it is searched from `initialLocation`.
// The easiest way to do this is to search it first.
queue.enqueue({ project: defaultProject, location: initialLocation });
// This will queue `defaultProject` a second time, but it will be dropped
// as a dup when it is dequeued.
forEachProjectInProjects(projects, initialLocation.fileName, (project, path) => {
const location = { fileName: path!, pos: initialLocation.pos };
queue.enqueue({ project, location });
});
const projectService = defaultProject.projectService;
const cancellationToken = defaultProject.getCancellationToken();
// Don't call these unless !!defaultDefinition
const getGeneratedDefinition = memoize(() =>
defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition!.fileName) ?
defaultDefinition :
defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition!)
);
const getSourceDefinition = memoize(() =>
defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition!.fileName) ?
defaultDefinition :
defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition!)
);
// The keys of resultsMap allow us to check which projects have already been searched, but we also
// maintain a set of strings because that's what `loadAncestorProjectTree` wants.
const searchedProjectKeys = new Set<string>();
onCancellation:
while (!queue.isEmpty()) {
while (!queue.isEmpty()) {
if (cancellationToken.isCancellationRequested()) break onCancellation;
const { project, location } = queue.dequeue();
if (resultsMap.has(project)) continue;
if (isLocationProjectReferenceRedirect(project, location)) continue;
// The project could be dirty and could no longer contain the location's file after it's updated,
// so we need to update the project and check if it still contains the file.
updateProjectIfDirty(project);
if (!project.containsFile(toNormalizedPath(location.fileName))) {
continue;
}
const projectResults = searchPosition(project, location);
resultsMap.set(project, projectResults ?? emptyArray);
searchedProjectKeys.add(getProjectKey(project));
}
// At this point, we know about all projects passed in as arguments and any projects in which
// `getResultsForPosition` has returned results. We expand that set to include any projects
// downstream from any of these and then queue new initial-position searches for any new project
// containing `initialLocation`.
if (defaultDefinition) {
// This seems to mean "load all projects downstream from any member of `seenProjects`".
projectService.loadAncestorProjectTree(searchedProjectKeys);
projectService.forEachEnabledProject(project => {
if (cancellationToken.isCancellationRequested()) return; // There's no mechanism for skipping the remaining projects
if (resultsMap.has(project)) return; // Can loop forever without this (enqueue here, dequeue above, repeat)
const location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition);
if (location) {
queue.enqueue({ project, location });
}
});
}
}
// In the common case where there's only one project, return a simpler result to make
// it easier for the caller to skip post-processing.
if (resultsMap.size === 1) {
return firstIterator(resultsMap.values());
}
return resultsMap;
function searchPosition(project: Project, location: DocumentPosition): readonly TResult[] | undefined {
const projectResults = getResultsForPosition(project, location);
if (!projectResults || !forPositionInResult) return projectResults;
for (const result of projectResults) {
forPositionInResult(result, position => {
// This may trigger a search for a tsconfig, but there are several layers of caching that make it inexpensive
const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position);
if (!originalLocation) return;
const originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName)!;
for (const project of originalScriptInfo.containingProjects) {
if (!project.isOrphan() && !resultsMap.has(project)) { // Optimization: don't enqueue if will be discarded
queue.enqueue({ project, location: originalLocation });
}
}
const symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo);
if (symlinkedProjectsMap) {
symlinkedProjectsMap.forEach((symlinkedProjects, symlinkedPath) => {
for (const symlinkedProject of symlinkedProjects) {
if (!symlinkedProject.isOrphan() && !resultsMap.has(symlinkedProject)) { // Optimization: don't enqueue if will be discarded
queue.enqueue({ project: symlinkedProject, location: { fileName: symlinkedPath as string, pos: originalLocation.pos } });
}
}
});
}
});
}
return projectResults;
}
}
function mapDefinitionInProjectIfFileInProject(
definition: DocumentPosition,
project: Project,
) {
// If the definition is actually from the project, definition is correct as is
if (
project.containsFile(toNormalizedPath(definition.fileName)) &&
!isLocationProjectReferenceRedirect(project, definition)
) {
return definition;
}
}
function mapDefinitionInProject(
definition: DocumentPosition,
project: Project,
getGeneratedDefinition: () => DocumentPosition | undefined,
getSourceDefinition: () => DocumentPosition | undefined,
): DocumentPosition | undefined {
// If the definition is actually from the project, definition is correct as is
const result = mapDefinitionInProjectIfFileInProject(definition, project);
if (result) return result;
const generatedDefinition = getGeneratedDefinition();
if (generatedDefinition && project.containsFile(toNormalizedPath(generatedDefinition.fileName))) return generatedDefinition;
const sourceDefinition = getSourceDefinition();
return sourceDefinition && project.containsFile(toNormalizedPath(sourceDefinition.fileName)) ? sourceDefinition : undefined;
}
function isLocationProjectReferenceRedirect(project: Project, location: Pick<DocumentPosition, "fileName"> | undefined) {
if (!location) return false;
const program = project.getLanguageService().getProgram();
if (!program) return false;
const sourceFile = program.getSourceFile(location.fileName);
// It is possible that location is attached to project but
// the program actually includes its redirect instead.
// This happens when rootFile in project is one of the file from referenced project
// Thus root is attached but program doesnt have the actual .ts file but .d.ts
// If this is not the file we were actually looking, return rest of the toDo
return !!sourceFile &&
sourceFile.resolvedPath !== sourceFile.path &&
sourceFile.resolvedPath !== project.toPath(location.fileName);
}
function getProjectKey(project: Project) {
return isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName();
}
function documentSpanLocation({ fileName, textSpan }: DocumentSpan): DocumentPosition {
return { fileName, pos: textSpan.start };
}
function getMappedLocationForProject(location: DocumentPosition, project: Project): DocumentPosition | undefined {
return getMappedLocation(location, project.getSourceMapper(), p => project.projectService.fileExists(p as NormalizedPath));
}
function getMappedDocumentSpanForProject(documentSpan: DocumentSpan, project: Project): DocumentSpan | undefined {
return getMappedDocumentSpan(documentSpan, project.getSourceMapper(), p => project.projectService.fileExists(p as NormalizedPath));
}
function getMappedContextSpanForProject(documentSpan: DocumentSpan, project: Project): TextSpan | undefined {
return getMappedContextSpan(documentSpan, project.getSourceMapper(), p => project.projectService.fileExists(p as NormalizedPath));
}
const invalidPartialSemanticModeCommands: readonly protocol.CommandTypes[] = [
protocol.CommandTypes.OpenExternalProject,
protocol.CommandTypes.OpenExternalProjects,
protocol.CommandTypes.CloseExternalProject,
protocol.CommandTypes.SynchronizeProjectList,
protocol.CommandTypes.EmitOutput,
protocol.CommandTypes.CompileOnSaveAffectedFileList,
protocol.CommandTypes.CompileOnSaveEmitFile,
protocol.CommandTypes.CompilerOptionsDiagnosticsFull,
protocol.CommandTypes.EncodedSemanticClassificationsFull,
protocol.CommandTypes.SemanticDiagnosticsSync,
protocol.CommandTypes.SuggestionDiagnosticsSync,
protocol.CommandTypes.GeterrForProject,
protocol.CommandTypes.Reload,
protocol.CommandTypes.ReloadProjects,
protocol.CommandTypes.GetCodeFixes,
protocol.CommandTypes.GetCodeFixesFull,
protocol.CommandTypes.GetCombinedCodeFix,
protocol.CommandTypes.GetCombinedCodeFixFull,
protocol.CommandTypes.ApplyCodeActionCommand,
protocol.CommandTypes.GetSupportedCodeFixes,
protocol.CommandTypes.GetApplicableRefactors,
protocol.CommandTypes.GetMoveToRefactoringFileSuggestions,
protocol.CommandTypes.GetEditsForRefactor,
protocol.CommandTypes.GetEditsForRefactorFull,
protocol.CommandTypes.OrganizeImports,
protocol.CommandTypes.OrganizeImportsFull,
protocol.CommandTypes.GetEditsForFileRename,
protocol.CommandTypes.GetEditsForFileRenameFull,
protocol.CommandTypes.PrepareCallHierarchy,
protocol.CommandTypes.ProvideCallHierarchyIncomingCalls,
protocol.CommandTypes.ProvideCallHierarchyOutgoingCalls,
protocol.CommandTypes.GetPasteEdits,
protocol.CommandTypes.CopilotRelated,
];
const invalidSyntacticModeCommands: readonly protocol.CommandTypes[] = [
...invalidPartialSemanticModeCommands,
protocol.CommandTypes.Definition,
protocol.CommandTypes.DefinitionFull,
protocol.CommandTypes.DefinitionAndBoundSpan,
protocol.CommandTypes.DefinitionAndBoundSpanFull,
protocol.CommandTypes.TypeDefinition,
protocol.CommandTypes.Implementation,
protocol.CommandTypes.ImplementationFull,
protocol.CommandTypes.References,
protocol.CommandTypes.ReferencesFull,
protocol.CommandTypes.Rename,
protocol.CommandTypes.RenameLocationsFull,
protocol.CommandTypes.RenameInfoFull,
protocol.CommandTypes.Quickinfo,
protocol.CommandTypes.QuickinfoFull,
protocol.CommandTypes.CompletionInfo,
protocol.CommandTypes.Completions,
protocol.CommandTypes.CompletionsFull,
protocol.CommandTypes.CompletionDetails,
protocol.CommandTypes.CompletionDetailsFull,
protocol.CommandTypes.SignatureHelp,
protocol.CommandTypes.SignatureHelpFull,
protocol.CommandTypes.Navto,
protocol.CommandTypes.NavtoFull,
protocol.CommandTypes.DocumentHighlights,
protocol.CommandTypes.DocumentHighlightsFull,
protocol.CommandTypes.PreparePasteEdits,
];
export interface SessionOptions {
host: ServerHost;
cancellationToken: ServerCancellationToken;
useSingleInferredProject: boolean;
useInferredProjectPerProjectRoot: boolean;
typingsInstaller?: ITypingsInstaller;
byteLength: (buf: string, encoding?: BufferEncoding) => number;
hrtime: (start?: [number, number]) => [number, number];
logger: Logger;
/**
* If falsy, all events are suppressed.
*/
canUseEvents: boolean;
canUseWatchEvents?: boolean;
eventHandler?: ProjectServiceEventHandler;
/** Has no effect if eventHandler is also specified. */
suppressDiagnosticEvents?: boolean;
serverMode?: LanguageServiceMode;
throttleWaitMilliseconds?: number;
noGetErrOnBackgroundUpdate?: boolean;
globalPlugins?: readonly string[];
pluginProbeLocations?: readonly string[];
allowLocalPluginLoads?: boolean;
typesMapLocation?: string;
/** @internal */ incrementalVerifier?: (service: ProjectService) => void;
}