forked from eclipse-lsp4e/lsp4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLanguageServerWrapper.java
More file actions
1793 lines (1631 loc) · 67.4 KB
/
LanguageServerWrapper.java
File metadata and controls
1793 lines (1631 loc) · 67.4 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) 2016, 2023 Red Hat Inc. and others.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Mickael Istria (Red Hat Inc.) - initial implementation
* Miro Spoenemann (TypeFox) - extracted LanguageClientImpl
* Jan Koehnlein (TypeFox) - bug 521744
* Martin Lippert (Pivotal, Inc.) - bug 531030, 527902, 534637
* Kris De Volder (Pivotal, Inc.) - dynamic command registration
* Tamas Miklossy (itemis) - bug 571162
* Rubén Porras Campo (Avaloq Evolution AG) - documentAboutToBeSaved implementation
* Sebastian Thomschke (Vegard IT GmbH) - textDocument/completion, workspace/didChangeWatchedFiles support; bug fixes
*******************************************************************************/
package org.eclipse.lsp4e;
import static org.eclipse.lsp4e.internal.NullSafetyHelper.castNonNull;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.IFileBuffer;
import org.eclipse.core.filebuffers.IFileBufferListener;
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.filebuffers.LocationKind;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.Adapters;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.IDocument;
import org.eclipse.lsp4e.LanguageServersRegistry.LanguageServerDefinition;
import org.eclipse.lsp4e.client.DefaultLanguageClient;
import org.eclipse.lsp4e.internal.ArrayUtil;
import org.eclipse.lsp4e.internal.CancellationUtil;
import org.eclipse.lsp4e.internal.FileBufferListenerAdapter;
import org.eclipse.lsp4e.internal.JsonUtil;
import org.eclipse.lsp4e.internal.SupportedFeatures;
import org.eclipse.lsp4e.internal.files.FileSystemWatcherManager;
import org.eclipse.lsp4e.server.StreamConnectionProvider;
import org.eclipse.lsp4e.ui.Messages;
import org.eclipse.lsp4j.ClientCapabilities;
import org.eclipse.lsp4j.ClientInfo;
import org.eclipse.lsp4j.CodeActionOptions;
import org.eclipse.lsp4j.CompletionOptions;
import org.eclipse.lsp4j.DidChangeWatchedFilesParams;
import org.eclipse.lsp4j.DidChangeWatchedFilesRegistrationOptions;
import org.eclipse.lsp4j.DidChangeWorkspaceFoldersParams;
import org.eclipse.lsp4j.DidSaveTextDocumentParams;
import org.eclipse.lsp4j.DocumentFormattingOptions;
import org.eclipse.lsp4j.DocumentOnTypeFormattingOptions;
import org.eclipse.lsp4j.DocumentRangeFormattingOptions;
import org.eclipse.lsp4j.ExecuteCommandOptions;
import org.eclipse.lsp4j.FileChangeType;
import org.eclipse.lsp4j.FileEvent;
import org.eclipse.lsp4j.InitializeParams;
import org.eclipse.lsp4j.InitializeResult;
import org.eclipse.lsp4j.InitializedParams;
import org.eclipse.lsp4j.Registration;
import org.eclipse.lsp4j.RegistrationParams;
import org.eclipse.lsp4j.SelectionRangeRegistrationOptions;
import org.eclipse.lsp4j.ServerCapabilities;
import org.eclipse.lsp4j.ServerInfo;
import org.eclipse.lsp4j.TextDocumentSyncKind;
import org.eclipse.lsp4j.TextDocumentSyncOptions;
import org.eclipse.lsp4j.TypeHierarchyRegistrationOptions;
import org.eclipse.lsp4j.UnregistrationParams;
import org.eclipse.lsp4j.WatchKind;
import org.eclipse.lsp4j.WindowClientCapabilities;
import org.eclipse.lsp4j.WorkspaceFolder;
import org.eclipse.lsp4j.WorkspaceFoldersChangeEvent;
import org.eclipse.lsp4j.WorkspaceFoldersOptions;
import org.eclipse.lsp4j.WorkspaceServerCapabilities;
import org.eclipse.lsp4j.WorkspaceSymbolOptions;
import org.eclipse.lsp4j.jsonrpc.Launcher;
import org.eclipse.lsp4j.jsonrpc.MessageConsumer;
import org.eclipse.lsp4j.jsonrpc.ResponseErrorException;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.jsonrpc.messages.Message;
import org.eclipse.lsp4j.jsonrpc.messages.ResponseErrorCode;
import org.eclipse.lsp4j.jsonrpc.messages.ResponseMessage;
import org.eclipse.lsp4j.services.LanguageServer;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Display;
import com.google.common.base.Functions;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.JsonObject;
public class LanguageServerWrapper {
private final IFileBufferListener fileBufferListener = new LSFileBufferListener();
private final class LSFileBufferListener extends FileBufferListenerAdapter {
@Override
public void bufferDisposed(IFileBuffer buffer) {
final var uri = LSPEclipseUtils.toUri(buffer);
if (uri != null) {
disconnect(uri);
}
}
@Override
public void stateChanging(IFileBuffer buffer) {
if (buffer.isDirty()) {
DocumentContentSynchronizer documentListener = connectedDocuments.get(LSPEclipseUtils.toUri(buffer));
if (documentListener != null) {
documentListener.documentAboutToBeSaved();
}
}
}
@Override
public void dirtyStateChanged(IFileBuffer buffer, boolean isDirty) {
if (isDirty) {
return;
}
DocumentContentSynchronizer documentListener = connectedDocuments.get(LSPEclipseUtils.toUri(buffer));
if (documentListener != null) {
documentListener.documentSaved(buffer);
}
}
@Override
public void underlyingFileMoved(IFileBuffer buffer, IPath newPath) {
URI oldUri = LSPEclipseUtils.toUri(buffer);
if (oldUri == null) {
return;
}
DocumentContentSynchronizer documentListener = connectedDocuments.get(oldUri);
if (documentListener == null) {
return;
}
LSPEclipseUtils.disconnectFromFileBuffer(buffer.getLocation());
/*
* This below is not working (will leak file buffer), because the client that connected the document
* via old URI can't always know that the file has moved and so it may try to use old URI.
* Better is to let the client act on bufferDisposed() event above and manually connect to the document if needed.
*
IFile newFile = ResourcesPlugin.getWorkspace().getRoot().getFile(newPath);
URI newUri = LSPEclipseUtils.toUri(newFile);
if (newUri == null) {
return;
}
if (!connectedDocuments.containsKey(newUri)) {
try {
bufferManager.connect(newPath, LocationKind.IFILE, new NullProgressMonitor());
connectedDocuments.put(newUri, documentListener);
} catch (CoreException e) {
LanguageServerPlugin.logError(e);
}
}
*/
}
@Override
public void underlyingFileDeleted(IFileBuffer buffer) {
URI oldUri = LSPEclipseUtils.toUri(buffer);
if (oldUri == null) {
return;
}
if (!isConnectedTo(oldUri)) {
return;
}
// We need full path from buffer because file is deleted and disconnectTextFileBuffer(URI) will not work
LSPEclipseUtils.disconnectFromFileBuffer(buffer.getLocation());
disconnect(oldUri);
}
}
private static class LanguageServerContext {
final AtomicBoolean cancelled = new AtomicBoolean(false);
@Nullable Future<?> launcherFuture;
@Nullable StreamConnectionProvider lspStreamProvider;
@Nullable LanguageServer languageServer;
synchronized void close() {
if (languageServer != null) {
CompletableFuture<Object> shutdown = languageServer.shutdown();
try {
shutdown.get(5, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (TimeoutException ex) {
LanguageServerPlugin.logWarning("The server did not stop after 5 seconds"); //$NON-NLS-1$
} catch (Exception ex) {
LanguageServerPlugin.logError(ex.getClass().getSimpleName() + " occurred during shutdown of " //$NON-NLS-1$
+ languageServer, ex);
}
}
if (launcherFuture != null) {
launcherFuture.cancel(true);
}
if (languageServer != null) {
languageServer.exit();
}
if (lspStreamProvider != null) {
lspStreamProvider.stop();
}
}
}
public final LanguageServerDefinition serverDefinition;
public final @Nullable IProject initialProject;
protected Map<URI, DocumentContentSynchronizer> connectedDocuments;
protected final @Nullable IPath initialPath;
protected final InitializeParams initParams = new InitializeParams();
private @Nullable CompletableFuture<@Nullable Void> initializeFuture;
private volatile @Nullable InitializeResult initializeResult;
private volatile @Nullable ServerCapabilities serverCapabilities;
private volatile @Nullable ServerInfo serverInfo;
private final AtomicReference<@Nullable IProgressMonitor> initializeFutureMonitorRef = new AtomicReference<>();
private final int initializeFutureNumberOfStages = 7;
private @Nullable DefaultLanguageClient languageClient;
private final Timer timer = new Timer("Stop Language Server Task Processor"); //$NON-NLS-1$
private @Nullable TimerTask stopTimerTask;
private final ExecutorService dispatcher;
private final ExecutorService listener;
private final ExecutorService cleaner;
private final ExecutorService errorProcessor;
private LanguageServerContext context = new LanguageServerContext();
/**
* Map containing unregistration handlers for dynamic capability registrations.
*/
private final Map<String, Runnable> dynamicRegistrations = new HashMap<>();
private boolean initiallySupportsWorkspaceFolders = false;
private final IResourceChangeListener workspaceFolderUpdater = new WorkspaceFolderListener();
private final FileSystemWatcherManager fileSystemWatcherManager;
private final WatchedFilesListener watchedFilesListener = new WatchedFilesListener();
/* Backwards compatible constructor */
public LanguageServerWrapper(IProject project, LanguageServerDefinition serverDefinition) {
this(project, serverDefinition, null);
}
public LanguageServerWrapper(LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) {
this(null, serverDefinition, initialPath);
}
/** Unified private constructor to set sensible defaults in all cases */
private LanguageServerWrapper(@Nullable IProject project, LanguageServerDefinition serverDefinition,
@Nullable IPath initialPath) {
this.initialProject = project;
this.initialPath = initialPath;
this.serverDefinition = serverDefinition;
this.connectedDocuments = new HashMap<>();
String projectName = (project != null && !serverDefinition.isSingleton) ? ("@" + project.getName()) : ""; //$NON-NLS-1$//$NON-NLS-2$
final var formatPrefix = "LS-" + serverDefinition.id + projectName; //$NON-NLS-1$
final var dispatcherThreadNameFormat = formatPrefix + "#dispatcher"; //$NON-NLS-1$
this.dispatcher = Executors
.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(dispatcherThreadNameFormat).build());
// Executor service passed through to the LSP4j layer when we attempt to start the LS. It will be used
// to create a listener that sits on the input stream and processes inbound messages (responses, or server-initiated
// requests).
final var listenerThreadNameFormat = formatPrefix + "#listener-%d"; //$NON-NLS-1$
this.listener = Executors
.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat(listenerThreadNameFormat).build());
// Executor service to run a thread waiting for the LS launcher to terminate.
final var livenessThreadNameFormat = formatPrefix + "#cleaner"; //$NON-NLS-1$
this.cleaner = Executors
.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(livenessThreadNameFormat).build());
// Executor service to run a thread processing the LS error stream.
final var errorsThreadNameFormat = formatPrefix + "#errorProcessor"; //$NON-NLS-1$
this.errorProcessor = Executors
.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(errorsThreadNameFormat).build());
this.fileSystemWatcherManager = new FileSystemWatcherManager(initialProject);
// Read preference to determine whether to enable the workspace resource fallback for this server.
this.resourceFallbackEnabled = isNonBufferedFileListenerEnabled();
}
void stopDispatcher() {
this.dispatcher.shutdownNow();
// Only really needed for testing - the listener (an instance of ConcurrentMessageProcessor) should exit
// as soon as the input stream from the LS is closed, and a cached thread pool will recycle idle
// threads after a 60 second timeout - or immediately in response to JVM shutdown.
// If we don't do this then a full test run will generate a lot of threads because we create new
// instances of this class for each test
this.listener.shutdownNow();
// Again only needed for testing as the cleaner should exit when the launcher terminates.
this.cleaner.shutdown();
// Similarly, the error stream should also close when the input/output streams close.
this.errorProcessor.shutdownNow();
}
/**
* @return the workspace folder to be announced to the language server
*/
private List<WorkspaceFolder> getRelevantWorkspaceFolders() {
final var languageClient = this.languageClient;
List<WorkspaceFolder> folders = null;
if (languageClient != null) {
try {
folders = languageClient.workspaceFolders().get(5, TimeUnit.SECONDS);
} catch (final ExecutionException | TimeoutException ex) {
LanguageServerPlugin.logError(ex);
} catch (final InterruptedException ex) {
LanguageServerPlugin.logError(ex);
Thread.currentThread().interrupt();
}
}
if (folders == null) {
folders = LSPEclipseUtils.getWorkspaceFolders();
}
return folders;
}
/**
* Starts a language server and triggers initialization. If language server has been started
* before, does nothing.
* If the initialization throws an exception (e.g. because the binary for the LS could not be found),
* call {@link #restart()} to force another startup attempt (e.g. because the exception could be handled programmatically).
* Use {@link #startupFailed()} to check if an exception has occurred.
*/
public synchronized void start() {
start(false);
}
/**
* Restarts a language server. If language server is not started, calling this
* method is the same as calling {@link #start()}.
*
* @since 0.18
*/
public synchronized void restart() {
start(true);
}
/**
* Starts a language server and triggers initialization. If language server is
* started and active and restart is not forced, does nothing.
* If language server is inactive or restart is forced, restart it.
*
* @param forceRestart
* whether to restart the language server, even it is not inactive.
*/
private synchronized void start(boolean forceRestart) {
final var filesToReconnect = new HashMap<URI, IDocument>();
if (this.context.languageServer != null) {
if (isActive() && !forceRestart) {
return;
} else {
for (Entry<URI, DocumentContentSynchronizer> entry : this.connectedDocuments.entrySet()) {
filesToReconnect.put(entry.getKey(), entry.getValue().getDocument());
}
stop();
}
}
if (this.initializeFuture == null || forceRestart) {
final URI rootURI = getRootURI();
final Job job = createInitializeLanguageServerJob();
final LanguageServerContext workingContext = context;
this.initializeFuture = CompletableFuture.supplyAsync(() -> {
synchronized (workingContext) {
markInitializationProgress(workingContext);
final StreamConnectionProvider lspStreamProvider;
if (LoggingStreamConnectionProviderProxy.shouldLog(serverDefinition.id)) {
lspStreamProvider = workingContext.lspStreamProvider = new LoggingStreamConnectionProviderProxy(
serverDefinition.createConnectionProvider(), serverDefinition.id);
} else {
lspStreamProvider = workingContext.lspStreamProvider = serverDefinition
.createConnectionProvider();
}
initParams.setInitializationOptions(lspStreamProvider.getInitializationOptions(rootURI));
try {
lspStreamProvider.start();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return null;
}).thenRun(() -> {
synchronized (workingContext) {
markInitializationProgress(workingContext);
final var languageClient = this.languageClient = serverDefinition.createLanguageClient();
initParams.setProcessId((int) ProcessHandle.current().pid());
if (rootURI != null) {
initParams.setRootUri(rootURI.toString());
initParams.setRootPath(rootURI.getPath());
}
UnaryOperator<MessageConsumer> wrapper = consumer -> message -> {
logMessage(message);
consumer.consume(message);
final var lspStreamProvider = workingContext.lspStreamProvider;
final var languageServer = workingContext.languageServer;
if (lspStreamProvider != null && isActive() && languageServer != null) {
lspStreamProvider.handleMessage(message, languageServer, rootURI);
}
};
initParams.setWorkspaceFolders(getRelevantWorkspaceFolders());
final var lspStreamProvider = castNonNull(workingContext.lspStreamProvider);
Launcher<LanguageServer> launcher = serverDefinition.createLauncherBuilder() //
.setLocalService(languageClient)//
.setRemoteInterface(serverDefinition.getServerInterface())//
.setInput(lspStreamProvider.getInputStream())//
.setOutput(lspStreamProvider.getOutputStream())//
.setExecutorService(listener)//
.wrapMessages(wrapper)//
.create();
final var languageServer = workingContext.languageServer = launcher.getRemoteProxy();
languageClient.connect(languageServer, this);
workingContext.launcherFuture = launcher.startListening();
}
}).thenCompose(unused -> {
markInitializationProgress(workingContext);
final var initFuture = initServer(rootURI);
CompletableFuture.runAsync(() -> {
Exception launchException = null;
try {
// wait for the launcher to terminate
castNonNull(workingContext.launcherFuture).get();
} catch (InterruptedException e) {
LanguageServerPlugin.logError(e);
Thread.currentThread().interrupt();
} catch (ExecutionException | CancellationException e) {
launchException = e;
}
// If the response to the init-request has not been sent by the server, then the init-future will never complete,
// so we force it to complete exceptionally here.
if (!initFuture.isDone()) {
workingContext.languageServer = null;
initFuture.completeExceptionally(new ExecutionException(
"Unexpected language server termination: " + getFullErrorStream(), launchException)); //$NON-NLS-1$
}
}, cleaner);
return initFuture;
}).thenAccept(res -> {
synchronized (workingContext) {
markInitializationProgress(workingContext);
initializeResult = res;
serverCapabilities = res.getCapabilities();
serverInfo = res.getServerInfo();
this.initiallySupportsWorkspaceFolders = supportsWorkspaceFolders(serverCapabilities);
}
}).thenRun(() -> {
synchronized (workingContext) {
markInitializationProgress(workingContext);
castNonNull(workingContext.languageServer).initialized(new InitializedParams());
}
}).thenRun(() -> {
synchronized (workingContext) {
markInitializationProgress(workingContext);
final Map<URI, IDocument> toReconnect = filesToReconnect;
castNonNull(initializeFuture).thenRunAsync(() -> {
watchProjects();
for (Entry<URI, IDocument> fileToReconnect : toReconnect.entrySet()) {
connect(fileToReconnect.getKey(), fileToReconnect.getValue());
}
});
FileBuffers.getTextFileBufferManager().addFileBufferListener(fileBufferListener);
// Register a workspace-level fallback listener to catch resource events for
// files not backed by buffers, if enabled for this server
if (resourceFallbackEnabled) {
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceFallbackListener,
IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_DELETE
| IResourceChangeEvent.PRE_CLOSE);
}
castNonNull(initializeFuture).thenRunAsync(() -> {
processErrorStream(castNonNull(context.lspStreamProvider), l -> LanguageServerPlugin.getDefault().getLog().error(l), e -> {throw new UncheckedIOException(e);});
}, errorProcessor);
}
}).exceptionally(e -> {
shutdown(workingContext);
final Throwable cause = e.getCause();
if (cause instanceof CancellationException c) {
throw c;
} else {
LanguageServerPlugin.logError(e);
// Create a RuntimeException with just the root cause message to avoid nested exception display
throw new RuntimeException(getRootCauseMessage(e),e);
}
});
if (!this.initializeFuture.isCompletedExceptionally()) {
job.schedule();
}
}
}
private void markInitializationProgress(LanguageServerContext context) {
if (context.cancelled.get()) {
throw new CancellationException();
}
advanceInitializeFutureMonitor();
}
private void advanceInitializeFutureMonitor() {
final var initializeFutureMonitor = initializeFutureMonitorRef.get();
if (initializeFutureMonitor != null) {
if (initializeFutureMonitor.isCanceled()) {
throw new CancellationException();
}
initializeFutureMonitor.worked(1);
}
}
private Job createInitializeLanguageServerJob() {
return new Job(NLS.bind(Messages.initializeLanguageServer_job, serverDefinition.label)) {
@Override
protected IStatus run(IProgressMonitor monitor) {
final var initializeFutureMonitor = SubMonitor.convert(monitor, initializeFutureNumberOfStages);
initializeFutureMonitorRef.set(initializeFutureMonitor);
CompletableFuture<@Nullable Void> currentInitializeFuture = initializeFuture;
try {
if (currentInitializeFuture != null) {
currentInitializeFuture.join();
}
} catch (CancellationException e) {
return Status.CANCEL_STATUS;
} catch (Exception e) {
return new Status(IStatus.ERROR, LanguageServerPlugin.PLUGIN_ID, getRootCauseMessage(e), e);
} finally {
initializeFutureMonitor.done();
initializeFutureMonitorRef.compareAndSet(initializeFutureMonitor, null);
}
return Status.OK_STATUS;
}
@Override
public boolean belongsTo(@Nullable Object family) {
return LanguageServerPlugin.FAMILY_INITIALIZE_LANGUAGE_SERVER == family;
}
};
}
private CompletableFuture<InitializeResult> initServer(final @Nullable URI rootURI) {
final IProduct product = Platform.getProduct();
final String name = product != null ? product.getName() : "Eclipse IDE"; //$NON-NLS-1$
final var workspaceClientCapabilities = SupportedFeatures.getWorkspaceClientCapabilities();
final var textDocumentClientCapabilities = SupportedFeatures.getTextDocumentClientCapabilities();
WindowClientCapabilities windowClientCapabilities = SupportedFeatures.getWindowClientCapabilities();
initParams.setCapabilities(new ClientCapabilities(
workspaceClientCapabilities,
textDocumentClientCapabilities,
windowClientCapabilities,
castNonNull(context.lspStreamProvider).getExperimentalFeaturesPOJO()));
initParams.setClientInfo(getClientInfo(name));
initParams.setTrace(castNonNull(context.lspStreamProvider).getTrace(rootURI));
// no then...Async future here as we want this chain of operation to be sequential and "atomic"-ish
return castNonNull(context.languageServer).initialize(initParams);
// FIXME race: this.context may not be what it is expected to be, should be parameter
}
private String getFullErrorStream() {
StringBuilder builder = new StringBuilder();
processErrorStream(castNonNull(context.lspStreamProvider), l -> builder.append(l + '\n'), e -> builder.append("Exception processing error stream: " + e)); //$NON-NLS-1$
if (!builder.isEmpty()) {
return builder.toString();
}
return "No errors recorded."; //$NON-NLS-1$
}
private void processErrorStream(StreamConnectionProvider streamProvider, Consumer<String> lineHandler, Consumer<IOException> exceptionHandler) {
var errorStream = streamProvider.getErrorStream();
if (errorStream != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
if (!line.isBlank()) {
lineHandler.accept(line);
}
}
} catch (IOException e) {
exceptionHandler.accept(e);
}
}
}
@Nullable
public ProcessHandle getProcessHandle() {
return Adapters.adapt(context.lspStreamProvider, ProcessHandle.class);
}
private ClientInfo getClientInfo(String name) {
String pluginVersion = Platform.getBundle(LanguageServerPlugin.PLUGIN_ID).getVersion().toString();
final var clientInfo = new ClientInfo(name, pluginVersion);
return clientInfo;
}
@Nullable
private URI getRootURI() {
final IProject project = this.initialProject;
if (project != null && project.exists()) {
return LSPEclipseUtils.toUri(project);
}
final IPath path = this.initialPath;
if (path != null) {
File projectDirectory = path.toFile();
if (projectDirectory.isFile()) {
projectDirectory = castNonNull(projectDirectory.getParentFile());
}
return LSPEclipseUtils.toUri(projectDirectory);
}
return null;
}
private static boolean supportsWorkspaceFolders(@Nullable ServerCapabilities serverCapabilities) {
return serverCapabilities != null
&& serverCapabilities.getWorkspace() != null
&& serverCapabilities.getWorkspace().getWorkspaceFolders() != null
&& Boolean.TRUE.equals(serverCapabilities.getWorkspace().getWorkspaceFolders().getSupported());
}
private void logMessage(Message message) {
if (message instanceof ResponseMessage responseMessage && responseMessage.getError() != null
&& Integer.toString(ResponseErrorCode.RequestCancelled.getValue()).equals(responseMessage.getId())) {
LanguageServerPlugin.logError(new ResponseErrorException(responseMessage.getError()));
} else if (LanguageServerPlugin.DEBUG) {
LanguageServerPlugin.logInfo(message.getClass().getSimpleName() + '\n' + message);
}
}
/**
* @return whether the underlying connection to language server is still active
*/
public synchronized boolean isActive() {
final var launcherFuture = context.launcherFuture;
return launcherFuture != null && !launcherFuture.isDone();
}
/**
* @return whether the last startup attempt has failed
*/
public synchronized boolean startupFailed() {
return this.initializeFuture != null && this.initializeFuture.isCompletedExceptionally();
}
private void removeStopTimerTask() {
synchronized (timer) {
if (stopTimerTask != null) {
stopTimerTask.cancel();
stopTimerTask = null;
}
}
}
private void startStopTimerTask() {
synchronized (timer) {
if (stopTimerTask != null) {
stopTimerTask.cancel();
}
stopTimerTask = new TimerTask() {
@Override
public void run() {
stop();
}
};
timer.schedule(stopTimerTask, TimeUnit.SECONDS.toMillis(this.serverDefinition.lastDocumentDisconnectedTimeout));
}
}
/**
* Internal hook so that the unwrapped remote proxy can be matched to the corresponding
* wrapper, which tracks things like whether it is still running or not
* @param server LanguageServer to match on
* @return True if this is the wrapper for the given server
*/
boolean isWrapperFor(LanguageServer server) {
return server == context.languageServer;
}
public synchronized void stop() {
if (initializeFuture != null) {
initializeFuture.cancel(true);
initializeFuture = null;
}
LanguageServerContext contextToStop = context;
context = new LanguageServerContext();
contextToStop.cancelled.set(true);
shutdown(contextToStop);
}
private void shutdown(LanguageServerContext workingContext) {
removeStopTimerTask();
if (this.languageClient != null) {
this.languageClient.dispose();
}
this.serverCapabilities = null;
this.dynamicRegistrations.clear();
ResourcesPlugin.getWorkspace().removeResourceChangeListener(workspaceFolderUpdater);
ResourcesPlugin.getWorkspace().removeResourceChangeListener(watchedFilesListener);
fileSystemWatcherManager.clear();
CompletableFuture.runAsync(workingContext::close);
while (!this.connectedDocuments.isEmpty()) {
disconnect(this.connectedDocuments.keySet().iterator().next());
}
FileBuffers.getTextFileBufferManager().removeFileBufferListener(fileBufferListener);
ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceFallbackListener);
}
public @Nullable CompletableFuture<LanguageServerWrapper> connect(@Nullable IDocument document, IFile file) {
final URI uri = LSPEclipseUtils.toUri(file);
if (uri != null) {
return connect(uri, document);
}
return null;
}
public @Nullable CompletableFuture<LanguageServerWrapper> connectDocument(IDocument document) {
IFile file = LSPEclipseUtils.getFile(document);
if (file != null && file.exists()) {
return connect(document, file);
}
final URI uri = LSPEclipseUtils.toUri(document);
return uri == null ? null : connect(uri, document);
}
private void watchProjects() {
if (!supportsWorkspaceFolderCapability()) {
return;
}
final LanguageServer currentLS = context.languageServer;
new WorkspaceJob("Setting watch projects on server " + serverDefinition.label) { //$NON-NLS-1$
@Override
public IStatus runInWorkspace(@Nullable IProgressMonitor monitor) throws CoreException {
final var wsFolderEvent = new WorkspaceFoldersChangeEvent();
wsFolderEvent.getAdded().addAll(getRelevantWorkspaceFolders());
if (currentLS != null && currentLS == context.languageServer) {
currentLS.getWorkspaceService()
.didChangeWorkspaceFolders(new DidChangeWorkspaceFoldersParams(wsFolderEvent));
}
ResourcesPlugin.getWorkspace().addResourceChangeListener(workspaceFolderUpdater,
IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.PRE_CLOSE);
return Status.OK_STATUS;
}
}.schedule();
}
/**
* Check whether this LS is suitable for provided project.
*
* @return whether this language server can operate on the given project
* @since 0.5
*/
public boolean canOperate(@Nullable IProject project) {
return Objects.equals(project, this.initialProject)
|| serverDefinition.isSingleton
|| supportsWorkspaceFolderCapability();
}
public boolean canOperate(IDocument document) {
URI documentUri = LSPEclipseUtils.toUri(document);
if (documentUri == null) {
return false;
}
if (this.isConnectedTo(documentUri)) {
return true;
}
if (this.initialProject == null && this.connectedDocuments.isEmpty()) {
return true;
}
IFile file = LSPEclipseUtils.getFile(document);
if (file != null && file.exists() && canOperate(file.getProject())) {
return true;
}
return serverDefinition.isSingleton || supportsWorkspaceFolderCapability();
}
/**
* @return true, if the server supports multi-root workspaces via workspace folders
* @since 0.6
*/
private boolean supportsWorkspaceFolderCapability() {
if (this.initializeFuture != null) {
try {
this.initializeFuture.get(1, TimeUnit.SECONDS);
} catch (ExecutionException e) {
LanguageServerPlugin.logError(e);
} catch (InterruptedException e) {
LanguageServerPlugin.logError(e);
Thread.currentThread().interrupt();
} catch (TimeoutException e) {
LanguageServerPlugin.logWarning("Could not get if the workspace folder capability is supported due to timeout after 1 second"); //$NON-NLS-1$
}
}
return initiallySupportsWorkspaceFolders || supportsWorkspaceFolders(serverCapabilities);
}
/**
* To make public when we support non IFiles
*
* @return null if not connection has happened, a future that completes when file is initialized otherwise
* @noreference internal so far
*/
private @Nullable CompletableFuture<LanguageServerWrapper> connect(URI uri, @Nullable IDocument document) {
removeStopTimerTask();
if (this.connectedDocuments.containsKey(uri)) {
return CompletableFuture.completedFuture(this);
}
start();
if (this.initializeFuture == null) {
return null;
}
if (document == null) {
final var docFile = (IFile) LSPEclipseUtils.findResourceFor(uri);
document = LSPEclipseUtils.getDocument(docFile);
}
if (document == null) {
return null;
}
final IDocument theDocument = document;
return castNonNull(initializeFuture).thenAcceptAsync(theVoid -> {
synchronized (connectedDocuments) {
if (this.connectedDocuments.containsKey(uri)) {
return;
}
TextDocumentSyncKind syncKind = initializeFuture == null ? null
: castNonNull(serverCapabilities).getTextDocumentSync().map(Functions.identity(), TextDocumentSyncOptions::getChange);
final var listener = new DocumentContentSynchronizer(this, castNonNull(context.languageServer), theDocument, syncKind);
theDocument.addPrenotifiedDocumentListener(listener);
LanguageServerWrapper.this.connectedDocuments.put(uri, listener);
}
}).thenApply(theVoid -> this);
}
/**
* @param uri
* @return null if not disconnection has happened, a future tracking the disconnection state otherwise
*/
public @Nullable CompletableFuture<@Nullable Void> disconnect(URI uri) {
DocumentContentSynchronizer documentListener = this.connectedDocuments.remove(uri);
if (documentListener != null) {
documentListener.getDocument().removePrenotifiedDocumentListener(documentListener);
documentListener.documentClosed();
disconnectTextFileBuffer(uri);
}
if (this.connectedDocuments.isEmpty()) {
if (this.serverDefinition.lastDocumentDisconnectedTimeout != 0) {
startStopTimerTask();
} else {
stop();
}
}
return CompletableFuture.completedFuture(null);
}
private static void disconnectTextFileBuffer(URI uri) {
IPath location = URIUtil.toPath(uri);
if (location == null) {
return;
}
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(location);
if (file != null) {
LSPEclipseUtils.disconnectFromFileBuffer(file.getFullPath());
}
}
public void disconnectContentType(IContentType contentType) {
final var urisToDisconnect = new ArrayList<URI>();
for (URI uri : connectedDocuments.keySet()) {
final var file = ArrayUtil.findFirst(ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(uri));
if (file != null && LSPEclipseUtils.getFileContentTypes(file).stream().anyMatch(contentType::equals)) {
urisToDisconnect.add(uri);
}
}
for (URI uri : urisToDisconnect) {
disconnect(uri);
}
}
/**
* checks if the wrapper is already connected to the document at the given uri
*
* @noreference test only
*/
public boolean isConnectedTo(URI uri) {
return connectedDocuments.containsKey(uri);
}
/**
* Starts and returns the language server, regardless of if it is initialized.
* If not in the UI Thread, will wait to return the initialized server.
*
*/
@Nullable
protected LanguageServer getServer() {
CompletableFuture<LanguageServer> languageServerFuture = getInitializedServer();
if (Display.getCurrent() != null) { // UI Thread
return context.languageServer;
} else {
return languageServerFuture.join();
}
}
/**
* Starts the language server and returns a CompletableFuture waiting for the
* server to be initialized and up-to-date (all related pending document changes
* notifications are sent).
* <p>If done in the UI thread, a job will be created
* displaying that the server is being initialized</p>
*/
protected CompletableFuture<LanguageServer> getInitializedServer() {
start();
final CompletableFuture<@Nullable Void> currentInitializeFuture = initializeFuture;
if (currentInitializeFuture != null && !currentInitializeFuture.isDone()) {
return currentInitializeFuture.thenApply(r -> castNonNull(context.languageServer));
}
return CompletableFuture.completedFuture(context.languageServer);
}
/**
* Sends a notification to the wrapped language server
*
* @param fn
* LS notification to send
*/
public void sendNotification(Consumer<LanguageServer> fn) {
// Enqueues a notification on the dispatch thread associated with the wrapped language server. This
// ensures the interleaving of document updates and other requests in the UI is mirrored in the
// order in which they get dispatched to the server
getInitializedServer().thenAcceptAsync(fn, this.dispatcher);
}