This repository has been archived by the owner on Dec 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 682
/
LspLanguageService.js
3002 lines (2766 loc) · 100 KB
/
LspLanguageService.js
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) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree.
*
* @flow
* @format
*/
import type {NuclideUri} from 'nuclide-commons/nuclideUri';
import type {DeadlineRequest} from 'nuclide-commons/promise';
import type {AdditionalLogFile} from '../../nuclide-logging/lib/rpc-types';
import type {
FileVersion,
FileOpenEvent,
FileCloseEvent,
FileEditEvent,
FileSaveEvent,
} from '../../nuclide-open-files-rpc/lib/rpc-types';
import type {TextEdit} from 'nuclide-commons-atom/text-edit';
import type {TypeHint} from '../../nuclide-type-hint/lib/rpc-types';
import type {CoverageResult} from '../../nuclide-type-coverage/lib/rpc-types';
import type {
DefinitionQueryResult,
FindReferencesReturn,
RenameReturn,
Outline,
OutlineTree,
CodeAction,
SignatureHelp,
} from 'atom-ide-ui';
import type {
AutocompleteRequest,
AutocompleteResult,
FileDiagnosticMap,
FileDiagnosticMessage,
FormatOptions,
SymbolResult,
Completion,
CodeLensData,
StatusData,
} from '../../nuclide-language-service/lib/LanguageService';
import type {
HostServices,
Progress,
} from '../../nuclide-language-service-rpc/lib/rpc-types';
import type {ConnectableObservable} from 'rxjs';
import type {
InitializeParams,
ClientCapabilities,
ServerCapabilities,
PublishDiagnosticsParams,
LogMessageParams,
ShowMessageParams,
ShowMessageRequestParams,
ShowStatusParams,
MessageActionItem,
ProgressParams,
ActionRequiredParams,
DidOpenTextDocumentParams,
DidSaveTextDocumentParams,
DidCloseTextDocumentParams,
DidChangeTextDocumentParams,
TextDocumentContentChangeEvent,
SymbolInformation,
UncoveredRange,
ApplyWorkspaceEditParams,
ApplyWorkspaceEditResponse,
Command,
RegistrationParams,
UnregistrationParams,
DidChangeWatchedFilesRegistrationOptions,
Registration,
FileSystemWatcher,
CompletionItem,
DocumentFormattingParams,
} from './protocol';
import {WatchmanClient} from 'nuclide-watchman-helpers';
import {runCommand, getOriginalEnvironment} from 'nuclide-commons/process';
import invariant from 'assert';
import nullthrows from 'nullthrows';
import {sleep, timeoutAfterDeadline} from 'nuclide-commons/promise';
import {stringifyError} from 'nuclide-commons/string';
import through from 'through';
import {fork, spawn} from 'nuclide-commons/process';
import nuclideUri from 'nuclide-commons/nuclideUri';
import {arrayCompact, collect} from 'nuclide-commons/collection';
import {compact} from 'nuclide-commons/observable';
import SafeStreamMessageReader from 'nuclide-commons/SafeStreamMessageReader';
import {track} from 'nuclide-analytics';
import {wordAtPositionFromBuffer} from 'nuclide-commons/range';
import {
FileCache,
FileVersionNotifier,
FileEventKind,
} from '../../nuclide-open-files-rpc';
import * as rpc from 'vscode-jsonrpc';
import * as convert from './convert';
import {Observable, Subject, BehaviorSubject} from 'rxjs';
import UniversalDisposable from 'nuclide-commons/UniversalDisposable';
import {Point, Range as atom$Range} from 'simple-text-buffer';
import {MemoryLogger, SnapshotLogger} from '../../commons-node/memoryLogger';
import {
ensureInvalidations,
forkHostServices,
} from '../../nuclide-language-service-rpc';
import {mapAtomLanguageIdToVsCode} from './languageIdMap';
import {
getLanguageSpecificCommand,
middleware_handleDiagnostics,
} from './languageExtensions';
import {LspConnection} from './LspConnection';
import {
ErrorCodes,
TextDocumentSyncKind,
MessageType as LspMessageType,
WatchKind,
FileChangeType,
InsertTextFormat,
TextDocumentSaveReason,
} from './protocol';
const WORD_REGEX = /\w+/gi;
type State =
| 'Initial'
| 'Starting'
| 'StartFailed'
| 'Running'
| 'Stopping'
| 'Stopped';
export type LspPreferences = {
// Most LSP servers don't provide an API specifically for outlines, so we have to
// fall back to textDocument/documentSymbols which provides a list of elements and
// their range+containerName. If the LSP server happens to provide the range of the
// entire symbol construct then we'll use that to reconstruct the tree, also
// lighting up Nuclide's "hightlight-outline" and "breadcrumbs" features. But
// if it only provides the range of the element identifier, then we'll have to
// fall back to containerName to reconstruct the tree, losing out on those two features.
// Default is 'range'
reconstructOutlineStrategy?: 'range' | 'containerName',
// See https://microsoft.github.io/language-server-protocol/specification#textDocument_formatting
additionalFormattingOptions?: Map<string, any>,
// Normally Nuclide will claim to the LSP server that it supports snippets,
// even though its support is incomplete (in cases of TextEdits, and multiple
// cursors). You can set this field to false to make Nuclide no longer make
// that claim. (default true).
snippetSupport?: boolean,
};
// Marshals messages from Nuclide's LanguageService
// to VS Code's Language Server Protocol
export class LspLanguageService {
// These fields are provided upon construction
_projectRoot: string;
_fileCache: FileCache; // tracks which fileversions we've received from Nuclide client
_masterHost: HostServices; // this is the one we're given
_host: HostServices; // this is created per-connection
_lspFileVersionNotifier: FileVersionNotifier; // tracks which fileversions we've sent to LSP
_fileEventSubscription: rxjs$ISubscription;
_languageServerName: string;
_command: string;
_args: Array<string>;
_spawnOptions: Object; // supplies the options for spawning a process
_spawnWithFork: boolean;
_fileExtensions: Array<string>;
_logger: MemoryLogger;
_snapshotter: SnapshotLogger;
_underlyingLogger: log4js$Logger;
_host: HostServices;
_fileCache: FileCache; // tracks which fileversions we've received from Nuclide client
_initializationOptions: Object;
_additionalLogFilesRetentionPeriod: number;
_useOriginalEnvironment: boolean;
_lspPreferences: LspPreferences;
// These fields reflect our own state.
// (Most should be nullable types, but it's not worth the bother.)
_state: BehaviorSubject<State> = new BehaviorSubject('Initial');
_stateIndicator: UniversalDisposable = new UniversalDisposable();
_progressIndicators: Map<string | number, Promise<Progress>> = new Map();
_actionRequiredIndicators: Map<
string | number,
UniversalDisposable,
> = new Map();
_recentRestarts: Array<number> = [];
_diagnosticUpdates: BehaviorSubject<
Observable<PublishDiagnosticsParams>,
> = new BehaviorSubject(Observable.empty());
_statusClickPromise: Promise<?string> = Promise.resolve(null);
_statusClickPromiseResolver: (?string) => void = _ => {};
_statusCounter: number = 0;
_statusUpdates: BehaviorSubject<StatusData> = new BehaviorSubject({
kind: 'null',
});
_supportsSymbolSearch: BehaviorSubject<?boolean> = new BehaviorSubject(null);
// Fields which become live inside start(), when we spawn the LSP process.
// Disposing of the _lspConnection will dispose of all of them.
_childOut: {stdout: ?string, stderr: string} = {stdout: '', stderr: ''};
_lspConnection: LspConnection; // is really "?LspConnection"
_childPid: ?number; // child process id
// Fields which become live after we receive an initializeResponse:
_serverCapabilities: ServerCapabilities;
_derivedServerCapabilities: DerivedServerCapabilities;
_lspFileVersionNotifier: FileVersionNotifier; // tracks which fileversions we've sent to LSP
// Map from registered capability id's to disposable for unregistering
_registeredCapabilities: Map<string, Promise<IDisposable>> = new Map();
// Whenever we trigger a new request, we cancel the outstanding request, so
// only one request of these types would be active at a time. Note that the
// language server is free to ignore any cancellation request, so we could
// still potentially have multiple outstanding requests of the same type.
_hoverCancellation: rpc.CancellationTokenSource = new rpc.CancellationTokenSource();
_highlightCancellation: rpc.CancellationTokenSource = new rpc.CancellationTokenSource();
_definitionCancellation: rpc.CancellationTokenSource = new rpc.CancellationTokenSource();
_autocompleteCancellation: rpc.CancellationTokenSource = new rpc.CancellationTokenSource();
_outlineCancellation: rpc.CancellationTokenSource = new rpc.CancellationTokenSource();
_disposables: UniversalDisposable = new UniversalDisposable();
constructor(
logger: log4js$Logger,
fileCache: FileCache,
host: HostServices,
languageServerName: string,
command: string,
args: Array<string>,
spawnOptions: Object = {},
spawnWithFork: boolean = false,
projectRoot: string,
fileExtensions: Array<string>,
initializationOptions: Object,
additionalLogFilesRetentionPeriod: number,
useOriginalEnvironment?: boolean = false,
lspPreferences?: LspPreferences = {},
) {
this._snapshotter = new SnapshotLogger(additionalLogFilesRetentionPeriod);
this._logger = new MemoryLogger(logger, additionalLogFilesRetentionPeriod);
this._underlyingLogger = logger;
this._fileCache = fileCache;
this._masterHost = host;
this._host = host;
this._projectRoot = projectRoot;
this._languageServerName = languageServerName;
this._command = command;
this._args = args;
this._spawnOptions = spawnOptions;
this._spawnWithFork = spawnWithFork;
this._fileExtensions = fileExtensions;
this._initializationOptions = initializationOptions;
this._additionalLogFilesRetentionPeriod = additionalLogFilesRetentionPeriod;
this._useOriginalEnvironment = useOriginalEnvironment;
this._lspPreferences = lspPreferences;
}
dispose(): void {
this._stop()
.catch(_ => {})
.then(_ => {
this._statusUpdates.complete();
this._masterHost.dispose();
this._snapshotter.dispose();
this._logger.dispose();
this._disposables.dispose();
});
}
_getState(): State {
return this._state.getValue();
}
_setState(
state: State,
actionRequiredDialogMessage?: string,
existingDialogToDismiss?: rxjs$ISubscription,
): void {
this._logger.trace(`State ${this._getState()} -> ${state}`);
this._state.next(state);
this._stateIndicator.dispose();
const nextDisposable = new UniversalDisposable();
this._stateIndicator = nextDisposable;
if (state === 'Initial' || state === 'Running') {
// No user indication needed for either state.
// In the case of 'Initial', that's because the only times we get
// in this state is when we're about to call start().
} else if (state === 'Starting' || state === 'Stopping') {
// Show a progress spinner
const tooltip =
state === 'Starting'
? `Starting ${this._languageServerName} language service...`
: `Stopping ${this._languageServerName} language service...`;
this._masterHost.showProgress(tooltip).then(progress => {
if (nextDisposable.disposed) {
progress.dispose();
} else {
nextDisposable.add(progress);
}
});
} else if (state === 'StartFailed' || state === 'Stopped') {
// StartFailed is when we failed to spawn the language server
// Stopped is when the JsonRPC transport has been erroring,
// or when the connection has been closed too many times and we give up.
const tooltip =
state === 'StartFailed'
? `Failed to start ${this._languageServerName} - click to retry.`
: `Crash in ${this._languageServerName} - click to restart.`;
const defaultMessage =
state === 'StartFailed'
? `Failed to start ${this._languageServerName} language service.`
: `Language service ${this._languageServerName} has crashed.`;
const button = state === 'StartFailed' ? 'Retry' : 'Restart';
// flowlint-next-line sketchy-null-string:off
const message = actionRequiredDialogMessage || defaultMessage;
const subscription = this._masterHost
.showActionRequired(tooltip, {clickable: true})
.refCount()
.switchMap(_ => {
if (existingDialogToDismiss != null) {
existingDialogToDismiss.unsubscribe();
}
return this._masterHost
.dialogRequest('error', message, [button], 'Close')
.refCount();
})
.subscribe(dialogResponse => {
if (dialogResponse !== button) {
return;
}
// Note that if a new state had come along, that would have
// unsubscribed nextDisposable, which would (1) dismiss the action-
// required indicator, (2) dismiss the dialogRequest. The fact that
// we're here now means that this has not happened, i.e. a new state
// has not come along.
this._masterHost.consoleNotification(
this._languageServerName,
'info',
`Restarting ${this._languageServerName}`,
);
this._setState('Initial');
this.start();
});
nextDisposable.add(subscription);
} else {
(state: empty);
invariant(false, 'unreachable state');
}
}
_showStatus(status: StatusData): Promise<?string> {
// If someone had previously called 'await button = _showStatus(.)' to find
// out which button the user clicked, but we end up switching state before
// the user clicked a button, then we'll cause that prior button promise
// to be resolved as 'null'
this._statusClickPromiseResolver(null);
this._statusClickPromise = new Promise((resolve, reject) => {
this._statusClickPromiseResolver = resolve;
});
// red and yellow status updates are accompanied by an id to correlate statusClicks
this._statusCounter++;
const status2 =
status.kind !== 'red' && status.kind !== 'yellow'
? status
: {...status, id: String(this._statusCounter)};
this._logger.trace(`_setStatus status: ${JSON.stringify(status2)}`);
// $FlowIgnore: flow has trouble disambiguating the 'kind: red' and 'kind: yellow' variants
this._statusUpdates.next(status2);
return this._statusClickPromise;
}
async clickStatus(
fileVersion: FileVersion,
id: string,
button: string,
): Promise<void> {
if (id === String(this._statusCounter)) {
this._statusClickPromiseResolver(button);
} else {
// The user might have clicked a button after we switched to a new status,
// and the messages crossed in flight. In this case ignore the button
}
}
observeStatus(fileVersion: FileVersion): ConnectableObservable<StatusData> {
return this._statusUpdates.asObservable().publish();
}
async start(): Promise<void> {
invariant(this._getState() === 'Initial');
this._setState('Starting');
const startTimeMs = Date.now();
let command;
try {
if (this._command == null) {
throw new Error('No command provided for launching language server');
// if we try to spawn an empty command, node itself throws a "bad
// type" error, which is jolly confusing. So we catch it ourselves.
} else if (this._command.startsWith('{')) {
command = await getLanguageSpecificCommand(
this._projectRoot,
JSON.parse(this._command),
);
} else {
command = this._command;
}
} catch (e) {
this._logLspException(e);
track('lsp-start', {
name: this._languageServerName,
status: 'getCommand failed',
command: this._command,
message: e.message,
stack: e.stack,
timeTakenMs: Date.now() - startTimeMs,
});
const message =
`Couldn't start ${this._languageServerName} server` +
` - ${this._errorString(e)}`;
const dialog = this._masterHost
.dialogNotification('error', message)
.refCount()
.subscribe();
this._setState('StartFailed', message, dialog);
return;
}
const spawnCommandForLogs = `${command} ${this._args.join(' ')}`;
try {
const perConnectionDisposables = new UniversalDisposable();
// The various resources+subscriptions associated with a LspConnection
// are stored in here. When you call _lspConnection.dispose(), it
// disposes of all of them (via the above perConnectionDisposables),
// and also sets _lspConnection and other per-connection fields to null
// so that any attempt to use them will throw an exception.
// Each connection gets its own 'host' object, as an easy way to
// get rid of all outstanding busy-signals and notifications and
// dialogs from that connection.
this._host = await forkHostServices(
this._masterHost,
this._underlyingLogger,
);
perConnectionDisposables.add(() => {
this._host.dispose();
this._host = this._masterHost;
});
// Error reporting? We'll be catching+reporting errors at each layer:
// 1. operating system support for launch the process itself
// 2. stdout/stderr sitting on top of that
// 3. jsonrpc on top of that
// 4. lsp on top of that
let childProcess;
try {
this._logger.info(`Spawn: ${spawnCommandForLogs}`);
const lspSpawnOptions = {
cwd: this._projectRoot,
// Forked processes don't pipe stdio by default.
stdio: this._spawnWithFork
? ['pipe', 'pipe', 'pipe', 'ipc']
: undefined,
...this._spawnOptions,
killTreeWhenDone: true,
};
if (this._useOriginalEnvironment) {
// NodeJS is the one thing where we need to make sure to use Nuclide's
// version.
const originalEnvironment = await getOriginalEnvironment();
const nodePath = nuclideUri.dirname(
await runCommand('which', ['node']).toPromise(),
);
if (originalEnvironment.PATH) {
originalEnvironment.PATH = `${nodePath}:${
originalEnvironment.PATH
}`;
} else {
this._logger.error('No path found in original environment.');
originalEnvironment.PATH = nodePath;
}
// If they specify both useOriginalEnvironment and an env key in their
// spawn options, merge them with the explicitly provided keys taking
// precedence.
lspSpawnOptions.env = {
...originalEnvironment,
...lspSpawnOptions.env,
};
} else if (lspSpawnOptions.env) {
lspSpawnOptions.env = {
...process.env,
...lspSpawnOptions.env,
};
}
const childProcessStream = this._spawnWithFork
? fork(command, this._args, lspSpawnOptions).publish()
: spawn(command, this._args, lspSpawnOptions).publish();
// disposing of the stream will kill the process, if it still exists
const processPromise = childProcessStream.take(1).toPromise();
perConnectionDisposables.add(childProcessStream.connect());
// if spawn failed to launch it, this await will throw.
childProcess = await processPromise;
this._childPid = childProcess.pid;
} catch (e) {
this._logLspException(e);
track('lsp-start', {
name: this._languageServerName,
status: 'spawn failed',
spawn: spawnCommandForLogs,
message: e.message,
stack: e.stack,
timeTakenMs: Date.now() - startTimeMs,
});
const message =
`Couldn't start ${this._languageServerName} server` +
` - ${this._errorString(e, command)}`;
const dialog = this._masterHost
.dialogNotification('error', message)
.refCount()
.subscribe();
this._setState('StartFailed', message, dialog);
return;
}
// The JsonRPC layer doesn't report what happened on stderr/stdout in
// case of an error, so we'll pick it up directly. CARE! Node has
// three means of consuming a stream, and it will crash if you mix them.
// Our JsonRPC library uses the .pipe() means, so we have to too.
// Semantics: a null value for stdout means "don't collect further output
// because we've established that the connection is JsonRPC".
this._childOut = {stdout: '', stderr: ''};
const accumulate = (streamName: 'stdout' | 'stderr', data: string) => {
if (
this._childOut[streamName] != null &&
this._childOut[streamName].length < 600
) {
const s = (this._childOut[streamName] + data).substr(0, 600);
this._childOut[streamName] = s;
}
};
childProcess.stdout.pipe(through(data => accumulate('stdout', data)));
if (childProcess.stderr != null) {
childProcess.stderr.pipe(through(data => accumulate('stderr', data)));
}
const jsonRpcConnection: rpc.MessageConnection = rpc.createMessageConnection(
new SafeStreamMessageReader(childProcess.stdout),
new rpc.StreamMessageWriter(childProcess.stdin),
new JsonRpcLogger(this._logger),
);
jsonRpcConnection.trace(
rpc.Trace.Verbose,
new JsonRpcTraceLogger(this._logger),
);
// We assign _lspConnection and wire up the handlers before calling
// initialize, because any of these events might fire before initialize
// has even returned.
this._lspConnection = new LspConnection(
jsonRpcConnection,
this._languageServerName,
);
this._lspConnection.onDispose(
perConnectionDisposables.dispose.bind(perConnectionDisposables),
);
perConnectionDisposables.add(() => {
this._lspConnection = ((null: any): LspConnection);
// cheating here: we're saying "no thank you" to compile-time warnings
// that _lspConnection might be invalid (since they're too burdensome)
// but "yes please" to runtime exceptions.
});
const perConnectionUpdates = new Subject();
perConnectionDisposables.add(
perConnectionUpdates.complete.bind(perConnectionUpdates),
);
jsonRpcConnection.onError(this._handleError.bind(this));
jsonRpcConnection.onClose(this._handleClose.bind(this));
// Following handlers all set _childOut.stdout to null, to indicate
// that we've established that the output is JsonRPC, and so any raw
// text content in stdout should NOT be used directly in error messages.
this._lspConnection.onTelemetryNotification(params => {
this._childOut.stdout = null;
this._handleTelemetryNotification(params);
});
this._lspConnection.onLogMessageNotification(params => {
this._childOut.stdout = null;
this._handleLogMessageNotification(params);
});
this._lspConnection.onShowMessageNotification(params => {
this._childOut.stdout = null;
this._handleShowMessageNotification(params);
});
this._lspConnection.onShowMessageRequest(async (params, cancel) => {
this._childOut.stdout = null;
return this._handleShowMessageRequest(params, cancel);
});
this._lspConnection.onShowStatusRequest(async (params, cancel) => {
this._childOut.stdout = null;
return this._handleStatusRequest(params, cancel);
});
this._lspConnection.onProgressNotification(params => {
this._childOut.stdout = null;
return this._handleProgressNotification(params);
});
this._lspConnection.onActionRequiredNotification(params => {
this._childOut.stdout = null;
return this._handleActionRequiredNotification(params);
});
this._lspConnection.onApplyEditRequest(async (params, cancel) => {
this._childOut.stdout = null;
return this._handleApplyEditRequest(params, cancel);
});
this._lspConnection.onDiagnosticsNotification(params => {
this._childOut.stdout = null;
middleware_handleDiagnostics(
params,
this._languageServerName,
this._host,
this._showStatus.bind(this),
);
perConnectionUpdates.next(params);
});
this._lspConnection.onRegisterCapabilityRequest(params => {
this._childOut.stdout = null;
this._handleRegisterCapability(params);
});
this._lspConnection.onUnregisterCapabilityRequest(params => {
this._childOut.stdout = null;
this._handleUnregisterCapability(params);
});
await new Promise(process.nextTick);
this._diagnosticUpdates.next(perConnectionUpdates);
// CARE! to avoid a race, we guarantee that we've yielded back
// to our caller before firing this next() and before sending any
// diagnostic updates down it. That lets our caller subscribe in time.
// Why this delicate? Because we don't want to buffer diagnostics, and we
// don't want to lose any of them.
// CARE! to avoid a different race, we await for the next tick only after
// signing up all our handlers.
this._logger.info('Establishing JsonRPC connection...');
jsonRpcConnection.listen();
const capabilities: ClientCapabilities = {
workspace: {
applyEdit: true,
workspaceEdit: {
documentChanges: true,
},
didChangeConfiguration: {
dynamicRegistration: false,
},
didChangeWatchedFiles: {
dynamicRegistration: true,
},
symbol: {
dynamicRegistration: false,
},
executeCommand: {
dynamicRegistration: false,
},
},
textDocument: {
synchronization: {
dynamicRegistration: false,
willSave: false,
willSaveWaitUntil: true,
didSave: true,
},
completion: {
dynamicRegistration: false,
completionItem: {
// True if LspPreferences.snippetSupport is not defined or
// it's set to true.
snippetSupport:
this._lspPreferences.snippetSupport == null ||
this._lspPreferences.snippetSupport,
},
},
hover: {
dynamicRegistration: false,
},
signatureHelp: {
dynamicRegistration: false,
},
references: {
dynamicRegistration: false,
},
documentHighlight: {
dynamicRegistration: false,
},
documentSymbol: {
dynamicRegistration: false,
},
formatting: {
dynamicRegistration: false,
},
rangeFormatting: {
dynamicRegistration: false,
},
onTypeFormatting: {
dynamicRegistration: false,
},
definition: {
dynamicRegistration: false,
},
codeAction: {
dynamicRegistration: false,
},
codeLens: {
dynamicRegistration: false,
},
documentLink: {
dynamicRegistration: false,
},
rename: {
dynamicRegistration: false,
},
},
window: {
status: {
dynamicRegistration: false,
},
progress: {
dynamicRegistration: false,
},
actionRequired: {
dynamicRegistration: false,
},
},
};
const params: InitializeParams = {
processId: process.pid,
rootPath: this._projectRoot,
rootUri: convert.localPath_lspUri(this._projectRoot),
capabilities,
initializationOptions: this._initializationOptions,
trace: this._underlyingLogger.isLevelEnabled('TRACE')
? 'verbose'
: 'off',
};
// We'll keep sending initialize requests until it either succeeds
// or the user says to stop retrying. This while loop will be potentially
// long-running since in the case of failure it awaits for the user to
// click a dialog button.
let userRetryCount = 0;
let initializeTimeTakenMs = 0;
while (true) {
let initializeResponse;
try {
this._logger.trace('Lsp.Initialize');
userRetryCount++;
const initializeStartTimeMs = Date.now();
// eslint-disable-next-line no-await-in-loop
initializeResponse = await this._lspConnection.initialize(params);
initializeTimeTakenMs = Date.now() - initializeStartTimeMs;
this._logger.trace('Lsp.Initialize.success');
// We might receive an onError or onClose event at this time too.
// Those are handled by _handleError and _handleClose methods.
// If those happen, then the response to initialize will never arrive,
// so the above await will block until we finally dispose of the
// connection.
} catch (e) {
this._logger.trace('Lsp.Initialize.error');
this._logLspException(e);
track('lsp-start', {
name: this._languageServerName,
status: 'initialize failed',
spawn: spawnCommandForLogs,
message: e.message,
stack: e.stack,
timeTakenMs: Date.now() - startTimeMs,
userRetryCount,
});
// CARE! Inside any exception handler of an rpc request,
// the lspConnection might already have been torn down.
this._childOut = {stdout: '', stderr: ''};
const message = `Couldn't initialize ${
this._languageServerName
} server`;
const longMessage = `${message} - ${this._errorString(e)}`;
// LSP has the notion that only some failures-to-start should
// offer a retry button; if the user clicks it then we send a second
// initialize request over the existing connection.
// Failing that, we have the fallback that for all crashes/failures
// we always offer a retry button; clicking on it causes a complete
// re-initialize from the start.
const offerRetry = e.data != null && Boolean(e.data.retry);
if (!offerRetry) {
const dialog = this._masterHost
.dialogNotification('error', longMessage)
.refCount()
.subscribe();
this._setState('StartFailed', message, dialog);
if (this._lspConnection != null) {
this._lspConnection.dispose();
}
return;
}
// eslint-disable-next-line no-await-in-loop
const button = await this._host
.dialogRequest('error', message, ['Retry'], 'Close')
.refCount()
.toPromise();
if (button === 'Retry') {
this._logger.trace('Lsp.Initialize.retry');
this._host.consoleNotification(
this._languageServerName,
'info',
'Retrying initialize',
);
if (this._lspConnection != null) {
this._logger.trace('Lsp.Initialize.retrying');
continue;
// Retry will re-use the same this._lspConnection,
// assuming it hasn't been torn down for whatever reason.
}
}
this._setState('StartFailed');
if (this._lspConnection != null) {
this._lspConnection.dispose();
}
return;
}
// If the process wrote to stderr but succeeded to initialize, we'd
// also like to log that. It was probably informational not error.
if (this._childOut.stderr !== '') {
this._host.consoleNotification(
this._languageServerName,
'info',
this._childOut.stderr,
);
}
// We'll reset _childOut now: stdout will become null because we've
// established that the process speaks JsonRPC, and so will deliver
// everything in JsonRPC messages, and so we never want to report
// errors with the raw text of stdout; stderr will become empty because
// we've already reported everything so far.
this._childOut = {stdout: null, stderr: ''};
this._serverCapabilities = initializeResponse.capabilities;
this._derivedServerCapabilities = new DerivedServerCapabilities(
this._serverCapabilities,
this._logger,
);
perConnectionDisposables.add(() => {
this._serverCapabilities = ((null: any): ServerCapabilities);
this._derivedServerCapabilities = ((null: any): DerivedServerCapabilities);
});
this._logger.info('Lsp state=Running!');
this._setState('Running');
// At this point we're good to call into LSP.
// CARE! Don't try to hook up file-events until after we're already
// good to send them to LSP.
this._lspFileVersionNotifier = new FileVersionNotifier();
perConnectionDisposables.add(this._subscribeToFileEvents(), () => {
this._lspFileVersionNotifier = ((null: any): FileVersionNotifier);
});
track('lsp-start', {
name: this._languageServerName,
status: 'ok',
spawn: spawnCommandForLogs,
timeTakenMs: Date.now() - startTimeMs,
initializeTimeTakenMs,
});
return;
}
} catch (e) {
// By this stage we've already handled+recovered from exceptions
// gracefully around every external operation - spawning, speaking lsp
// over jsonrpc, sending the initialize message. If an exception fell
// through then it's an internal logic error.
// Don't know how to recover.
this._logger.error(`Lsp.start - unexpected error ${e}`);
track('lsp-start', {
name: this._languageServerName,
status: 'start failed',
spawn: spawnCommandForLogs,
message: e.message,
stack: e.stack,
timeTakenMs: Date.now() - startTimeMs,
});
throw e;
} finally {
this._supportsSymbolSearch.next(
this._serverCapabilities != null &&
Boolean(this._serverCapabilities.workspaceSymbolProvider),
);
}
}
_subscribeToFileEvents(): rxjs$Subscription {
// This code's goal is to keep the LSP process aware of the current status of opened
// files. Challenge: LSP has no insight into fileversion: it relies wholly upon us
// to give a correct sequence of versions in didChange events and can't even verify them.
//
// The _lspFileVersionNotifier tracks which fileversion we've sent downstream to LSP so far.
//
// The _fileCache tracks our upstream connection to the Nuclide editor, and from that
// synthesizes a sequential consistent stream of Open/Edit/Close/Save events.
// If the (potentially flakey) connection temporarily goes down, the _fileCache
// recovers, resyncs, and synthesizes for us an appropriate whole-document Edit event.
// Therefore, it's okay for us to simply send _fileCache's sequential stream of edits
// directly on to the LSP server.
//
// Note: if the LSP encounters an internal error responding to one of these notifications,
// then it will be out of sync. JsonRPC doesn't allow for notifications to have
// responses. So all we can do is trust the LSP server to terminate itself it
// it encounters a problem.
return (
this._fileCache
.observeFileEvents()
// The "observeFileEvents" will first send an 'open' event for every
// already-open file, and after that it will give live updates.
.filter(fileEvent => {
const fileExtension = nuclideUri.extname(
fileEvent.fileVersion.filePath,
);
return (
this._fileExtensions.indexOf(fileExtension) !== -1 &&
this._isFileInProject(fileEvent.fileVersion.filePath)
);
})
.subscribe(fileEvent => {
invariant(fileEvent.fileVersion.notifier === this._fileCache);
// This invariant just self-documents that _fileCache is asked on observe file
// events about fileVersions that themselves point directly back to the _fileCache.
// (It's a convenience so that folks can pass around just a fileVersion on its own.)
// TODO: if LSP responds with error to any of the file events, then we'll become
// out of sync, and we must stop. (potentially restart).
switch (fileEvent.kind) {
case FileEventKind.OPEN:
this._fileOpen(fileEvent);
break;
case FileEventKind.CLOSE:
this._fileClose(fileEvent);
break;
case FileEventKind.EDIT:
this._fileEdit(fileEvent);
break;
case FileEventKind.SAVE:
this._fileSave(fileEvent);
break;
default:
(fileEvent.kind: empty);
this._logger.error(
'Unrecognized fileEvent ' + JSON.stringify(fileEvent),
);
}
this._lspFileVersionNotifier.onEvent(fileEvent);
})
);
}
async _stop(): Promise<void> {
this._logger.trace('Lsp._stop');
if (this._getState() === 'Stopping' || this._getState() === 'Stopped') {
return;
}
if (this._lspConnection == null) {
this._setState('Stopped');
return;
}