forked from apache/netbeans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextDocumentServiceImpl.java
1798 lines (1700 loc) · 90.6 KB
/
TextDocumentServiceImpl.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.java.lsp.server.protocol;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.LineMap;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.Trees;
import com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.IntFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import java.util.stream.Collectors;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
import org.eclipse.lsp4j.CodeAction;
import org.eclipse.lsp4j.CodeActionKind;
import org.eclipse.lsp4j.CodeActionParams;
import org.eclipse.lsp4j.CodeLens;
import org.eclipse.lsp4j.CodeLensParams;
import org.eclipse.lsp4j.Command;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionItemKind;
import org.eclipse.lsp4j.CompletionItemTag;
import org.eclipse.lsp4j.CompletionList;
import org.eclipse.lsp4j.CompletionParams;
import org.eclipse.lsp4j.CreateFile;
import org.eclipse.lsp4j.DefinitionParams;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.DiagnosticSeverity;
import org.eclipse.lsp4j.DidChangeTextDocumentParams;
import org.eclipse.lsp4j.DidCloseTextDocumentParams;
import org.eclipse.lsp4j.DidOpenTextDocumentParams;
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.DocumentSymbolParams;
import org.eclipse.lsp4j.FoldingRange;
import org.eclipse.lsp4j.FoldingRangeKind;
import org.eclipse.lsp4j.FoldingRangeRequestParams;
import org.eclipse.lsp4j.Hover;
import org.eclipse.lsp4j.HoverParams;
import org.eclipse.lsp4j.ImplementationParams;
import org.eclipse.lsp4j.InsertTextFormat;
import org.eclipse.lsp4j.Location;
import org.eclipse.lsp4j.LocationLink;
import org.eclipse.lsp4j.MarkupContent;
import org.eclipse.lsp4j.MessageParams;
import org.eclipse.lsp4j.MessageType;
import org.eclipse.lsp4j.Position;
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.RenameFile;
import org.eclipse.lsp4j.RenameParams;
import org.eclipse.lsp4j.ResourceOperation;
import org.eclipse.lsp4j.SignatureHelp;
import org.eclipse.lsp4j.SignatureHelpParams;
import org.eclipse.lsp4j.SymbolInformation;
import org.eclipse.lsp4j.TextDocumentContentChangeEvent;
import org.eclipse.lsp4j.TextDocumentEdit;
import org.eclipse.lsp4j.TextEdit;
import org.eclipse.lsp4j.VersionedTextDocumentIdentifier;
import org.eclipse.lsp4j.WorkspaceEdit;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.jsonrpc.messages.ResponseErrorCode;
import org.eclipse.lsp4j.services.LanguageClient;
import org.eclipse.lsp4j.services.LanguageClientAware;
import org.eclipse.lsp4j.services.TextDocumentService;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.java.lexer.JavaTokenId;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.java.source.CompilationController;
import org.netbeans.api.java.source.CompilationInfo;
import org.netbeans.api.java.source.ElementHandle;
import org.netbeans.api.java.source.GeneratorUtilities;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.api.java.source.JavaSource.Phase;
import org.netbeans.api.java.source.ModificationResult;
import org.netbeans.api.java.source.SourceUtils;
import org.netbeans.api.java.source.Task;
import org.netbeans.api.java.source.TreePathHandle;
import org.netbeans.api.java.source.TreeUtilities;
import org.netbeans.api.java.source.WorkingCopy;
import org.netbeans.api.java.source.ui.ElementJavadoc;
import org.netbeans.api.java.source.ui.ElementOpen;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.api.lsp.Completion;
import org.netbeans.api.lsp.HyperlinkLocation;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.netbeans.modules.editor.java.GoToSupport;
import org.netbeans.modules.editor.java.GoToSupport.Context;
import org.netbeans.modules.editor.java.GoToSupport.GoToTarget;
import org.netbeans.modules.gsf.testrunner.ui.api.TestMethodController.TestMethod;
import org.netbeans.modules.java.completion.JavaDocumentationTask;
import org.netbeans.modules.java.editor.base.fold.JavaElementFoldVisitor;
import org.netbeans.modules.java.editor.base.fold.JavaElementFoldVisitor.FoldCreator;
import org.netbeans.modules.java.editor.base.semantic.MarkOccurrencesHighlighterBase;
import org.netbeans.modules.java.editor.codegen.GeneratorUtils;
import org.netbeans.modules.java.editor.options.MarkOccurencesSettings;
import org.netbeans.modules.java.editor.overridden.ComputeOverriders;
import org.netbeans.modules.java.editor.overridden.ComputeOverriding;
import org.netbeans.modules.java.editor.overridden.ElementDescription;
import org.netbeans.modules.java.hints.errors.CreateFixBase;
import org.netbeans.modules.java.hints.errors.ImportClass;
import org.netbeans.modules.java.hints.infrastructure.CreatorBasedLazyFixList;
import org.netbeans.modules.java.hints.infrastructure.ErrorHintsProvider;
import org.netbeans.modules.java.hints.introduce.IntroduceFixBase;
import org.netbeans.modules.java.hints.introduce.IntroduceHint;
import org.netbeans.modules.java.hints.introduce.IntroduceKind;
import org.netbeans.modules.java.hints.project.IncompleteClassPath;
import org.netbeans.modules.java.hints.spiimpl.JavaFixImpl;
import org.netbeans.modules.java.hints.spiimpl.hints.HintsInvoker;
import org.netbeans.modules.java.hints.spiimpl.options.HintsSettings;
import org.netbeans.modules.java.lsp.server.LspServerState;
import org.netbeans.modules.java.lsp.server.Utils;
import org.netbeans.modules.java.lsp.server.debugging.utils.ErrorUtilities;
import org.netbeans.modules.java.testrunner.ui.spi.ComputeTestMethods;
import org.netbeans.modules.parsing.api.ParserManager;
import org.netbeans.modules.parsing.api.ResultIterator;
import org.netbeans.modules.parsing.api.Source;
import org.netbeans.modules.parsing.api.UserTask;
import org.netbeans.modules.parsing.impl.indexing.implspi.ActiveDocumentProvider.IndexingAware;
import org.netbeans.modules.parsing.spi.ParseException;
import org.netbeans.modules.parsing.spi.SchedulerEvent;
import org.netbeans.modules.refactoring.api.Problem;
import org.netbeans.modules.refactoring.api.RefactoringElement;
import org.netbeans.modules.refactoring.api.RefactoringSession;
import org.netbeans.modules.refactoring.api.RenameRefactoring;
import org.netbeans.modules.refactoring.api.WhereUsedQuery;
import org.netbeans.modules.refactoring.api.impl.APIAccessor;
import org.netbeans.modules.refactoring.api.impl.SPIAccessor;
import org.netbeans.modules.refactoring.java.spi.hooks.JavaModificationResult;
import org.netbeans.modules.refactoring.plugins.FileRenamePlugin;
import org.netbeans.modules.refactoring.spi.RefactoringCommit;
import org.netbeans.modules.refactoring.spi.RefactoringElementImplementation;
import org.netbeans.modules.refactoring.spi.Transaction;
import org.netbeans.spi.editor.hints.EnhancedFix;
import org.netbeans.spi.editor.hints.ErrorDescription;
import org.netbeans.spi.editor.hints.Fix;
import org.netbeans.spi.editor.hints.LazyFixList;
import org.netbeans.spi.editor.hints.Severity;
import org.netbeans.spi.java.hints.JavaFix;
import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileObject;
import org.openide.text.NbDocument;
import org.openide.text.PositionBounds;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.RequestProcessor;
import org.openide.util.WeakSet;
import org.openide.util.lookup.Lookups;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author lahvac
*/
public class TextDocumentServiceImpl implements TextDocumentService, LanguageClientAware {
private static final Logger LOG = Logger.getLogger(TextDocumentServiceImpl.class.getName());
private static final RequestProcessor BACKGROUND_TASKS = new RequestProcessor(TextDocumentServiceImpl.class.getName(), 1, false, false);
private static final RequestProcessor WORKER = new RequestProcessor(TextDocumentServiceImpl.class.getName(), 1, false, false);
/**
* File URIs touched / queried by the client.
*/
private Map<String, Instant> knownFiles = new HashMap<>();
/**
* Documents actually opened by the client.
*/
private final Map<String, Document> openedDocuments = new ConcurrentHashMap<>();
private final Map<String, RequestProcessor.Task> diagnosticTasks = new HashMap<>();
private final LspServerState server;
private NbCodeLanguageClient client;
TextDocumentServiceImpl(LspServerState server) {
this.server = server;
Lookup.getDefault().lookup(RefreshDocument.class).register(this);
}
private void reRunDiagnostics() {
Set<String> documents = new HashSet<>(openedDocuments.keySet());
for (String doc : documents) {
runDiagnoticTasks(doc);
}
}
@ServiceProvider(service=IndexingAware.class, position=0)
public static final class RefreshDocument implements IndexingAware {
private final Set<TextDocumentServiceImpl> delegates = new WeakSet<>();
public synchronized void register(TextDocumentServiceImpl delegate) {
delegates.add(delegate);
}
@Override
public void indexingComplete(Set<URL> indexedRoots) {
TextDocumentServiceImpl[] delegates;
synchronized (this) {
delegates = this.delegates.toArray(new TextDocumentServiceImpl[this.delegates.size()]);
}
for (TextDocumentServiceImpl delegate : delegates) {
delegate.reRunDiagnostics();
}
}
}
private List<Completion> lastCompletions = null;
@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams params) {
lastCompletions = new ArrayList<>();
AtomicInteger index = new AtomicInteger(0);
final CompletionList completionList = new CompletionList();
// shortcut: if the projects are not yet initialized, return empty:
if (server.openedProjects().getNow(null) == null) {
return CompletableFuture.completedFuture(Either.forRight(completionList));
}
try {
String uri = params.getTextDocument().getUri();
FileObject file = fromURI(uri);
if (file == null) {
return CompletableFuture.completedFuture(Either.forRight(completionList));
}
EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
Document doc = ec.openDocument();
final int caret = Utils.getOffset(doc, params.getPosition());
List<CompletionItem> items = new ArrayList<>();
Completion.Context context = params.getContext() != null
? new Completion.Context(Completion.TriggerKind.valueOf(params.getContext().getTriggerKind().name()),
params.getContext().getTriggerCharacter() == null || params.getContext().getTriggerCharacter().isEmpty() ? null : params.getContext().getTriggerCharacter().charAt(0))
: null;
boolean isComplete = Completion.collect(doc, caret, context, completion -> {
CompletionItem item = new CompletionItem(completion.getLabel());
if (completion.getKind() != null) {
item.setKind(CompletionItemKind.valueOf(completion.getKind().name()));
}
if (completion.getTags() != null) {
item.setTags(completion.getTags().stream().map(tag -> CompletionItemTag.valueOf(tag.name())).collect(Collectors.toList()));
}
if (completion.getDetail() != null && completion.getDetail().isDone()) {
item.setDetail(completion.getDetail().getNow(null));
}
if (completion.getDocumentation() != null && completion.getDocumentation().isDone()) {
String documentation = completion.getDocumentation().getNow(null);
if (documentation != null) {
MarkupContent markup = new MarkupContent();
markup.setKind("markdown");
markup.setValue(html2MD(documentation));
item.setDocumentation(markup);
}
}
if (completion.isPreselect()) {
item.setPreselect(true);
}
item.setSortText(completion.getSortText());
item.setFilterText(completion.getFilterText());
item.setInsertText(completion.getInsertText());
if (completion.getInsertTextFormat() != null) {
item.setInsertTextFormat(InsertTextFormat.valueOf(completion.getInsertTextFormat().name()));
}
org.netbeans.api.lsp.TextEdit edit = completion.getTextEdit();
if (edit != null) {
item.setTextEdit(new TextEdit(new Range(Utils.createPosition(file, edit.getStartOffset()), Utils.createPosition(file, edit.getEndOffset())), edit.getNewText()));
}
if (completion.getAdditionalTextEdits() != null && completion.getAdditionalTextEdits().isDone()) {
List<org.netbeans.api.lsp.TextEdit> additionalTextEdits = completion.getAdditionalTextEdits().getNow(null);
if (additionalTextEdits != null) {
item.setAdditionalTextEdits(additionalTextEdits.stream().map(ed -> {
return new TextEdit(new Range(Utils.createPosition(file, ed.getStartOffset()), Utils.createPosition(file, ed.getEndOffset())), ed.getNewText());
}).collect(Collectors.toList()));
}
}
if (completion.getCommitCharacters() != null) {
item.setCommitCharacters(completion.getCommitCharacters().stream().map(ch -> ch.toString()).collect(Collectors.toList()));
}
lastCompletions.add(completion);
item.setData(new CompletionData(uri, index.getAndIncrement()));
items.add(item);
});
if (!isComplete) {
completionList.setIsIncomplete(true);
}
completionList.setItems(items);
return CompletableFuture.completedFuture(Either.forRight(completionList));
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
public static final class CompletionData {
public String uri;
public int index;
public CompletionData() {
}
public CompletionData(String uri, int index) {
this.uri = uri;
this.index = index;
}
@Override
public String toString() {
return "CompletionData{" + "uri=" + uri + ", index=" + index + '}';
}
}
@Override
public void connect(LanguageClient client) {
this.client = (NbCodeLanguageClient)client;
}
private static final RequestProcessor JAVADOC_WORKER = new RequestProcessor(TextDocumentServiceImpl.class.getName() + ".javadoc", 1);
@Override
public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem ci) {
JsonObject rawData = (JsonObject) ci.getData();
if (rawData != null) {
CompletionData data = new Gson().fromJson(rawData, CompletionData.class);
Completion completion = lastCompletions.get(data.index);
if (completion != null) {
FileObject file = fromURI(data.uri);
if (file != null) {
CompletableFuture<CompletionItem> result = new CompletableFuture<>();
JAVADOC_WORKER.post(() -> {
if (completion.getDetail() != null) {
try {
String detail = completion.getDetail().get();
if (detail != null) {
ci.setDetail(detail);
}
} catch (Exception ex) {
}
}
if (completion.getDocumentation() != null) {
try {
String documentation = completion.getDocumentation().get();
if (documentation != null) {
MarkupContent markup = new MarkupContent();
markup.setKind("markdown");
markup.setValue(html2MD(documentation));
ci.setDocumentation(markup);
}
} catch (Exception ex) {
}
}
if (completion.getAdditionalTextEdits() != null) {
try {
List<org.netbeans.api.lsp.TextEdit> additionalTextEdits = completion.getAdditionalTextEdits().get();
if (additionalTextEdits != null && !additionalTextEdits.isEmpty()) {
ci.setAdditionalTextEdits(additionalTextEdits.stream().map(ed -> {
return new TextEdit(new Range(Utils.createPosition(file, ed.getStartOffset()), Utils.createPosition(file, ed.getEndOffset())), ed.getNewText());
}).collect(Collectors.toList()));
}
} catch (Exception ex) {
}
}
result.complete(ci);
});
return result;
}
}
}
return CompletableFuture.completedFuture(ci);
}
public static String html2MD(String html) {
int idx = html.indexOf("<p id=\"not-found\">"); // strip "No Javadoc found" message
return FlexmarkHtmlConverter.builder().build().convert(idx >= 0 ? html.substring(0, idx) : html).replaceAll("<br />[ \n]*$", "");
}
@Override
public CompletableFuture<Hover> hover(HoverParams params) {
// shortcut: if the projects are not yet initialized, return empty:
if (server.openedProjects().getNow(null) == null) {
return CompletableFuture.completedFuture(null);
}
try {
String uri = params.getTextDocument().getUri();
FileObject file = fromURI(uri);
if (file == null) {
return CompletableFuture.completedFuture(null);
}
EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
Document doc = ec.openDocument();
final JavaDocumentationTask<Future<String>> task = JavaDocumentationTask.create(Utils.getOffset(doc, params.getPosition()), null, new JavaDocumentationTask.DocumentationFactory<Future<String>>() {
@Override
public Future<String> create(CompilationInfo compilationInfo, Element element, Callable<Boolean> cancel) {
return ElementJavadoc.create(compilationInfo, element, cancel).getTextAsync();
}
}, () -> false);
ParserManager.parse(Collections.singletonList(Source.create(doc)), new UserTask() {
@Override
public void run(ResultIterator resultIterator) throws Exception {
task.run(resultIterator);
}
});
Future<String> futureJavadoc = task.getDocumentation();
CompletableFuture<Hover> result = new CompletableFuture<Hover>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return futureJavadoc != null && futureJavadoc.cancel(mayInterruptIfRunning) && super.cancel(mayInterruptIfRunning);
}
};
JAVADOC_WORKER.post(() -> {
try {
String javadoc = futureJavadoc != null ? futureJavadoc.get() : null;
if (javadoc != null) {
MarkupContent markup = new MarkupContent();
markup.setKind("markdown");
markup.setValue(html2MD(javadoc));
result.complete(new Hover(markup));
} else {
result.complete(null);
}
} catch (ExecutionException | InterruptedException ex) {
result.completeExceptionally(ex);
}
});
return result;
} catch (IOException | ParseException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public CompletableFuture<SignatureHelp> signatureHelp(SignatureHelpParams params) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> definition(DefinitionParams params) {
try {
String uri = params.getTextDocument().getUri();
Document doc = openedDocuments.get(uri);
if (doc != null) {
FileObject file = Utils.fromUri(uri);
if (file != null) {
int offset = Utils.getOffset(doc, params.getPosition());
return HyperlinkLocation.resolve(doc, offset).thenApply(locs -> {
return Either.forLeft(locs.stream().map(location -> {
FileObject fo = location.getFileObject();
return new Location(Utils.toUri(fo), new Range(Utils.createPosition(fo, location.getStartOffset()), Utils.createPosition(fo, location.getEndOffset())));
}).collect(Collectors.toList()));
});
}
}
} catch (MalformedURLException ex) {
client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
}
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> implementation(ImplementationParams params) {
// shortcut: if the projects are not yet initialized, return empty:
if (server.openedProjects().getNow(null) == null) {
return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
}
String uri = params.getTextDocument().getUri();
JavaSource js = getJavaSource(uri);
if (js == null) {
return CompletableFuture.completedFuture(Either.forLeft(Collections.emptyList()));
}
List<GoToTarget> targets = new ArrayList<>();
LineMap[] thisFileLineMap = new LineMap[1];
try {
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
Document doc = cc.getSnapshot().getSource().getDocument(true);
int offset = Utils.getOffset(doc, params.getPosition());
Element el = null;
Context context = GoToSupport.resolveContext(cc, doc, offset, false, false);
if (context == null) {
TreePath tp = cc.getTreeUtilities().pathFor(offset);
if (tp.getLeaf().getKind() == Kind.MODIFIERS) tp = tp.getParentPath();
int[] elementNameSpan = null;
switch (tp.getLeaf().getKind()) {
case ANNOTATION_TYPE:
case CLASS:
case ENUM:
case INTERFACE:
elementNameSpan = cc.getTreeUtilities().findNameSpan((ClassTree) tp.getLeaf());
break;
case METHOD:
elementNameSpan = cc.getTreeUtilities().findNameSpan((MethodTree) tp.getLeaf());
break;
}
if (elementNameSpan != null && offset <= elementNameSpan[1]) {
el = cc.getTrees().getElement(tp);
}
} else if (EnumSet.of(ElementKind.METHOD, ElementKind.ANNOTATION_TYPE, ElementKind.CLASS, ElementKind.ENUM, ElementKind.INTERFACE).contains(context.resolved.getKind())) {
el = context.resolved;
}
if (el != null) {
TypeElement type = el.getKind() == ElementKind.METHOD ? (TypeElement) el.getEnclosingElement() : (TypeElement) el;
ExecutableElement method = el.getKind() == ElementKind.METHOD ? (ExecutableElement) el : null;
Map<ElementHandle<? extends Element>, List<ElementDescription>> overriding = new ComputeOverriders(new AtomicBoolean()).process(cc, type, method, true);
List<ElementDescription> overridingMethods = overriding != null ? overriding.get(ElementHandle.create(el)) : null;
if (overridingMethods != null) {
for (ElementDescription ed : overridingMethods) {
Element elm = ed.getHandle().resolve(cc);
TreePath tp = cc.getTrees().getPath(elm);
long startPos = tp != null && cc.getCompilationUnit() == tp.getCompilationUnit() ? cc.getTrees().getSourcePositions().getStartPosition(cc.getCompilationUnit(), tp.getLeaf()) : -1;
if (startPos >= 0) {
long endPos = cc.getTrees().getSourcePositions().getEndPosition(cc.getCompilationUnit(), tp.getLeaf());
targets.add(new GoToTarget(cc.getSnapshot().getOriginalOffset((int) startPos),
cc.getSnapshot().getOriginalOffset((int) endPos), GoToSupport.getNameSpan(tp.getLeaf(), cc.getTreeUtilities()),
null, null, null, ed.getDisplayName(), true));
} else {
TypeElement te = elm != null ? cc.getElementUtilities().outermostTypeElement(elm) : null;
targets.add(new GoToTarget(-1, -1, null, cc.getClasspathInfo(),ed.getHandle(),
te != null ? te.getQualifiedName().toString().replace('.', '/') + ".class" : null,
ed.getDisplayName(), true));
}
}
}
}
thisFileLineMap[0] = cc.getCompilationUnit().getLineMap();
}, true);
} catch (IOException ex) {
//TODO: include stack trace:
client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
CompletableFuture<Location>[] futures = targets.stream().map(target -> gotoTarget2Location(uri, target, thisFileLineMap[0])).toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures).thenApply(value -> {
ArrayList<Location> locations = new ArrayList<>(futures.length);
for (CompletableFuture<Location> future : futures) {
Location location = future.getNow(null);
if (location != null) {
locations.add(location);
}
}
return Either.forLeft(locations);
});
}
@Override
public CompletableFuture<List<? extends Location>> references(ReferenceParams params) {
final Project[] projects = server.openedProjects().getNow(null);
// shortcut: if the projects are not yet initialized, return empty:
if (projects == null) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
AtomicBoolean cancel = new AtomicBoolean();
Runnable[] cancelCallback = new Runnable[1];
CompletableFuture<List<? extends Location>> result = new CompletableFuture<List<? extends Location>>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
cancel.set(mayInterruptIfRunning);
if (cancelCallback[0] != null) {
cancelCallback[0].run();
}
return super.cancel(mayInterruptIfRunning);
}
};
WORKER.post(() -> {
JavaSource js = getJavaSource(params.getTextDocument().getUri());
if (js == null) {
result.complete(new ArrayList<>());
return;
}
try {
WhereUsedQuery[] query = new WhereUsedQuery[1];
List<Location> locations = new ArrayList<>();
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
if (cancel.get()) return ;
Document doc = cc.getSnapshot().getSource().getDocument(true);
TreePath path = cc.getTreeUtilities().pathFor(Utils.getOffset(doc, params.getPosition()));
if (params.getContext().isIncludeDeclaration()) {
Element decl = cc.getTrees().getElement(path);
if (decl != null) {
TreePath declPath = cc.getTrees().getPath(decl);
if (declPath != null && cc.getCompilationUnit() == declPath.getCompilationUnit()) {
Range range = declarationRange(cc, declPath);
if (range != null) {
locations.add(new Location(Utils.toUri(cc.getFileObject()),
range));
}
} else {
ElementHandle<Element> declHandle = ElementHandle.create(decl);
FileObject sourceFile = SourceUtils.getFile(declHandle, cc.getClasspathInfo());
JavaSource source = sourceFile != null ? JavaSource.forFileObject(sourceFile) : null;
if (source != null) {
source.runUserActionTask(nestedCC -> {
nestedCC.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
Element declHandle2 = declHandle.resolve(nestedCC);
TreePath declPath2 = declHandle2 != null ? nestedCC.getTrees().getPath(declHandle2) : null;
if (declPath2 != null) {
Range range = declarationRange(nestedCC, declPath2);
if (range != null) {
locations.add(new Location(Utils.toUri(nestedCC.getFileObject()),
range));
}
}
}, true);
}
}
}
}
query[0] = new WhereUsedQuery(Lookups.singleton(TreePathHandle.create(path, cc)));
}, true);
if (cancel.get()) return ;
List<FileObject> sourceRoots = new ArrayList<>();
for (Project project : projects) {
Sources sources = ProjectUtils.getSources(project);
for (SourceGroup sourceGroup : sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA)) {
sourceRoots.add(sourceGroup.getRootFolder());
}
}
if (!sourceRoots.isEmpty()) {
query[0].getContext().add(org.netbeans.modules.refactoring.api.Scope.create(sourceRoots, null, null));
}
cancelCallback[0] = () -> query[0].cancelRequest();
RefactoringSession refactoring = RefactoringSession.create("FindUsages");
Problem p;
p = query[0].checkParameters();
if (cancel.get()) return ;
if (p != null && p.isFatal()) {
ErrorUtilities.completeExceptionally(result, p.getMessage(), ResponseErrorCode.UnknownErrorCode);
return ;
}
p = query[0].preCheck();
if (p != null && p.isFatal()) {
ErrorUtilities.completeExceptionally(result, p.getMessage(), ResponseErrorCode.UnknownErrorCode);
return ;
}
if (cancel.get()) return ;
p = query[0].prepare(refactoring);
if (p != null && p.isFatal()) {
ErrorUtilities.completeExceptionally(result, p.getMessage(), ResponseErrorCode.UnknownErrorCode);
return ;
}
for (RefactoringElement re : refactoring.getRefactoringElements()) {
if (cancel.get()) return ;
locations.add(new Location(Utils.toUri(re.getParentFile()), toRange(re.getPosition())));
}
refactoring.finished();
result.complete(locations);
} catch (Throwable ex) {
result.completeExceptionally(ex);
}
});
return result;
}
private static Range declarationRange(CompilationInfo info, TreePath tp) {
Tree t = tp.getLeaf();
int[] span;
if (TreeUtilities.CLASS_TREE_KINDS.contains(t.getKind())) {
span = info.getTreeUtilities().findNameSpan((ClassTree) t);
} else if (t.getKind() == Kind.VARIABLE) {
span = info.getTreeUtilities().findNameSpan((VariableTree) t);
} else if (t.getKind() == Kind.METHOD) {
span = info.getTreeUtilities().findNameSpan((MethodTree) t);
if (span == null) {
span = info.getTreeUtilities().findNameSpan((ClassTree) tp.getParentPath().getLeaf());
}
} else {
return null;
}
if (span == null) {
return null;
}
return new Range(Utils.createPosition(info.getCompilationUnit().getLineMap(), span[0]),
Utils.createPosition(info.getCompilationUnit().getLineMap(), span[1]));
}
private static Range toRange(PositionBounds bounds) throws IOException {
return new Range(new Position(bounds.getBegin().getLine(),
bounds.getBegin().getColumn()),
new Position(bounds.getEnd().getLine(),
bounds.getEnd().getColumn()));
}
@Override
public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(DocumentHighlightParams params) {
class MOHighligther extends MarkOccurrencesHighlighterBase {
@Override
protected void process(CompilationInfo arg0, Document arg1, SchedulerEvent arg2) {
throw new UnsupportedOperationException("Should not be called.");
}
@Override
public List<int[]> processImpl(CompilationInfo info, Preferences node, Document doc, int caretPosition) {
return super.processImpl(info, node, doc, caretPosition);
}
}
Preferences node = MarkOccurencesSettings.getCurrentNode();
JavaSource js = getJavaSource(params.getTextDocument().getUri());
List<DocumentHighlight> result = new ArrayList<>();
if (js == null) {
return CompletableFuture.completedFuture(result);
}
try {
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
Document doc = cc.getSnapshot().getSource().getDocument(true);
int offset = Utils.getOffset(doc, params.getPosition());
List<int[]> spans = new MOHighligther().processImpl(cc, node, doc, offset);
if (spans != null) {
for (int[] span : spans) {
result.add(new DocumentHighlight(new Range(Utils.createPosition(cc.getCompilationUnit(), span[0]),
Utils.createPosition(cc.getCompilationUnit(), span[1]))));
}
}
}, true);
} catch (IOException ex) {
//TODO: include stack trace:
client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
return CompletableFuture.completedFuture(result);
}
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(DocumentSymbolParams params) {
// shortcut: if the projects are not yet initialized, return empty:
if (server.openedProjects().getNow(null) == null) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
JavaSource js = getJavaSource(params.getTextDocument().getUri());
if (js == null) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
List<Either<SymbolInformation, DocumentSymbol>> result = new ArrayList<>();
try {
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
for (Element tel : cc.getTopLevelElements()) {
DocumentSymbol ds = element2DocumentSymbol(cc, tel);
if (ds != null)
result.add(Either.forRight(ds));
}
}, true);
} catch (IOException ex) {
//TODO: include stack trace:
client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
return CompletableFuture.completedFuture(result);
}
private DocumentSymbol element2DocumentSymbol(CompilationInfo info, Element el) throws BadLocationException {
TreePath path = info.getTrees().getPath(el);
if (path == null)
return null;
Range range = Utils.treeRange(info, path.getLeaf());
if (range == null)
return null;
List<DocumentSymbol> children = new ArrayList<>();
for (Element c : el.getEnclosedElements()) {
DocumentSymbol ds = element2DocumentSymbol(info, c);
if (ds != null) {
children.add(ds);
}
}
String simpleName;
if (el.getKind() == ElementKind.CONSTRUCTOR) {
simpleName = el.getEnclosingElement().getSimpleName().toString();
} else {
simpleName = el.getSimpleName().toString();
}
return new DocumentSymbol(simpleName, Utils.elementKind2SymbolKind(el.getKind()), range, range, null, children);
}
@Override
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params) {
// shortcut: if the projects are not yet initialized, return empty:
if (server.openedProjects().getNow(null) == null) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
Document doc = openedDocuments.get(params.getTextDocument().getUri());
if (doc == null) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
JavaSource js = JavaSource.forDocument(doc);
if (js == null) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
Map<String, ErrorDescription> id2Errors = (Map<String, ErrorDescription>) doc.getProperty("lsp-errors");
List<Either<Command, CodeAction>> result = new ArrayList<>();
if (id2Errors != null) {
for (Diagnostic diag : params.getContext().getDiagnostics()) {
ErrorDescription err = id2Errors.get(diag.getCode().getLeft());
if (err == null) {
client.logMessage(new MessageParams(MessageType.Log, "Cannot resolve error, code: " + diag.getCode().getLeft()));
continue;
}
TreePathHandle[] topLevelHandle = new TreePathHandle[1];
LazyFixList lfl = err.getFixes();
if (lfl instanceof CreatorBasedLazyFixList) {
try {
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
((CreatorBasedLazyFixList) lfl).compute(cc, new AtomicBoolean());
topLevelHandle[0] = TreePathHandle.create(new TreePath(cc.getCompilationUnit()), cc);
}, true);
} catch (IOException ex) {
//TODO: include stack trace:
client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
}
List<Fix> fixes = sortFixes(lfl.getFixes());
//TODO: ordering
for (Fix f : fixes) {
if (f instanceof IncompleteClassPath.ResolveFix) {
CodeAction action = new CodeAction(f.getText());
action.setDiagnostics(Collections.singletonList(diag));
action.setKind(CodeActionKind.QuickFix);
action.setCommand(new Command(f.getText(), Server.JAVA_BUILD_WORKSPACE));
result.add(Either.forRight(action));
}
if (f instanceof ImportClass.FixImport) {
//TODO: FixImport is not a JavaFix, create one. Is there a better solution?
String text = f.getText();
CharSequence sortText = ((ImportClass.FixImport) f).getSortText();
ElementHandle<Element> toImport = ((ImportClass.FixImport) f).getToImport();
f = new JavaFix(topLevelHandle[0], sortText != null ? sortText.toString() : null) {
@Override
protected String getText() {
return text;
}
@Override
protected void performRewrite(JavaFix.TransformationContext ctx) throws Exception {
Element resolved = toImport.resolve(ctx.getWorkingCopy());
if (resolved == null) {
return ;
}
WorkingCopy copy = ctx.getWorkingCopy();
CompilationUnitTree cut = GeneratorUtilities.get(copy).addImports(
copy.getCompilationUnit(),
Collections.singleton(resolved)
);
copy.rewrite(copy.getCompilationUnit(), cut);
}
}.toEditorFix();
}
if (f instanceof JavaFixImpl) {
try {
JavaFix jf = ((JavaFixImpl) f).jf;
List<TextEdit> edits = modify2TextEdits(js, wc -> {
wc.toPhase(JavaSource.Phase.RESOLVED);
Map<FileObject, byte[]> resourceContentChanges = new HashMap<FileObject, byte[]>();
JavaFixImpl.Accessor.INSTANCE.process(jf, wc, true, resourceContentChanges, /*Ignored in editor:*/new ArrayList<>());
});
TextDocumentEdit te = new TextDocumentEdit(new VersionedTextDocumentIdentifier(params.getTextDocument().getUri(),
-1),
edits);
CodeAction action = new CodeAction(f.getText());
action.setDiagnostics(Collections.singletonList(diag));
action.setKind(CodeActionKind.QuickFix);
action.setEdit(new WorkspaceEdit(Collections.singletonList(Either.forLeft(te))));
result.add(Either.forRight(action));
} catch (IOException ex) {
//TODO: include stack trace:
client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
}
if (f instanceof CreateFixBase) {
try {
CreateFixBase cf = (CreateFixBase) f;
ModificationResult changes = cf.getModificationResult();
List<Either<TextDocumentEdit, ResourceOperation>> documentChanges = new ArrayList<>();
Set<File> newFiles = changes.getNewFiles();
if (newFiles.size() > 1) {
throw new IllegalStateException();
}
String newFilePath = null;
for (File newFile : newFiles) {
newFilePath = newFile.getPath();
documentChanges.add(Either.forRight(new CreateFile(newFilePath)));
}
outer: for (FileObject fileObject : changes.getModifiedFileObjects()) {
List<? extends ModificationResult.Difference> diffs = changes.getDifferences(fileObject);
if (diffs != null) {
List<TextEdit> edits = new ArrayList<>();
for (ModificationResult.Difference diff : diffs) {
String newText = diff.getNewText();
if (diff.getKind() == ModificationResult.Difference.Kind.CREATE) {
if (newFilePath != null) {
documentChanges.add(Either.forLeft(new TextDocumentEdit(new VersionedTextDocumentIdentifier(newFilePath, -1),
Collections.singletonList(new TextEdit(new Range(Utils.createPosition(fileObject, 0), Utils.createPosition(fileObject, 0)),
newText != null ? newText : "")))));
}
continue outer;
} else {
edits.add(new TextEdit(new Range(Utils.createPosition(fileObject, diff.getStartPosition().getOffset()),
Utils.createPosition(fileObject, diff.getEndPosition().getOffset())),
newText != null ? newText : ""));
}
}
documentChanges.add(Either.forLeft(new TextDocumentEdit(new VersionedTextDocumentIdentifier(Utils.toUri(fileObject), -1), edits)));
}
}
if (!documentChanges.isEmpty()) {
CodeAction codeAction = new CodeAction(f.getText());
codeAction.setKind(CodeActionKind.QuickFix);
codeAction.setEdit(new WorkspaceEdit(documentChanges));
result.add(Either.forRight(codeAction));
}
} catch (IOException ex) {
client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
}
}
}
}
try {
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
//code generators:
for (CodeGenerator codeGenerator : Lookup.getDefault().lookupAll(CodeGenerator.class)) {
for (CodeAction codeAction : codeGenerator.getCodeActions(cc, params)) {
result.add(Either.forRight(codeAction));
}