-
Notifications
You must be signed in to change notification settings - Fork 317
/
LanguageServerImpl.java
1306 lines (1173 loc) · 46 KB
/
LanguageServerImpl.java
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, 2021 TypeFox GmbH (http://www.typefox.io) 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
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.ide.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.log4j.Logger;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.lsp4j.ClientCapabilities;
import org.eclipse.lsp4j.CodeAction;
import org.eclipse.lsp4j.CodeActionParams;
import org.eclipse.lsp4j.CodeLens;
import org.eclipse.lsp4j.CodeLensOptions;
import org.eclipse.lsp4j.CodeLensParams;
import org.eclipse.lsp4j.Command;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionList;
import org.eclipse.lsp4j.CompletionOptions;
import org.eclipse.lsp4j.CompletionParams;
import org.eclipse.lsp4j.DefinitionParams;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.DiagnosticSeverity;
import org.eclipse.lsp4j.DidChangeConfigurationParams;
import org.eclipse.lsp4j.DidChangeNotebookDocumentParams;
import org.eclipse.lsp4j.DidChangeTextDocumentParams;
import org.eclipse.lsp4j.DidChangeWatchedFilesParams;
import org.eclipse.lsp4j.DidChangeWorkspaceFoldersParams;
import org.eclipse.lsp4j.DidCloseNotebookDocumentParams;
import org.eclipse.lsp4j.DidCloseTextDocumentParams;
import org.eclipse.lsp4j.DidOpenNotebookDocumentParams;
import org.eclipse.lsp4j.DidOpenTextDocumentParams;
import org.eclipse.lsp4j.DidSaveNotebookDocumentParams;
import org.eclipse.lsp4j.DidSaveTextDocumentParams;
import org.eclipse.lsp4j.DocumentFormattingParams;
import org.eclipse.lsp4j.DocumentHighlight;
import org.eclipse.lsp4j.DocumentHighlightParams;
import org.eclipse.lsp4j.DocumentOnTypeFormattingParams;
import org.eclipse.lsp4j.DocumentRangeFormattingParams;
import org.eclipse.lsp4j.DocumentSymbol;
import org.eclipse.lsp4j.DocumentSymbolCapabilities;
import org.eclipse.lsp4j.DocumentSymbolParams;
import org.eclipse.lsp4j.ExecuteCommandCapabilities;
import org.eclipse.lsp4j.ExecuteCommandOptions;
import org.eclipse.lsp4j.ExecuteCommandParams;
import org.eclipse.lsp4j.FileChangeType;
import org.eclipse.lsp4j.FoldingRange;
import org.eclipse.lsp4j.FoldingRangeCapabilities;
import org.eclipse.lsp4j.FoldingRangeRequestParams;
import org.eclipse.lsp4j.Hover;
import org.eclipse.lsp4j.HoverParams;
import org.eclipse.lsp4j.InitializeParams;
import org.eclipse.lsp4j.InitializeResult;
import org.eclipse.lsp4j.InitializedParams;
import org.eclipse.lsp4j.Location;
import org.eclipse.lsp4j.LocationLink;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.PrepareRenameDefaultBehavior;
import org.eclipse.lsp4j.PrepareRenameParams;
import org.eclipse.lsp4j.PrepareRenameResult;
import org.eclipse.lsp4j.PublishDiagnosticsParams;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.ReferenceParams;
import org.eclipse.lsp4j.RenameCapabilities;
import org.eclipse.lsp4j.RenameOptions;
import org.eclipse.lsp4j.RenameParams;
import org.eclipse.lsp4j.SemanticTokens;
import org.eclipse.lsp4j.SemanticTokensLegend;
import org.eclipse.lsp4j.SemanticTokensParams;
import org.eclipse.lsp4j.SemanticTokensWithRegistrationOptions;
import org.eclipse.lsp4j.ServerCapabilities;
import org.eclipse.lsp4j.SignatureHelp;
import org.eclipse.lsp4j.SignatureHelpOptions;
import org.eclipse.lsp4j.SignatureHelpParams;
import org.eclipse.lsp4j.SymbolInformation;
import org.eclipse.lsp4j.TextDocumentClientCapabilities;
import org.eclipse.lsp4j.TextDocumentIdentifier;
import org.eclipse.lsp4j.TextDocumentItem;
import org.eclipse.lsp4j.TextDocumentPositionParams;
import org.eclipse.lsp4j.TextDocumentSyncKind;
import org.eclipse.lsp4j.TextEdit;
import org.eclipse.lsp4j.VersionedTextDocumentIdentifier;
import org.eclipse.lsp4j.WorkspaceClientCapabilities;
import org.eclipse.lsp4j.WorkspaceEdit;
import org.eclipse.lsp4j.WorkspaceFolder;
import org.eclipse.lsp4j.WorkspaceFoldersOptions;
import org.eclipse.lsp4j.WorkspaceServerCapabilities;
import org.eclipse.lsp4j.WorkspaceSymbol;
import org.eclipse.lsp4j.WorkspaceSymbolParams;
import org.eclipse.lsp4j.jsonrpc.Endpoint;
import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethod;
import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethodProvider;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.jsonrpc.messages.Either3;
import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints;
import org.eclipse.lsp4j.services.LanguageClient;
import org.eclipse.lsp4j.services.LanguageClientAware;
import org.eclipse.lsp4j.services.LanguageServer;
import org.eclipse.lsp4j.services.NotebookDocumentService;
import org.eclipse.lsp4j.services.TextDocumentService;
import org.eclipse.lsp4j.services.WorkspaceService;
import org.eclipse.xtext.diagnostics.Severity;
import org.eclipse.xtext.findReferences.IReferenceFinder;
import org.eclipse.xtext.ide.server.BuildManager.Buildable;
import org.eclipse.xtext.ide.server.ILanguageServerAccess.IBuildListener;
import org.eclipse.xtext.ide.server.codeActions.ICodeActionService2;
import org.eclipse.xtext.ide.server.codelens.ICodeLensResolver;
import org.eclipse.xtext.ide.server.codelens.ICodeLensService;
import org.eclipse.xtext.ide.server.commands.ExecutableCommandRegistry;
import org.eclipse.xtext.ide.server.concurrent.RequestManager;
import org.eclipse.xtext.ide.server.contentassist.ContentAssistService;
import org.eclipse.xtext.ide.server.findReferences.WorkspaceResourceAccess;
import org.eclipse.xtext.ide.server.folding.FoldingRangeService;
import org.eclipse.xtext.ide.server.formatting.FormattingService;
import org.eclipse.xtext.ide.server.hover.IHoverService;
import org.eclipse.xtext.ide.server.occurrences.IDocumentHighlightService;
import org.eclipse.xtext.ide.server.rename.IRenameService2;
import org.eclipse.xtext.ide.server.semantictokens.SemanticTokensService;
import org.eclipse.xtext.ide.server.signatureHelp.ISignatureHelpService;
import org.eclipse.xtext.ide.server.symbol.DocumentSymbolService;
import org.eclipse.xtext.ide.server.symbol.HierarchicalDocumentSymbolService;
import org.eclipse.xtext.ide.server.symbol.IDocumentSymbolService;
import org.eclipse.xtext.ide.server.symbol.WorkspaceSymbolService;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.resource.IResourceServiceProvider;
import org.eclipse.xtext.util.BufferedCancelIndicator;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.validation.Issue;
import org.eclipse.xtext.xbase.lib.Pair;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.inject.Inject;
/**
* @author Sven Efftinge - Initial contribution and API
* @since 2.11
*/
public class LanguageServerImpl implements LanguageServer, WorkspaceService, TextDocumentService, NotebookDocumentService, LanguageClientAware,
Endpoint, JsonRpcMethodProvider, ILanguageServerAccess.IBuildListener {
private static final Logger LOG = Logger.getLogger(LanguageServerImpl.class);
@Inject
private RequestManager requestManager;
@Inject
private WorkspaceSymbolService workspaceSymbolService;
@Inject
private UriExtensions uriExtensions;
@Inject
private IResourceServiceProvider.Registry languagesRegistry;
@Inject
private ExecutableCommandRegistry commandRegistry;
@Inject
private ILanguageServerShutdownAndExitHandler shutdownAndExitHandler;
@Inject
private SemanticTokensService semanticTokensService;
private WorkspaceManager workspaceManager;
private InitializeParams initializeParams;
private InitializeResult initializeResult;
private WorkspaceResourceAccess resourceAccess;
private LanguageClient client;
private volatile Map<String, JsonRpcMethod> supportedMethods;
private final CompletableFuture<InitializedParams> initialized = new CompletableFuture<>();
private final Multimap<String, Endpoint> extensionProviders = LinkedListMultimap.create();
@Inject
public void setWorkspaceManager(WorkspaceManager manager) {
workspaceManager = manager;
resourceAccess = new WorkspaceResourceAccess(workspaceManager);
}
private Set<? extends IResourceServiceProvider> getAllLanguages() {
// provide a stable order
Map<String, IResourceServiceProvider> sorted = new TreeMap<>();
for (String ext : languagesRegistry.getExtensionToFactoryMap().keySet()) {
sorted.put(ext, languagesRegistry.getResourceServiceProvider(URI.createURI("synth:///file." + ext)));
}
return ImmutableSet.copyOf(sorted.values());
}
@Override
public CompletableFuture<InitializeResult> initialize(InitializeParams params) {
if (initializeParams != null) {
throw new IllegalStateException("This language server has already been initialized.");
}
if (languagesRegistry.getExtensionToFactoryMap().isEmpty()) {
throw new IllegalStateException(
"No Xtext languages have been registered. Please make sure you have added the languages\'s setup class in \'/META-INF/services/org.eclipse.xtext.ISetup\'");
}
initializeParams = params;
InitializeResult result = new InitializeResult();
result.setCapabilities(createServerCapabilities(params));
access.addBuildListener(this);
return requestManager.runWrite(() -> {
if (clientSupportsWorkspaceFolders() && workspaceManager.isSupportsWorkspaceFolders()) {
List<WorkspaceFolder> workspaceFolders = params.getWorkspaceFolders();
if (workspaceFolders == null)
workspaceFolders = Collections.emptyList();
workspaceManager.initialize(workspaceFolders, this::publishDiagnostics, CancelIndicator.NullImpl);
} else {
URI baseDir = getBaseDir(params);
workspaceManager.initialize(baseDir, this::publishDiagnostics, CancelIndicator.NullImpl);
}
return result;
}, (cancelIndicator, it) -> it).thenApply(it -> initializeResult = it);
}
protected boolean clientSupportsWorkspaceFolders() {
return this.initializeParams.getCapabilities() != null
&& this.initializeParams.getCapabilities().getWorkspace() != null
&& Objects.equal(this.initializeParams.getCapabilities().getWorkspace().getWorkspaceFolders(), Boolean.TRUE);
}
/**
* Configure the server capabilities for this instance.
*
* @param params
* the initialization parameters
* @return the server capabilities
* @since 2.20
*/
protected ServerCapabilities createServerCapabilities(InitializeParams params) {
ServerCapabilities serverCapabilities = new ServerCapabilities();
serverCapabilities.setHoverProvider(true);
serverCapabilities.setDefinitionProvider(true);
serverCapabilities.setReferencesProvider(true);
serverCapabilities.setDocumentSymbolProvider(true);
serverCapabilities.setWorkspaceSymbolProvider(true);
Set<? extends IResourceServiceProvider> allLanguages = getAllLanguages();
if (allLanguages.stream().anyMatch((serviceProvider) -> serviceProvider.get(ICodeLensService.class) != null)) {
CodeLensOptions codeLensOptions = new CodeLensOptions();
codeLensOptions.setResolveProvider(allLanguages.stream()
.anyMatch((serviceProvider) -> serviceProvider.get(ICodeLensResolver.class) != null));
serverCapabilities.setCodeLensProvider(codeLensOptions);
}
serverCapabilities.setCodeActionProvider(allLanguages.stream()
.anyMatch((serviceProvider) -> serviceProvider.get(ICodeActionService2.class) != null));
serverCapabilities.setSignatureHelpProvider(new SignatureHelpOptions(ImmutableList.of("(", ",")));
serverCapabilities.setTextDocumentSync(TextDocumentSyncKind.Incremental);
SemanticTokensLegend legend = new SemanticTokensLegend(semanticTokensService.getTokenTypes(), semanticTokensService.getTokenModifiers());
SemanticTokensWithRegistrationOptions semanticTokensWithRegistrationOptions = new SemanticTokensWithRegistrationOptions(legend);
semanticTokensWithRegistrationOptions.setFull(true);
semanticTokensWithRegistrationOptions.setRange(false);
serverCapabilities.setSemanticTokensProvider(semanticTokensWithRegistrationOptions);
CompletionOptions completionOptions = new CompletionOptions();
completionOptions.setResolveProvider(false);
completionOptions.setTriggerCharacters(ImmutableList.of("."));
serverCapabilities.setCompletionProvider(completionOptions);
serverCapabilities.setDocumentFormattingProvider(true);
serverCapabilities.setDocumentRangeFormattingProvider(true);
serverCapabilities.setDocumentHighlightProvider(true);
ClientCapabilities clientCapabilities = null;
if (params != null) {
clientCapabilities = params.getCapabilities();
}
TextDocumentClientCapabilities textDocument = null;
if (clientCapabilities != null) {
textDocument = clientCapabilities.getTextDocument();
}
RenameCapabilities rename = null;
FoldingRangeCapabilities folding = null;
if (textDocument != null) {
rename = textDocument.getRename();
folding = textDocument.getFoldingRange();
}
if (folding != null) {
serverCapabilities.setFoldingRangeProvider(allLanguages.stream()
.anyMatch(serviceProvider -> serviceProvider.get(FoldingRangeService.class) != null));
}
Boolean prepareSupport = null;
if (rename != null) {
prepareSupport = rename.getPrepareSupport();
}
boolean clientPrepareSupport = Objects.equal(Boolean.TRUE, prepareSupport);
if (clientPrepareSupport && allLanguages.stream()
.anyMatch(serviceProvider -> serviceProvider.get(IRenameService2.class) != null)) {
RenameOptions renameOptions = new RenameOptions();
renameOptions.setPrepareProvider(true);
serverCapabilities.setRenameProvider(Either.<Boolean, RenameOptions>forRight(renameOptions));
} else {
serverCapabilities.setRenameProvider(Either.forLeft(allLanguages.stream()
.anyMatch((serviceProvider) -> serviceProvider.get(IRenameService2.class) != null)));
}
WorkspaceClientCapabilities workspace = null;
if (clientCapabilities != null) {
workspace = clientCapabilities.getWorkspace();
}
ExecuteCommandCapabilities executeCommand = null;
if (workspace != null) {
executeCommand = workspace.getExecuteCommand();
if (workspace.getWorkspaceFolders() == Boolean.TRUE && workspaceManager.isSupportsWorkspaceFolders()) {
WorkspaceFoldersOptions workspaceFoldersOptions = new WorkspaceFoldersOptions();
workspaceFoldersOptions.setSupported(true);
workspaceFoldersOptions.setChangeNotifications(true);
serverCapabilities.setWorkspace(new WorkspaceServerCapabilities(workspaceFoldersOptions));
}
}
if (executeCommand != null) {
commandRegistry.initialize(allLanguages, clientCapabilities, client);
ExecuteCommandOptions executeCommandOptions = new ExecuteCommandOptions();
executeCommandOptions.setCommands(commandRegistry.getCommands());
serverCapabilities.setExecuteCommandProvider(executeCommandOptions);
}
for (IResourceServiceProvider language : allLanguages) {
ICapabilitiesContributor capabilitiesContributor = language.get(ICapabilitiesContributor.class);
if (capabilitiesContributor != null) {
capabilitiesContributor.contribute(serverCapabilities, params);
}
}
return serverCapabilities;
}
@Override
public void initialized(InitializedParams params) {
initialized.complete(params);
}
@Deprecated
private URI deprecatedToBaseDir(InitializeParams params) {
String rootPath = params.getRootPath();
if (rootPath != null) {
return uriExtensions.toUri(uriExtensions.toUriString(URI.createFileURI(rootPath)));
}
return null;
}
/**
* Compute the base dir.
*/
@Deprecated
protected URI getBaseDir(InitializeParams params) {
String rootUri = params.getRootUri();
if (rootUri != null) {
return uriExtensions.toUri(rootUri);
}
return deprecatedToBaseDir(params);
}
@Override
public void connect(LanguageClient client) {
this.client = client;
}
@Override
public void exit() {
shutdownAndExitHandler.exit();
}
@Override
public CompletableFuture<Object> shutdown() {
shutdownAndExitHandler.shutdown();
return CompletableFuture.completedFuture(new Object());
}
@Override
public TextDocumentService getTextDocumentService() {
return this;
}
@Override
public WorkspaceService getWorkspaceService() {
return this;
}
@Override
public NotebookDocumentService getNotebookDocumentService() {
return this;
}
@Override
public void didOpen(DidOpenTextDocumentParams params) {
runBuildable(() -> toBuildable(params));
}
/**
* Evaluate the params and deduce the respective build command.
* @since 2.20
*/
protected Buildable toBuildable(DidOpenTextDocumentParams params) {
TextDocumentItem textDocument = params.getTextDocument();
return workspaceManager.didOpen(getURI(textDocument), textDocument.getVersion(), textDocument.getText());
}
@Override
public void didChange(DidChangeTextDocumentParams params) {
runBuildable(() -> toBuildable(params));
}
/**
* Evaluate the params and deduce the respective build command.
*/
protected Buildable toBuildable(DidChangeTextDocumentParams params) {
VersionedTextDocumentIdentifier textDocument = params.getTextDocument();
return workspaceManager.didChangeTextDocumentContent(getURI(textDocument), textDocument.getVersion(),
params.getContentChanges());
}
@Override
public void didClose(DidCloseTextDocumentParams params) {
runBuildable(() -> toBuildable(params));
}
/**
* Evaluate the params and deduce the respective build command.
*/
protected Buildable toBuildable(DidCloseTextDocumentParams params) {
return workspaceManager.didClose(getURI(params.getTextDocument()));
}
@Override
public void didSave(DidSaveTextDocumentParams params) {
// nothing to do
}
@Override
public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) {
runBuildable(() -> toBuildable(params));
}
/**
* Evaluate the params and deduce the respective build command.
*/
protected Buildable toBuildable(DidChangeWatchedFilesParams params) {
List<URI> dirtyFiles = new ArrayList<>();
List<URI> deletedFiles = new ArrayList<>();
params.getChanges().stream()
.map((fileEvent) -> Pair.of(uriExtensions.toUri(fileEvent.getUri()), fileEvent.getType()))
.filter(pair -> !workspaceManager.isDocumentOpen(pair.getKey())).forEach(pair -> {
if (pair.getValue() == FileChangeType.Deleted) {
deletedFiles.add(pair.getKey());
} else {
dirtyFiles.add(pair.getKey());
}
});
return workspaceManager.didChangeFiles(dirtyFiles, deletedFiles);
}
/**
* Compute a buildable and run the build in a write action
*
* @param newBuildable
* the factory for the buildable.
* @since 2.20
*/
protected void runBuildable(Supplier<? extends Buildable> newBuildable) {
requestManager.runWrite(newBuildable::get, (cancelIndicator, buildable) -> buildable.build(cancelIndicator));
}
@Override
public void didChangeConfiguration(DidChangeConfigurationParams params) {
requestManager.runWrite(() -> {
workspaceManager.refreshWorkspaceConfig(CancelIndicator.NullImpl);
return null;
}, (a, b) -> null);
}
/**
* @since 2.21
*/
@Override
public void didChangeWorkspaceFolders(DidChangeWorkspaceFoldersParams params) {
requestManager.runWrite(() -> {
workspaceManager.didChangeWorkspaceFolders(params, CancelIndicator.NullImpl);
return null;
}, (a, b) -> null);
}
private void publishDiagnostics(URI uri, Iterable<? extends Issue> issues) {
initialized.thenAccept((initParams) -> {
PublishDiagnosticsParams publishDiagnosticsParams = new PublishDiagnosticsParams();
publishDiagnosticsParams.setUri(uriExtensions.toUriString(uri));
publishDiagnosticsParams.setDiagnostics(toDiagnostics(issues));
client.publishDiagnostics(publishDiagnosticsParams);
});
}
/**
* Convert the given issues to diagnostics. Does not return any issue with severity {@link Severity#IGNORE ignore}
* by default.
*/
protected List<Diagnostic> toDiagnostics(Iterable<? extends Issue> issues) {
List<Diagnostic> result = new ArrayList<>();
for (Issue issue : issues) {
if (issue.getSeverity() != Severity.IGNORE) {
result.add(toDiagnostic(issue));
}
}
return result;
}
/**
* Convert the given issue to a diagnostic.
*/
protected Diagnostic toDiagnostic(Issue issue) {
Diagnostic result = new Diagnostic();
result.setCode(issue.getCode());
result.setData(issue.getData());
result.setMessage(issue.getMessage());
result.setSeverity(toDiagnosticSeverity(issue.getSeverity()));
// line and column numbers in LSP are 0-based
Position start = new Position(Math.max(0, issue.getLineNumber() - 1), Math.max(0, issue.getColumn() - 1));
Position end = new Position(Math.max(0, issue.getLineNumberEnd() - 1), Math.max(0, issue.getColumnEnd() - 1));
result.setRange(new Range(start, end));
return result;
}
/**
* Convert the severity to a lsp {@link DiagnosticSeverity}.
*
* Defaults to severity {@link DiagnosticSeverity#Hint hint}.
*/
protected DiagnosticSeverity toDiagnosticSeverity(Severity severity) {
switch (severity) {
case ERROR:
return DiagnosticSeverity.Error;
case IGNORE:
return DiagnosticSeverity.Hint;
case INFO:
return DiagnosticSeverity.Information;
case WARNING:
return DiagnosticSeverity.Warning;
default:
return DiagnosticSeverity.Hint;
}
}
@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams params) {
return requestManager.runRead((cancelIndicator) -> completion(cancelIndicator, params));
}
/**
* Compute the completion items.
*/
protected Either<List<CompletionItem>, CompletionList> completion(CancelIndicator originalCancelIndicator,
CompletionParams params) {
URI uri = getURI(params);
ContentAssistService contentAssistService = getService(uri, ContentAssistService.class);
if (contentAssistService == null) {
return Either.forRight(new CompletionList());
}
BufferedCancelIndicator cancelIndicator = new BufferedCancelIndicator(originalCancelIndicator);
return Either.forRight(workspaceManager.doRead(uri,
(doc, res) -> contentAssistService.createCompletionList(doc, res, params, cancelIndicator)));
}
/**
* Obtain the URI from the given parameters.
* @since 2.20
*/
protected URI getURI(TextDocumentPositionParams params) {
return getURI(params.getTextDocument());
}
/**
* Obtain the URI from the given identifier.
* @since 2.20
*/
protected URI getURI(TextDocumentIdentifier documentIdentifier) {
return uriExtensions.toUri(documentIdentifier.getUri());
}
/**
* Obtain the URI from the given document item.
* @since 2.20
*/
protected URI getURI(TextDocumentItem documentItem) {
return uriExtensions.toUri(documentItem.getUri());
}
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> definition(
DefinitionParams params) {
return requestManager.runRead(cancelIndicator -> definition(params, cancelIndicator));
}
/**
* Compute the definition. Executed in a read request.
* @since 2.20
*/
protected Either<List<? extends Location>, List<? extends LocationLink>> definition(
DefinitionParams params, CancelIndicator cancelIndicator) {
return Either.forLeft(definition(cancelIndicator, params));
}
/**
* Compute the definition.
*/
protected List<? extends Location> definition(CancelIndicator cancelIndicator, DefinitionParams params) {
URI uri = getURI(params);
DocumentSymbolService documentSymbolService = getService(uri, DocumentSymbolService.class);
if (documentSymbolService == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri,
(doc, res) -> documentSymbolService.getDefinitions(doc, res, params, resourceAccess, cancelIndicator));
}
@Override
public CompletableFuture<List<? extends Location>> references(ReferenceParams params) {
return requestManager.runRead(cancelIndicator -> references(params, cancelIndicator));
}
/**
* Compute the references. Executed in read request.
* @since 2.20
*/
protected List<? extends Location> references(ReferenceParams params, CancelIndicator cancelIndicator) {
URI uri = getURI(params);
DocumentSymbolService documentSymbolService = getService(uri, DocumentSymbolService.class);
if (documentSymbolService == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri, (document, resource) -> documentSymbolService.getReferences(document,
resource, params, resourceAccess, workspaceManager.getIndex(), cancelIndicator));
}
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(
DocumentSymbolParams params) {
return requestManager.runRead((cancelIndicator) -> {
List<DocumentSymbol> symbols = documentSymbol(params, cancelIndicator);
return Lists.transform(symbols, Either::forRight);
});
}
/**
* Compute the symbol information. Executed in a read request.
* @since 2.20
*/
protected List<DocumentSymbol> documentSymbol(DocumentSymbolParams params,
CancelIndicator cancelIndicator) {
URI uri = getURI(params.getTextDocument());
IDocumentSymbolService documentSymbolService = getIDocumentSymbolService(getResourceServiceProvider(uri));
if (documentSymbolService == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri,
(document, resource) -> documentSymbolService.getSymbols(document, resource, params, cancelIndicator));
}
/**
* @since 2.16
*/
protected IDocumentSymbolService getIDocumentSymbolService(IResourceServiceProvider serviceProvider) {
if (serviceProvider == null) {
return null;
}
if (isHierarchicalDocumentSymbolSupport()) {
return serviceProvider.get(HierarchicalDocumentSymbolService.class);
} else {
return serviceProvider.get(DocumentSymbolService.class);
}
}
/**
* {@code true} if the {@code TextDocumentClientCapabilities} explicitly declares the hierarchical document symbol
* support at LS initialization time. Otherwise, false.
*/
protected boolean isHierarchicalDocumentSymbolSupport() {
ClientCapabilities capabilities = initializeParams.getCapabilities();
if (capabilities == null) {
return false;
}
TextDocumentClientCapabilities textDocument = capabilities.getTextDocument();
if (textDocument == null) {
return false;
}
DocumentSymbolCapabilities documentSymbol = textDocument.getDocumentSymbol();
if (documentSymbol == null) {
return false;
}
Boolean hierarchicalDocumentSymbolSupport = documentSymbol.getHierarchicalDocumentSymbolSupport();
if (hierarchicalDocumentSymbolSupport == null) {
return false;
}
return hierarchicalDocumentSymbolSupport;
}
@Override
public CompletableFuture<Either<List<? extends SymbolInformation>, List<? extends WorkspaceSymbol>>> symbol(WorkspaceSymbolParams params) {
return requestManager.runRead((cancelIndicator) -> {
List<? extends WorkspaceSymbol> symbols = symbol(params, cancelIndicator);
return Either.forRight(symbols);
});
}
/**
* Compute the symbol information. Executed in a read request.
* @since 2.20
*/
protected List<? extends WorkspaceSymbol> symbol(WorkspaceSymbolParams params, CancelIndicator cancelIndicator) {
return workspaceSymbolService.getSymbols(params.getQuery(), resourceAccess, workspaceManager.getIndex(), cancelIndicator);
}
@Override
public CompletableFuture<Hover> hover(HoverParams params) {
return requestManager.runRead((cancelIndicator) -> hover(params, cancelIndicator));
}
/**
* Compute the hover. Executed in a read request.
* @since 2.20
*/
protected Hover hover(HoverParams params, CancelIndicator cancelIndicator) {
URI uri = getURI(params);
IHoverService hoverService = getService(uri, IHoverService.class);
if (hoverService == null) {
return IHoverService.EMPTY_HOVER;
}
return workspaceManager.<Hover>doRead(uri,
(document, resource) -> hoverService.hover(document, resource, params, cancelIndicator));
}
@Override
public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem unresolved) {
return CompletableFuture.<CompletionItem>completedFuture(unresolved);
}
@Override
public CompletableFuture<SignatureHelp> signatureHelp(SignatureHelpParams params) {
return requestManager.runRead((cancelIndicator) -> signatureHelp(params, cancelIndicator));
}
/**
* Compute the signature help. Executed in a read request.
* @since 2.20
*/
protected SignatureHelp signatureHelp(SignatureHelpParams params, CancelIndicator cancelIndicator) {
URI uri = getURI(params);
ISignatureHelpService helper = getService(uri, ISignatureHelpService.class);
if (helper == null) {
return ISignatureHelpService.EMPTY;
}
return workspaceManager.doRead(uri,
(doc, resource) -> helper.getSignatureHelp(doc, resource, params, cancelIndicator));
}
@Override
public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(DocumentHighlightParams params) {
return requestManager.runRead((cancelIndicator) -> documentHighlight(params, cancelIndicator));
}
/**
* Compute the document highlights. Executed in a read request.
* @since 2.20
*/
protected List<? extends DocumentHighlight> documentHighlight(DocumentHighlightParams params,
CancelIndicator cancelIndicator) {
URI uri = getURI(params);
IDocumentHighlightService service = getService(uri, IDocumentHighlightService.class);
if (service == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri,
(doc, resource) -> service.getDocumentHighlights(doc, resource, params, cancelIndicator));
}
@Override
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params) {
return requestManager.runRead((cancelIndicator) -> codeAction(params, cancelIndicator));
}
/**
* Compute the code action commands. Executed in a read request.
* @since 2.20
*/
protected List<Either<Command, CodeAction>> codeAction(CodeActionParams params, CancelIndicator cancelIndicator) {
URI uri = getURI(params.getTextDocument());
IResourceServiceProvider serviceProvider = getResourceServiceProvider(uri);
ICodeActionService2 codeActionService = getService(serviceProvider, ICodeActionService2.class);
if (codeActionService == null) {
return Collections.emptyList();
}
ICodeActionService2.Options options = new ICodeActionService2.Options();
options.setURI(params.getTextDocument().getUri());
options.setLanguageServerAccess(access);
options.setCodeActionParams(params);
options.setCancelIndicator(cancelIndicator);
List<Either<Command, CodeAction>> actions = codeActionService.getCodeActions(options);
if (actions != null) {
return actions;
}
return Collections.emptyList();
}
/**
* Put the document uri into the data of the given code lenses.
*/
protected void installURI(List<? extends CodeLens> codeLenses, String uri) {
for (CodeLens lens : codeLenses) {
Object data = lens.getData();
if (data != null) {
lens.setData(Arrays.asList(uri, lens.getData()));
} else {
lens.setData(uri);
}
}
}
/**
* Remove the document uri from the data of the given code lense.
*/
protected URI uninstallURI(CodeLens lens) {
URI result = null;
Object data = lens.getData();
if (data instanceof String) {
result = URI.createURI(data.toString());
lens.setData(null);
} else {
if (data instanceof List<?>) {
List<?> l = (List<?>) data;
result = URI.createURI(l.get(0).toString());
lens.setData(l.get(1));
}
}
return result;
}
@Override
public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) {
return requestManager.runRead((cancelIndicator) -> codeLens(params, cancelIndicator));
}
/**
* Compute the code lenses. Executed in a read request.
* @since 2.20
*/
protected List<? extends CodeLens> codeLens(CodeLensParams params, CancelIndicator cancelIndicator) {
URI uri = getURI(params.getTextDocument());
ICodeLensService codeLensService = getService(uri, ICodeLensService.class);
if (codeLensService == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri, (document, resource) -> {
List<? extends CodeLens> result = codeLensService.computeCodeLenses(document, resource, params,
cancelIndicator);
installURI(result, uri.toString());
return result;
});
}
@Override
public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) {
URI uri = uninstallURI(unresolved);
if (uri == null) {
return CompletableFuture.completedFuture(unresolved);
}
return requestManager.runRead((cancelIndicator) -> resolveCodeLens(uri, unresolved, cancelIndicator));
}
/**
* Resolve the given code lens. Executed in a read request.
* @since 2.20
*/
protected CodeLens resolveCodeLens(URI uri, CodeLens unresolved, CancelIndicator cancelIndicator) {
ICodeLensResolver resolver = getService(uri, ICodeLensResolver.class);
if (resolver == null) {
return unresolved;
}
return workspaceManager.doRead(uri,
(document, resource) -> resolver.resolveCodeLens(document, resource, unresolved, cancelIndicator));
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
return requestManager.runRead((cancelIndicator) -> formatting(params, cancelIndicator));
}
/**
* Create the text edits for the formatter. Executed in a read request.
* @since 2.20
*/
protected List<? extends TextEdit> formatting(DocumentFormattingParams params, CancelIndicator cancelIndicator) {
URI uri = getURI(params.getTextDocument());
FormattingService formatterService = getService(uri, FormattingService.class);
if (formatterService == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri,
(document, resource) -> formatterService.format(document, resource, params, cancelIndicator));
}
@Override
public CompletableFuture<List<? extends TextEdit>> rangeFormatting(DocumentRangeFormattingParams params) {
return requestManager.runRead((cancelIndicator) -> rangeFormatting(params, cancelIndicator));
}
/**
* Create the text edits for the formatter. Executed in a read request.
* @since 2.20
*/
protected List<? extends TextEdit> rangeFormatting(DocumentRangeFormattingParams params,
CancelIndicator cancelIndicator) {
URI uri = getURI(params.getTextDocument());
FormattingService formatterService = getService(uri, FormattingService.class);
if (formatterService == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri,
(document, resource) -> formatterService.format(document, resource, params, cancelIndicator));
}
/**
* @param uri
* the current URI
* @param type
* the type of the service
* @return the service instance or null if the language does not exist or if it does not expose the service.
* @since 2.20
*/
protected <Service> Service getService(URI uri, Class<Service> type) {
return getService(getResourceServiceProvider(uri), type);
}
/**
* @param <Service>
* the type of the service
* @param resourceServiceProvider
* the resource service provider. May be null
* @param type
* the type of the service
* @return the service instance or null if not available.
* @since 2.20
*/
protected <Service> Service getService(IResourceServiceProvider resourceServiceProvider, Class<Service> type) {
if (resourceServiceProvider == null) {
return null;
}
return resourceServiceProvider.get(type);
}
@Override
public CompletableFuture<Object> executeCommand(ExecuteCommandParams params) {
return requestManager.runRead((cancelIndicator) -> executeCommand(params, cancelIndicator));
}
/**
* Execute the command. Runs in a read request.
* @since 2.20
*/
protected Object executeCommand(ExecuteCommandParams params, CancelIndicator cancelIndicator) {
return commandRegistry.executeCommand(params, access, cancelIndicator);
}
@Override
public CompletableFuture<List<? extends TextEdit>> onTypeFormatting(DocumentOnTypeFormattingParams params) {
throw new UnsupportedOperationException("TODO: auto-generated method stub");
}
@Override
public CompletableFuture<WorkspaceEdit> rename(RenameParams renameParams) {
return requestManager.runRead(cancelIndicator -> rename(renameParams, cancelIndicator));
}
/**
* Compute the rename edits. Executed in a read request.