This repository was archived by the owner on Oct 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathtypescript-service.ts
1832 lines (1726 loc) · 87.9 KB
/
typescript-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Operation } from 'fast-json-patch'
import iterate from 'iterare'
import { castArray, merge, omit } from 'lodash'
import { toPairs } from 'lodash'
import hashObject = require('object-hash')
import { Span } from 'opentracing'
import { Observable } from 'rxjs'
import * as ts from 'typescript'
import * as url from 'url'
import {
CodeActionParams,
Command,
CompletionItemKind,
CompletionList,
DidChangeConfigurationParams,
DidChangeTextDocumentParams,
DidCloseTextDocumentParams,
DidOpenTextDocumentParams,
DidSaveTextDocumentParams,
DocumentSymbolParams,
ExecuteCommandParams,
Hover,
InsertTextFormat,
Location,
MarkedString,
ParameterInformation,
ReferenceParams,
RenameParams,
SignatureHelp,
SignatureInformation,
SymbolInformation,
TextDocumentPositionParams,
TextDocumentSyncKind,
TextEdit,
WorkspaceEdit,
} from 'vscode-languageserver'
import { walkMostAST } from './ast'
import { convertTsDiagnostic } from './diagnostics'
import { FileSystem, FileSystemUpdater, LocalFileSystem, RemoteFileSystem } from './fs'
import { LanguageClient } from './lang-handler'
import { Logger, LSPLogger } from './logging'
import { InMemoryFileSystem, isTypeScriptLibrary } from './memfs'
import {
DEPENDENCY_KEYS,
extractDefinitelyTypedPackageName,
extractNodeModulesPackageName,
PackageJson,
PackageManager,
} from './packages'
import { ProjectConfiguration, ProjectManager } from './project-manager'
import {
CompletionItem,
DependencyReference,
InitializeParams,
InitializeResult,
PackageDescriptor,
PackageInformation,
PluginSettings,
ReferenceInformation,
SymbolDescriptor,
SymbolLocationInformation,
WorkspaceReferenceParams,
WorkspaceSymbolParams,
} from './request-type'
import {
definitionInfoToSymbolDescriptor,
locationUri,
navigateToItemToSymbolInformation,
navigationTreeIsSymbol,
navigationTreeToSymbolDescriptor,
navigationTreeToSymbolInformation,
walkNavigationTree,
} from './symbols'
import { traceObservable } from './tracing'
import {
getMatchingPropertyCount,
getPropertyCount,
JSONPTR,
normalizeUri,
observableFromIterable,
path2uri,
toUnixPath,
uri2path,
} from './util'
export interface TypeScriptServiceOptions {
traceModuleResolution?: boolean
strict?: boolean
}
export type TypeScriptServiceFactory = (client: LanguageClient, options?: TypeScriptServiceOptions) => TypeScriptService
/**
* Settings synced through `didChangeConfiguration`
*/
export interface Settings extends PluginSettings {
format: ts.FormatCodeSettings
}
/**
* Maps string-based CompletionEntry::kind to enum-based CompletionItemKind
*/
const completionKinds = new Map<string, CompletionItemKind>([
[`class`, CompletionItemKind.Class],
[`constructor`, CompletionItemKind.Constructor],
[`enum`, CompletionItemKind.Enum],
[`field`, CompletionItemKind.Field],
[`file`, CompletionItemKind.File],
[`function`, CompletionItemKind.Function],
[`interface`, CompletionItemKind.Interface],
[`keyword`, CompletionItemKind.Keyword],
[`method`, CompletionItemKind.Method],
[`module`, CompletionItemKind.Module],
[`property`, CompletionItemKind.Property],
[`reference`, CompletionItemKind.Reference],
[`snippet`, CompletionItemKind.Snippet],
[`text`, CompletionItemKind.Text],
[`unit`, CompletionItemKind.Unit],
[`value`, CompletionItemKind.Value],
[`variable`, CompletionItemKind.Variable],
])
/**
* Handles incoming requests and return responses. There is a one-to-one-to-one
* correspondence between TCP connection, TypeScriptService instance, and
* language workspace. TypeScriptService caches data from the compiler across
* requests. The lifetime of the TypeScriptService instance is tied to the
* lifetime of the TCP connection, so its caches are deleted after the
* connection is torn down.
*
* Methods are camelCase versions of the LSP spec methods and dynamically
* dispatched. Methods not to be exposed over JSON RPC are prefixed with an
* underscore.
*/
export class TypeScriptService {
public projectManager: ProjectManager
/**
* The rootPath as passed to `initialize` or converted from `rootUri`
*/
public root: string
/**
* The root URI as passed to `initialize` or converted from `rootPath`
*/
protected rootUri: string
/**
* Cached response for empty workspace/symbol query
*/
private emptyQueryWorkspaceSymbols: Observable<Operation>
private traceModuleResolution: boolean
/**
* The remote (or local), asynchronous, file system to fetch files from
*/
protected fileSystem: FileSystem
protected logger: Logger
/**
* Holds file contents and workspace structure in memory
*/
protected inMemoryFileSystem: InMemoryFileSystem
/**
* Syncs the remote file system with the in-memory file system
*/
protected updater: FileSystemUpdater
/**
* Emits true or false depending on whether the root package.json is named "definitely-typed".
* On DefinitelyTyped, files are not prefetched and a special workspace/symbol algorithm is used.
*/
protected isDefinitelyTyped: Observable<boolean>
/**
* Keeps track of package.jsons in the workspace
*/
protected packageManager: PackageManager
/**
* Settings synced though `didChangeConfiguration`
*/
protected settings: Settings = {
format: {
tabSize: 4,
indentSize: 4,
newLineCharacter: '\n',
convertTabsToSpaces: false,
insertSpaceAfterCommaDelimiter: true,
insertSpaceAfterSemicolonInForStatements: true,
insertSpaceBeforeAndAfterBinaryOperators: true,
insertSpaceAfterKeywordsInControlFlowStatements: true,
insertSpaceAfterFunctionKeywordForAnonymousFunctions: true,
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
insertSpaceBeforeFunctionParenthesis: false,
placeOpenBraceOnNewLineForFunctions: false,
placeOpenBraceOnNewLineForControlBlocks: false,
},
allowLocalPluginLoads: false,
globalPlugins: [],
pluginProbeLocations: [],
}
/**
* Indicates if the client prefers completion results formatted as snippets.
*/
private supportsCompletionWithSnippets = false
constructor(protected client: LanguageClient, protected options: TypeScriptServiceOptions = {}) {
this.logger = new LSPLogger(client)
}
/**
* The initialize request is sent as the first request from the client to the server. If the
* server receives request or notification before the `initialize` request it should act as
* follows:
*
* - for a request the respond should be errored with `code: -32002`. The message can be picked by
* the server.
* - notifications should be dropped, except for the exit notification. This will allow the exit a
* server without an initialize request.
*
* Until the server has responded to the `initialize` request with an `InitializeResult` the
* client must not sent any additional requests or notifications to the server.
*
* During the `initialize` request the server is allowed to send the notifications
* `window/showMessage`, `window/logMessage` and `telemetry/event` as well as the
* `window/showMessageRequest` request to the client.
*
* @return Observable of JSON Patches that build an `InitializeResult`
*/
public initialize(params: InitializeParams, span = new Span()): Observable<Operation> {
// tslint:disable:deprecation
if (params.rootUri || params.rootPath) {
this.root = params.rootPath || uri2path(params.rootUri!)
this.rootUri = params.rootUri || path2uri(params.rootPath!)
// tslint:enable:deprecation
this.supportsCompletionWithSnippets =
(params.capabilities.textDocument &&
params.capabilities.textDocument.completion &&
params.capabilities.textDocument.completion.completionItem &&
params.capabilities.textDocument.completion.completionItem.snippetSupport) ||
false
// The root URI always refers to a directory
if (!this.rootUri.endsWith('/')) {
this.rootUri += '/'
}
this._initializeFileSystems(
!this.options.strict && !(params.capabilities.xcontentProvider && params.capabilities.xfilesProvider)
)
this.updater = new FileSystemUpdater(this.fileSystem, this.inMemoryFileSystem)
this.projectManager = new ProjectManager(
this.root,
this.inMemoryFileSystem,
this.updater,
this.traceModuleResolution,
this.settings,
this.logger
)
this.packageManager = new PackageManager(this.updater, this.inMemoryFileSystem, this.logger)
// Detect DefinitelyTyped
// Fetch root package.json (if exists)
const normRootUri = this.rootUri.endsWith('/') ? this.rootUri : this.rootUri + '/'
const packageJsonUri = normRootUri + 'package.json'
this.isDefinitelyTyped = Observable.from(this.packageManager.getPackageJson(packageJsonUri, span))
// Check name
.map(packageJson => packageJson.name === 'definitely-typed')
.catch(err => [false])
.publishReplay()
.refCount()
// Pre-fetch files in the background if not DefinitelyTyped
this.isDefinitelyTyped
.mergeMap(isDefinitelyTyped => {
if (!isDefinitelyTyped) {
return this.projectManager.ensureOwnFiles(span)
}
return []
})
.subscribe(undefined, err => {
this.logger.error(err)
})
}
const result: InitializeResult = {
capabilities: {
// Tell the client that the server works in FULL text document sync mode
textDocumentSync: TextDocumentSyncKind.Full,
hoverProvider: true,
signatureHelpProvider: {
triggerCharacters: ['(', ','],
},
definitionProvider: true,
typeDefinitionProvider: true,
referencesProvider: true,
documentSymbolProvider: true,
workspaceSymbolProvider: true,
xworkspaceReferencesProvider: true,
xdefinitionProvider: true,
xdependenciesProvider: true,
completionProvider: {
resolveProvider: true,
triggerCharacters: ['.'],
},
codeActionProvider: true,
renameProvider: true,
executeCommandProvider: {
commands: [],
},
xpackagesProvider: true,
},
}
return Observable.of({
op: 'add',
path: '',
value: result,
} as Operation)
}
/**
* Initializes the remote file system and in-memory file system.
* Can be overridden
*
* @param accessDisk Whether the language server is allowed to access the local file system
*/
protected _initializeFileSystems(accessDisk: boolean): void {
this.fileSystem = accessDisk ? new LocalFileSystem(this.rootUri) : new RemoteFileSystem(this.client)
this.inMemoryFileSystem = new InMemoryFileSystem(this.root, this.logger)
}
/**
* The shutdown request is sent from the client to the server. It asks the server to shut down,
* but to not exit (otherwise the response might not be delivered correctly to the client).
* There is a separate exit notification that asks the server to exit.
*
* @return Observable of JSON Patches that build a `null` result
*/
public shutdown(params = {}, span = new Span()): Observable<Operation> {
this.projectManager.dispose()
this.packageManager.dispose()
return Observable.of({ op: 'add', path: '', value: null } as Operation)
}
/**
* A notification sent from the client to the server to signal the change of configuration
* settings.
*/
public workspaceDidChangeConfiguration(params: DidChangeConfigurationParams): void {
merge(this.settings, params.settings)
}
/**
* The goto definition request is sent from the client to the server to resolve the definition
* location of a symbol at a given text document position.
*
* @return Observable of JSON Patches that build a `Location[]` result
*/
public textDocumentDefinition(params: TextDocumentPositionParams, span = new Span()): Observable<Operation> {
return this._getDefinitionLocations(params, span, false)
.map((location: Location): Operation => ({ op: 'add', path: '/-', value: location }))
.startWith({ op: 'add', path: '', value: [] })
}
/**
* The goto type definition request is sent from the client to the server to resolve the type
* location of a symbol at a given text document position.
*
* @return Observable of JSON Patches that build a `Location[]` result
*/
public textDocumentTypeDefinition(params: TextDocumentPositionParams, span = new Span()): Observable<Operation> {
return this._getDefinitionLocations(params, span, true)
.map((location: Location): Operation => ({ op: 'add', path: '/-', value: location }))
.startWith({ op: 'add', path: '', value: [] })
}
/**
* Returns an Observable of all definition locations found for a symbol.
*/
protected _getDefinitionLocations(
params: TextDocumentPositionParams,
span = new Span(),
goToType = false
): Observable<Location> {
const uri = normalizeUri(params.textDocument.uri)
// Fetch files needed to resolve definition
return this.projectManager
.ensureReferencedFiles(uri, undefined, undefined, span)
.toArray()
.mergeMap(() => {
const fileName: string = uri2path(uri)
const configuration = this.projectManager.getConfiguration(fileName)
configuration.ensureBasicFiles(span)
const sourceFile = this._getSourceFile(configuration, fileName, span)
if (!sourceFile) {
throw new Error(`Expected source file ${fileName} to exist`)
}
const offset: number = ts.getPositionOfLineAndCharacter(
sourceFile,
params.position.line,
params.position.character
)
const definitions: ts.DefinitionInfo[] | undefined = goToType
? configuration.getService().getTypeDefinitionAtPosition(fileName, offset)
: configuration.getService().getDefinitionAtPosition(fileName, offset)
return Observable.from(definitions || []).map(
(definition): Location => {
const sourceFile = this._getSourceFile(configuration, definition.fileName, span)
if (!sourceFile) {
throw new Error(
'expected source file "' + definition.fileName + '" to exist in configuration'
)
}
const start = ts.getLineAndCharacterOfPosition(sourceFile, definition.textSpan.start)
const end = ts.getLineAndCharacterOfPosition(
sourceFile,
definition.textSpan.start + definition.textSpan.length
)
return {
uri: locationUri(definition.fileName),
range: {
start,
end,
},
}
}
)
})
}
/**
* This method is the same as textDocument/definition, except that:
*
* - The method returns metadata about the definition (the same metadata that
* workspace/xreferences searches for).
* - The concrete location to the definition (location field)
* is optional. This is useful because the language server might not be able to resolve a goto
* definition request to a concrete location (e.g. due to lack of dependencies) but still may
* know some information about it.
*
* @return Observable of JSON Patches that build a `SymbolLocationInformation[]` result
*/
public textDocumentXdefinition(params: TextDocumentPositionParams, span = new Span()): Observable<Operation> {
return this._getSymbolLocationInformations(params, span)
.map(symbol => ({ op: 'add', path: '/-', value: symbol } as Operation))
.startWith({ op: 'add', path: '', value: [] })
}
/**
* Returns an Observable of SymbolLocationInformations for the definition of a symbol at the given position
*/
protected _getSymbolLocationInformations(
params: TextDocumentPositionParams,
span = new Span()
): Observable<SymbolLocationInformation> {
const uri = normalizeUri(params.textDocument.uri)
// Ensure files needed to resolve SymbolLocationInformation are fetched
return this.projectManager
.ensureReferencedFiles(uri, undefined, undefined, span)
.toArray()
.mergeMap(() => {
// Convert URI to file path
const fileName: string = uri2path(uri)
// Get closest tsconfig configuration
const configuration = this.projectManager.getConfiguration(fileName)
configuration.ensureBasicFiles(span)
const sourceFile = this._getSourceFile(configuration, fileName, span)
if (!sourceFile) {
throw new Error(`Unknown text document ${uri}`)
}
// Convert line/character to offset
const offset: number = ts.getPositionOfLineAndCharacter(
sourceFile,
params.position.line,
params.position.character
)
// Query TypeScript for references
return Observable.from(
configuration.getService().getDefinitionAtPosition(fileName, offset) || []
).mergeMap(
(definition: ts.DefinitionInfo): Observable<SymbolLocationInformation> => {
const definitionUri = locationUri(definition.fileName)
// Get the PackageDescriptor
return this._getPackageDescriptor(definitionUri)
.defaultIfEmpty(undefined)
.map(
(packageDescriptor: PackageDescriptor | undefined): SymbolLocationInformation => {
const sourceFile = this._getSourceFile(configuration, definition.fileName, span)
if (!sourceFile) {
throw new Error(
`Expected source file ${definition.fileName} to exist in configuration`
)
}
const symbol = definitionInfoToSymbolDescriptor(definition, this.root)
if (packageDescriptor) {
symbol.package = packageDescriptor
}
return {
symbol,
location: {
uri: definitionUri,
range: {
start: ts.getLineAndCharacterOfPosition(
sourceFile,
definition.textSpan.start
),
end: ts.getLineAndCharacterOfPosition(
sourceFile,
definition.textSpan.start + definition.textSpan.length
),
},
},
}
}
)
}
)
})
}
/**
* Finds the PackageDescriptor a given file belongs to
*
* @return Observable that emits a single PackageDescriptor or never if the definition does not belong to any package
*/
protected _getPackageDescriptor(uri: string, childOf = new Span()): Observable<PackageDescriptor> {
return traceObservable('Get PackageDescriptor', childOf, span => {
span.addTags({ uri })
// Get package name of the dependency in which the symbol is defined in, if any
const packageName = extractNodeModulesPackageName(uri)
if (packageName) {
// The symbol is part of a dependency in node_modules
// Build URI to package.json of the Dependency
const encodedPackageName = packageName
.split('/')
.map(encodeURIComponent)
.join('/')
const parts: url.UrlObject = url.parse(uri)
const packageJsonUri = url.format({
...parts,
pathname:
parts.pathname!.slice(0, parts.pathname!.lastIndexOf('/node_modules/' + encodedPackageName)) +
`/node_modules/${encodedPackageName}/package.json`,
})
// Fetch the package.json of the dependency
return this.updater.ensure(packageJsonUri, span).concat(
Observable.defer(
(): Observable<PackageDescriptor> => {
const packageJson: PackageJson = JSON.parse(
this.inMemoryFileSystem.getContent(packageJsonUri)
)
const { name, version } = packageJson
if (!name) {
return Observable.empty()
}
// Used by the LSP proxy to shortcut database lookup of repo URL for PackageDescriptor
let repoURL: string | undefined
if (name.startsWith('@types/')) {
// if the dependency package is an @types/ package, point the repo to DefinitelyTyped
repoURL = 'https://github.com/DefinitelyTyped/DefinitelyTyped'
} else {
// else use repository field from package.json
repoURL =
typeof packageJson.repository === 'object' ? packageJson.repository.url : undefined
}
return Observable.of({ name, version, repoURL })
}
)
)
} else {
// The symbol is defined in the root package of the workspace, not in a dependency
// Get root package.json
return this.packageManager.getClosestPackageJson(uri, span).mergeMap(packageJson => {
let { name, version } = packageJson
if (!name) {
return []
}
let repoURL = typeof packageJson.repository === 'object' ? packageJson.repository.url : undefined
// If the root package is DefinitelyTyped, find out the proper @types package name for each typing
if (name === 'definitely-typed') {
name = extractDefinitelyTypedPackageName(uri)
if (!name) {
this.logger.error(`Could not extract package name from DefinitelyTyped URI ${uri}`)
return []
}
version = undefined
repoURL = 'https://github.com/DefinitelyTyped/DefinitelyTyped'
}
return [{ name, version, repoURL } as PackageDescriptor]
})
}
})
}
/**
* The hover request is sent from the client to the server to request hover information at a
* given text document position.
*
* @return Observable of JSON Patches that build a `Hover` result
*/
public textDocumentHover(params: TextDocumentPositionParams, span = new Span()): Observable<Operation> {
return this._getHover(params, span).map(hover => ({ op: 'add', path: '', value: hover } as Operation))
}
/**
* Returns an Observable for a Hover at the given position
*/
protected _getHover(params: TextDocumentPositionParams, span = new Span()): Observable<Hover> {
const uri = normalizeUri(params.textDocument.uri)
// Ensure files needed to resolve hover are fetched
return this.projectManager
.ensureReferencedFiles(uri, undefined, undefined, span)
.toArray()
.map(
(): Hover => {
const fileName: string = uri2path(uri)
const configuration = this.projectManager.getConfiguration(fileName)
configuration.ensureBasicFiles(span)
const sourceFile = this._getSourceFile(configuration, fileName, span)
if (!sourceFile) {
throw new Error(`Unknown text document ${uri}`)
}
const offset: number = ts.getPositionOfLineAndCharacter(
sourceFile,
params.position.line,
params.position.character
)
const info = configuration.getService().getQuickInfoAtPosition(fileName, offset)
if (!info) {
return { contents: [] }
}
const contents: (MarkedString | string)[] = []
// Add declaration without the kind
const declaration = ts.displayPartsToString(info.displayParts).replace(/^\(.+?\)\s+/, '')
contents.push({ language: 'typescript', value: declaration })
// Add kind with modifiers, e.g. "method (private, ststic)", "class (exported)"
if (info.kind) {
let kind = '**' + info.kind + '**'
const modifiers = info.kindModifiers
.split(',')
// Filter out some quirks like "constructor (exported)"
.filter(
mod =>
mod &&
(mod !== ts.ScriptElementKindModifier.exportedModifier ||
info.kind !== ts.ScriptElementKind.constructorImplementationElement)
)
// Make proper adjectives
.map(mod => {
switch (mod) {
case ts.ScriptElementKindModifier.ambientModifier:
return 'ambient'
case ts.ScriptElementKindModifier.exportedModifier:
return 'exported'
default:
return mod
}
})
if (modifiers.length > 0) {
kind += ' _(' + modifiers.join(', ') + ')_'
}
contents.push(kind)
}
// Add documentation
const documentation = ts.displayPartsToString(info.documentation)
if (documentation) {
contents.push(documentation)
}
const start = ts.getLineAndCharacterOfPosition(sourceFile, info.textSpan.start)
const end = ts.getLineAndCharacterOfPosition(sourceFile, info.textSpan.start + info.textSpan.length)
return {
contents,
range: {
start,
end,
},
}
}
)
}
/**
* The references request is sent from the client to the server to resolve project-wide
* references for the symbol denoted by the given text document position.
*
* Returns all references to the symbol at the position in the own workspace, including references inside node_modules.
*
* @return Observable of JSON Patches that build a `Location[]` result
*/
public textDocumentReferences(params: ReferenceParams, span = new Span()): Observable<Operation> {
const uri = normalizeUri(params.textDocument.uri)
// Ensure all files were fetched to collect all references
return (
this.projectManager
.ensureOwnFiles(span)
.concat(
Observable.defer(() => {
// Convert URI to file path because TypeScript doesn't work with URIs
const fileName = uri2path(uri)
// Get tsconfig configuration for requested file
const configuration = this.projectManager.getConfiguration(fileName)
// Ensure all files have been added
configuration.ensureAllFiles(span)
const program = configuration.getProgram(span)
if (!program) {
return Observable.empty<never>()
}
// Get SourceFile object for requested file
const sourceFile = this._getSourceFile(configuration, fileName, span)
if (!sourceFile) {
throw new Error(`Source file ${fileName} does not exist`)
}
// Convert line/character to offset
const offset: number = ts.getPositionOfLineAndCharacter(
sourceFile,
params.position.line,
params.position.character
)
// Request references at position from TypeScript
// Despite the signature, getReferencesAtPosition() can return undefined
return Observable.from(
configuration.getService().getReferencesAtPosition(fileName, offset) || []
)
.filter(
reference =>
// Filter declaration if not requested
(!reference.isDefinition ||
(params.context && params.context.includeDeclaration)) &&
// Filter references in node_modules
!reference.fileName.includes('/node_modules/')
)
.map(
(reference): Location => {
const sourceFile = program.getSourceFile(reference.fileName)
if (!sourceFile) {
throw new Error(`Source file ${reference.fileName} does not exist`)
}
// Convert offset to line/character position
const start = ts.getLineAndCharacterOfPosition(sourceFile, reference.textSpan.start)
const end = ts.getLineAndCharacterOfPosition(
sourceFile,
reference.textSpan.start + reference.textSpan.length
)
return {
uri: path2uri(reference.fileName),
range: {
start,
end,
},
}
}
)
})
)
.map((location: Location): Operation => ({ op: 'add', path: '/-', value: location }))
// Initialize with array
.startWith({ op: 'add', path: '', value: [] })
)
}
/**
* The workspace symbol request is sent from the client to the server to list project-wide
* symbols matching the query string. The text document parameter specifies the active document
* at time of the query. This can be used to rank or limit results.
*
* @return Observable of JSON Patches that build a `SymbolInformation[]` result
*/
public workspaceSymbol(params: WorkspaceSymbolParams, span = new Span()): Observable<Operation> {
// Return cached result for empty query, if available
if (!params.query && !params.symbol && this.emptyQueryWorkspaceSymbols) {
return this.emptyQueryWorkspaceSymbols
}
/** A sorted array that keeps track of symbol match scores to determine the index to insert the symbol at */
const scores: number[] = []
let observable = this.isDefinitelyTyped
.mergeMap(
(isDefinitelyTyped: boolean): Observable<[number, SymbolInformation]> => {
// Use special logic for DefinitelyTyped
// Search only in the correct subdirectory for the given PackageDescriptor
if (isDefinitelyTyped) {
// Error if not passed a SymbolDescriptor query with an `@types` PackageDescriptor
if (
!params.symbol ||
!params.symbol.package ||
!params.symbol.package.name ||
!params.symbol.package.name.startsWith('@types/')
) {
return Observable.throw(
new Error(
'workspace/symbol on DefinitelyTyped is only supported with a SymbolDescriptor query with an @types PackageDescriptor'
)
)
}
// Fetch all files in the package subdirectory
// All packages are in the types/ subdirectory
const normRootUri = this.rootUri.endsWith('/') ? this.rootUri : this.rootUri + '/'
const packageRootUri = normRootUri + params.symbol.package.name.substr(1) + '/'
return this.updater
.ensureStructure(span)
.concat(Observable.defer(() => observableFromIterable(this.inMemoryFileSystem.uris())))
.filter(uri => uri.startsWith(packageRootUri))
.mergeMap(uri => this.updater.ensure(uri, span))
.concat(
Observable.defer(() => {
span.log({ event: 'fetched package files' })
const config = this.projectManager.getParentConfiguration(packageRootUri, 'ts')
if (!config) {
throw new Error(`Could not find tsconfig for ${packageRootUri}`)
}
// Don't match PackageDescriptor on symbols
return this._getSymbolsInConfig(config, omit(params.symbol!, 'package'), span)
})
)
}
// Regular workspace symbol search
// Search all symbols in own code, but not in dependencies
return (
this.projectManager
.ensureOwnFiles(span)
.concat(
Observable.defer(() => {
if (params.symbol && params.symbol.package && params.symbol.package.name) {
// If SymbolDescriptor query with PackageDescriptor, search for package.jsons with matching package name
return (
observableFromIterable(this.packageManager.packageJsonUris())
.filter(
packageJsonUri =>
(JSON.parse(
this.inMemoryFileSystem.getContent(packageJsonUri)
) as PackageJson).name === params.symbol!.package!.name
)
// Find their parent and child tsconfigs
.mergeMap(packageJsonUri =>
Observable.merge(
castArray<ProjectConfiguration>(
this.projectManager.getParentConfiguration(
packageJsonUri
) || []
),
// Search child directories starting at the directory of the package.json
observableFromIterable(
this.projectManager.getChildConfigurations(
url.resolve(packageJsonUri, '.')
)
)
)
)
)
}
// Else search all tsconfigs in the workspace
return observableFromIterable(this.projectManager.configurations())
})
)
// If PackageDescriptor is given, only search project with the matching package name
.mergeMap(config => this._getSymbolsInConfig(config, params.query || params.symbol, span))
)
}
)
// Filter duplicate symbols
// There may be few configurations that contain the same file(s)
// or files from different configurations may refer to the same file(s)
.distinct(symbol => hashObject(symbol, { respectType: false } as any))
// Limit the total amount of symbols returned for text or empty queries
// Higher limit for programmatic symbol queries because it could exclude results with a higher score
.take(params.symbol ? 1000 : 100)
// Find out at which index to insert the symbol to maintain sorting order by score
.map(([score, symbol]) => {
const index = scores.findIndex(s => s < score)
if (index === -1) {
scores.push(score)
return { op: 'add', path: '/-', value: symbol } as Operation
}
scores.splice(index, 0, score)
return { op: 'add', path: '/' + index, value: symbol } as Operation
})
.startWith({ op: 'add', path: '', value: [] })
if (!params.query && !params.symbol) {
observable = this.emptyQueryWorkspaceSymbols = observable.publishReplay().refCount()
}
return observable
}
/**
* The document symbol request is sent from the client to the server to list all symbols found
* in a given text document.
*
* @return Observable of JSON Patches that build a `SymbolInformation[]` result
*/
public textDocumentDocumentSymbol(params: DocumentSymbolParams, span = new Span()): Observable<Operation> {
const uri = normalizeUri(params.textDocument.uri)
// Ensure files needed to resolve symbols are fetched
return this.projectManager
.ensureReferencedFiles(uri, undefined, undefined, span)
.toArray()
.mergeMap(() => {
const fileName = uri2path(uri)
const config = this.projectManager.getConfiguration(fileName)
config.ensureBasicFiles(span)
const sourceFile = this._getSourceFile(config, fileName, span)
if (!sourceFile) {
return []
}
const tree = config.getService().getNavigationTree(fileName)
return observableFromIterable(walkNavigationTree(tree))
.filter(({ tree, parent }) => navigationTreeIsSymbol(tree))
.map(({ tree, parent }) => navigationTreeToSymbolInformation(tree, parent, sourceFile, this.root))
})
.map(symbol => ({ op: 'add', path: '/-', value: symbol } as Operation))
.startWith({ op: 'add', path: '', value: [] } as Operation)
}
/**
* The workspace references request is sent from the client to the server to locate project-wide
* references to a symbol given its description / metadata.
*
* @return Observable of JSON Patches that build a `ReferenceInformation[]` result
*/
public workspaceXreferences(params: WorkspaceReferenceParams, span = new Span()): Observable<Operation> {
const queryWithoutPackage = omit(params.query, 'package')
const minScore = Math.min(4.75, getPropertyCount(queryWithoutPackage))
return this.isDefinitelyTyped
.mergeMap(isDefinitelyTyped => {
if (isDefinitelyTyped) {
throw new Error('workspace/xreferences not supported in DefinitelyTyped')
}
return this.projectManager.ensureAllFiles(span)
})
.concat(
Observable.defer(() => {
// if we were hinted that we should only search a specific package, find it and only search the owning tsconfig.json
if (params.hints && params.hints.dependeePackageName) {
return observableFromIterable(this.packageManager.packageJsonUris())
.filter(
uri =>
(JSON.parse(this.inMemoryFileSystem.getContent(uri)) as PackageJson).name ===
params.hints!.dependeePackageName
)
.take(1)
.mergeMap(uri => {
const config = this.projectManager.getParentConfiguration(uri)
if (!config) {
return observableFromIterable(this.projectManager.configurations())
}
return [config]
})
}
// else search all tsconfig.jsons
return observableFromIterable(this.projectManager.configurations())
})
)
.mergeMap((config: ProjectConfiguration) => {
config.ensureAllFiles(span)
const program = config.getProgram(span)
if (!program) {
return Observable.empty<never>()
}
return (
Observable.from(program.getSourceFiles())
// Ignore dependency files
.filter(source => !toUnixPath(source.fileName).includes('/node_modules/'))
.mergeMap(source =>
// Iterate AST of source file
observableFromIterable(walkMostAST(source))
// Filter Identifier Nodes
// TODO: include string-interpolated references
.filter((node): node is ts.Identifier => node.kind === ts.SyntaxKind.Identifier)
.mergeMap(node => {
try {
// Find definition for node
return Observable.from(
config
.getService()
.getDefinitionAtPosition(source.fileName, node.pos + 1) || []
)
.mergeMap(definition => {
const symbol = definitionInfoToSymbolDescriptor(definition, this.root)
// Check if SymbolDescriptor without PackageDescriptor matches