-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathfourslash.ts
2741 lines (2269 loc) · 128 KB
/
fourslash.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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// <reference path='..\services\services.ts' />
/// <reference path='..\services\shims.ts' />
/// <reference path='harnessLanguageService.ts' />
/// <reference path='harness.ts' />
/// <reference path='fourslashRunner.ts' />
module FourSlash {
ts.disableIncrementalParsing = false;
// Represents a parsed source file with metadata
export interface FourSlashFile {
// The contents of the file (with markers, etc stripped out)
content: string;
fileName: string;
version: number;
// File-specific options (name/value pairs)
fileOptions: { [index: string]: string; };
}
// Represents a set of parsed source files and options
export interface FourSlashData {
// Global options (name/value pairs)
globalOptions: { [index: string]: string; };
files: FourSlashFile[];
// A mapping from marker names to name/position pairs
markerPositions: { [index: string]: Marker; };
markers: Marker[];
ranges: Range[];
}
export interface TestXmlData {
invalidReason: string;
originalName: string;
actions: string[];
}
interface MemberListData {
result: {
maybeInaccurate: boolean;
isMemberCompletion: boolean;
entries: {
name: string;
type: string;
kind: string;
kindModifiers: string;
}[];
};
}
export interface Marker {
fileName: string;
position: number;
data?: any;
}
interface MarkerMap {
[index: string]: Marker;
}
export interface Range {
fileName: string;
start: number;
end: number;
marker?: Marker;
}
interface ILocationInformation {
position: number;
sourcePosition: number;
sourceLine: number;
sourceColumn: number;
}
interface IRangeLocationInformation extends ILocationInformation {
marker?: Marker;
}
export interface TextSpan {
start: number;
end: number;
}
let entityMap: ts.Map<string> = {
'&': '&',
'"': '"',
"'": ''',
'/': '/',
'<': '<',
'>': '>'
};
export function escapeXmlAttributeValue(s: string) {
return s.replace(/[&<>"'\/]/g, ch => entityMap[ch]);
}
// 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
let metadataOptionNames = {
baselineFile: 'BaselineFile',
declaration: 'declaration',
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',
mapRoot: 'mapRoot',
module: 'module',
out: 'out',
outDir: 'outDir',
sourceMap: 'sourceMap',
sourceRoot: 'sourceRoot',
allowNonTsExtensions: 'allowNonTsExtensions',
resolveReference: 'ResolveReference', // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file
};
// List of allowed metadata names
let fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference];
let globalMetadataNames = [metadataOptionNames.allowNonTsExtensions, metadataOptionNames.baselineFile, metadataOptionNames.declaration,
metadataOptionNames.mapRoot, metadataOptionNames.module, metadataOptionNames.out,
metadataOptionNames.outDir, metadataOptionNames.sourceMap, metadataOptionNames.sourceRoot];
function convertGlobalOptionsToCompilerOptions(globalOptions: { [idx: string]: string }): ts.CompilerOptions {
let settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 };
// Convert all property in globalOptions into ts.CompilationSettings
for (let prop in globalOptions) {
if (globalOptions.hasOwnProperty(prop)) {
switch (prop) {
case metadataOptionNames.allowNonTsExtensions:
settings.allowNonTsExtensions = globalOptions[prop] === "true";
break;
case metadataOptionNames.declaration:
settings.declaration = globalOptions[prop] === "true";
break;
case metadataOptionNames.mapRoot:
settings.mapRoot = globalOptions[prop];
break;
case metadataOptionNames.module:
// create appropriate external module target for CompilationSettings
switch (globalOptions[prop]) {
case "AMD":
settings.module = ts.ModuleKind.AMD;
break;
case "CommonJS":
settings.module = ts.ModuleKind.CommonJS;
break;
default:
ts.Debug.assert(globalOptions[prop] === undefined || globalOptions[prop] === "None");
settings.module = ts.ModuleKind.None;
break;
}
break;
case metadataOptionNames.out:
settings.out = globalOptions[prop];
break;
case metadataOptionNames.outDir:
settings.outDir = globalOptions[prop];
break;
case metadataOptionNames.sourceMap:
settings.sourceMap = globalOptions[prop] === "true";
break;
case metadataOptionNames.sourceRoot:
settings.sourceRoot = globalOptions[prop];
break;
}
}
}
return settings;
}
export let currentTestState: TestState = null;
function assertionMessage(msg: string) {
return "\nMarker: " + currentTestState.lastKnownMarker + "\nChecking: " + msg + "\n\n";
}
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 NotCanceled: number = -1;
private numberOfCallsBeforeCancellation: number = TestCancellationToken.NotCanceled;
public isCancellationRequested(): boolean {
if (this.numberOfCallsBeforeCancellation < 0) {
return false;
}
if (this.numberOfCallsBeforeCancellation > 0) {
this.numberOfCallsBeforeCancellation--;
return false;
}
return true;
}
public setCancelled(numberOfCalls: number = 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");
}
// This function creates IScriptSnapshot object for testing getPreProcessedFileInfo
// Return object may lack some functionalities for other purposes.
function createScriptSnapShot(sourceText: string): ts.IScriptSnapshot {
return {
getText: (start: number, end: number) => {
return sourceText.substr(start, end - start);
},
getLength: () => {
return sourceText.length;
},
getChangeRange: (oldSnapshot: ts.IScriptSnapshot) => {
return <ts.TextChangeRange>undefined;
}
};
}
export class TestState {
// Language service instance
private languageServiceAdapterHost: Harness.LanguageService.LanguageServiceAdapterHost;
private languageService: ts.LanguageService;
private cancellationToken: TestCancellationToken;
// The current caret position in the active file
public currentCaretPosition = 0;
public lastKnownMarker: string = "";
// The file that's currently 'opened'
public activeFile: FourSlashFile = null;
// Whether or not we should format on keystrokes
public enableFormatting = true;
public formatCodeOptions: ts.FormatCodeOptions;
private scenarioActions: string[] = [];
private taoInvalidReason: string = null;
private inputFiles: ts.Map<string> = {}; // Map between inputFile's fileName and its content for easily looking up when resolving references
// 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) {
let inputFile = this.inputFiles[referenceFilePath];
if (inputFile && !Harness.isLibraryFile(referenceFilePath)) {
this.languageServiceAdapterHost.addScript(referenceFilePath, inputFile);
}
}
private getLanguageServiceAdapter(testType: FourSlashTestType, cancellationToken: TestCancellationToken, compilationOptions: ts.CompilerOptions): Harness.LanguageService.LanguageServiceAdapter {
switch (testType) {
case FourSlashTestType.Native:
return new Harness.LanguageService.NativeLanugageServiceAdapter(cancellationToken, compilationOptions);
case FourSlashTestType.Shims:
return new Harness.LanguageService.ShimLanugageServiceAdapter(cancellationToken, compilationOptions);
case FourSlashTestType.Server:
return new Harness.LanguageService.ServerLanugageServiceAdapter(cancellationToken, compilationOptions);
default:
throw new Error("Unknown FourSlash test type: ");
}
}
constructor(private basePath: string, private testType: FourSlashTestType, public testData: FourSlashData) {
// Create a new Services Adapter
this.cancellationToken = new TestCancellationToken();
let compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
let languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
this.languageService = languageServiceAdapter.getLanguageService();
// Initialize the language service with all the scripts
let startResolveFileRef: FourSlashFile;
ts.forEach(testData.files, file => {
// Create map between fileName and its content for easily looking up when resolveReference flag is specified
this.inputFiles[file.fileName] = file.content;
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");
}
});
if (startResolveFileRef) {
// Add the entry-point file itself into the languageServiceShimHost
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content);
let resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content);
let referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles;
let 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
let referenceFilePath = this.basePath + '/' + referenceFile.fileName;
this.addMatchedInputFile(referenceFilePath);
});
// 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
let importedFilePath = this.basePath + '/' + importedFile.fileName + ".ts";
this.addMatchedInputFile(importedFilePath);
});
// 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.defaultLibSourceFile.text);
}
}
else {
// resolveReference file-option is not specified then do not resolve any files and include all inputFiles
ts.forEachKey(this.inputFiles, fileName => {
if (!Harness.isLibraryFile(fileName)) {
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName]);
}
});
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.defaultLibSourceFile.text);
}
this.formatCodeOptions = {
IndentSize: 4,
TabSize: 4,
NewLineCharacter: ts.sys.newLine,
ConvertTabsToSpaces: true,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
InsertSpaceBeforeAndAfterBinaryOperators: true,
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
};
this.testData.files.forEach(file => {
let fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), '').substr(1);
let fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf("."));
this.scenarioActions.push('<CreateFileOnDisk FileId="' + fileName + '" FileNameWithoutExtension="' + fileNameWithoutExtension + '" FileExtension=".ts"><![CDATA[' + file.content + ']]></CreateFileOnDisk>');
});
// Open the first file by default
this.openFile(0);
}
private getFileContent(fileName: string): string {
let script = this.languageServiceAdapterHost.getScriptInfo(fileName);
return script.content;
}
// Entry points from fourslash.ts
public goToMarker(name = '') {
let marker = this.getMarkerByName(name);
if (this.activeFile.fileName !== marker.fileName) {
this.openFile(marker.fileName);
}
let 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.');
}
this.lastKnownMarker = name;
this.goToPosition(marker.position);
}
public goToPosition(pos: number) {
this.currentCaretPosition = pos;
let lineStarts = ts.computeLineStarts(this.getFileContent(this.activeFile.fileName));
let lineCharPos = ts.computeLineAndCharacterOfPosition(lineStarts, pos);
this.scenarioActions.push(`<MoveCaretToLineAndChar LineNumber=${ lineCharPos.line + 1 } CharNumber=${ lineCharPos.character + 1 } />`);
}
public moveCaretRight(count = 1) {
this.currentCaretPosition += count;
this.currentCaretPosition = Math.min(this.currentCaretPosition, this.getFileContent(this.activeFile.fileName).length);
if (count > 0) {
this.scenarioActions.push('<MoveCaretRight NumberOfChars="' + count + '" />');
} else {
this.scenarioActions.push('<MoveCaretLeft NumberOfChars="' + (-count) + '" />');
}
}
// Opens a file given its 0-based index or fileName
public openFile(index: number): void;
public openFile(name: string): void;
public openFile(indexOrName: any) {
let fileToOpen: FourSlashFile = this.findFile(indexOrName);
fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName);
this.activeFile = fileToOpen;
let fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), '').substr(1);
this.scenarioActions.push('<OpenFile FileName="" SrcFileId="' + fileName + '" FileId="' + fileName + '" />');
// Let the host know that this file is now open
this.languageServiceAdapterHost.openFile(fileToOpen.fileName);
}
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
let startMarker = this.getMarkerByName(startMarkerName);
let endMarker = this.getMarkerByName(endMarkerName);
let predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
};
let exists = this.anyErrorInRange(predicate, startMarker, endMarker);
this.taoInvalidReason = 'verifyErrorExistsBetweenMarkers NYI';
if (exists !== negative) {
this.printErrorLog(negative, this.getAllDiagnostics());
throw new Error("Failure between markers: " + startMarkerName + ", " + endMarkerName);
}
}
private raiseError(message: string) {
message = this.messageAtLastKnownMarker(message);
throw new Error(message);
}
private messageAtLastKnownMarker(message: string) {
return "Marker: " + currentTestState.lastKnownMarker + "\n" + message;
}
private getDiagnostics(fileName: string): ts.Diagnostic[] {
let syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName);
let semanticErrors = this.languageService.getSemanticDiagnostics(fileName);
let diagnostics: ts.Diagnostic[] = [];
diagnostics.push.apply(diagnostics, syntacticErrors);
diagnostics.push.apply(diagnostics, semanticErrors);
return diagnostics;
}
private getAllDiagnostics(): ts.Diagnostic[] {
let diagnostics: ts.Diagnostic[] = [];
let fileNames = this.languageServiceAdapterHost.getFilenames();
for (let i = 0, n = fileNames.length; i < n; i++) {
diagnostics.push.apply(this.getDiagnostics(fileNames[i]));
}
return diagnostics;
}
public verifyErrorExistsAfterMarker(markerName: string, negative: boolean, after: boolean) {
let marker: Marker = this.getMarkerByName(markerName);
let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean;
if (after) {
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false;
};
} else {
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false;
};
}
this.taoInvalidReason = 'verifyErrorExistsAfterMarker NYI';
let exists = this.anyErrorInRange(predicate, marker);
let diagnostics = this.getAllDiagnostics();
if (exists !== negative) {
this.printErrorLog(negative, diagnostics);
throw new Error("Failure at marker: " + markerName);
}
}
private anyErrorInRange(predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean, startMarker: Marker, endMarker?: Marker) {
let errors = this.getDiagnostics(startMarker.fileName);
let exists = false;
let startPos = startMarker.position;
let endPos: number = undefined;
if (endMarker !== undefined) {
endPos = endMarker.position;
}
errors.forEach(function (error: ts.Diagnostic) {
if (predicate(error.start, error.start + error.length, startPos, endPos)) {
exists = true;
}
});
return exists;
}
private printErrorLog(expectErrors: boolean, errors: ts.Diagnostic[]) {
if (expectErrors) {
Harness.IO.log("Expected error not found. Error list is:");
} else {
Harness.IO.log("Unexpected error(s) found. Error list is:");
}
errors.forEach(function (error: ts.Diagnostic) {
Harness.IO.log(" minChar: " + error.start +
", limChar: " + (error.start + error.length) +
", message: " + ts.flattenDiagnosticMessageText(error.messageText, ts.sys.newLine) + "\n");
});
}
public verifyNumberOfErrorsInCurrentFile(expected: number) {
let errors = this.getDiagnostics(this.activeFile.fileName);
let actual = errors.length;
this.scenarioActions.push('<CheckErrorList ExpectedNumOfErrors="' + expected + '" />');
if (actual !== expected) {
this.printErrorLog(false, errors);
let 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) {
let 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);
}
this.taoInvalidReason = 'verifyEval impossible';
let evaluation = new Function(emit.outputFiles[0].text + ';\r\nreturn (' + expr + ');')();
if (evaluation !== value) {
this.raiseError('Expected evaluation of expression "' + expr + '" to equal "' + value + '", but got "' + evaluation + '"');
}
}
public verifyGetEmitOutputForCurrentFile(expected: string): void {
let 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);
}
this.taoInvalidReason = 'verifyGetEmitOutputForCurrentFile impossible';
let actual = emit.outputFiles[0].text;
if (actual !== expected) {
this.raiseError("Expected emit output to be '" + expected + "', but got '" + actual + "'");
}
}
public verifyMemberListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionContainsItem ItemName="' + symbol + '"/>');
if (text || documentation || kind) {
this.taoInvalidReason = 'verifyMemberListContains only supports the "symbol" parameter';
}
let members = this.getMemberListAtCaret();
if (members) {
this.assertItemInCompletionList(members.entries, symbol, text, documentation, kind);
}
else {
this.raiseError("Expected a member list, but none was provided");
}
}
public verifyMemberListCount(expectedCount: number, negative: boolean) {
if (expectedCount === 0) {
if (negative) {
this.verifyMemberListIsEmpty(false);
return;
} else {
this.scenarioActions.push('<ShowCompletionList />');
}
} else {
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionItemsCount Count="' + expectedCount + '" ' + (negative ? 'ExpectsFailure="true"' : '') + ' />');
}
let members = this.getMemberListAtCaret();
if (members) {
let match = members.entries.length === expectedCount;
if ((!match && !negative) || (match && negative)) {
this.raiseError("Member list count was " + members.entries.length + ". Expected " + expectedCount);
}
}
else if (expectedCount) {
this.raiseError("Member list count was 0. Expected " + expectedCount);
}
}
public verifyMemberListDoesNotContain(symbol: string) {
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionDoesNotContainItem ItemName="' + escapeXmlAttributeValue(symbol) + '" />');
let members = this.getMemberListAtCaret();
if (members && members.entries.filter(e => e.name === symbol).length !== 0) {
this.raiseError('Member list did contain ' + symbol);
}
}
public verifyCompletionListItemsCountIsGreaterThan(count: number) {
this.taoInvalidReason = 'verifyCompletionListItemsCountIsGreaterThan NYI';
let completions = this.getCompletionListAtCaret();
let itemsCount = completions.entries.length;
if (itemsCount <= count) {
this.raiseError('Expected completion list items count to be greater than ' + count + ', but is actually ' + itemsCount);
}
}
public verifyMemberListIsEmpty(negative: boolean) {
if (negative) {
this.scenarioActions.push('<ShowCompletionList />');
} else {
this.scenarioActions.push('<ShowCompletionList ExpectsFailure="true" />');
}
let members = this.getMemberListAtCaret();
if ((!members || members.entries.length === 0) && negative) {
this.raiseError("Member list is empty at Caret");
} else if ((members && members.entries.length !== 0) && !negative) {
let errorMsg = "\n" + "Member List contains: [" + members.entries[0].name;
for (let i = 1; i < members.entries.length; i++) {
errorMsg += ", " + members.entries[i].name;
}
errorMsg += "]\n";
this.raiseError("Member list is not empty at Caret: " + errorMsg);
}
}
public verifyCompletionListIsEmpty(negative: boolean) {
this.scenarioActions.push('<ShowCompletionList ExpectsFailure="true" />');
let completions = this.getCompletionListAtCaret();
if ((!completions || completions.entries.length === 0) && negative) {
this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition);
}
else if (completions && completions.entries.length !== 0 && !negative) {
let errorMsg = "\n" + "Completion List contains: [" + completions.entries[0].name;
for (let i = 1; i < completions.entries.length; i++) {
errorMsg += ", " + completions.entries[i].name;
}
errorMsg += "]\n";
this.raiseError("Completion list is not empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition + errorMsg);
}
}
public verifyCompletionListAllowsNewIdentifier(negative: boolean) {
let completions = this.getCompletionListAtCaret();
if ((completions && !completions.isNewIdentifierLocation) && !negative) {
this.raiseError("Expected builder completion entry");
} else if ((completions && completions.isNewIdentifierLocation) && negative) {
this.raiseError("Un-expected builder completion entry");
}
}
public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
let completions = this.getCompletionListAtCaret();
if (completions) {
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind);
}
else {
this.raiseError(`No completions at position '${ this.currentCaretPosition }' when looking for '${ symbol }'.`);
}
}
/**
* Verify that the completion list does NOT contain the given symbol.
* The symbol is considered matched with the symbol in the list if and only if all given parameters must matched.
* When any parameter is omitted, the parameter is ignored during comparison and assumed that the parameter with
* that property of the symbol in the list.
* @param symbol the name of symbol
* @param expectedText the text associated with the symbol
* @param expectedDocumentation the documentation text associated with the symbol
* @param expectedKind the kind of symbol (see ScriptElementKind)
*/
public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string) {
let that = this;
function filterByTextOrDocumentation(entry: ts.CompletionEntry) {
let details = that.getCompletionEntryDetails(entry.name);
let documentation = ts.displayPartsToString(details.documentation);
let text = ts.displayPartsToString(details.displayParts);
if (expectedText && expectedDocumentation) {
return (documentation === expectedDocumentation && text === expectedText) ? true : false;
}
else if (expectedText && !expectedDocumentation) {
return text === expectedText ? true : false;
}
else if (expectedDocumentation && !expectedText) {
return documentation === expectedDocumentation ? true : false;
}
// Because expectedText and expectedDocumentation are undefined, we assume that
// users don't care to compare them so we will treat that entry as if the entry has matching text and documentation
// and keep it in the list of filtered entry.
return true;
}
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionDoesNotContainItem ItemName="' + escapeXmlAttributeValue(symbol) + '" />');
let completions = this.getCompletionListAtCaret();
if (completions) {
let filterCompletions = completions.entries.filter(e => e.name === symbol);
filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind) : filterCompletions;
filterCompletions = filterCompletions.filter(filterByTextOrDocumentation);
if (filterCompletions.length !== 0) {
// After filtered using all present criterion, if there are still symbol left in the list
// then these symbols must meet the criterion for Not supposed to be in the list. So we
// raise an error
let error = "Completion list did contain \'" + symbol + "\'.";
let details = this.getCompletionEntryDetails(filterCompletions[0].name);
if (expectedText) {
error += "Expected text: " + expectedText + " to equal: " + ts.displayPartsToString(details.displayParts) + ".";
}
if (expectedDocumentation) {
error += "Expected documentation: " + expectedDocumentation + " to equal: " + ts.displayPartsToString(details.documentation) + ".";
}
if (expectedKind) {
error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + ".";
}
this.raiseError(error);
}
}
}
public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string) {
this.taoInvalidReason = 'verifyCompletionEntryDetails NYI';
let details = this.getCompletionEntryDetails(entryName);
assert.equal(ts.displayPartsToString(details.displayParts), expectedText, assertionMessage("completion entry details text"));
if (expectedDocumentation !== undefined) {
assert.equal(ts.displayPartsToString(details.documentation), expectedDocumentation, assertionMessage("completion entry documentation"));
}
if (kind !== undefined) {
assert.equal(details.kind, kind, assertionMessage("completion entry kind"));
}
}
public verifyReferencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) {
this.taoInvalidReason = 'verifyReferencesAtPositionListContains NYI';
let references = this.getReferencesAtCaret();
if (!references || references.length === 0) {
this.raiseError('verifyReferencesAtPositionListContains failed - found 0 references, expected at least one.');
}
for (let i = 0; i < references.length; i++) {
let reference = references[i];
if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) {
if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) {
this.raiseError('verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.');
}
return;
}
}
let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess };
this.raiseError('verifyReferencesAtPositionListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(references) + ')');
}
public verifyReferencesCountIs(count: number, localFilesOnly: boolean = true) {
this.taoInvalidReason = 'verifyReferences NYI';
let references = this.getReferencesAtCaret();
let referencesCount = 0;
if (localFilesOnly) {
let localFiles = this.testData.files.map<string>(file => file.fileName);
// Count only the references in local files. Filter the ones in lib and other files.
ts.forEach(references, entry => {
if (localFiles.some((fileName) => fileName === entry.fileName)) {
++referencesCount;
}
});
}
else {
referencesCount = references && references.length || 0;
}
if (referencesCount !== count) {
let condition = localFilesOnly ? "excluding libs" : "including libs";
this.raiseError("Expected references count (" + condition + ") to be " + count + ", but is actually " + referencesCount);
}
}
private getMemberListAtCaret() {
return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition);
}
private getCompletionListAtCaret() {
return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition);
}
private getCompletionEntryDetails(entryName: string) {
return this.languageService.getCompletionEntryDetails(this.activeFile.fileName, this.currentCaretPosition, entryName);
}
private getReferencesAtCaret() {
return this.languageService.getReferencesAtPosition(this.activeFile.fileName, this.currentCaretPosition);
}
private assertionMessage(name: string, actualValue: any, expectedValue: any) {
return "\nActual " + name + ":\n\t" + actualValue + "\nExpected value:\n\t" + expectedValue;
}
public getSyntacticDiagnostics(expected: string) {
let diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
this.testDiagnostics(expected, diagnostics);
}
public getSemanticDiagnostics(expected: string) {
let diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
this.testDiagnostics(expected, diagnostics);
}
private testDiagnostics(expected: string, diagnostics: ts.Diagnostic[]) {
let realized = ts.realizeDiagnostics(diagnostics, "\r\n");
let actual = JSON.stringify(realized, null, " ");
assert.equal(actual, expected);
}
public verifyQuickInfoString(negative: boolean, expectedText?: string, expectedDocumentation?: string) {
[expectedText, expectedDocumentation].forEach(str => {
if (str) {
this.scenarioActions.push('<ShowQuickInfo />');
this.scenarioActions.push('<VerifyQuickInfoTextContains IgnoreSpacing="true" Text="' + escapeXmlAttributeValue(str) + '" ' + (negative ? 'ExpectsFailure="true"' : '') + ' />');
}
});
let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
let actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : "";
let actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : "";
if (negative) {
if (expectedText !== undefined) {
assert.notEqual(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
}
// TODO: should be '==='?
if (expectedDocumentation != undefined) {
assert.notEqual(actualQuickInfoDocumentation, expectedDocumentation, this.messageAtLastKnownMarker("quick info doc comment"));
}
} else {
if (expectedText !== undefined) {
assert.equal(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
}
// TODO: should be '==='?
if (expectedDocumentation != undefined) {
assert.equal(actualQuickInfoDocumentation, expectedDocumentation, assertionMessage("quick info doc"));
}
}
}
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; },
displayParts: ts.SymbolDisplayPart[],
documentation: ts.SymbolDisplayPart[]) {
this.scenarioActions.push('<ShowQuickInfo />');
this.scenarioActions.push('<Verify return values of quickInfo="' + JSON.stringify(displayParts) + '"/>');
function getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) {
let result = "";
ts.forEach(displayParts, part => {
if (result) {
result += ",\n ";
}
else {
result = "[\n ";
}
result += JSON.stringify(part);
});
if (result) {
result += "\n]";
}
return result;
}
let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind"));
assert.equal(actualQuickInfo.kindModifiers, kindModifiers, this.messageAtLastKnownMarker("QuickInfo kindModifiers"));
assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan"));
assert.equal(getDisplayPartsJson(actualQuickInfo.displayParts), getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts"));
assert.equal(getDisplayPartsJson(actualQuickInfo.documentation), getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation"));
}
public verifyRenameLocations(findInStrings: boolean, findInComments: boolean) {
let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition);
if (renameInfo.canRename) {
let references = this.languageService.findRenameLocations(
this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments);
let ranges = this.getRanges();
if (!references) {
if (ranges.length !== 0) {
this.raiseError(`Expected ${ranges.length} rename locations; got none.`);
}
return;
}
if (ranges.length !== references.length) {
this.raiseError("Rename location count does not match result.\n\nExpected: " + JSON.stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
}
ranges = ranges.sort((r1, r2) => r1.start - r2.start);
references = references.sort((r1, r2) => r1.textSpan.start - r2.textSpan.start);
for (let i = 0, n = ranges.length; i < n; i++) {
let reference = references[i];
let range = ranges[i];
if (reference.textSpan.start !== range.start ||
ts.textSpanEnd(reference.textSpan) !== range.end) {
this.raiseError("Rename location results do not match.\n\nExpected: " + JSON.stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
}
}
}
else {
this.raiseError("Expected rename to succeed, but it actually failed.");
}
}
public verifyQuickInfoExists(negative: boolean) {
this.taoInvalidReason = 'verifyQuickInfoExists NYI';
let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (negative) {
if (actualQuickInfo) {
this.raiseError('verifyQuickInfoExists failed. Expected quick info NOT to exist');
}
}
else {
if (!actualQuickInfo) {
this.raiseError('verifyQuickInfoExists failed. Expected quick info to exist');
}
}
}
public verifyCurrentSignatureHelpIs(expected: string) {
this.taoInvalidReason = 'verifyCurrentSignatureHelpIs NYI';
let help = this.getActiveSignatureHelpItem();
assert.equal(
ts.displayPartsToString(help.prefixDisplayParts) +
help.parameters.map(p => ts.displayPartsToString(p.displayParts)).join(ts.displayPartsToString(help.separatorDisplayParts)) +
ts.displayPartsToString(help.suffixDisplayParts), expected);
}
public verifyCurrentParameterIsletiable(isVariable: boolean) {
this.taoInvalidReason = 'verifyCurrentParameterIsletiable NYI';
let signature = this.getActiveSignatureHelpItem();
assert.isNotNull(signature);
assert.equal(isVariable, signature.isVariadic);
}
public verifyCurrentParameterHelpName(name: string) {