forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpullLanguageService.ts
More file actions
2167 lines (1755 loc) · 107 KB
/
pullLanguageService.ts
File metadata and controls
2167 lines (1755 loc) · 107 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. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
///<reference path='references.ts' />
module TypeScript.Services {
export class LanguageService implements ILanguageService {
private logger: TypeScript.ILogger;
private compiler: LanguageServiceCompiler;
private _syntaxTreeCache: SyntaxTreeCache;
private formattingRulesProvider: TypeScript.Services.Formatting.RulesProvider;
private activeCompletionSession: CompletionSession = null;
private cancellationToken: CancellationToken;
constructor(public host: ILanguageServiceHost, documentRegistry: IDocumentRegistry) {
this.logger = this.host;
this.cancellationToken = new CancellationToken(this.host.getCancellationToken());
this.compiler = new LanguageServiceCompiler(this.host, documentRegistry, this.cancellationToken);
this._syntaxTreeCache = new SyntaxTreeCache(this.host);
// Check if the localized messages json is set, otherwise query the host for it
if (!TypeScript.LocalizedDiagnosticMessages) {
TypeScript.LocalizedDiagnosticMessages = this.host.getLocalizedDiagnosticMessages();
}
}
public dispose() {
this.compiler.dispose();
}
public cleanupSemanticCache(): void {
this.compiler.cleanupSemanticCache();
}
public refresh(): void {
// No-op. Only kept around for compatability with the interface we shipped.
}
private getSemanticInfoChain(): SemanticInfoChain {
return this.compiler.getSemanticInfoChain();
}
private getSymbolInfoAtPosition(fileName: string, pos: number, requireName: boolean): { symbol: TypeScript.PullSymbol; containingASTOpt: TypeScript.ISyntaxElement } {
var document = this.compiler.getDocument(fileName);
var sourceUnit = document.sourceUnit();
/// TODO: this does not allow getting references on "constructor"
var topNode = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, pos);
return this.getSymbolInfoAtAST(document, topNode, pos, requireName);
}
private getSymbolInfoAtAST(document: Document, topNode: ISyntaxElement, pos: number, requireName: boolean): { symbol: TypeScript.PullSymbol; containingASTOpt: TypeScript.ISyntaxElement } {
if (topNode === null || (requireName && topNode.kind() !== TypeScript.SyntaxKind.IdentifierName)) {
this.logger.log("No name found at the given position");
return null;
}
// Store the actual name before calling getSymbolInformationFromPath
var symbolInfoAtPosition = this.compiler.getSymbolInformationFromAST(topNode, document);
if (symbolInfoAtPosition === null || (symbolInfoAtPosition.symbol === null && symbolInfoAtPosition.aliasSymbol)) {
this.logger.log("No symbol found at the given position");
// only single reference
return { symbol: null, containingASTOpt: null };
}
var symbol = symbolInfoAtPosition.aliasSymbol || symbolInfoAtPosition.symbol;
var symbolName = symbol.getName();
// if we are not looking for any but we get an any symbol, then we ran into a wrong symbol
if (requireName) {
var actualNameAtPosition = tokenValueText(<TypeScript.ISyntaxToken>topNode);
if ((symbol.isError() || symbol.isAny()) && actualNameAtPosition !== symbolName) {
this.logger.log("Unknown symbol found at the given position");
// only single reference
return { symbol: null, containingASTOpt: null };
}
}
var containingASTOpt = this.getSymbolScopeAST(symbol, topNode);
return { symbol: symbol, containingASTOpt: containingASTOpt };
}
public getReferencesAtPosition(fileName: string, pos: number): ReferenceEntry[] {
fileName = TypeScript.switchToForwardSlashes(fileName);
var symbolAndContainingAST = this.getSymbolInfoAtPosition(fileName, pos, /*requireName:*/ true);
if (symbolAndContainingAST === null) {
// Didn't even have a name at that position.
return [];
}
if (symbolAndContainingAST.symbol === null) {
// Had a name, but couldn't bind it to anything.
return this.getSingleNodeReferenceAtPosition(fileName, pos);
}
var result: ReferenceEntry[] = [];
var symbol = symbolAndContainingAST.symbol;
var symbolName = symbol.getName();
var containingASTOpt = symbolAndContainingAST.containingASTOpt;
var fileNames = this.compiler.fileNames();
for (var i = 0, n = fileNames.length; i < n; i++) {
this.cancellationToken.throwIfCancellationRequested();
var tempFileName = fileNames[i];
if (containingASTOpt && fileName != tempFileName) {
continue;
}
var tempDocument = this.compiler.getDocument(tempFileName);
var filter = tempDocument.bloomFilter();
if (filter.probablyContains(symbolName)) {
result = result.concat(this.getReferencesInFile(tempFileName, symbol, containingASTOpt));
}
}
return result;
}
private getSymbolScopeAST(symbol: TypeScript.PullSymbol, ast: TypeScript.ISyntaxElement): TypeScript.ISyntaxElement {
if (symbol.kind === TypeScript.PullElementKind.TypeParameter &&
symbol.getDeclarations().length > 0 &&
symbol.getDeclarations()[0].getParentDecl() &&
symbol.getDeclarations()[0].getParentDecl().kind === TypeScript.PullElementKind.Method) {
// The compiler shares class method type parameter symbols. So if we get one,
// scope our search down to the method ast so we don't find other hits elsewhere.
while (ast) {
if (ast.kind() === TypeScript.SyntaxKind.FunctionDeclaration ||
ast.kind() === TypeScript.SyntaxKind.MemberFunctionDeclaration) {
return ast;
}
ast = ast.parent;
}
}
// Todo: we could add more smarts about things like local variables and parameters here.
return null;
}
public getOccurrencesAtPosition(fileName: string, pos: number): ReferenceEntry[] {
fileName = TypeScript.switchToForwardSlashes(fileName);
var symbolAndContainingAST = this.getSymbolInfoAtPosition(fileName, pos, /*requireName:*/ true);
if (symbolAndContainingAST === null) {
// Didn't even have a name at that position.
return [];
}
if (symbolAndContainingAST.symbol === null) {
// Had a name, but couldn't bind it to anything.
return this.getSingleNodeReferenceAtPosition(fileName, pos);
}
var symbol = symbolAndContainingAST.symbol;
var containingASTOpt = symbolAndContainingAST.containingASTOpt;
return this.getReferencesInFile(fileName, symbol, containingASTOpt);
}
private getSingleNodeReferenceAtPosition(fileName: string, position: number): ReferenceEntry[] {
var document = this.compiler.getDocument(fileName);
var sourceUnit = document.sourceUnit();
var node = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, position);
if (node === null || node.kind() !== TypeScript.SyntaxKind.IdentifierName) {
return [];
}
var isWriteAccess = this.isWriteAccess(node);
return [new ReferenceEntry(this._getHostFileName(fileName), TextSpan.fromBounds(start(node), end(node)), isWriteAccess)];
}
public getImplementorsAtPosition(fileName: string, pos: number): ReferenceEntry[] {
fileName = TypeScript.switchToForwardSlashes(fileName);
var result: ReferenceEntry[] = [];
var document = this.compiler.getDocument(fileName);
var sourceUnit = document.sourceUnit();
var ast = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, pos);
if (ast === null || ast.kind() !== TypeScript.SyntaxKind.IdentifierName) {
this.logger.log("No identifier at the specified location.");
return result;
}
// Store the actual name before calling getSymbolInformationFromPath
var actualNameAtPosition = tokenValueText(<TypeScript.ISyntaxToken>ast);
var symbolInfoAtPosition = this.compiler.getSymbolInformationFromAST(ast, document);
var symbol = symbolInfoAtPosition.symbol;
if (symbol === null) {
this.logger.log("No symbol annotation on the identifier ISyntaxElement.");
return result;
}
var symbolName: string = symbol.getName();
// if we are not looking for any but we get an any symbol, then we ran into a wrong symbol
if ((symbol.isError() || symbol.isAny()) && actualNameAtPosition !== symbolName) {
this.logger.log("Unknown symbol found at the given position");
return result;
}
var typeSymbol: TypeScript.PullTypeSymbol = symbol.type;
var typesToSearch: TypeScript.PullTypeSymbol[];
if (typeSymbol.isClass() || typeSymbol.isInterface()) {
typesToSearch = typeSymbol.getTypesThatExtendThisType();
}
else if (symbol.kind == TypeScript.PullElementKind.Property || typeSymbol.isMethod() || typeSymbol.isProperty()) {
var declaration: TypeScript.PullDecl = symbol.getDeclarations()[0];
var classSymbol: TypeScript.PullTypeSymbol = declaration.getParentDecl().getSymbol(symbol.semanticInfoChain).type;
typesToSearch = [];
var extendingTypes = classSymbol.getTypesThatExtendThisType();
var extendedTypes = classSymbol.getExtendedTypes();
extendingTypes.forEach(type => {
var overrides = this.getOverrides(type, symbol);
overrides.forEach(override => {
typesToSearch.push(override);
});
});
extendedTypes.forEach(type => {
var overrides = this.getOverrides(type, symbol);
overrides.forEach(override => {
typesToSearch.push(override);
});
});
}
if (typesToSearch) {
var fileNames = this.compiler.fileNames();
for (var i = 0, n = fileNames.length; i < n; i++) {
var tempFileName = fileNames[i];
var tempDocument = this.compiler.getDocument(tempFileName);
var filter = tempDocument.bloomFilter();
typesToSearch.forEach(typeToSearch => {
var symbolName: string = typeToSearch.getName();
if (filter.probablyContains(symbolName)) {
result = result.concat(this.getImplementorsInFile(tempFileName, typeToSearch));
}
});
}
}
return result;
}
public getOverrides(container: TypeScript.PullTypeSymbol, memberSym: TypeScript.PullSymbol): TypeScript.PullTypeSymbol[] {
var result: TypeScript.PullTypeSymbol[] = [];
var members: TypeScript.PullSymbol[];
if (container.isClass()) {
members = container.getMembers();
}
else if (container.isInterface()) {
members = container.getMembers();
}
if (members == null)
return null;
members.forEach(member => {
var typeMember = <TypeScript.PullTypeSymbol>member;
if (typeMember.getName() === memberSym.getName()) {
// Not currently checking whether static-ness matches: typeMember.isStatic() === memberSym.isStatic() or whether
// typeMember.isMethod() === memberSym.isMethod() && typeMember.isProperty() === memberSym.isProperty()
result.push(typeMember);
}
});
return result;
}
private getImplementorsInFile(fileName: string, symbol: TypeScript.PullTypeSymbol): ReferenceEntry[] {
var result: ReferenceEntry[] = [];
var symbolName = symbol.getDisplayName();
var possiblePositions = this.getPossibleSymbolReferencePositions(fileName, symbolName);
if (possiblePositions && possiblePositions.length > 0) {
var document = this.compiler.getDocument(fileName);
var sourceUnit = document.sourceUnit();
possiblePositions.forEach(p => {
var nameAST = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, p);
if (nameAST === null || nameAST.kind() !== TypeScript.SyntaxKind.IdentifierName) {
return;
}
var searchSymbolInfoAtPosition = this.compiler.getSymbolInformationFromAST(nameAST, document);
if (searchSymbolInfoAtPosition !== null) {
var normalizedSymbol: TypeScript.PullSymbol;
if (symbol.kind === TypeScript.PullElementKind.Class || symbol.kind === TypeScript.PullElementKind.Interface) {
normalizedSymbol = searchSymbolInfoAtPosition.symbol.type;
}
else {
var declaration = searchSymbolInfoAtPosition.symbol.getDeclarations()[0];
normalizedSymbol = declaration.getSymbol(symbol.semanticInfoChain);
}
if (normalizedSymbol === symbol) {
var isWriteAccess = this.isWriteAccess(nameAST);
result.push(new ReferenceEntry(this._getHostFileName(fileName),
TextSpan.fromBounds(start(nameAST), end(nameAST)), isWriteAccess));
}
}
});
}
return result;
}
private getReferencesInFile(fileName: string, symbol: TypeScript.PullSymbol, containingASTOpt: TypeScript.ISyntaxElement): ReferenceEntry[] {
var result: ReferenceEntry[] = [];
var symbolName = symbol.getDisplayName();
var possiblePositions = this.getPossibleSymbolReferencePositions(fileName, symbolName);
if (possiblePositions && possiblePositions.length > 0) {
var document = this.compiler.getDocument(fileName);
var sourceUnit = document.sourceUnit();
possiblePositions.forEach(p => {
this.cancellationToken.throwIfCancellationRequested();
// If it's not in the bounds of the ISyntaxElement we're asking for, then this can't possibly be a hit.
if (containingASTOpt && (p < start(containingASTOpt) || p > end(containingASTOpt))) {
return;
}
// Each position we're searching for should be at the start of an identifier.
// As such, we useTrailingTriviaAsLimChar=false so that the position doesn't
// accidently return another node (which may end at that position).
var nameAST = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, p, /*useTrailingTriviaAsLimChar:*/ false);
// Compare the length so we filter out strict superstrings of the symbol we are looking for
if (nameAST === null || nameAST.kind() !== TypeScript.SyntaxKind.IdentifierName || (end(nameAST) - start(nameAST) !== symbolName.length)) {
return;
}
var symbolInfoAtPosition = this.compiler.getSymbolInformationFromAST(nameAST, document);
if (symbolInfoAtPosition !== null) {
var searchSymbol = symbolInfoAtPosition.aliasSymbol || symbolInfoAtPosition.symbol;
if (FindReferenceHelpers.compareSymbolsForLexicalIdentity(searchSymbol, symbol)) {
var isWriteAccess = this.isWriteAccess(nameAST);
result.push(new ReferenceEntry(this._getHostFileName(fileName), TextSpan.fromBounds(start(nameAST), end(nameAST)), isWriteAccess));
}
}
});
}
return result;
}
private isWriteAccess(current: TypeScript.ISyntaxElement): boolean {
var parent = current.parent;
if (parent !== null) {
var parentNodeType = parent.kind();
switch (parentNodeType) {
case TypeScript.SyntaxKind.ClassDeclaration:
return (<TypeScript.ClassDeclarationSyntax>parent).identifier === current;
case TypeScript.SyntaxKind.InterfaceDeclaration:
return (<TypeScript.InterfaceDeclarationSyntax>parent).identifier === current;
case TypeScript.SyntaxKind.ModuleDeclaration:
return (<TypeScript.ModuleDeclarationSyntax>parent).name === current || (<TypeScript.ModuleDeclarationSyntax>parent).stringLiteral === current;
case TypeScript.SyntaxKind.FunctionDeclaration:
return (<TypeScript.FunctionDeclarationSyntax>parent).identifier === current;
case TypeScript.SyntaxKind.ImportDeclaration:
return (<TypeScript.ImportDeclarationSyntax>parent).identifier === current;
case TypeScript.SyntaxKind.VariableDeclarator:
var varDeclarator = <TypeScript.VariableDeclaratorSyntax>parent;
return !!(varDeclarator.equalsValueClause && varDeclarator.propertyName === current);
case TypeScript.SyntaxKind.Parameter:
return true;
case TypeScript.SyntaxKind.AssignmentExpression:
case TypeScript.SyntaxKind.AddAssignmentExpression:
case TypeScript.SyntaxKind.SubtractAssignmentExpression:
case TypeScript.SyntaxKind.MultiplyAssignmentExpression:
case TypeScript.SyntaxKind.DivideAssignmentExpression:
case TypeScript.SyntaxKind.ModuloAssignmentExpression:
case TypeScript.SyntaxKind.OrAssignmentExpression:
case TypeScript.SyntaxKind.AndAssignmentExpression:
case TypeScript.SyntaxKind.ExclusiveOrAssignmentExpression:
case TypeScript.SyntaxKind.LeftShiftAssignmentExpression:
case TypeScript.SyntaxKind.UnsignedRightShiftAssignmentExpression:
case TypeScript.SyntaxKind.SignedRightShiftAssignmentExpression:
return (<TypeScript.BinaryExpressionSyntax>parent).left === current;
case TypeScript.SyntaxKind.PreIncrementExpression:
case TypeScript.SyntaxKind.PostIncrementExpression:
return true;
case TypeScript.SyntaxKind.PreDecrementExpression:
case TypeScript.SyntaxKind.PostDecrementExpression:
return true;
}
}
return false;
}
private isIdentifierChar(char: number): boolean {
return this.isLetterOrDigit(char) ||
char === TypeScript.CharacterCodes._ ||
char === TypeScript.CharacterCodes.$ ||
(char > 127 && TypeScript.Unicode.isIdentifierPart(char, TypeScript.LanguageVersion.EcmaScript5));
}
private isLetterOrDigit(char: number): boolean {
return (char >= TypeScript.CharacterCodes.a && char <= TypeScript.CharacterCodes.z) ||
(char >= TypeScript.CharacterCodes.A && char <= TypeScript.CharacterCodes.Z) ||
(char >= TypeScript.CharacterCodes._0 && char <= TypeScript.CharacterCodes._9);
}
private getPossibleSymbolReferencePositions(fileName: string, symbolName: string): number[] {
var positions: number[] = [];
/// TODO: Cache symbol existence for files to save text search
// Also, need to make this work for unicode escapes.
// Be reseliant in the face of a symbol with no name or zero length name
if (!symbolName || !symbolName.length) {
return positions;
}
var sourceText = this.compiler.getScriptSnapshot(fileName);
var sourceLength = sourceText.getLength();
var text = sourceText.getText(0, sourceLength);
var symbolNameLength = symbolName.length;
var position = text.indexOf(symbolName);
while (position >= 0) {
this.cancellationToken.throwIfCancellationRequested();
// We found a match. Make sure it's not part of a larger word (i.e. the char
// before and after it have to be a non-identifier char).
var endPosition = position + symbolNameLength;
if ((position <= 0 || !this.isIdentifierChar(text.charCodeAt(position - 1))) &&
(endPosition >= sourceLength || !this.isIdentifierChar(text.charCodeAt(endPosition)))) {
// Found a real match. Keep searching.
positions.push(position);
}
position = text.indexOf(symbolName, position + symbolNameLength + 1);
}
return positions;
}
private charAtIndex(document: Document, index: number): number {
var scriptSnapshot = document.scriptSnapshot;
if (index < 0 || index >= scriptSnapshot.getLength()) {
return null;
}
return scriptSnapshot.getText(index, index + 1).charCodeAt(0);
}
private recoverExpressionWithArgumentList(document: Document, openParenIndex: number): IExpressionWithArgumentListSyntax {
var sourceUnit = document.sourceUnit();
var token = findToken(sourceUnit, openParenIndex);
if (token && start(token) === openParenIndex && token.kind() === SyntaxKind.OpenParenToken &&
token.parent && token.parent.parent &&
token.parent.kind() === SyntaxKind.ArgumentList) {
if (token.parent.parent.kind() === SyntaxKind.InvocationExpression ||
token.parent.parent.kind() === SyntaxKind.ObjectCreationExpression) {
return <IExpressionWithArgumentListSyntax>token.parent.parent;
}
}
return null;
}
public getSignatureHelpCurrentArgumentState(fileName: string, position: number, applicableSpanStart: number): SignatureHelpState {
fileName = TypeScript.switchToForwardSlashes(fileName);
var document = this.compiler.getDocument(fileName);
var openCharIndex = applicableSpanStart;
var char = this.charAtIndex(document, openCharIndex);
if (char === CharacterCodes.lessThan) {
// TODO: handle generics.
return null;
}
else if (char === CharacterCodes.openParen) {
var expressionWithArgumentList = this.recoverExpressionWithArgumentList(document, openCharIndex);
var argumentList = expressionWithArgumentList.argumentList;
if (position < end(argumentList.openParenToken)) {
return null;
}
var closeToken = argumentList.closeParenToken;
if (closeToken.fullWidth() > 0 &&
position > start(closeToken)) {
return null;
}
var index = 0;
for (var i = 0, n = argumentList.arguments.separators.length; i < n; i++) {
var separator = argumentList.arguments.separators[i];
if (position >= end(separator)) {
index++;
}
}
var count = expressionWithArgumentList.argumentList.arguments.separatorCount();
return new SignatureHelpState(index, count);
}
return null;
}
private getSignatureHelpApplicableSpan(document: Document, applicableSpanStart: number): TextSpan {
var scriptSnapshot = document.scriptSnapshot;
var openCharIndex = applicableSpanStart;
var char = this.charAtIndex(document, openCharIndex);
if (char === CharacterCodes.lessThan) {
// TODO: handle generics.
return null;
}
else if (char === CharacterCodes.openParen) {
var expressionWithArgumentList = this.recoverExpressionWithArgumentList(document, openCharIndex);
var lastToken = expressionWithArgumentList.argumentList.closeParenToken;
if (lastToken.fullWidth() !== 0) {
// invocation has a close paren. The span that we want to pass back is from
// the start of the invocation itself, to the start of the close paren token.
return TextSpan.fromBounds(start(expressionWithArgumentList.argumentList.openParenToken), start(lastToken));
}
// we're missing the close paren. The span should be up to the start of the next
// token (or the end of the document if there is no next token).
var nextToken = TypeScript.nextToken(TypeScript.lastToken(expressionWithArgumentList));
var end = nextToken === null ? scriptSnapshot.getLength() : start(nextToken);
return TextSpan.fromBounds(start(expressionWithArgumentList.argumentList.openParenToken), end);
}
return null;
}
public getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems {
fileName = TypeScript.switchToForwardSlashes(fileName);
var document = this.compiler.getDocument(fileName);
if (SignatureInfoHelpers.isSignatureHelpBlocker(document.syntaxTree().sourceUnit(), position)) {
this.logger.log("position is not a valid singature help location");
return null;
}
// Second check if we are inside a generic parameter
var genericTypeArgumentListInfo = SignatureInfoHelpers.isInPartiallyWrittenTypeArgumentList(document.syntaxTree(), position);
if (genericTypeArgumentListInfo) {
// The expression could be messed up because we are parsing a partial generic expression, so set the search path to a place where we know it
// can find a call expression
return null;
// return this.getSignatureHelpItemsFromPartiallyWrittenTypeArgumentList(document, position, genericTypeArgumentListInfo);
}
// Third set the path to find ask the type system about the call expression
var sourceUnit = document.sourceUnit();
var node = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, position);
if (!node) {
return null;
}
// Find call expression
while (node) {
if (node.kind() === TypeScript.SyntaxKind.InvocationExpression ||
node.kind() === TypeScript.SyntaxKind.ObjectCreationExpression || // Valid call or new expressions
(isSignatureHelpBlocker(node) && position > start(node))) // Its a declaration node - call expression cannot be in parent scope
{
break;
}
node = node.parent;
}
if (!node) {
return null;
}
if (node.kind() !== TypeScript.SyntaxKind.InvocationExpression && node.kind() !== TypeScript.SyntaxKind.ObjectCreationExpression) {
this.logger.log("No call expression or generic arguments found for the given position");
return null;
}
var callExpression = <TypeScript.Services.IExpressionWithArgumentListSyntax>node;
var isNew = callExpression.kind() === TypeScript.SyntaxKind.ObjectCreationExpression;
if (isNew && callExpression.argumentList === null) {
this.logger.log("No signature help for a object creation expression without arguments");
return null;
}
TypeScript.Debug.assert(callExpression.argumentList.arguments !== null, "Expected call expression to have arguments, but it did not");
var argumentsStart = end(callExpression.argumentList.openParenToken);
var argumentsEnd = callExpression.argumentList.closeParenToken.fullWidth() > 0
? start(callExpression.argumentList.closeParenToken)
: fullEnd(callExpression.argumentList);
if (position < argumentsStart || position > argumentsEnd) {
this.logger.log("Outside argument list");
return null;
}
// Resolve symbol
var callSymbolInfo = this.compiler.getCallInformationFromAST(node, document);
if (!callSymbolInfo || !callSymbolInfo.targetSymbol || !callSymbolInfo.resolvedSignatures) {
this.logger.log("Could not find symbol for call expression");
return null;
}
// We use the start of the argument list as the 'id' for this signature help item so
// that we can try to recover it later on when we get subsequent sig help questions.
var applicableSpanStart = start(callExpression.argumentList.openParenToken);
// Build the result
var items = SignatureInfoHelpers.getSignatureInfoFromSignatureSymbol(
callSymbolInfo.targetSymbol, callSymbolInfo.resolvedSignatures, callSymbolInfo.enclosingScopeSymbol, this.compiler);
var selectedItemIndex = callSymbolInfo.resolvedSignatures && callSymbolInfo.candidateSignature
? callSymbolInfo.resolvedSignatures.indexOf(callSymbolInfo.candidateSignature)
: 0;
if (items === null || items.length === 0) {
this.logger.log("Can't compute actual and/or formal signature of the call expression");
return null;
}
return new SignatureHelpItems(items, this.getSignatureHelpApplicableSpan(document, applicableSpanStart), selectedItemIndex);
}
//private getSignatureHelpItemsFromPartiallyWrittenTypeArgumentList(document: TypeScript.Document, position: number, genericTypeArgumentListInfo: IPartiallyWrittenTypeArgumentListInformation): SignatureHelpItems {
// var sourceUnit = document.sourceUnit();
// // Get the identifier information
// var ast = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, genericTypeArgumentListInfo.genericIdentifer.start());
// if (ast === null || ast.kind() !== TypeScript.SyntaxKind.IdentifierName) {
// this.logger.log(["getTypeParameterSignatureAtPosition: Unexpected ast found at position:", position, ast === null ? "ast was null" : "ast kind: " + SyntaxKind[ast.kind()]].join(' '));
// return null;
// }
// var symbolInformation = this.compiler.getSymbolInformationFromAST(ast, document);
// if (!symbolInformation.symbol) {
// return null;
// }
// // TODO: are we in an new expression?
// var isNew = SignatureInfoHelpers.isTargetOfObjectCreationExpression(genericTypeArgumentListInfo.genericIdentifer);
// var typeSymbol = symbolInformation.symbol.type;
// if (typeSymbol.kind === TypeScript.PullElementKind.FunctionType ||
// (isNew && typeSymbol.kind === TypeScript.PullElementKind.ConstructorType)) {
// var signatures = isNew ? typeSymbol.getConstructSignatures() : typeSymbol.getCallSignatures();
// // Build the result
// var items = SignatureInfoHelpers.getSignatureInfoFromSignatureSymbol(symbolInformation.symbol, signatures, symbolInformation.enclosingScopeSymbol, this.compiler);
// if (items === null || items.length === 0) {
// return null;
// }
// return new SignatureHelpItems(items, 0);
// }
// else if (typeSymbol.isGeneric()) {
// // The symbol is a generic type
// // Get the class symbol for constuctor symbol
// if (typeSymbol.kind === TypeScript.PullElementKind.ConstructorType) {
// typeSymbol = typeSymbol.getAssociatedContainerType();
// }
// // Build the result
// var items = SignatureInfoHelpers.getSignatureInfoFromGenericSymbol(typeSymbol, symbolInformation.enclosingScopeSymbol, this.compiler);
// if (items === null || items.length === 0) {
// return null;
// }
// return new SignatureHelpItems(items, 0);
// }
// // Nothing to handle
// return null;
//}
public getRenameInfo(fileName: string, position: number): RenameInfo {
fileName = TypeScript.switchToForwardSlashes(fileName);
var symbolInfo = this.getSymbolInfoAtPosition(fileName, position, /*requireName:*/ true);
if (symbolInfo === null) {
return RenameInfo.CreateError(TypeScript.getDiagnosticMessage(DiagnosticCode.You_must_rename_an_identifier, null));
}
if (symbolInfo.symbol === null) {
return RenameInfo.CreateError(TypeScript.getDiagnosticMessage(DiagnosticCode.You_cannot_rename_this_element, null));
}
var document = this.compiler.getDocument(fileName);
var sourceUnit = document.sourceUnit();
var topNode = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, position);
var definitions = this.getDefinitionAtPosition(fileName, position);
if (definitions === null || definitions.length === 0) {
return RenameInfo.CreateError(TypeScript.getDiagnosticMessage(DiagnosticCode.You_cannot_rename_this_element, null));
}
var definition = definitions[0];
var symbol = symbolInfo.symbol;
return RenameInfo.Create(
symbol.name,
symbol.name,
this.mapPullElementKind(symbol.kind, symbol),
this.getScriptElementKindModifiers(symbol),
TextSpan.fromBounds(start(topNode), end(topNode)));
}
public getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
fileName = TypeScript.switchToForwardSlashes(fileName);
var document = this.compiler.getDocument(fileName);
var sourceUnit = document.sourceUnit();
var currentNode = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, position);
// first check if we are at InvocationExpression\ObjectCreationExpression - if yes then try to obtain concrete overload that was used
var callExpressionTarget = ASTHelpers.getCallExpressionTarget(currentNode);
var callInformation = callExpressionTarget && callExpressionTarget.parent && this.compiler.getCallInformationFromAST(callExpressionTarget.parent, document);
var symbol: PullSymbol = callInformation && callInformation.candidateSignature;
if (!symbol) {
var symbolInfo = this.getSymbolInfoAtAST(document, currentNode, position, /*requireName:*/ false);
if (symbolInfo === null || symbolInfo.symbol === null) {
return null;
}
var symbol = symbolInfo.symbol;
TypeScript.Debug.assert(symbol.kind !== TypeScript.PullElementKind.None &&
symbol.kind !== TypeScript.PullElementKind.Global &&
symbol.kind !== TypeScript.PullElementKind.Script, "getDefinitionAtPosition - Invalid symbol kind");
if (symbol.kind === TypeScript.PullElementKind.Primitive) {
// Primitive symbols do not have definition locations that map to host soruces.
// Return null to indicate they have no "definition locations".
return null;
}
}
var declarations = symbol.getDeclarations();
var symbolName = symbol.getDisplayName();
var symbolKind = this.mapPullElementKind(symbol.kind, symbol);
var container = symbol.getContainer();
var containerName = container ? container.fullName() : "";
var containerKind = container ? this.mapPullElementKind(container.kind, container) : "";
var result: DefinitionInfo[] = [];
if (!this.tryAddDefinition(symbolKind, symbolName, containerKind, containerName, declarations, result) &&
!this.tryAddSignatures(symbolKind, symbolName, containerKind, containerName, declarations, result) &&
!this.tryAddConstructor(symbolKind, symbolName, containerKind, containerName, declarations, result)) {
// Just add all the declarations.
this.addDeclarations(symbolKind, symbolName, containerKind, containerName, declarations, result);
}
return result;
}
private addDeclarations(symbolKind: string, symbolName: string, containerKind: string, containerName: string, declarations: TypeScript.PullDecl[], result: DefinitionInfo[]): void {
for (var i = 0, n = declarations.length; i < n; i++) {
this.addDeclaration(symbolKind, symbolName, containerKind, containerName, declarations[i], result);
}
}
private addDeclaration(symbolKind: string, symbolName: string, containerKind: string, containerName: string, declaration: TypeScript.PullDecl, result: DefinitionInfo[]): void {
var ast = declaration.ast();
result.push(new DefinitionInfo(
this._getHostFileName(declaration.fileName()),
TextSpan.fromBounds(start(ast), end(ast)), symbolKind, symbolName, containerKind, containerName));
}
private tryAddDefinition(symbolKind: string, symbolName: string, containerKind: string, containerName: string, declarations: TypeScript.PullDecl[], result: DefinitionInfo[]): boolean {
// First, if there are definitions and signatures, then just pick the definition.
var definitionDeclaration = TypeScript.ArrayUtilities.firstOrDefault(declarations, d => {
var signature = d.getSignatureSymbol(this.getSemanticInfoChain());
return signature && signature.isDefinition();
});
if (!definitionDeclaration) {
return false;
}
this.addDeclaration(symbolKind, symbolName, containerKind, containerName, definitionDeclaration, result);
return true;
}
private tryAddSignatures(symbolKind: string, symbolName: string, containerKind: string, containerName: string, declarations: TypeScript.PullDecl[], result: DefinitionInfo[]): boolean {
// We didn't have a definition. Check and see if we have any signatures. If so, just
// add the last one.
var signatureDeclarations = TypeScript.ArrayUtilities.where(declarations, d => {
var signature = d.getSignatureSymbol(this.getSemanticInfoChain());
return signature && !signature.isDefinition();
});
if (signatureDeclarations.length === 0) {
return false;
}
this.addDeclaration(symbolKind, symbolName, containerKind, containerName, TypeScript.ArrayUtilities.last(signatureDeclarations), result);
return true;
}
private tryAddConstructor(symbolKind: string, symbolName: string, containerKind: string, containerName: string, declarations: TypeScript.PullDecl[], result: DefinitionInfo[]): boolean {
var constructorDeclarations = TypeScript.ArrayUtilities.where(declarations, d => d.kind === TypeScript.PullElementKind.ConstructorMethod);
if (constructorDeclarations.length === 0) {
return false;
}
this.addDeclaration(symbolKind, symbolName, containerKind, containerName, TypeScript.ArrayUtilities.last(constructorDeclarations), result);
return true;
}
// Return array of NavigateToItems in which each item has matched name with searchValue. If none is found, return an empty array.
// The function will search all files (both close and open) in the solutions. SearchValue can be either one search term or multiple terms separated by comma.
public getNavigateToItems(searchValue: string): NavigateToItem[] {
Debug.assert(searchValue !== null && searchValue !== undefined, "The searchValue argument was not supplied or null");
// Split search value in terms array
var terms = searchValue.split(" ");
// default NavigateTo approach: if search term contains only lower-case chars - use case-insensitive search, otherwise switch to case-sensitive version
var searchTerms = terms.map((t) => ({ caseSensitive: this.hasAnyUpperCaseCharacter(t), term: t }));
var items: NavigateToItem[] = [];
var fileNames = this.compiler.fileNames();
for (var i = 0, n = fileNames.length; i < n; i++) {
var fileName = fileNames[i];
var declaration = this.compiler.getCachedTopLevelDeclaration(fileName);
this.findSearchValueInPullDecl(fileName, [declaration], /*onlyFunctions:*/ false, items, searchTerms);
}
return items;
}
private hasAnyUpperCaseCharacter(s: string): boolean {
for (var i = 0; i < s.length; ++i) {
if (s.charAt(i).toLocaleLowerCase() !== s.charAt(i)) {
return true;
}
}
return false;
}
// Search given file's declaration and output matched NavigateToItem into array of NavigateToItem[] which is passed in as
// one of the function's arguements. The function will recruseively call itself to visit all children declarations
// of each member of declarations array.
//
// @param fileName: name of the file which the function is currently visiting its PullDecl members.
// delcarations: array of PullDecl, containing current visiting top level PullDecl objects.
// results: array of NavigateToItem to be filled in with matched NavigateToItem objects.
// searchTerms: array of search terms.
// searchRegExpTerms: array of regular expressions in which each expression corresponding to each item in the searchTerms array.
// parentName: a name of the parent of declarations array.
// parentKindName: a kind of parent in string format.
private findSearchValueInPullDecl(fileName: string, declarations: TypeScript.PullDecl[], onlyFunctions: boolean, results: NavigateToItem[],
searchTerms: { caseSensitive: boolean; term: string }[], parentName?: string, parentkindName?: string): void {
for (var i = 0, declLength = declarations.length; i < declLength; ++i) {
var declaration = declarations[i];
if (this.shouldIncludeDeclarationInNavigationItems(declaration, onlyFunctions)) {
var declName = declaration.getDisplayName();
var matchKind = this.getMatchKind(searchTerms, declName);
if (matchKind) {
var ast = declaration.ast();
var item = new NavigateToItem();
item.name = declName;
item.matchKind = matchKind;
item.kind = this.mapPullElementKind(declaration.kind);
item.kindModifiers = this.getScriptElementKindModifiersFromDecl(declaration);
item.fileName = this._getHostFileName(fileName);
item.textSpan = TextSpan.fromBounds(start(ast), end(ast));
item.containerName = parentName || "";
item.containerKind = parentkindName || "";
results.push(item);
}
}
if (this.isContainerDeclaration(declaration)) {
var declName = declaration.kind === PullElementKind.Script ? undefined : declaration.getDisplayName();
var fullName = parentName ? parentName + "." + declName : declName;
this.findSearchValueInPullDecl(
fileName, declaration.getChildDecls(), /*onlyFunctions:*/ declaration.kind === PullElementKind.Function,
results, searchTerms, fullName, this.mapPullElementKind(declaration.kind));
}
}
}
private getMatchKind(searchTerms: { caseSensitive: boolean; term: string }[], declName: string) {
var matchKind: MatchKind = null;
for (var j = 0, termsLength = searchTerms.length; j < termsLength; ++j) {
var searchTerm = searchTerms[j];
var declNameToSearch = searchTerm.caseSensitive ? declName : declName.toLocaleLowerCase();
// in case of case-insensitive search searchTerm.term will already be lower-cased
var index = declNameToSearch.indexOf(searchTerm.term);
if (index < 0) {
// Didn't match.
return null;
}
var termKind = MatchKind.substring
if (index === 0) {
// here we know that match occur at the beginning of the string.
// if search term and declName has the same length - we have an exact match, otherwise declName have longer length and this will be prefix match
termKind = declName.length === searchTerm.term.length ? MatchKind.exact : MatchKind.prefix;
}
// Update our match kind if we don't have one, or if this match is better.
if (matchKind === null || termKind < matchKind) {
matchKind = termKind;
}
}
return matchKind === null ? null : MatchKind[matchKind];
}
// Return ScriptElementKind in string of a given declaration.
private getScriptElementKindModifiersFromDecl(decl: TypeScript.PullDecl): string {
var result: string[] = [];
var flags = decl.flags;
if (flags & TypeScript.PullElementFlags.Exported) {
result.push(ScriptElementKindModifier.exportedModifier);
}
if (flags & TypeScript.PullElementFlags.Ambient) {
result.push(ScriptElementKindModifier.ambientModifier);
}
if (flags & TypeScript.PullElementFlags.Public) {
result.push(ScriptElementKindModifier.publicMemberModifier);
}
if (flags & TypeScript.PullElementFlags.Private) {
result.push(ScriptElementKindModifier.privateMemberModifier);
}
if (flags & TypeScript.PullElementFlags.Static) {
result.push(ScriptElementKindModifier.staticModifier);
}
return result.length > 0 ? result.join(',') : ScriptElementKindModifier.none;
}
// Return true if the declaration has PullElementKind that is one of
// the following container types and return false otherwise.
private isContainerDeclaration(declaration: TypeScript.PullDecl): boolean {
switch (declaration.kind) {
case TypeScript.PullElementKind.Script: