forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfourslashImpl.ts
4916 lines (4262 loc) · 238 KB
/
fourslashImpl.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 * as fakes from "./_namespaces/fakes";
import * as FourSlashInterface from "./_namespaces/FourSlashInterface";
import * as Harness from "./_namespaces/Harness";
import * as ts from "./_namespaces/ts";
import * as Utils from "./_namespaces/Utils";
import * as vfs from "./_namespaces/vfs";
import * as vpath from "./_namespaces/vpath";
import ArrayOrSingle = FourSlashInterface.ArrayOrSingle;
export const enum FourSlashTestType {
Native,
Shims,
ShimsWithPreprocess,
Server
}
// Represents a parsed source file with metadata
interface FourSlashFile {
// The contents of the file (with markers, etc stripped out)
content: string;
fileName: string;
symlinks?: string[];
version: number;
// File-specific options (name/value pairs)
fileOptions: Harness.TestCaseParser.CompilerSettings;
}
// Represents a set of parsed source files and options
interface FourSlashData {
// Global options (name/value pairs)
globalOptions: Harness.TestCaseParser.CompilerSettings;
files: FourSlashFile[];
symlinks: vfs.FileSet | undefined;
// A mapping from marker names to name/position pairs
markerPositions: Map<string, Marker>;
markers: Marker[];
/**
* Inserted in source files by surrounding desired text
* in a range with `[|` and `|]`. For example,
*
* [|text in range|]
*
* is a range with `text in range` "selected".
*/
ranges: Range[];
rangesByText?: ts.MultiMap<string, Range>;
}
export interface Marker {
fileName: string;
position: number;
data?: {};
}
export interface Range extends ts.TextRange {
fileName: string;
marker?: Marker;
}
interface LocationInformation {
position: number;
sourcePosition: number;
sourceLine: number;
sourceColumn: number;
}
interface RangeLocationInformation extends LocationInformation {
marker?: Marker;
}
interface ImplementationLocationInformation extends ts.ImplementationLocation {
matched?: boolean;
}
export interface TextSpan {
start: number;
end: number;
}
// Name of testcase metadata including ts.CompilerOptions properties that will be used by globalOptions
// To add additional option, add property into the testOptMetadataNames, refer the property in either globalMetadataNames or fileMetadataNames
// Add cases into convertGlobalOptionsToCompilationsSettings function for the compiler to acknowledge such option from meta data
const enum MetadataOptionNames {
baselineFile = "baselinefile",
emitThisFile = "emitthisfile", // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project
fileName = "filename",
resolveReference = "resolvereference", // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file
symlink = "symlink",
}
// List of allowed metadata names
const fileMetadataNames = [MetadataOptionNames.fileName, MetadataOptionNames.emitThisFile, MetadataOptionNames.resolveReference, MetadataOptionNames.symlink];
function convertGlobalOptionsToCompilerOptions(globalOptions: Harness.TestCaseParser.CompilerSettings): ts.CompilerOptions {
const settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5, newLine: ts.NewLineKind.CarriageReturnLineFeed };
Harness.Compiler.setCompilerOptionsFromHarnessSetting(globalOptions, settings);
return settings;
}
export class TestCancellationToken implements ts.HostCancellationToken {
// 0 - cancelled
// >0 - not cancelled
// <0 - not cancelled and value denotes number of isCancellationRequested after which token become cancelled
private static readonly notCanceled = -1;
private numberOfCallsBeforeCancellation = TestCancellationToken.notCanceled;
public isCancellationRequested(): boolean {
if (this.numberOfCallsBeforeCancellation < 0) {
return false;
}
if (this.numberOfCallsBeforeCancellation > 0) {
this.numberOfCallsBeforeCancellation--;
return false;
}
return true;
}
public setCancelled(numberOfCalls = 0): void {
ts.Debug.assert(numberOfCalls >= 0);
this.numberOfCallsBeforeCancellation = numberOfCalls;
}
public resetCancelled(): void {
this.numberOfCallsBeforeCancellation = TestCancellationToken.notCanceled;
}
}
export function verifyOperationIsCancelled(f: () => void) {
try {
f();
}
catch (e) {
if (e instanceof ts.OperationCanceledException) {
return;
}
}
throw new Error("Operation should be cancelled");
}
export function ignoreInterpolations(diagnostic: string | ts.DiagnosticMessage): FourSlashInterface.DiagnosticIgnoredInterpolations {
return { template: typeof diagnostic === "string" ? diagnostic : diagnostic.message };
}
// This function creates IScriptSnapshot object for testing getPreProcessedFileInfo
// Return object may lack some functionalities for other purposes.
function createScriptSnapShot(sourceText: string): ts.IScriptSnapshot {
return ts.ScriptSnapshot.fromString(sourceText);
}
const enum CallHierarchyItemDirection {
Root,
Incoming,
Outgoing
}
export class TestState {
// Language service instance
private languageServiceAdapterHost: Harness.LanguageService.LanguageServiceAdapterHost;
private languageService: ts.LanguageService;
private cancellationToken: TestCancellationToken;
private assertTextConsistent: ((fileName: string) => void) | undefined;
// The current caret position in the active file
public currentCaretPosition = 0;
// The position of the end of the current selection, or -1 if nothing is selected
public selectionEnd = -1;
public lastKnownMarker: string | undefined;
// The file that's currently 'opened'
public activeFile!: FourSlashFile;
// Whether or not we should format on keystrokes
public enableFormatting = true;
public formatCodeSettings: ts.FormatCodeSettings;
private inputFiles = new Map<string, string>(); // Map between inputFile's fileName and its content for easily looking up when resolving references
private static getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[] | undefined) {
let result = "";
ts.forEach(displayParts, part => {
if (result) {
result += ",\n ";
}
else {
result = "[\n ";
}
result += JSON.stringify(part);
});
if (result) {
result += "\n]";
}
return result;
}
// Add input file which has matched file name with the given reference-file path.
// This is necessary when resolveReference flag is specified
private addMatchedInputFile(referenceFilePath: string, extensions: readonly string[] | undefined) {
const inputFiles = this.inputFiles;
const languageServiceAdapterHost = this.languageServiceAdapterHost;
const didAdd = tryAdd(referenceFilePath);
if (extensions && !didAdd) {
ts.forEach(extensions, ext => tryAdd(referenceFilePath + ext));
}
function tryAdd(path: string) {
const inputFile = inputFiles.get(path);
if (inputFile && !Harness.isDefaultLibraryFile(path)) {
languageServiceAdapterHost.addScript(path, inputFile, /*isRootFile*/ true);
return true;
}
}
}
private getLanguageServiceAdapter(testType: FourSlashTestType, cancellationToken: TestCancellationToken, compilationOptions: ts.CompilerOptions): Harness.LanguageService.LanguageServiceAdapter {
switch (testType) {
case FourSlashTestType.Native:
return new Harness.LanguageService.NativeLanguageServiceAdapter(cancellationToken, compilationOptions);
case FourSlashTestType.Shims:
return new Harness.LanguageService.ShimLanguageServiceAdapter(/*preprocessToResolve*/ false, cancellationToken, compilationOptions);
case FourSlashTestType.ShimsWithPreprocess:
return new Harness.LanguageService.ShimLanguageServiceAdapter(/*preprocessToResolve*/ true, cancellationToken, compilationOptions);
case FourSlashTestType.Server:
return new Harness.LanguageService.ServerLanguageServiceAdapter(cancellationToken, compilationOptions);
default:
throw new Error("Unknown FourSlash test type: ");
}
}
constructor(private originalInputFileName: string, private basePath: string, private testType: FourSlashTestType, public testData: FourSlashData) {
// Create a new Services Adapter
this.cancellationToken = new TestCancellationToken();
let compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
compilationOptions.skipDefaultLibCheck = true;
// Initialize the language service with all the scripts
let startResolveFileRef: FourSlashFile | undefined;
let configFileName: string | undefined;
for (const file of testData.files) {
// Create map between fileName and its content for easily looking up when resolveReference flag is specified
this.inputFiles.set(file.fileName, file.content);
if (isConfig(file)) {
const configJson = ts.parseConfigFileTextToJson(file.fileName, file.content);
if (configJson.config === undefined) {
throw new Error(`Failed to parse test ${file.fileName}: ${configJson.error!.messageText}`);
}
// Extend our existing compiler options so that we can also support tsconfig only options
if (configJson.config.compilerOptions) {
const baseDirectory = ts.normalizePath(ts.getDirectoryPath(file.fileName));
const tsConfig = ts.convertCompilerOptionsFromJson(configJson.config.compilerOptions, baseDirectory, file.fileName);
if (!tsConfig.errors || !tsConfig.errors.length) {
compilationOptions = ts.extend(tsConfig.options, compilationOptions);
}
}
configFileName = file.fileName;
}
if (!startResolveFileRef && file.fileOptions[MetadataOptionNames.resolveReference] === "true") {
startResolveFileRef = file;
}
else if (startResolveFileRef) {
// If entry point for resolving file references is already specified, report duplication error
throw new Error("There exists a Fourslash file which has resolveReference flag specified; remove duplicated resolveReference flag");
}
}
let configParseResult: ts.ParsedCommandLine | undefined;
if (configFileName) {
const baseDir = ts.normalizePath(ts.getDirectoryPath(configFileName));
const files: vfs.FileSet = { [baseDir]: {} };
this.inputFiles.forEach((data, path) => {
const scriptInfo = new Harness.LanguageService.ScriptInfo(path, undefined!, /*isRootFile*/ false); // TODO: GH#18217
files[path] = new vfs.File(data, { meta: { scriptInfo } });
});
const fs = new vfs.FileSystem(/*ignoreCase*/ true, { cwd: baseDir, files });
const host = new fakes.ParseConfigHost(fs);
const jsonSourceFile = ts.parseJsonText(configFileName, this.inputFiles.get(configFileName)!);
configParseResult = ts.parseJsonSourceFileConfigFileContent(jsonSourceFile, host, baseDir, compilationOptions, configFileName);
compilationOptions = configParseResult.options;
}
if (compilationOptions.typeRoots) {
compilationOptions.typeRoots = compilationOptions.typeRoots.map(p => ts.getNormalizedAbsolutePath(p, this.basePath));
}
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
this.languageService = memoWrap(languageServiceAdapter.getLanguageService(), this); // Wrap the LS to cache some expensive operations certain tests call repeatedly
if (this.testType === FourSlashTestType.Server) {
this.assertTextConsistent = fileName => (languageServiceAdapter as Harness.LanguageService.ServerLanguageServiceAdapter).assertTextConsistent(fileName);
}
if (startResolveFileRef) {
// Add the entry-point file itself into the languageServiceShimHost
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content, /*isRootFile*/ true);
const resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content);
const referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles;
const importedFiles: ts.FileReference[] = resolvedResult.importedFiles;
// Add triple reference files into language-service host
ts.forEach(referencedFiles, referenceFile => {
// Fourslash insert tests/cases/fourslash into inputFile.unitName so we will properly append the same base directory to refFile path
const referenceFilePath = this.basePath + "/" + referenceFile.fileName;
this.addMatchedInputFile(referenceFilePath, /* extensions */ undefined);
});
const exts = ts.flatten(ts.getSupportedExtensions(compilationOptions));
// Add import files into language-service host
ts.forEach(importedFiles, importedFile => {
// Fourslash insert tests/cases/fourslash into inputFile.unitName and import statement doesn't require ".ts"
// so convert them before making appropriate comparison
const importedFilePath = this.basePath + "/" + importedFile.fileName;
this.addMatchedInputFile(importedFilePath, exts);
});
// Check if no-default-lib flag is false and if so add default library
if (!resolvedResult.isLibFile) {
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile()!.text, /*isRootFile*/ false);
compilationOptions.lib?.forEach(fileName => {
const libFile = Harness.Compiler.getDefaultLibrarySourceFile(fileName);
ts.Debug.assertIsDefined(libFile, `Could not find lib file '${fileName}'`);
if (libFile) {
this.languageServiceAdapterHost.addScript(fileName, libFile.text, /*isRootFile*/ false);
}
});
}
}
else {
// resolveReference file-option is not specified then do not resolve any files and include all inputFiles
this.inputFiles.forEach((file, fileName) => {
if (!Harness.isDefaultLibraryFile(fileName)) {
// all files if config file not specified, otherwise root files from the config and typings cache files are root files
const isRootFile = !configParseResult ||
ts.contains(configParseResult.fileNames, fileName) ||
(ts.isDeclarationFileName(fileName) && ts.containsPath("/Library/Caches/typescript", fileName));
this.languageServiceAdapterHost.addScript(fileName, file, isRootFile);
}
});
if (!compilationOptions.noLib) {
const seen = new Set<string>();
const addSourceFile = (fileName: string) => {
if (seen.has(fileName)) return;
seen.add(fileName);
const libFile = Harness.Compiler.getDefaultLibrarySourceFile(fileName);
ts.Debug.assertIsDefined(libFile, `Could not find lib file '${fileName}'`);
this.languageServiceAdapterHost.addScript(fileName, libFile.text, /*isRootFile*/ false);
if (!ts.some(libFile.libReferenceDirectives)) return;
for (const directive of libFile.libReferenceDirectives) {
addSourceFile(`lib.${directive.fileName}.d.ts`);
}
};
addSourceFile(Harness.Compiler.defaultLibFileName);
compilationOptions.lib?.forEach(addSourceFile);
}
}
for (const file of testData.files) {
ts.forEach(file.symlinks, link => {
this.languageServiceAdapterHost.vfs.mkdirpSync(vpath.dirname(link));
this.languageServiceAdapterHost.vfs.symlinkSync(file.fileName, link);
});
}
if (testData.symlinks) {
this.languageServiceAdapterHost.vfs.apply(testData.symlinks);
}
this.formatCodeSettings = ts.testFormatSettings;
// Open the first file by default
this.openFile(0);
function memoWrap(ls: ts.LanguageService, target: TestState): ts.LanguageService {
const cacheableMembers: (keyof typeof ls)[] = [
"getCompletionEntryDetails",
"getCompletionEntrySymbol",
"getQuickInfoAtPosition",
"getReferencesAtPosition",
"getDocumentHighlights",
];
const proxy = {} as ts.LanguageService;
const keys = ts.getAllKeys(ls);
for (const k of keys) {
const key = k as keyof typeof ls;
if (cacheableMembers.indexOf(key) === -1) {
proxy[key] = (...args: any[]) => (ls[key] as Function)(...args);
continue;
}
const memo = Utils.memoize(
(_version: number, _active: string, _caret: number, _selectEnd: number, _marker: string | undefined, ...args: any[]) => (ls[key] as Function)(...args),
(...args) => args.map(a => a && typeof a === "object" ? JSON.stringify(a) : a).join("|,|")
);
proxy[key] = (...args: any[]) => memo(
target.languageServiceAdapterHost.getScriptInfo(target.activeFile.fileName)!.version,
target.activeFile.fileName,
target.currentCaretPosition,
target.selectionEnd,
target.lastKnownMarker,
...args
);
}
return proxy;
}
}
private getFileContent(fileName: string): string {
return ts.Debug.checkDefined(this.tryGetFileContent(fileName));
}
private tryGetFileContent(fileName: string): string | undefined {
const script = this.languageServiceAdapterHost.getScriptInfo(fileName);
return script && script.content;
}
// Entry points from fourslash.ts
public goToMarker(name: string | Marker = "") {
const marker = ts.isString(name) ? this.getMarkerByName(name) : name;
if (this.activeFile.fileName !== marker.fileName) {
this.openFile(marker.fileName);
}
const content = this.getFileContent(marker.fileName);
if (marker.position === -1 || marker.position > content.length) {
throw new Error(`Marker "${name}" has been invalidated by unrecoverable edits to the file.`);
}
const mName = ts.isString(name) ? name : this.markerName(marker);
this.lastKnownMarker = mName;
this.goToPosition(marker.position);
}
public goToEachMarker(markers: readonly Marker[], action: (marker: Marker, index: number) => void) {
assert(markers.length);
for (let i = 0; i < markers.length; i++) {
this.goToMarker(markers[i]);
action(markers[i], i);
}
}
public goToEachRange(action: (range: Range) => void) {
const ranges = this.getRanges();
assert(ranges.length);
for (const range of ranges) {
this.selectRange(range);
action(range);
}
}
public markerName(m: Marker): string {
return ts.forEachEntry(this.testData.markerPositions, (marker, name) => {
if (marker === m) {
return name;
}
})!;
}
public goToPosition(positionOrLineAndCharacter: number | ts.LineAndCharacter) {
const pos = typeof positionOrLineAndCharacter === "number"
? positionOrLineAndCharacter
: this.languageServiceAdapterHost.lineAndCharacterToPosition(this.activeFile.fileName, positionOrLineAndCharacter);
this.currentCaretPosition = pos;
this.selectionEnd = -1;
}
public select(startMarker: string, endMarker: string) {
const start = this.getMarkerByName(startMarker), end = this.getMarkerByName(endMarker);
ts.Debug.assert(start.fileName === end.fileName);
if (this.activeFile.fileName !== start.fileName) {
this.openFile(start.fileName);
}
this.goToPosition(start.position);
this.selectionEnd = end.position;
}
public selectAllInFile(fileName: string) {
this.openFile(fileName);
this.goToPosition(0);
this.selectionEnd = this.activeFile.content.length;
}
public selectRange(range: Range): void {
this.goToRangeStart(range);
this.selectionEnd = range.end;
}
public selectLine(index: number) {
const lineStart = this.languageServiceAdapterHost.lineAndCharacterToPosition(this.activeFile.fileName, { line: index, character: 0 });
const lineEnd = lineStart + this.getLineContent(index).length;
this.selectRange({ fileName: this.activeFile.fileName, pos: lineStart, end: lineEnd });
}
public moveCaretRight(count = 1) {
this.currentCaretPosition += count;
this.currentCaretPosition = Math.min(this.currentCaretPosition, this.getFileContent(this.activeFile.fileName).length);
this.selectionEnd = -1;
}
// Opens a file given its 0-based index or fileName
public openFile(indexOrName: number | string, content?: string, scriptKindName?: string): void {
const fileToOpen: FourSlashFile = this.findFile(indexOrName);
fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName);
this.activeFile = fileToOpen;
// Let the host know that this file is now open
this.languageServiceAdapterHost.openFile(fileToOpen.fileName, content, scriptKindName);
}
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, shouldExist: boolean) {
const startMarker = this.getMarkerByName(startMarkerName);
const endMarker = this.getMarkerByName(endMarkerName);
const predicate = (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) =>
((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
const exists = this.anyErrorInRange(predicate, startMarker, endMarker);
if (exists !== shouldExist) {
this.printErrorLog(shouldExist, this.getAllDiagnostics());
throw new Error(`${shouldExist ? "Expected" : "Did not expect"} failure between markers: '${startMarkerName}', '${endMarkerName}'`);
}
}
public verifyOrganizeImports(newContent: string, mode?: ts.OrganizeImportsMode, preferences?: ts.UserPreferences) {
const changes = this.languageService.organizeImports({ fileName: this.activeFile.fileName, type: "file", mode }, this.formatCodeSettings, preferences);
this.applyChanges(changes);
this.verifyFileContent(this.activeFile.fileName, newContent);
}
private raiseError(message: string): never {
throw new Error(this.messageAtLastKnownMarker(message));
}
private messageAtLastKnownMarker(message: string) {
const locationDescription = this.lastKnownMarker !== undefined ? this.lastKnownMarker : this.getLineColStringAtPosition(this.currentCaretPosition);
return `At marker '${locationDescription}': ${message}`;
}
private assertionMessageAtLastKnownMarker(msg: string) {
return "\nMarker: " + this.lastKnownMarker + "\nChecking: " + msg + "\n\n";
}
private getDiagnostics(fileName: string, includeSuggestions = false): ts.Diagnostic[] {
return [
...this.languageService.getSyntacticDiagnostics(fileName),
...this.languageService.getSemanticDiagnostics(fileName),
...(includeSuggestions ? this.languageService.getSuggestionDiagnostics(fileName) : ts.emptyArray),
];
}
private getAllDiagnostics(): readonly ts.Diagnostic[] {
return ts.flatMap(this.languageServiceAdapterHost.getFilenames(), fileName => {
if (!ts.isAnySupportedFileExtension(fileName)) {
return [];
}
const baseName = ts.getBaseFileName(fileName);
if (baseName === "package.json" || baseName === "tsconfig.json" || baseName === "jsconfig.json") {
return [];
}
return this.getDiagnostics(fileName);
});
}
public verifyErrorExistsAfterMarker(markerName: string, shouldExist: boolean, after: boolean) {
const marker: Marker = this.getMarkerByName(markerName);
let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) => boolean;
if (after) {
predicate = (errorMinChar: number, errorLimChar: number, startPos: number) =>
((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false;
}
else {
predicate = (errorMinChar: number, errorLimChar: number, startPos: number) =>
((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false;
}
const exists = this.anyErrorInRange(predicate, marker);
const diagnostics = this.getAllDiagnostics();
if (exists !== shouldExist) {
this.printErrorLog(shouldExist, diagnostics);
throw new Error(`${shouldExist ? "Expected" : "Did not expect"} failure at marker '${markerName}'`);
}
}
private anyErrorInRange(predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) => boolean, startMarker: Marker, endMarker?: Marker): boolean {
return this.getDiagnostics(startMarker.fileName).some(({ start, length }) =>
predicate(start!, start! + length!, startMarker.position, endMarker === undefined ? undefined : endMarker.position)); // TODO: GH#18217
}
private printErrorLog(expectErrors: boolean, errors: readonly ts.Diagnostic[]): void {
if (expectErrors) {
Harness.IO.log("Expected error not found. Error list is:");
}
else {
Harness.IO.log("Unexpected error(s) found. Error list is:");
}
for (const { start, length, messageText, file } of errors) {
Harness.IO.log(" " + this.formatRange(file, start!, length!) + // TODO: GH#18217
", message: " + ts.flattenDiagnosticMessageText(messageText, Harness.IO.newLine()) + "\n");
}
}
private formatRange(file: ts.SourceFile | undefined, start: number, length: number) {
if (file) {
return `from: ${this.formatLineAndCharacterOfPosition(file, start)}, to: ${this.formatLineAndCharacterOfPosition(file, start + length)}`;
}
return "global";
}
private formatLineAndCharacterOfPosition(file: ts.SourceFile, pos: number) {
if (file) {
const { line, character } = ts.getLineAndCharacterOfPosition(file, pos);
return `${line}:${character}`;
}
return "global";
}
private formatPosition(file: ts.SourceFile, pos: number) {
if (file) {
return file.fileName + "@" + pos;
}
return "global";
}
public verifyNoErrors() {
ts.forEachKey(this.inputFiles, fileName => {
if (!ts.isAnySupportedFileExtension(fileName)
|| Harness.getConfigNameFromFileName(fileName)
// Can't get a Program in Server tests
|| this.testType !== FourSlashTestType.Server && !ts.getAllowJSCompilerOption(this.getProgram().getCompilerOptions()) && !ts.resolutionExtensionIsTSOrJson(ts.extensionFromPath(fileName))
|| ts.getBaseFileName(fileName) === "package.json") return;
const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion);
if (errors.length) {
this.printErrorLog(/*expectErrors*/ false, errors);
const error = errors[0];
const message = typeof error.messageText === "string" ? error.messageText : error.messageText.messageText;
this.raiseError(`Found an error: ${this.formatPosition(error.file!, error.start!)}: ${message}`);
}
});
}
public verifyErrorExistsAtRange(range: Range, code: number, expectedMessage?: string) {
const span = ts.createTextSpanFromRange(range);
const hasMatchingError = ts.some(
this.getDiagnostics(range.fileName),
({ code, messageText, start, length }) =>
code === code &&
(!expectedMessage || expectedMessage === messageText) &&
ts.isNumber(start) && ts.isNumber(length) &&
ts.textSpansEqual(span, { start, length }));
if (!hasMatchingError) {
this.raiseError(`No error with code ${code} found at provided range.`);
}
}
public verifyNumberOfErrorsInCurrentFile(expected: number) {
const errors = this.getDiagnostics(this.activeFile.fileName);
const actual = errors.length;
if (actual !== expected) {
this.printErrorLog(/*expectErrors*/ false, errors);
const errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")";
Harness.IO.log(errorMsg);
this.raiseError(errorMsg);
}
}
public verifyEval(expr: string, value: any) {
const emit = this.languageService.getEmitOutput(this.activeFile.fileName);
if (emit.outputFiles.length !== 1) {
throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName);
}
const evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); // eslint-disable-line no-new-func
if (evaluation !== value) {
this.raiseError(`Expected evaluation of expression "${expr}" to equal "${value}", but got "${evaluation}"`);
}
}
public verifyGoToDefinitionIs(endMarker: ArrayOrSingle<string>) {
this.verifyGoToXWorker(/*startMarker*/ undefined, toArray(endMarker), () => this.getGoToDefinition());
}
public verifyGoToDefinition(arg0: any, endMarkerNames?: ArrayOrSingle<string | { marker: string, unverified?: boolean }> | { file: string, unverified?: boolean }) {
this.verifyGoToX(arg0, endMarkerNames, () => this.getGoToDefinitionAndBoundSpan());
}
public verifyGoToSourceDefinition(startMarkerNames: ArrayOrSingle<string>, end?: ArrayOrSingle<string | { marker: string, unverified?: boolean }> | { file: string, unverified?: boolean }) {
if (this.testType !== FourSlashTestType.Server) {
this.raiseError("goToSourceDefinition may only be used in fourslash/server tests.");
}
this.verifyGoToX(startMarkerNames, end, () => (this.languageService as ts.server.SessionClient).getSourceDefinitionAndBoundSpan(this.activeFile.fileName, this.currentCaretPosition)!);
}
private getGoToDefinition(): readonly ts.DefinitionInfo[] {
return this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition)!;
}
private getGoToDefinitionAndBoundSpan(): ts.DefinitionInfoAndBoundSpan {
return this.languageService.getDefinitionAndBoundSpan(this.activeFile.fileName, this.currentCaretPosition)!;
}
public verifyGoToType(arg0: any, endMarkerNames?: ArrayOrSingle<string>) {
this.verifyGoToX(arg0, endMarkerNames, () =>
this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition));
}
private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle<string | { marker: string, unverified?: boolean }> | { file: string, unverified?: boolean } | undefined, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) {
if (endMarkerNames) {
this.verifyGoToXPlain(arg0, endMarkerNames, getDefs);
}
else if (ts.isArray(arg0)) {
const pairs = arg0 as readonly [ArrayOrSingle<string>, ArrayOrSingle<string>][];
for (const [start, end] of pairs) {
this.verifyGoToXPlain(start, end, getDefs);
}
}
else {
const obj: { [startMarkerName: string]: ArrayOrSingle<string> } = arg0;
for (const startMarkerName in obj) {
if (ts.hasProperty(obj, startMarkerName)) {
this.verifyGoToXPlain(startMarkerName, obj[startMarkerName], getDefs);
}
}
}
}
private verifyGoToXPlain(startMarkerNames: ArrayOrSingle<string>, endMarkerNames: ArrayOrSingle<string | { marker: string, unverified?: boolean }> | { file: string, unverified?: boolean }, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) {
for (const start of toArray(startMarkerNames)) {
this.verifyGoToXSingle(start, endMarkerNames, getDefs);
}
}
public verifyGoToDefinitionForMarkers(markerNames: string[]) {
for (const markerName of markerNames) {
this.verifyGoToXSingle(`${markerName}Reference`, `${markerName}Definition`, () => this.getGoToDefinition());
}
}
private verifyGoToXSingle(startMarkerName: string, endMarkerNames: ArrayOrSingle<string | { marker: string, unverified?: boolean }> | { file: string, unverified?: boolean }, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) {
this.goToMarker(startMarkerName);
this.verifyGoToXWorker(startMarkerName, toArray(endMarkerNames), getDefs, startMarkerName);
}
private verifyGoToXWorker(startMarker: string | undefined, endMarkers: readonly (string | { marker?: string, file?: string, unverified?: boolean })[], getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined, startMarkerName?: string) {
const defs = getDefs();
let definitions: readonly ts.DefinitionInfo[];
let testName: string;
if (!defs || ts.isArray(defs)) {
definitions = defs as ts.DefinitionInfo[] || [];
testName = "goToDefinitions";
}
else {
this.verifyDefinitionTextSpan(defs, startMarkerName!);
definitions = defs.definitions!; // TODO: GH#18217
testName = "goToDefinitionsAndBoundSpan";
}
if (endMarkers.length !== definitions.length) {
const markers = definitions.map(d => ({ text: "HERE", fileName: d.fileName, position: d.textSpan.start }));
const actual = this.renderMarkers(markers);
this.raiseError(`${testName} failed - expected to find ${endMarkers.length} definitions but got ${definitions.length}\n\n${actual}`);
}
ts.zipWith(endMarkers, definitions, (endMarkerOrFileResult, definition, i) => {
const markerName = typeof endMarkerOrFileResult === "string" ? endMarkerOrFileResult : endMarkerOrFileResult.marker;
const marker = markerName !== undefined ? this.getMarkerByName(markerName) : undefined;
const expectedFileName = marker?.fileName || typeof endMarkerOrFileResult !== "string" && endMarkerOrFileResult.file;
ts.Debug.assert(typeof expectedFileName === "string");
const expectedPosition = marker?.position || 0;
if (ts.comparePaths(expectedFileName, definition.fileName, /*ignoreCase*/ true) !== ts.Comparison.EqualTo || expectedPosition !== definition.textSpan.start) {
const markers = [{ text: "EXPECTED", fileName: expectedFileName, position: expectedPosition }, { text: "ACTUAL", fileName: definition.fileName, position: definition.textSpan.start }];
const text = this.renderMarkers(markers);
this.raiseError(`${testName} failed for definition ${markerName || expectedFileName} (${i}): expected ${expectedFileName} at ${expectedPosition}, got ${definition.fileName} at ${definition.textSpan.start}\n\n${text}\n`);
}
if (definition.unverified && (typeof endMarkerOrFileResult === "string" || !endMarkerOrFileResult.unverified)) {
const isFileResult = typeof endMarkerOrFileResult !== "string" && !!endMarkerOrFileResult.file;
this.raiseError(
`${testName} failed for definition ${markerName || expectedFileName} (${i}): The actual definition was an \`unverified\` result. Use:\n\n` +
` verify.goToDefinition(${startMarker === undefined ? "startMarker" : `"${startMarker}"`}, { ${isFileResult ? `file: "${expectedFileName}"` : `marker: "${markerName}"`}, unverified: true })\n\n` +
`if this is expected.`
);
}
});
}
private verifyDefinitionTextSpan(defs: ts.DefinitionInfoAndBoundSpan, startMarkerName: string) {
const range = this.testData.ranges.find(range => this.markerName(range.marker!) === startMarkerName);
if (!range && !defs.textSpan) {
return;
}
if (!range) {
const marker = this.getMarkerByName(startMarkerName);
const startFile = marker.fileName;
const fileContent = this.getFileContent(startFile);
const spanContent = fileContent.slice(defs.textSpan.start, ts.textSpanEnd(defs.textSpan));
const spanContentWithMarker = spanContent.slice(0, marker.position - defs.textSpan.start) + `/*${startMarkerName}*/` + spanContent.slice(marker.position - defs.textSpan.start);
const suggestedFileContent = (fileContent.slice(0, defs.textSpan.start) + `\x1b[1;4m[|${spanContentWithMarker}|]\x1b[0;31m` + fileContent.slice(ts.textSpanEnd(defs.textSpan)))
.split(/\r?\n/).map(line => " ".repeat(6) + line).join(ts.sys.newLine);
this.raiseError(`goToDefinitionsAndBoundSpan failed. Found a starting TextSpan around '${spanContent}' in '${startFile}' (at position ${defs.textSpan.start}). `
+ `If this is the correct input span, put a fourslash range around it: \n\n${suggestedFileContent}\n`);
}
else {
this.assertTextSpanEqualsRange(defs.textSpan, range, "goToDefinitionsAndBoundSpan failed");
}
}
private renderMarkers(markers: { text: string, fileName: string, position: number }[], useTerminalBoldSequence = true) {
const filesToDisplay = ts.deduplicate(markers.map(m => m.fileName), ts.equateValues);
return filesToDisplay.map(fileName => {
const markersToRender = markers.filter(m => m.fileName === fileName).sort((a, b) => b.position - a.position);
let fileContent = this.tryGetFileContent(fileName) || "";
for (const marker of markersToRender) {
fileContent = fileContent.slice(0, marker.position) + bold(`/*${marker.text}*/`) + fileContent.slice(marker.position);
}
return `// @Filename: ${fileName}\n${fileContent}`;
}).join("\n\n");
function bold(text: string) {
return useTerminalBoldSequence ? `\x1b[1;4m${text}\x1b[0;31m` : text;
}
}
public verifyGetEmitOutputForCurrentFile(expected: string): void {
const emit = this.languageService.getEmitOutput(this.activeFile.fileName);
if (emit.outputFiles.length !== 1) {
throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName);
}
const actual = emit.outputFiles[0].text;
if (actual !== expected) {
this.raiseError(`Expected emit output to be "${expected}", but got "${actual}"`);
}
}
public verifyGetEmitOutputContentsForCurrentFile(expected: ts.OutputFile[]): void {
const emit = this.languageService.getEmitOutput(this.activeFile.fileName);
assert.equal(emit.outputFiles.length, expected.length, "Number of emit output files");
ts.zipWith(emit.outputFiles, expected, (outputFile, expected) => {
assert.equal(outputFile.name, expected.name, "FileName");
assert.equal(outputFile.text, expected.text, "Content");
});
}
public verifyInlayHints(expected: readonly FourSlashInterface.VerifyInlayHintsOptions[], span: ts.TextSpan = { start: 0, length: this.activeFile.content.length }, preference?: ts.UserPreferences) {
const hints = this.languageService.provideInlayHints(this.activeFile.fileName, span, preference);
assert.equal(hints.length, expected.length, "Number of hints");
interface HasPosition { position: number; }
const sortHints = (a: HasPosition, b: HasPosition) => {
return a.position - b.position;
};
ts.zipWith(hints.sort(sortHints), [...expected].sort(sortHints), (actual, expected) => {
assert.equal(actual.text, expected.text, "Text");
assert.equal(actual.position, expected.position, "Position");
assert.equal(actual.kind, expected.kind, "Kind");
assert.equal(actual.whitespaceBefore, expected.whitespaceBefore, "whitespaceBefore");
assert.equal(actual.whitespaceAfter, expected.whitespaceAfter, "whitespaceAfter");
});
}
public verifyCompletions(options: FourSlashInterface.VerifyCompletionsOptions) {
if (options.marker === undefined) {
return this.verifyCompletionsWorker(options);
}
else {
if (ts.isArray(options.marker)) {
for (const marker of options.marker) {
this.goToMarker(marker);
this.verifyCompletionsWorker({ ...options, marker });
}
return {
andApplyCodeAction: () => {
this.raiseError(`Cannot apply code action when multiple markers are specified.`);
}
};
}
this.goToMarker(options.marker);
return this.verifyCompletionsWorker({ ...options, marker: options.marker });
}
}
private verifyCompletionsWorker(options: FourSlashInterface.VerifyCompletionsOptions) {
const preferences = options.preferences;
const actualCompletions = this.getCompletionListAtCaret({ ...preferences, triggerCharacter: options.triggerCharacter })!;
if (!actualCompletions) {
if (ts.hasProperty(options, "exact") && (options.exact === undefined || ts.isArray(options.exact) && !options.exact.length)) {
return;
}
this.raiseError(`No completions at position '${this.currentCaretPosition}'.`);
}
if (actualCompletions.isNewIdentifierLocation !== (options.isNewIdentifierLocation || false)) {
this.raiseError(`Expected 'isNewIdentifierLocation' to be ${options.isNewIdentifierLocation || false}, got ${actualCompletions.isNewIdentifierLocation}`);
}
if (ts.hasProperty(options, "isGlobalCompletion") && actualCompletions.isGlobalCompletion !== options.isGlobalCompletion) {
this.raiseError(`Expected 'isGlobalCompletion to be ${options.isGlobalCompletion}, got ${actualCompletions.isGlobalCompletion}`);
}
if (ts.hasProperty(options, "optionalReplacementSpan")) {
assert.deepEqual(
actualCompletions.optionalReplacementSpan && actualCompletions.optionalReplacementSpan,
options.optionalReplacementSpan && ts.createTextSpanFromRange(options.optionalReplacementSpan),
"Expected 'optionalReplacementSpan' properties to match");
}
const nameToEntries = new Map<string, ts.CompletionEntry[]>();
const nameAndSourceToData = new Map<string, ts.CompletionEntryData | false>();
for (const entry of actualCompletions.entries) {
const entries = nameToEntries.get(entry.name);
if (!entries) {
nameToEntries.set(entry.name, [entry]);
}
else {
if (entries.some(e =>
e.source === entry.source &&
e.data?.exportName === entry.data?.exportName &&
e.data?.fileName === entry.data?.fileName &&
e.data?.moduleSpecifier === entry.data?.moduleSpecifier &&
e.data?.ambientModuleName === entry.data?.ambientModuleName
)) {
this.raiseError(`Duplicate completions for ${entry.name}`);
}
entries.push(entry);
}
if (entry.data && entry.source) {
const key = `${entry.name}|${entry.source}`;
if (nameAndSourceToData.has(key)) {
nameAndSourceToData.set(key, false);
}
else {
nameAndSourceToData.set(key, entry.data);
}
}
}
if (ts.hasProperty(options, "exact")) {
ts.Debug.assert(!ts.hasProperty(options, "includes") && !ts.hasProperty(options, "excludes") && !ts.hasProperty(options, "unsorted"));
if (options.exact === undefined) throw this.raiseError("Expected no completions");
this.verifyCompletionsAreExactly(actualCompletions.entries, options.exact, options.marker);
}
else if (options.unsorted) {
ts.Debug.assert(!ts.hasProperty(options, "includes") && !ts.hasProperty(options, "excludes"));
for (const expectedEntry of options.unsorted) {
const name = typeof expectedEntry === "string" ? expectedEntry : expectedEntry.name;
const found = nameToEntries.get(name);
if (!found) throw this.raiseError(`Unsorted: completion '${name}' not found.`);
if (!found.length) throw this.raiseError(`Unsorted: no completions with name '${name}' remain unmatched.`);
this.verifyCompletionEntry(found.shift()!, expectedEntry);
}
if (actualCompletions.entries.length !== options.unsorted.length) {
const unmatched: string[] = [];
nameToEntries.forEach(entries => {
unmatched.push(...entries.map(e => e.name));
});
this.raiseError(`Additional completions found not included in 'unsorted': ${unmatched.join("\n")}`);
}
}
else {
if (options.includes) {
for (const include of toArray(options.includes)) {
const name = typeof include === "string" ? include : include.name;
const found = nameToEntries.get(name);
if (!found) throw this.raiseError(`Includes: completion '${name}' not found.`);
if (!found.length) throw this.raiseError(`Includes: no completions with name '${name}' remain unmatched.`);
this.verifyCompletionEntry(found.shift()!, include);
}
}
if (options.excludes) {
for (const exclude of toArray(options.excludes)) {
assert(typeof exclude === "string");
if (nameToEntries.has(exclude)) {
this.raiseError(`Excludes: unexpected completion '${exclude}' found.`);
}
}
}
}