forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfourslash.ts
More file actions
2340 lines (1901 loc) · 106 KB
/
Copy pathfourslash.ts
File metadata and controls
2340 lines (1901 loc) · 106 KB
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='harness.ts' />
module FourSlash {
// Represents a parsed source file with metadata
export interface FourSlashFile {
// The contents of the file (with markers, etc stripped out)
content: string;
fileName: string;
// 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;
}
export enum IncrementalEditValidation {
None,
SyntacticOnly,
Complete
}
export enum TypingFidelity {
/// Performs typing and formatting (if formatting is enabled)
Low,
/// Performs typing, checks completion lists, signature help, and formatting (if enabled)
High
}
var entityMap: TypeScript.IIndexable<string> = {
'&': '&',
'"': '"',
"'": ''',
'/': '/',
'<': '<',
'>': '>'
};
export function escapeXmlAttributeValue(s: string) {
return s.replace(/[&<>"'\/]/g, ch => entityMap[ch]);
}
// List of allowed metadata names
var fileMetadataNames = ['Filename'];
var globalMetadataNames = ['Module', 'Target', 'BaselineFile']; // Note: Only BaselineFile is actually supported at the moment
export var currentTestState: TestState = null;
export class TestCancellationToken implements TypeScript.ICancellationToken {
// 0 - cancelled
// >0 - not cancelled
// <0 - not cancelled and value denotes number of isCancellationRequested after which token become cancelled
private static NotCancelled: number = -1;
private numberOfCallsBeforeCancellation: number = TestCancellationToken.NotCancelled;
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 {
TypeScript.Debug.assert(numberOfCalls >= 0);
this.numberOfCallsBeforeCancellation = numberOfCalls;
}
public resetCancelled(): void {
this.numberOfCallsBeforeCancellation = TestCancellationToken.NotCancelled;
}
}
export function verifyOperationIsCancelled(f: () => void) {
try {
f();
}
catch (e) {
if (e instanceof TypeScript.OperationCanceledException) {
return;
}
}
throw new Error("Operation should be cancelled");
}
export class TestState {
// Language service instance
public languageServiceShimHost: Harness.TypeScriptLS = null;
private languageService: TypeScript.Services.ILanguageService = null;
private newLanguageService: ts.LanguageService = null;
// A reference to the language service's compiler state's compiler instance
private compiler: () => { getSyntaxTree(fileName: string): TypeScript.SyntaxTree; getSourceUnit(fileName: string): TypeScript.SourceUnitSyntax; };
// 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: TypeScript.Services.FormatCodeOptions = null;
public cancellationToken: TestCancellationToken;
public editValidation = IncrementalEditValidation.Complete;
public typingFidelity = TypingFidelity.Low;
private scenarioActions: string[] = [];
private taoInvalidReason: string = null;
constructor(public testData: FourSlashData) {
// Initialize the language service with all the scripts
this.cancellationToken = new TestCancellationToken();
this.languageServiceShimHost = new Harness.TypeScriptLS(this.cancellationToken);
var harnessCompiler = Harness.Compiler.getCompiler();
var inputFiles: { unitName: string; content: string }[] = [];
testData.files.forEach(file => {
var fixedPath = file.fileName.substr(file.fileName.indexOf('tests/'));
harnessCompiler.addInputFile({ unitName: fixedPath, content: file.content });
});
// If the last unit contains require( or /// reference then consider it the only input file
// and the rest will be added via resolution. If not, then assume we have multiple files
// with 0 references in any of them. We could be smarter here to allow scenarios like
// 2 files without references and 1 file with a reference but we have 0 tests like that
// at the moment and an exhaustive search of the test files for that content could be quite slow.
var lastFile = testData.files[testData.files.length - 1];
if (/require\(/.test(lastFile.content) || /reference\spath/.test(lastFile.content)) {
inputFiles.push({ unitName: lastFile.fileName, content: lastFile.content });
} else {
inputFiles = testData.files.map(file => {
return { unitName: file.fileName, content: file.content };
});
}
// NEWTODO: Re-implement commented-out section
// harnessCompiler.addInputFiles(inputFiles);
try {
// var resolvedFiles = harnessCompiler.resolve();
//resolvedFiles.forEach(file => {
// if (!Harness.isLibraryFile(file.path)) {
// var fixedPath = file.path.substr(file.path.indexOf('tests/'));
// var content = harnessCompiler.getContentForFile(fixedPath);
// this.languageServiceShimHost.addScript(fixedPath, content);
// }
//});
// NEWTODO: For now do not resolve, just use the input files
inputFiles.forEach(file => {
if (!Harness.isLibraryFile(file.unitName)) {
this.languageServiceShimHost.addScript(file.unitName, file.content);
}
});
this.languageServiceShimHost.addScript('lib.d.ts', Harness.Compiler.libTextMinimal);
}
finally {
// harness no longer needs the results of the above work, make sure the next test operations are in a clean state
//harnessCompiler.reset();
}
// Sneak into the language service and get its compiler so we can examine the syntax trees
this.languageService = this.languageServiceShimHost.getLanguageService().languageService;
this.newLanguageService = this.languageServiceShimHost.newLS;
var compilerState = (<any>this.languageService).compiler;
this.compiler = () => compilerState.compiler;
this.formatCodeOptions = new TypeScript.Services.FormatCodeOptions();
this.testData.files.forEach(file => {
var filename = file.fileName.replace(Harness.IO.directoryName(file.fileName), '').substr(1);
var 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);
}
// Entry points from fourslash.ts
public goToMarker(name = '') {
var marker = this.getMarkerByName(name);
if (this.activeFile.fileName !== marker.fileName) {
this.openFile(marker.fileName);
}
var scriptSnapshot = this.languageServiceShimHost.getScriptSnapshot(marker.fileName);
if (marker.position === -1 || marker.position > scriptSnapshot.getLength()) {
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;
var lineCharPos = TypeScript.LineMap1.fromString(this.getCurrentFileContent()).getLineAndCharacterFromPosition(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.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getLength());
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) {
var fileToOpen: FourSlashFile = this.findFile(indexOrName);
fileToOpen.fileName = Harness.Path.switchToForwardSlashes(fileToOpen.fileName);
this.activeFile = fileToOpen;
var filename = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), '').substr(1);
this.scenarioActions.push('<OpenFile FileName="" SrcFileId="' + filename + '" FileId="' + filename + '" />');
}
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
var startMarker = this.getMarkerByName(startMarkerName);
var endMarker = this.getMarkerByName(endMarkerName);
var predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
// NEWTODO: make this more specific again
//return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
return ((errorMinChar >= startPos) && (errorLimChar <= endPos)) ? true : false;
};
var exists = this.anyErrorInRange(predicate, startMarker, endMarker);
this.taoInvalidReason = 'verifyErrorExistsBetweenMarkers NYI';
if (exists !== negative) {
this.new_printErrorLog(negative, this.new_getAllDiagnostics());
throw new Error("Failure between markers: " + startMarkerName + ", " + endMarkerName);
}
}
private getDiagnostics(fileName: string): TypeScript.Diagnostic[] {
var syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName);
var semanticErrors = this.languageService.getSemanticDiagnostics(fileName);
var diagnostics: TypeScript.Diagnostic[] = [];
diagnostics.push.apply(diagnostics, syntacticErrors);
diagnostics.push.apply(diagnostics, semanticErrors);
return diagnostics;
}
private new_getDiagnostics(fileName: string): ts.Diagnostic[] {
var syntacticErrors = this.newLanguageService.getSyntacticDiagnostics(fileName);
var semanticErrors = this.newLanguageService.getSemanticDiagnostics(fileName);
var diagnostics: ts.Diagnostic[] = [];
diagnostics.push.apply(diagnostics, syntacticErrors);
diagnostics.push.apply(diagnostics, semanticErrors);
return diagnostics;
}
private getAllDiagnostics(): TypeScript.Diagnostic[] {
var diagnostics: TypeScript.Diagnostic[] = [];
var fileNames = JSON.parse(this.languageServiceShimHost.getScriptFileNames());
for (var i = 0, n = fileNames.length; i < n; i++) {
diagnostics.push.apply(this.getDiagnostics(fileNames[i]));
}
return diagnostics;
}
private new_getAllDiagnostics(): ts.Diagnostic[] {
var diagnostics: ts.Diagnostic[] = [];
var fileNames = JSON.parse(this.languageServiceShimHost.getScriptFileNames());
for (var i = 0, n = fileNames.length; i < n; i++) {
diagnostics.push.apply(this.new_getDiagnostics(fileNames[i]));
}
return diagnostics;
}
public verifyErrorExistsAfterMarker(markerName: string, negative: boolean, after: boolean) {
var marker: Marker = this.getMarkerByName(markerName);
var 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';
var exists = this.anyErrorInRange(predicate, marker);
var diagnostics = this.new_getAllDiagnostics();
if (exists !== negative) {
this.new_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) {
var errors = this.new_getDiagnostics(startMarker.fileName);
var exists = false;
var startPos = startMarker.position;
if (endMarker !== undefined) {
var endPos = endMarker.position;
}
errors.forEach((error)=> {
if (predicate(error.start, error.start + error.length, startPos, endPos)) {
exists = true;
}
});
return exists;
}
private printErrorLog(expectErrors: boolean, errors: TypeScript.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: TypeScript.Diagnostic) {
Harness.IO.log(" minChar: " + error.start() + ", limChar: " + (error.start() + error.length()) + ", message: " + error.message() + "\n");
});
}
private new_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(error => {
Harness.IO.log(" minChar: " + error.start + ", limChar: " + (error.start + error.length) + ", message: " + error.messageText + "\n");
});
}
public verifyNumberOfErrorsInCurrentFile(expected: number) {
var errors = this.getDiagnostics(this.activeFile.fileName);
var actual = errors.length;
this.scenarioActions.push('<CheckErrorList ExpectedNumOfErrors="' + expected + '" />');
if (actual !== expected) {
var errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")";
Harness.IO.log(errorMsg);
throw new Error(errorMsg);
}
}
public verifyEval(expr: string, value: any) {
var 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';
var evaluation = new Function(emit.outputFiles[0].text + ';\r\nreturn (' + expr + ');')();
if (evaluation !== value) {
throw new Error('Expected evaluation of expression "' + expr + '" to equal "' + value + '", but got "' + evaluation + '"');
}
}
public verifyMemberListContains(symbol: string, type?: string, docComment?: string, fullSymbolName?: string, kind?: string) {
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionContainsItem ItemName="' + symbol + '"/>');
if (type || docComment || fullSymbolName || kind) {
this.taoInvalidReason = 'verifyMemberListContains only supports the "symbol" parameter';
}
var members = this.getMemberListAtCaret();
if (members) {
this.assertItemInCompletionList(members.entries, symbol, type, docComment, fullSymbolName, kind);
}
else {
throw new Error("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"' : '') + ' />');
}
var members = this.getMemberListAtCaret();
if (members) {
var match = members.entries.length === expectedCount;
if ((!match && !negative) || (match && negative)) {
throw new Error("Member list count was " + members.entries.length + ". Expected " + expectedCount);
}
}
else if (expectedCount) {
throw new Error("Member list count was 0. Expected " + expectedCount);
}
}
public verifyMemberListDoesNotContain(symbol: string) {
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionDoesNotContainItem ItemName="' + escapeXmlAttributeValue(symbol) + '" />');
var members = this.getMemberListAtCaret();
if (members.entries.filter(e => e.name === symbol).length !== 0) {
throw new Error('Member list did contain ' + symbol);
}
}
public verifyCompletionListItemsCountIsGreaterThan(count: number) {
this.taoInvalidReason = 'verifyCompletionListItemsCountIsGreaterThan NYI';
var completions = this.getCompletionListAtCaret();
var itemsCount = completions.entries.length;
if (itemsCount <= count) {
throw new Error('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" />');
}
var members = this.getMemberListAtCaret();
if ((!members || members.entries.length === 0) && negative) {
throw new Error("Member list is empty at Caret");
} else if ((members && members.entries.length !== 0) && !negative) {
var errorMsg = "\n" + "Member List contains: [" + members.entries[0].name;
for (var i = 1; i < members.entries.length; i++) {
errorMsg += ", " + members.entries[i].name;
}
errorMsg += "]\n";
Harness.IO.log(errorMsg);
throw new Error("Member list is not empty at Caret");
}
}
public verifyCompletionListIsEmpty(negative: boolean) {
this.scenarioActions.push('<ShowCompletionList ExpectsFailure="true" />');
var completions = this.getCompletionListAtCaret();
if ((!completions || completions.entries.length === 0) && negative) {
throw new Error("Completion list is empty at Caret");
} else if ((completions && completions.entries.length !== 0) && !negative) {
var errorMsg = "\n" + "Completion List contains: [" + completions.entries[0].name;
for (var i = 1; i < completions.entries.length; i++) {
errorMsg += ", " + completions.entries[i].name;
}
errorMsg += "]\n";
Harness.IO.log(errorMsg);
throw new Error("Completion list is not empty at Caret");
}
}
public verifyCompletionListContains(symbol: string, type?: string, docComment?: string, fullSymbolName?: string, kind?: string) {
var completions = this.getCompletionListAtCaret();
this.assertItemInCompletionList(completions.entries, symbol, type, docComment, fullSymbolName, kind);
}
public verifyCompletionListDoesNotContain(symbol: string) {
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionDoesNotContainItem ItemName="' + escapeXmlAttributeValue(symbol) + '" />');
var completions = this.getCompletionListAtCaret();
if (completions && completions.entries && completions.entries.filter(e => e.name === symbol).length !== 0) {
throw new Error('Completion list did contain ' + symbol);
}
}
public verifyCompletionEntryDetails(entryName: string, type: string, docComment?: string, fullSymbolName?: string, kind?: string) {
this.taoInvalidReason = 'verifyCompletionEntryDetails NYI';
var details = this.getCompletionEntryDetails(entryName);
assert.equal(details.type, type);
if (docComment != undefined) {
assert.equal(details.docComment, docComment);
}
if (fullSymbolName !== undefined) {
assert.equal(details.fullSymbolName, fullSymbolName);
}
if (kind !== undefined) {
assert.equal(details.kind, kind);
}
}
public verifyReferencesCountIs(count: number, localFilesOnly: boolean = true) {
this.taoInvalidReason = 'verifyReferences NYI';
var references = this.getReferencesAtCaret();
var referencesCount = 0;
if (localFilesOnly) {
var localFiles = this.testData.files.map<string>(file => file.fileName);
// Count only the references in local files. Filter the ones in lib and other files.
references.forEach((entry) => {
if (localFiles.some((filename) => filename === entry.fileName)) {
++referencesCount;
}
});
}
else {
referencesCount = references.length;
}
if (referencesCount !== count) {
var condition = localFilesOnly ? "excluding libs" : "including libs";
throw new Error("Expected references count (" + condition + ") to be " + count + ", but is actually " + references.length);
}
}
public verifyImplementorsCountIs(count: number, localFilesOnly: boolean = true) {
var implementors = this.getImplementorsAtCaret();
var implementorsCount = 0;
if (localFilesOnly) {
var localFiles = this.testData.files.map<string>(file => file.fileName);
// Count only the references in local files. Filter the ones in lib and other files.
implementors.forEach((entry) => {
if (localFiles.some((filename) => filename === entry.fileName)) {
++implementorsCount;
}
});
}
else {
implementorsCount = implementors.length;
}
if (implementorsCount !== count) {
var condition = localFilesOnly ? "excluding libs" : "including libs";
throw new Error("Expected implementors count (" + condition + ") to be " + count + ", but is actually " + implementors.length);
}
}
private getMemberListAtCaret() {
return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition, true);
}
private getCompletionListAtCaret() {
return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition, false);
}
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 getImplementorsAtCaret() {
return this.languageService.getImplementorsAtPosition(this.activeFile.fileName, this.currentCaretPosition);
}
public verifyQuickInfo(negative: boolean, expectedTypeName?: string, docComment?: string, symbolName?: string, kind?: string) {
[expectedTypeName, docComment, symbolName, kind].forEach(str => {
if (str) {
this.scenarioActions.push('<ShowQuickInfo />');
this.scenarioActions.push('<VerifyQuickInfoTextContains IgnoreSpacing="true" Text="' + escapeXmlAttributeValue(str) + '" ' + (negative ? 'ExpectsFailure="true"' : '') + ' />');
}
});
var actualQuickInfo = this.languageService.getTypeAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var actualQuickInfoMemberName = actualQuickInfo ? actualQuickInfo.memberName.toString() : "";
var actualQuickInfoDocComment = actualQuickInfo ? actualQuickInfo.docComment : "";
var actualQuickInfoSymbolName = actualQuickInfo ? actualQuickInfo.fullSymbolName : "";
var actualQuickInfoKind = actualQuickInfo ? actualQuickInfo.kind : "";
function assertionMessage(name: string, actualValue: string, expectedValue: string) {
return "\nActual " + name + ":\n\t" + actualValue + "\nExpected value:\n\t" + expectedValue;
}
if (negative) {
if (expectedTypeName !== undefined) {
assert.notEqual(actualQuickInfoMemberName, expectedTypeName, assertionMessage("quick info member name", actualQuickInfoMemberName, expectedTypeName));
}
if (docComment != undefined) {
assert.notEqual(actualQuickInfoDocComment, docComment, assertionMessage("quick info doc comment", actualQuickInfoDocComment, docComment));
}
if (symbolName !== undefined) {
assert.notEqual(actualQuickInfoSymbolName, symbolName, assertionMessage("quick info symbol name", actualQuickInfoSymbolName, symbolName));
}
if (kind !== undefined) {
assert.notEqual(actualQuickInfoKind, kind, assertionMessage("quick info kind", actualQuickInfoKind, kind));
}
} else {
if (expectedTypeName !== undefined) {
assert.equal(actualQuickInfoMemberName, expectedTypeName, assertionMessage("quick info member", actualQuickInfoMemberName, expectedTypeName));
}
if (docComment != undefined) {
assert.equal(actualQuickInfoDocComment, docComment, assertionMessage("quick info doc", actualQuickInfoDocComment, docComment));
}
if (symbolName !== undefined) {
assert.equal(actualQuickInfoSymbolName, symbolName, assertionMessage("quick info symbol name", actualQuickInfoSymbolName, symbolName));
}
if (kind !== undefined) {
assert.equal(actualQuickInfoKind, kind, assertionMessage("quick info kind", actualQuickInfoKind, kind));
}
}
}
public verifyQuickInfoExists(negative: number) {
this.taoInvalidReason = 'verifyQuickInfoExists NYI';
var actualQuickInfo = this.languageService.getTypeAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (negative) {
if (actualQuickInfo) {
throw new Error('verifyQuickInfoExists failed. Expected quick info NOT to exist');
}
}
else {
if (!actualQuickInfo) {
throw new Error('verifyQuickInfoExists failed. Expected quick info to exist');
}
}
}
public verifyCurrentSignatureHelpIs(expected: string) {
this.taoInvalidReason = 'verifyCurrentSignatureHelpIs NYI';
var help = this.getActiveSignatureHelp();
assert.equal(help.prefix + help.parameters.map(p => p.display).join(help.separator) + help.suffix, expected);
}
public verifyCurrentParameterIsVariable(isVariable: boolean) {
this.taoInvalidReason = 'verifyCurrentParameterIsVariable NYI';
var signature = this.getActiveSignatureHelp();
assert.isNotNull(signature);
assert.equal(isVariable, signature.isVariadic);
}
public verifyCurrentParameterHelpName(name: string) {
this.taoInvalidReason = 'verifyCurrentParameterHelpName NYI';
var activeParameter = this.getActiveParameter();
var activeParameterName = activeParameter.name;
assert.equal(activeParameterName, name);
}
public verifyCurrentParameterSpanIs(parameter: string) {
this.taoInvalidReason = 'verifyCurrentParameterSpanIs NYI';
var activeSignature = this.getActiveSignatureHelp();
var activeParameter = this.getActiveParameter();
assert.equal(activeParameter.display, parameter);
}
public verifyCurrentParameterHelpDocComment(docComment: string) {
this.taoInvalidReason = 'verifyCurrentParameterHelpDocComment NYI';
var activeParameter = this.getActiveParameter();
var activeParameterDocComment = activeParameter.documentation;
assert.equal(activeParameterDocComment, docComment);
}
public verifyCurrentSignatureHelpParameterCount(expectedCount: number) {
this.taoInvalidReason = 'verifyCurrentSignatureHelpParameterCount NYI';
assert.equal(this.getActiveSignatureHelp().parameters.length, expectedCount);
}
public verifyCurrentSignatureHelpTypeParameterCount(expectedCount: number) {
this.taoInvalidReason = 'verifyCurrentSignatureHelpTypeParameterCount NYI';
// assert.equal(this.getActiveSignatureHelp().typeParameters.length, expectedCount);
}
public verifyCurrentSignatureHelpDocComment(docComment: string) {
this.taoInvalidReason = 'verifyCurrentSignatureHelpDocComment NYI';
var actualDocComment = this.getActiveSignatureHelp().documentation;
assert.equal(actualDocComment, docComment);
}
public verifySignatureHelpCount(expected: number) {
this.scenarioActions.push('<InvokeSignatureHelp />');
this.scenarioActions.push('<VerifySignatureHelpOverloadCountEquals Count="' + expected + '" />');
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
var actual = help && help.items ? help.items.length : 0;
assert.equal(actual, expected);
}
public verifySignatureHelpPresent(shouldBePresent = true) {
this.taoInvalidReason = 'verifySignatureHelpPresent NYI';
var actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
if (shouldBePresent) {
if (!actual) {
throw new Error("Expected signature help to be present, but it wasn't");
}
} else {
if (actual) {
throw new Error("Expected no signature help, but got '" + JSON.stringify(actual) + "'");
}
}
}
//private getFormalParameter() {
// var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
// return help.formal;
//}
private getActiveSignatureHelp() {
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
// If the signature hasn't been narrowed down yet (e.g. no parameters have yet been entered),
// 'activeFormal' will be -1 (even if there is only 1 signature). Signature help will show the
// first signature in the signature group, so go with that
var index = help.selectedItemIndex < 0 ? 0 : help.selectedItemIndex;
return help.items[index];
}
private getActiveParameter(): TypeScript.Services.SignatureHelpParameter {
var currentSig = this.getActiveSignatureHelp();
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
var item = help.items[help.selectedItemIndex];
var state = this.languageService.getSignatureHelpCurrentArgumentState(this.activeFile.fileName, this.currentCaretPosition, help.applicableSpan.start());
// Same logic as in getActiveSignatureHelp - this value might be -1 until a parameter value actually gets typed
var currentParam = state === null ? 0 : state.argumentIndex;
return item.parameters[currentParam];
}
public getBreakpointStatementLocation(pos: number) {
this.taoInvalidReason = 'getBreakpointStatementLocation NYI';
var spanInfo = this.languageService.getBreakpointStatementAtPosition(this.activeFile.fileName, pos);
var resultString = "\n**Pos: " + pos + " SpanInfo: " + JSON.stringify(spanInfo) + "\n** Statement: ";
if (spanInfo !== null) {
resultString = resultString + this.activeFile.content.substr(spanInfo.start(), spanInfo.length());
}
return resultString;
}
public baselineCurrentFileBreakpointLocations() {
this.taoInvalidReason = 'baselineCurrentFileBreakpointLocations impossible';
Harness.Baseline.runBaseline(
"Breakpoint Locations for " + this.activeFile.fileName,
this.testData.globalOptions['BaselineFile'],
() => {
var fileLength = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getLength();
var resultString = "";
for (var pos = 0; pos < fileLength; pos++) {
resultString = resultString + this.getBreakpointStatementLocation(pos);
}
return resultString;
});
}
public printBreakpointLocation(pos: number) {
Harness.IO.log(this.getBreakpointStatementLocation(pos));
}
public printBreakpointAtCurrentLocation() {
this.printBreakpointLocation(this.currentCaretPosition);
}
public printCurrentParameterHelp() {
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
Harness.IO.log(JSON.stringify(help));
}
public printCurrentQuickInfo() {
var quickInfo = this.languageService.getTypeAtPosition(this.activeFile.fileName, this.currentCaretPosition);
Harness.IO.log(JSON.stringify(quickInfo));
}
public printErrorList() {
Harness.IO.log("--------------");
Harness.IO.log("Old Errors");
Harness.IO.log("--------------");
var syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
var semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
var errorList = syntacticErrors.concat(semanticErrors);
Harness.IO.log('Error list (' + errorList.length + ' errors)');
if (errorList.length) {
errorList.forEach(err => {
Harness.IO.log("start: " + err.start() + ", length: " + err.length() + ", message: " + err.message());
});
}
Harness.IO.log("--------------");
Harness.IO.log("New Errors");
Harness.IO.log("--------------");
this.new_printErrorList();
}
public new_printErrorList() {
var syntacticErrors = this.newLanguageService.getSyntacticDiagnostics(this.activeFile.fileName);
var semanticErrors = this.newLanguageService.getSemanticDiagnostics(this.activeFile.fileName);
var errorList = syntacticErrors.concat(semanticErrors);
Harness.IO.log('Error list (' + errorList.length + ' errors)');
if (errorList.length) {
errorList.forEach(error => {
Harness.IO.log("start: " + error.start + ", length: " + error.length +
", message: " + error.messageText);
});
}
}
public printCurrentFileState(makeWhitespaceVisible = false, makeCaretVisible = true) {
for (var i = 0; i < this.testData.files.length; i++) {
var file = this.testData.files[i];
var active = (this.activeFile === file);
Harness.IO.log('=== Script (' + file.fileName + ') ' + (active ? '(active, cursor at |)' : '') + ' ===');
var snapshot = this.languageServiceShimHost.getScriptSnapshot(file.fileName);
var content = snapshot.getText(0, snapshot.getLength());
if (active) {
content = content.substr(0, this.currentCaretPosition) + (makeCaretVisible ? '|' : "") + content.substr(this.currentCaretPosition);
}
if (makeWhitespaceVisible) {
content = TestState.makeWhitespaceVisible(content);
}
Harness.IO.log(content);
}
}
public printCurrentSignatureHelp() {
var sigHelp = this.getActiveSignatureHelp();
Harness.IO.log(JSON.stringify(sigHelp));
}
public printMemberListMembers() {
var members = this.getMemberListAtCaret();
Harness.IO.log(JSON.stringify(members));
}
public printCompletionListMembers() {
var completions = this.getCompletionListAtCaret();
Harness.IO.log(JSON.stringify(completions));
}
private editCheckpoint(filename: string) {
// TODO: What's this for? It is being called by deleteChar
// this.languageService.getScriptLexicalStructure(filename);
}
public deleteChar(count = 1) {
this.scenarioActions.push('<DeleteCharNext Count="' + count + '" />');
var offset = this.currentCaretPosition;
var ch = "";
for (var i = 0; i < count; i++) {
// Make the edit
this.languageServiceShimHost.editScript(this.activeFile.fileName, offset, offset + 1, ch);
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch);
this.editCheckpoint(this.activeFile.fileName);
// Handle post-keystroke formatting
if (this.enableFormatting) {
var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
offset += this.applyEdits(this.activeFile.fileName, edits, true);
}
}