This is an automated email from the ASF dual-hosted git repository.
dbalek pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/netbeans.git
The following commit(s) were added to refs/heads/master by this push:
new b872ac4 LSP: various refactor bugfixes (#3196)
b872ac4 is described below
commit b872ac464730ef99e050d45bf3b3cedae87d0134
Author: Dusan Balek <[email protected]>
AuthorDate: Tue Oct 5 10:05:11 2021 +0200
LSP: various refactor bugfixes (#3196)
* GR-33924: Code completion partially broken in method bodies in latest
builds.
* GR-32319: Hover failed: ClassCastException: FilterDocument cannot be cast
to LineDocument.
* GR-33740: Using .class on a type completes with null on the end.
* GR-31747: JUnit tests that fail to initialise lead to false success state.
* GR-33741: Quick fix for checked exception should not add
java.util.logging.
* GR-33804: Null related message in Extract Superclass.
* GR-33785: Try/catch block with resources.
* GR-33778: Can't rename constructor.
* GR-33807: Generate toString method default template.
* GR-33789: VSCode is accepting moving inner class inside itself.
---
.../editor/java/JavaCompletionCollector.java | 4 +-
.../java/editor/codegen/ToStringGenerator.java | 12 +-
.../java/hints/errors/ErrorFixesFakeHint.java | 10 +
.../hints/errors/MagicSurroundWithTryCatchFix.java | 5 +-
.../java/hints/errors/SurroundWithTryCatchLog.form | 28 +-
.../java/hints/errors/SurroundWithTryCatchLog.java | 27 +-
...FixesFakeHintSURROUND_WITH_TRY_CATCH.properties | 22 ++
.../netbeans/modules/java/lsp/server/Utils.java | 5 +-
.../ExtractSuperclassOrInterfaceRefactoring.java | 4 +-
.../server/protocol/TextDocumentServiceImpl.java | 349 +++++++++++----------
.../java/lsp/server/protocol/ServerTest.java | 23 +-
java/java.lsp.server/vscode/src/testAdapter.ts | 9 +
.../java/plugins/MoveFileRefactoringPlugin.java | 5 +
13 files changed, 298 insertions(+), 205 deletions(-)
diff --git
a/java/java.editor/src/org/netbeans/modules/editor/java/JavaCompletionCollector.java
b/java/java.editor/src/org/netbeans/modules/editor/java/JavaCompletionCollector.java
index b6aae13..bab6cf2 100644
---
a/java/java.editor/src/org/netbeans/modules/editor/java/JavaCompletionCollector.java
+++
b/java/java.editor/src/org/netbeans/modules/editor/java/JavaCompletionCollector.java
@@ -180,7 +180,7 @@ public class JavaCompletionCollector implements
CompletionCollector {
return CompletionCollector.newBuilder(kwd)
.kind(Completion.Kind.Keyword)
.sortText(String.format("%04d%s", smartType ? 670 : 1670,
kwd))
- .insertText(kwd + postfix)
+ .insertText(postfix != null ? kwd + postfix : kwd)
.insertTextFormat(Completion.TextFormat.PlainText)
.build();
}
@@ -1095,7 +1095,7 @@ public class JavaCompletionCollector implements
CompletionCollector {
if (t1.getKind().isPrimitive() &&
types.isSameType(types.boxedClass((PrimitiveType)t1).asType(), t2)) {
return true;
}
- return t2.getKind().isPrimitive() && types.isSameType(t1,
types.boxedClass((PrimitiveType)t1).asType());
+ return t2.getKind().isPrimitive() && types.isSameType(t1,
types.boxedClass((PrimitiveType)t2).asType());
}
private static boolean isOfKind(Element e, EnumSet<ElementKind> kinds)
{
diff --git
a/java/java.editor/src/org/netbeans/modules/java/editor/codegen/ToStringGenerator.java
b/java/java.editor/src/org/netbeans/modules/java/editor/codegen/ToStringGenerator.java
index c855d3c..a0dbf39 100644
---
a/java/java.editor/src/org/netbeans/modules/java/editor/codegen/ToStringGenerator.java
+++
b/java/java.editor/src/org/netbeans/modules/java/editor/codegen/ToStringGenerator.java
@@ -258,18 +258,20 @@ public class ToStringGenerator implements CodeGenerator {
NewClassTree newStringBuilder = make.NewClass(null,
Collections.emptyList(), stringBuilder, Collections.emptyList(), null);
VariableTree variable =
make.Variable(make.Modifiers(Collections.emptySet()), "sb", stringBuilder,
newStringBuilder); // NOI18N
statements.add(variable); // StringBuilder sb = new StringBuilder();
-
IdentifierTree varName = make.Identifier(variable.getName());
+ statements.add(make.ExpressionStatement(createAppendInvocation( //
sb.append("typeName{");
+ make,
+ varName,
+ Collections.singletonList(make.Literal(typeName + '{'))
+ )));
boolean first = true;
for (VariableElement variableElement : fields) {
StringBuilder sb = new StringBuilder();
- if (first) {
- sb.append(typeName).append('{');
- } else {
+ if (!first) {
sb.append(", "); // NOI18N
}
sb.append(variableElement.getSimpleName().toString()).append('=');
- // sb.append("typeName{fieldName=").append(fieldName); or
sb.append(", fieldName=").append(fieldName);
+ // sb.append("fieldName=").append(fieldName); or sb.append(",
fieldName=").append(fieldName);
statements.add(make.ExpressionStatement(createAppendInvocation(
make,
createAppendInvocation(
diff --git
a/java/java.hints/src/org/netbeans/modules/java/hints/errors/ErrorFixesFakeHint.java
b/java/java.hints/src/org/netbeans/modules/java/hints/errors/ErrorFixesFakeHint.java
index 5bec418..d28e2ed 100644
---
a/java/java.hints/src/org/netbeans/modules/java/hints/errors/ErrorFixesFakeHint.java
+++
b/java/java.hints/src/org/netbeans/modules/java/hints/errors/ErrorFixesFakeHint.java
@@ -84,6 +84,7 @@ public class ErrorFixesFakeHint extends AbstractHint {
customizer = new SurroundWithTryCatchLog(node);
setRethrow(node, isRethrow(node));
setRethrowAsRuntimeException(node,
isRethrowAsRuntimeException(node));
+ setPrintStackTrace(node, isPrintStackTrace(node));
setUseExceptions(node, isUseExceptions(node));
setUseLogger(node, isUseLogger(node));
break;
@@ -162,6 +163,14 @@ public class ErrorFixesFakeHint extends AbstractHint {
p.putBoolean(SURROUND_USE_EXCEPTIONS, v);
}
+ public static boolean isPrintStackTrace(Preferences p) {
+ return p.getBoolean(SURROUND_PRINT_STACK_TRACE, true);
+ }
+
+ public static void setPrintStackTrace(Preferences p, boolean v) {
+ p.putBoolean(SURROUND_PRINT_STACK_TRACE, v);
+ }
+
public static boolean isRethrowAsRuntimeException(Preferences p) {
return p.getBoolean(SURROUND_RETHROW_AS_RUNTIME, false);
}
@@ -188,6 +197,7 @@ public class ErrorFixesFakeHint extends AbstractHint {
public static final String LOCAL_VARIABLES_INPLACE =
"create-local-variables-in-place"; // NOI18N
public static final String SURROUND_USE_EXCEPTIONS =
"surround-try-catch-org-openide-util-Exceptions"; // NOI18N
+ public static final String SURROUND_PRINT_STACK_TRACE =
"surround-try-catch-printStackTrace"; // NOI18N
public static final String SURROUND_RETHROW_AS_RUNTIME =
"surround-try-catch-rethrow-runtime"; // NOI18N
public static final String SURROUND_RETHROW =
"surround-try-catch-rethrow"; // NOI18N
public static final String SURROUND_USE_JAVA_LOGGER =
"surround-try-catch-java-util-logging-Logger"; // NOI18N
diff --git
a/java/java.hints/src/org/netbeans/modules/java/hints/errors/MagicSurroundWithTryCatchFix.java
b/java/java.hints/src/org/netbeans/modules/java/hints/errors/MagicSurroundWithTryCatchFix.java
index 625d91b..624dd66 100644
---
a/java/java.hints/src/org/netbeans/modules/java/hints/errors/MagicSurroundWithTryCatchFix.java
+++
b/java/java.hints/src/org/netbeans/modules/java/hints/errors/MagicSurroundWithTryCatchFix.java
@@ -444,6 +444,9 @@ final class MagicSurroundWithTryCatchFix extends JavaFix {
}
private static StatementTree
createPrintStackTraceStatement(CompilationInfo info, TreeMaker make, String
name) {
+ if
(!ErrorFixesFakeHint.isPrintStackTrace(ErrorFixesFakeHint.getPreferences(info.getFileObject(),
FixKind.SURROUND_WITH_TRY_CATCH))) {
+ return null;
+ }
return
make.ExpressionStatement(make.MethodInvocation(Collections.<ExpressionTree>emptyList(),
make.MemberSelect(make.Identifier(name), "printStackTrace"),
Collections.<ExpressionTree>emptyList()));
}
@@ -466,7 +469,7 @@ final class MagicSurroundWithTryCatchFix extends JavaFix {
logStatement = createPrintStackTraceStatement(info, make, name);
}
- return
make.Catch(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name,
make.Type(type), null), make.Block(Collections.singletonList(logStatement),
false));
+ return
make.Catch(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name,
make.Type(type), null), make.Block(logStatement != null ?
Collections.singletonList(logStatement) : Collections.emptyList(), false));
}
static List<CatchTree> createCatches(WorkingCopy info, TreeMaker make,
List<TypeMirrorHandle> thandles, TreePath currentPath) {
diff --git
a/java/java.hints/src/org/netbeans/modules/java/hints/errors/SurroundWithTryCatchLog.form
b/java/java.hints/src/org/netbeans/modules/java/hints/errors/SurroundWithTryCatchLog.form
index 4946c0d..6db149a 100644
---
a/java/java.hints/src/org/netbeans/modules/java/hints/errors/SurroundWithTryCatchLog.form
+++
b/java/java.hints/src/org/netbeans/modules/java/hints/errors/SurroundWithTryCatchLog.form
@@ -1,4 +1,4 @@
-<?xml version="1.1" encoding="UTF-8" ?>
+<?xml version="1.0" encoding="UTF-8" ?>
<!--
@@ -46,13 +46,13 @@
<Group type="103" groupAlignment="0" attributes="0">
<Component id="logger" alignment="0" min="-2"
max="-2" attributes="0"/>
<Component id="exceptions" alignment="0" min="-2"
max="-2" attributes="0"/>
+ <Component id="printStackTrace" alignment="0"
min="-2" max="-2" attributes="0"/>
<Component id="rethrowRuntime" alignment="0"
min="-2" max="-2" attributes="0"/>
<Component id="rethrow" alignment="0" min="-2"
max="-2" attributes="0"/>
- <Component id="printStackTrace" alignment="0"
min="-2" max="-2" attributes="0"/>
</Group>
</Group>
</Group>
- <EmptySpace pref="57" max="-2" attributes="0"/>
+ <EmptySpace min="-2" pref="221" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
@@ -66,17 +66,24 @@
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="logger" min="-2" max="-2" attributes="0"/>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
+ <Component id="printStackTrace" min="-2" max="-2"
attributes="0"/>
+ <EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="rethrowRuntime" min="-2" max="-2" attributes="0"/>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="rethrow" min="-2" max="-2" attributes="0"/>
- <EmptySpace type="unrelated" max="-2" attributes="0"/>
- <Component id="printStackTrace" min="-2" max="-2"
attributes="0"/>
<EmptySpace pref="134" max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String"
editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
+ <ResourceString
bundle="org/netbeans/modules/java/hints/errors/Bundle.properties"
key="SurroundWithTryCatchLog.jLabel1.text"
replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
+ </Property>
+ </Properties>
+ </Component>
<Component class="javax.swing.JCheckBox" name="exceptions">
<Properties>
<Property name="selected" type="boolean" value="true"/>
@@ -111,19 +118,14 @@
<Property name="text" type="java.lang.String"
editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
<ResourceString
bundle="org/netbeans/modules/java/hints/errors/Bundle.properties"
key="SurroundWithTryCatchLog.printStackTrace.text"
replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
</Property>
- <Property name="enabled" type="boolean" value="false"/>
</Properties>
+ <Events>
+ <EventHandler event="actionPerformed"
listener="java.awt.event.ActionListener"
parameters="java.awt.event.ActionEvent"
handler="printStackTraceActionPerformed"/>
+ </Events>
<AuxValues>
<AuxValue name="generateMnemonicsCode" type="java.lang.Boolean"
value="true"/>
</AuxValues>
</Component>
- <Component class="javax.swing.JLabel" name="jLabel1">
- <Properties>
- <Property name="text" type="java.lang.String"
editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
- <ResourceString
bundle="org/netbeans/modules/java/hints/errors/Bundle.properties"
key="SurroundWithTryCatchLog.jLabel1.text"
replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
- </Property>
- </Properties>
- </Component>
<Component class="javax.swing.JCheckBox" name="rethrowRuntime">
<Properties>
<Property name="text" type="java.lang.String"
editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
diff --git
a/java/java.hints/src/org/netbeans/modules/java/hints/errors/SurroundWithTryCatchLog.java
b/java/java.hints/src/org/netbeans/modules/java/hints/errors/SurroundWithTryCatchLog.java
index e35b731..e11d37c 100644
---
a/java/java.hints/src/org/netbeans/modules/java/hints/errors/SurroundWithTryCatchLog.java
+++
b/java/java.hints/src/org/netbeans/modules/java/hints/errors/SurroundWithTryCatchLog.java
@@ -35,6 +35,7 @@ public class SurroundWithTryCatchLog extends
javax.swing.JPanel {
this.p = p;
exceptions.setSelected(ErrorFixesFakeHint.isUseExceptions(p));
logger.setSelected(ErrorFixesFakeHint.isUseLogger(p));
+ printStackTrace.setSelected(ErrorFixesFakeHint.isPrintStackTrace(p));
rethrowRuntime.setSelected(ErrorFixesFakeHint.isRethrowAsRuntimeException(p));
rethrow.setSelected(ErrorFixesFakeHint.isRethrow(p));
}
@@ -48,13 +49,15 @@ public class SurroundWithTryCatchLog extends
javax.swing.JPanel {
// <editor-fold defaultstate="collapsed" desc="Generated
Code">//GEN-BEGIN:initComponents
private void initComponents() {
+ jLabel1 = new javax.swing.JLabel();
exceptions = new javax.swing.JCheckBox();
logger = new javax.swing.JCheckBox();
printStackTrace = new javax.swing.JCheckBox();
- jLabel1 = new javax.swing.JLabel();
rethrowRuntime = new javax.swing.JCheckBox();
rethrow = new javax.swing.JCheckBox();
+
jLabel1.setText(org.openide.util.NbBundle.getBundle(SurroundWithTryCatchLog.class).getString("SurroundWithTryCatchLog.jLabel1.text"));
// NOI18N
+
exceptions.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(exceptions,
org.openide.util.NbBundle.getBundle(SurroundWithTryCatchLog.class).getString("SurroundWithTryCatchLog.exceptions.text"));
// NOI18N
exceptions.addActionListener(new java.awt.event.ActionListener() {
@@ -73,9 +76,11 @@ public class SurroundWithTryCatchLog extends
javax.swing.JPanel {
printStackTrace.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(printStackTrace,
org.openide.util.NbBundle.getBundle(SurroundWithTryCatchLog.class).getString("SurroundWithTryCatchLog.printStackTrace.text"));
// NOI18N
- printStackTrace.setEnabled(false);
-
-
jLabel1.setText(org.openide.util.NbBundle.getBundle(SurroundWithTryCatchLog.class).getString("SurroundWithTryCatchLog.jLabel1.text"));
// NOI18N
+ printStackTrace.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ printStackTraceActionPerformed(evt);
+ }
+ });
rethrowRuntime.setText(org.openide.util.NbBundle.getMessage(SurroundWithTryCatchLog.class,
"SurroundWithTryCatchLog.rethrowRuntime.text")); // NOI18N
rethrowRuntime.addActionListener(new java.awt.event.ActionListener() {
@@ -104,10 +109,10 @@ public class SurroundWithTryCatchLog extends
javax.swing.JPanel {
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(logger)
.addComponent(exceptions)
+ .addComponent(printStackTrace)
.addComponent(rethrowRuntime)
- .addComponent(rethrow)
- .addComponent(printStackTrace))))
- .addContainerGap(57, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addComponent(rethrow))))
+ .addGap(221, 221, 221))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
@@ -119,11 +124,11 @@ public class SurroundWithTryCatchLog extends
javax.swing.JPanel {
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(logger)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(printStackTrace)
+
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(rethrowRuntime)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(rethrow)
-
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addComponent(printStackTrace)
.addContainerGap(134, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
@@ -144,6 +149,10 @@ private void
rethrowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST
ErrorFixesFakeHint.setRethrow(p, rethrow.isSelected());
}//GEN-LAST:event_rethrowActionPerformed
+ private void printStackTraceActionPerformed(java.awt.event.ActionEvent
evt) {//GEN-FIRST:event_printStackTraceActionPerformed
+ ErrorFixesFakeHint.setPrintStackTrace(p, printStackTrace.isSelected());
+ }//GEN-LAST:event_printStackTraceActionPerformed
+
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox exceptions;
diff --git
a/java/java.lsp.server/nbcode/integration/release/config/Preferences/org/netbeans/modules/java/hints/default/org.netbeans.modules.java.hints.errors.ErrorFixesFakeHintSURROUND_WITH_TRY_CATCH.properties
b/java/java.lsp.server/nbcode/integration/release/config/Preferences/org/netbeans/modules/java/hints/default/org.netbeans.modules.java.hints.errors.ErrorFixesFakeHintSURROUND_WITH_TRY_CATCH.properties
new file mode 100644
index 0000000..9c592b0
--- /dev/null
+++
b/java/java.lsp.server/nbcode/integration/release/config/Preferences/org/netbeans/modules/java/hints/default/org.netbeans.modules.java.hints.errors.ErrorFixesFakeHintSURROUND_WITH_TRY_CATCH.properties
@@ -0,0 +1,22 @@
+# 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.
+
+surround-try-catch-java-util-logging-Logger=false
+surround-try-catch-org-openide-util-Exceptions=false
+surround-try-catch-printStackTrace=false
+surround-try-catch-rethrow=false
+surround-try-catch-rethrow-runtime=false
diff --git
a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/Utils.java
b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/Utils.java
index 248f642..309a3de 100644
--- a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/Utils.java
+++ b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/Utils.java
@@ -34,7 +34,6 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import javax.lang.model.element.ElementKind;
-import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.Range;
@@ -128,8 +127,8 @@ public class Utils {
}
}
- public static int getOffset(Document doc, Position pos) {
- return LineDocumentUtils.getLineStartFromIndex((LineDocument) doc,
pos.getLine()) + pos.getCharacter();
+ public static int getOffset(LineDocument doc, Position pos) {
+ return LineDocumentUtils.getLineStartFromIndex(doc, pos.getLine()) +
pos.getCharacter();
}
public static synchronized String toUri(FileObject file) {
diff --git
a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/ExtractSuperclassOrInterfaceRefactoring.java
b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/ExtractSuperclassOrInterfaceRefactoring.java
index 89700a9..87d4807 100644
---
a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/ExtractSuperclassOrInterfaceRefactoring.java
+++
b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/ExtractSuperclassOrInterfaceRefactoring.java
@@ -176,7 +176,9 @@ public final class ExtractSuperclassOrInterfaceRefactoring
extends CodeRefactori
String label =
EXTRACT_SUPERCLASS_REFACTORING_COMMAND.equals(command) ?
Bundle.DN_SelectClassName() : Bundle.DN_SelectInterfaceName();
String value =
EXTRACT_SUPERCLASS_REFACTORING_COMMAND.equals(command) ? "NewClass" :
"NewInterface";
client.showInputBox(new ShowInputBoxParams(label,
value)).thenAccept(name -> {
- extract(client, uri, command, type, selected, name);
+ if (name != null && !name.isEmpty()) {
+ extract(client, uri, command, type, selected,
name);
+ }
});
}
});
diff --git
a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/TextDocumentServiceImpl.java
b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/TextDocumentServiceImpl.java
index d69bc85..c6baa76 100644
---
a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/TextDocumentServiceImpl.java
+++
b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/TextDocumentServiceImpl.java
@@ -46,6 +46,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -131,6 +132,8 @@ 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.editor.document.LineDocument;
+import org.netbeans.api.editor.document.LineDocumentUtils;
import org.netbeans.api.editor.mimelookup.MimeLookup;
import org.netbeans.api.java.lexer.JavaTokenId;
import org.netbeans.api.java.project.JavaProjectConstants;
@@ -287,7 +290,10 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
}
EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
Document doc = ec.openDocument();
- final int caret = Utils.getOffset(doc, params.getPosition());
+ if (!(doc instanceof LineDocument)) {
+ return
CompletableFuture.completedFuture(Either.forRight(completionList));
+ }
+ final int caret = Utils.getOffset((LineDocument) doc,
params.getPosition());
List<CompletionItem> items = new ArrayList<>();
Completion.Context context = params.getContext() != null
? new
Completion.Context(Completion.TriggerKind.valueOf(params.getContext().getTriggerKind().name()),
@@ -442,10 +448,10 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
String uri = params.getTextDocument().getUri();
FileObject file = fromURI(uri);
Document doc = server.getOpenedDocuments().getDocument(uri);
- if (file == null || doc == null) {
+ if (file == null || !(doc instanceof LineDocument)) {
return CompletableFuture.completedFuture(null);
}
- return org.netbeans.api.lsp.Hover.getContent(doc, Utils.getOffset(doc,
params.getPosition())).thenApply(content -> {
+ return org.netbeans.api.lsp.Hover.getContent(doc,
Utils.getOffset((LineDocument) doc, params.getPosition())).thenApply(content ->
{
if (content != null) {
MarkupContent markup = new MarkupContent();
markup.setKind("markdown");
@@ -466,10 +472,10 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
try {
String uri = params.getTextDocument().getUri();
Document doc = server.getOpenedDocuments().getDocument(uri);
- if (doc != null) {
+ if (doc instanceof LineDocument) {
FileObject file = Utils.fromUri(uri);
if (file != null) {
- int offset = Utils.getOffset(doc, params.getPosition());
+ int offset = Utils.getOffset((LineDocument) doc,
params.getPosition());
return HyperlinkLocation.resolve(doc,
offset).thenApply(locs -> {
return Either.forLeft(locs.stream().map(location -> {
FileObject fo = location.getFileObject();
@@ -489,10 +495,10 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
try {
String uri = params.getTextDocument().getUri();
Document doc = server.getOpenedDocuments().getDocument(uri);
- if (doc != null) {
+ if (doc instanceof LineDocument) {
FileObject file = Utils.fromUri(uri);
if (file != null) {
- int offset = Utils.getOffset(doc, params.getPosition());
+ int offset = Utils.getOffset((LineDocument) doc,
params.getPosition());
return HyperlinkLocation.resolveTypeDefinition(doc,
offset).thenApply(locs -> {
return Either.forLeft(locs.stream().map(location -> {
FileObject fo = location.getFileObject();
@@ -548,39 +554,41 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
cc.toPhase(JavaSource.Phase.RESOLVED);
if (cancel.get()) return ;
Document doc =
cc.getSnapshot().getSource().getDocument(true);
- TreePath path =
cc.getTreeUtilities().pathFor(Utils.getOffset(doc, position));
- query[0] = new
WhereUsedQuery(Lookups.singleton(TreePathHandle.create(path, cc)));
- if (implementations) {
-
query[0].putValue(WhereUsedQueryConstants.FIND_SUBCLASSES, true);
-
query[0].putValue(WhereUsedQueryConstants.FIND_OVERRIDING_METHODS, true);
- query[0].putValue(WhereUsedQuery.FIND_REFERENCES,
false);
- } else if (includeDeclaration) {
- 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));
+ if (doc instanceof LineDocument) {
+ TreePath path =
cc.getTreeUtilities().pathFor(Utils.getOffset((LineDocument) doc, position));
+ query[0] = new
WhereUsedQuery(Lookups.singleton(TreePathHandle.create(path, cc)));
+ if (implementations) {
+
query[0].putValue(WhereUsedQueryConstants.FIND_SUBCLASSES, true);
+
query[0].putValue(WhereUsedQueryConstants.FIND_OVERRIDING_METHODS, true);
+ query[0].putValue(WhereUsedQuery.FIND_REFERENCES,
false);
+ } else if (includeDeclaration) {
+ 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);
+ }, true);
+ }
}
}
}
@@ -688,12 +696,14 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
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]))));
+ if (doc instanceof LineDocument) {
+ int offset = Utils.getOffset((LineDocument) 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);
@@ -765,68 +775,84 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
return CompletableFuture.completedFuture(Collections.emptyList());
}
Document doc =
server.getOpenedDocuments().getDocument(params.getTextDocument().getUri());
- if (doc == null) {
+ if (!(doc instanceof LineDocument)) {
return CompletableFuture.completedFuture(Collections.emptyList());
}
+ List<Either<Command, CodeAction>> result = new ArrayList<>();
Range range = params.getRange();
- int startOffset = Utils.getOffset(doc, range.getStart());
- int endOffset = Utils.getOffset(doc, range.getEnd());
-
- ArrayList<Diagnostic> diagnostics = new
ArrayList<>(params.getContext().getDiagnostics());
- diagnostics.addAll(computeDiags(params.getTextDocument().getUri(),
startOffset, ErrorProvider.Kind.HINTS, documentVersion(doc)));
+ int startOffset = Utils.getOffset((LineDocument) doc,
range.getStart());
+ int endOffset = Utils.getOffset((LineDocument) doc, range.getEnd());
+ if (startOffset == endOffset) {
+ int lineStartOffset =
LineDocumentUtils.getLineStart((LineDocument) doc, startOffset);
+ int lineEndOffset;
+ try {
+ lineEndOffset = LineDocumentUtils.getLineEnd((LineDocument)
doc, endOffset);
+ } catch (BadLocationException ex) {
+ lineEndOffset = endOffset;
+ }
- Map<String, org.netbeans.api.lsp.Diagnostic> id2Errors = (Map<String,
org.netbeans.api.lsp.Diagnostic>) doc.getProperty("lsp-errors");
- List<Either<Command, CodeAction>> result = new ArrayList<>();
- if (id2Errors != null) {
- for (Diagnostic diag : diagnostics) {
- org.netbeans.api.lsp.Diagnostic err =
id2Errors.get(diag.getCode().getLeft());
+ ArrayList<Diagnostic> diagnostics = new
ArrayList<>(params.getContext().getDiagnostics());
+ diagnostics.addAll(computeDiags(params.getTextDocument().getUri(),
startOffset, ErrorProvider.Kind.HINTS, documentVersion(doc)));
- if (err == null) {
- client.logMessage(new MessageParams(MessageType.Log,
"Cannot resolve error, code: " + diag.getCode().getLeft()));
- continue;
- }
- org.netbeans.api.lsp.Diagnostic.LazyCodeActions actions =
err.getActions();
- if (actions != null) {
- for (org.netbeans.api.lsp.CodeAction inputAction :
actions.computeCodeActions(ex -> client.logMessage(new
MessageParams(MessageType.Error, ex.getMessage())))) {
- CodeAction action = new
CodeAction(inputAction.getTitle());
- action.setDiagnostics(Collections.singletonList(diag));
- action.setKind(kind(err.getSeverity()));
- if (inputAction.getCommand() != null) {
- action.setCommand(new
Command(inputAction.getCommand().getTitle(),
inputAction.getCommand().getCommand()));
+ Map<String, org.netbeans.api.lsp.Diagnostic> id2Errors =
(Map<String, org.netbeans.api.lsp.Diagnostic>) doc.getProperty("lsp-errors");
+ if (id2Errors != null) {
+ for (Entry<String, org.netbeans.api.lsp.Diagnostic> entry :
id2Errors.entrySet()) {
+ org.netbeans.api.lsp.Diagnostic err = entry.getValue();
+ if (err.getSeverity() ==
org.netbeans.api.lsp.Diagnostic.Severity.Error) {
+ if (err.getEndPosition().getOffset() < startOffset ||
err.getStartPosition().getOffset() > endOffset) {
+ continue;
}
- if (inputAction.getEdit() != null) {
- org.netbeans.api.lsp.WorkspaceEdit edit =
inputAction.getEdit();
- List<Either<TextDocumentEdit, ResourceOperation>>
documentChanges = new ArrayList<>();
- for (Union2<org.netbeans.api.lsp.TextDocumentEdit,
org.netbeans.api.lsp.ResourceOperation> parts : edit.getDocumentChanges()) {
- if (parts.hasFirst()) {
- String docUri =
parts.first().getDocument();
- try {
- FileObject file =
Utils.fromUri(docUri);
- if (file == null) {
- file =
Utils.fromUri(params.getTextDocument().getUri());
- }
- FileObject fo = file;
- if (fo != null) {
- List<TextEdit> edits =
parts.first().getEdits().stream().map(te -> new TextEdit(new
Range(Utils.createPosition(fo, te.getStartOffset()), Utils.createPosition(fo,
te.getEndOffset())), te.getNewText())).collect(Collectors.toList());
- TextDocumentEdit tde = new
TextDocumentEdit(new VersionedTextDocumentIdentifier(docUri, -1), edits);
-
documentChanges.add(Either.forLeft(tde));
+ } else {
+ if (err.getEndPosition().getOffset() < lineStartOffset
|| err.getStartPosition().getOffset() > lineEndOffset) {
+ continue;
+ }
+ }
+ Optional<Diagnostic> diag = diagnostics.stream().filter(d
-> entry.getKey().equals(d.getCode().getLeft())).findFirst();
+ org.netbeans.api.lsp.Diagnostic.LazyCodeActions actions =
err.getActions();
+ if (actions != null) {
+ for (org.netbeans.api.lsp.CodeAction inputAction :
actions.computeCodeActions(ex -> client.logMessage(new
MessageParams(MessageType.Error, ex.getMessage())))) {
+ CodeAction action = new
CodeAction(inputAction.getTitle());
+ if (diag.isPresent()) {
+
action.setDiagnostics(Collections.singletonList(diag.get()));
+ }
+ action.setKind(kind(err.getSeverity()));
+ if (inputAction.getCommand() != null) {
+ action.setCommand(new
Command(inputAction.getCommand().getTitle(),
inputAction.getCommand().getCommand()));
+ }
+ if (inputAction.getEdit() != null) {
+ org.netbeans.api.lsp.WorkspaceEdit edit =
inputAction.getEdit();
+ List<Either<TextDocumentEdit,
ResourceOperation>> documentChanges = new ArrayList<>();
+ for
(Union2<org.netbeans.api.lsp.TextDocumentEdit,
org.netbeans.api.lsp.ResourceOperation> parts : edit.getDocumentChanges()) {
+ if (parts.hasFirst()) {
+ String docUri =
parts.first().getDocument();
+ try {
+ FileObject file =
Utils.fromUri(docUri);
+ if (file == null) {
+ file =
Utils.fromUri(params.getTextDocument().getUri());
+ }
+ FileObject fo = file;
+ if (fo != null) {
+ List<TextEdit> edits =
parts.first().getEdits().stream().map(te -> new TextEdit(new
Range(Utils.createPosition(fo, te.getStartOffset()), Utils.createPosition(fo,
te.getEndOffset())), te.getNewText())).collect(Collectors.toList());
+ TextDocumentEdit tde = new
TextDocumentEdit(new VersionedTextDocumentIdentifier(docUri, -1), edits);
+
documentChanges.add(Either.forLeft(tde));
+ }
+ } catch (Exception ex) {
+ client.logMessage(new
MessageParams(MessageType.Error, ex.getMessage()));
}
- } catch (Exception ex) {
- client.logMessage(new
MessageParams(MessageType.Error, ex.getMessage()));
- }
- } else {
- if (parts.second() instanceof
org.netbeans.api.lsp.ResourceOperation.CreateFile) {
-
documentChanges.add(Either.forRight(new
CreateFile(((org.netbeans.api.lsp.ResourceOperation.CreateFile)
parts.second()).getNewFile())));
} else {
- throw new
IllegalStateException(String.valueOf(parts.second()));
+ if (parts.second() instanceof
org.netbeans.api.lsp.ResourceOperation.CreateFile) {
+
documentChanges.add(Either.forRight(new
CreateFile(((org.netbeans.api.lsp.ResourceOperation.CreateFile)
parts.second()).getNewFile())));
+ } else {
+ throw new
IllegalStateException(String.valueOf(parts.second()));
+ }
}
}
- }
- action.setEdit(new WorkspaceEdit(documentChanges));
+ action.setEdit(new
WorkspaceEdit(documentChanges));
+ }
+ result.add(Either.forRight(action));
}
- result.add(Either.forRight(action));
}
}
}
@@ -1037,18 +1063,21 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
public CompletableFuture<Either<Range, PrepareRenameResult>>
prepareRename(PrepareRenameParams params) {
// shortcut: if the projects are not yet initialized, return empty:
if (server.openedProjects().getNow(null) == null) {
- return CompletableFuture.completedFuture(Either.forLeft(null));
+ return CompletableFuture.completedFuture(null);
}
JavaSource source = getJavaSource(params.getTextDocument().getUri());
if (source == null) {
- return CompletableFuture.completedFuture(Either.forLeft(null));
+ return CompletableFuture.completedFuture(null);
}
CompletableFuture<Either<Range, PrepareRenameResult>> result = new
CompletableFuture<>();
try {
source.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
Document doc = cc.getSnapshot().getSource().getDocument(true);
- int pos = Utils.getOffset(doc, params.getPosition());
+ if (!(doc instanceof LineDocument)) {
+ result.complete(null);
+ }
+ int pos = Utils.getOffset((LineDocument) doc,
params.getPosition());
TreePath path = cc.getTreeUtilities().pathFor(pos);
RenameRefactoring ref = new
RenameRefactoring(Lookups.singleton(TreePathHandle.create(path, cc)));
ref.setNewName("any");
@@ -1112,24 +1141,26 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
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()));
- List<Object> lookupContent = new ArrayList<>();
-
- lookupContent.add(TreePathHandle.create(path, cc));
-
- //from RenameRefactoringUI:
- Element selected = cc.getTrees().getElement(path);
- if (selected instanceof TypeElement && !((TypeElement)
selected).getNestingKind().isNested()) {
- ElementHandle<TypeElement> handle =
ElementHandle.create((TypeElement) selected);
- FileObject f = SourceUtils.getFile(handle,
cc.getClasspathInfo());
- if (f != null &&
selected.getSimpleName().toString().equals(f.getName())) {
- lookupContent.add(f);
+ if (doc instanceof LineDocument) {
+ TreePath path =
cc.getTreeUtilities().pathFor(Utils.getOffset((LineDocument) doc,
params.getPosition()));
+ List<Object> lookupContent = new ArrayList<>();
+
+ lookupContent.add(TreePathHandle.create(path, cc));
+
+ //from RenameRefactoringUI:
+ Element selected = cc.getTrees().getElement(path);
+ if (selected instanceof TypeElement && !((TypeElement)
selected).getNestingKind().isNested()) {
+ ElementHandle<TypeElement> handle =
ElementHandle.create((TypeElement) selected);
+ FileObject f = SourceUtils.getFile(handle,
cc.getClasspathInfo());
+ if (f != null &&
selected.getSimpleName().toString().equals(f.getName())) {
+ lookupContent.add(f);
+ }
}
- }
- refactoring[0] = new
RenameRefactoring(Lookups.fixed(lookupContent.toArray(new Object[0])));
- refactoring[0].setNewName(params.getNewName());
- refactoring[0].setSearchInComments(true); //TODO?
+ refactoring[0] = new
RenameRefactoring(Lookups.fixed(lookupContent.toArray(new Object[0])));
+ refactoring[0].setNewName(params.getNewName());
+ refactoring[0].setSearchInComments(true); //TODO?
+ }
}, true);
if (cancel.get()) return ;
cancelCallback[0] = () -> refactoring[0].cancelRequest();
@@ -1307,8 +1338,8 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
NbDocument.runAtomic((StyledDocument) doc, () -> {
for (TextDocumentContentChangeEvent change :
params.getContentChanges()) {
try {
- int start = Utils.getOffset(doc,
change.getRange().getStart());
- int end = Utils.getOffset(doc,
change.getRange().getEnd());
+ int start = Utils.getOffset((LineDocument) doc,
change.getRange().getStart());
+ int end = Utils.getOffset((LineDocument) doc,
change.getRange().getEnd());
doc.remove(start, end - start);
doc.insertString(start, change.getText(), null);
} catch (BadLocationException ex) {
@@ -1353,55 +1384,57 @@ public class TextDocumentServiceImpl implements
TextDocumentService, LanguageCli
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
Document doc =
cc.getSnapshot().getSource().getDocument(true);
- int offset = Utils.getOffset(doc, position);
- TreeUtilities treeUtilities = cc.getTreeUtilities();
- TreePath path =
treeUtilities.getPathElementOfKind(EnumSet.of(Kind.CLASS, Kind.INTERFACE,
Kind.ENUM, Kind.ANNOTATION_TYPE, Kind.METHOD), treeUtilities.pathFor(offset));
- if (path != null) {
- Trees trees = cc.getTrees();
- Element resolved = trees.getElement(path);
- if (resolved != null) {
- if (resolved.getKind() == ElementKind.METHOD) {
- Map<ElementHandle<? extends Element>,
List<ElementDescription>> overriding = new ComputeOverriding(new
AtomicBoolean()).process(cc);
- List<ElementDescription> eds =
overriding.get(ElementHandle.create(resolved));
- if (eds != null) {
- for (ElementDescription ed : eds) {
- Element el =
ed.getHandle().resolve(cc);
- TreePath tp = trees.getPath(el);
- long startPos = tp != null &&
cc.getCompilationUnit() == tp.getCompilationUnit() ?
trees.getSourcePositions().getStartPosition(cc.getCompilationUnit(),
tp.getLeaf()) : -1;
- if (startPos >= 0) {
- long endPos =
trees.getSourcePositions().getEndPosition(cc.getCompilationUnit(),
tp.getLeaf());
- targets.add(new
GoToTarget(cc.getSnapshot().getOriginalOffset((int) startPos),
-
cc.getSnapshot().getOriginalOffset((int) endPos),
GoToSupport.getNameSpan(tp.getLeaf(), treeUtilities),
- null, null, null,
ed.getDisplayName(), true));
- } else {
- TypeElement te = el != null ?
cc.getElementUtilities().outermostTypeElement(el) : null;
- targets.add(new GoToTarget(-1, -1,
null, ed.getOriginalCPInfo(), ed.getHandle(), getResourceName(te,
ed.getHandle()), ed.getDisplayName(), true));
+ if (doc instanceof LineDocument) {
+ int offset = Utils.getOffset((LineDocument) doc,
position);
+ TreeUtilities treeUtilities = cc.getTreeUtilities();
+ TreePath path =
treeUtilities.getPathElementOfKind(EnumSet.of(Kind.CLASS, Kind.INTERFACE,
Kind.ENUM, Kind.ANNOTATION_TYPE, Kind.METHOD), treeUtilities.pathFor(offset));
+ if (path != null) {
+ Trees trees = cc.getTrees();
+ Element resolved = trees.getElement(path);
+ if (resolved != null) {
+ if (resolved.getKind() == ElementKind.METHOD) {
+ Map<ElementHandle<? extends Element>,
List<ElementDescription>> overriding = new ComputeOverriding(new
AtomicBoolean()).process(cc);
+ List<ElementDescription> eds =
overriding.get(ElementHandle.create(resolved));
+ if (eds != null) {
+ for (ElementDescription ed : eds) {
+ Element el =
ed.getHandle().resolve(cc);
+ TreePath tp = trees.getPath(el);
+ long startPos = tp != null &&
cc.getCompilationUnit() == tp.getCompilationUnit() ?
trees.getSourcePositions().getStartPosition(cc.getCompilationUnit(),
tp.getLeaf()) : -1;
+ if (startPos >= 0) {
+ long endPos =
trees.getSourcePositions().getEndPosition(cc.getCompilationUnit(),
tp.getLeaf());
+ targets.add(new
GoToTarget(cc.getSnapshot().getOriginalOffset((int) startPos),
+
cc.getSnapshot().getOriginalOffset((int) endPos),
GoToSupport.getNameSpan(tp.getLeaf(), treeUtilities),
+ null, null, null,
ed.getDisplayName(), true));
+ } else {
+ TypeElement te = el != null ?
cc.getElementUtilities().outermostTypeElement(el) : null;
+ targets.add(new GoToTarget(-1,
-1, null, ed.getOriginalCPInfo(), ed.getHandle(), getResourceName(te,
ed.getHandle()), ed.getDisplayName(), true));
+ }
}
}
- }
- } else if (resolved.getKind().isClass() ||
resolved.getKind().isInterface()) {
- List<TypeMirror> superTypes = new
ArrayList<>();
-
superTypes.add(((TypeElement)resolved).getSuperclass());
-
superTypes.addAll(((TypeElement)resolved).getInterfaces());
- for (TypeMirror superType : superTypes) {
- if (superType.getKind() ==
TypeKind.DECLARED) {
- Element el = ((DeclaredType)
superType).asElement();
- TreePath tp = trees.getPath(el);
- long startPos = tp != null &&
cc.getCompilationUnit() == tp.getCompilationUnit() ?
trees.getSourcePositions().getStartPosition(cc.getCompilationUnit(),
tp.getLeaf()) : -1;
- if (startPos >= 0) {
- long endPos =
trees.getSourcePositions().getEndPosition(cc.getCompilationUnit(),
tp.getLeaf());
- targets.add(new
GoToTarget(cc.getSnapshot().getOriginalOffset((int) startPos),
-
cc.getSnapshot().getOriginalOffset((int) endPos),
GoToSupport.getNameSpan(tp.getLeaf(), treeUtilities),
- null, null, null,
cc.getElementUtilities().getElementName(el, false).toString(), true));
- } else {
- TypeElement te = el != null ?
cc.getElementUtilities().outermostTypeElement(el) : null;
- targets.add(new GoToTarget(-1, -1,
null, cc.getClasspathInfo(), ElementHandle.create(el), getResourceName(te,
null),
-
cc.getElementUtilities().getElementName(el, false).toString(), true));
+ } else if (resolved.getKind().isClass() ||
resolved.getKind().isInterface()) {
+ List<TypeMirror> superTypes = new
ArrayList<>();
+
superTypes.add(((TypeElement)resolved).getSuperclass());
+
superTypes.addAll(((TypeElement)resolved).getInterfaces());
+ for (TypeMirror superType : superTypes) {
+ if (superType.getKind() ==
TypeKind.DECLARED) {
+ Element el = ((DeclaredType)
superType).asElement();
+ TreePath tp = trees.getPath(el);
+ long startPos = tp != null &&
cc.getCompilationUnit() == tp.getCompilationUnit() ?
trees.getSourcePositions().getStartPosition(cc.getCompilationUnit(),
tp.getLeaf()) : -1;
+ if (startPos >= 0) {
+ long endPos =
trees.getSourcePositions().getEndPosition(cc.getCompilationUnit(),
tp.getLeaf());
+ targets.add(new
GoToTarget(cc.getSnapshot().getOriginalOffset((int) startPos),
+
cc.getSnapshot().getOriginalOffset((int) endPos),
GoToSupport.getNameSpan(tp.getLeaf(), treeUtilities),
+ null, null, null,
cc.getElementUtilities().getElementName(el, false).toString(), true));
+ } else {
+ TypeElement te = el != null ?
cc.getElementUtilities().outermostTypeElement(el) : null;
+ targets.add(new GoToTarget(-1,
-1, null, cc.getClasspathInfo(), ElementHandle.create(el), getResourceName(te,
null),
+
cc.getElementUtilities().getElementName(el, false).toString(), true));
+ }
}
}
}
+ thisFileLineMap[0] =
cc.getCompilationUnit().getLineMap();
}
- thisFileLineMap[0] =
cc.getCompilationUnit().getLineMap();
}
}
}, true);
diff --git
a/java/java.lsp.server/test/unit/src/org/netbeans/modules/java/lsp/server/protocol/ServerTest.java
b/java/java.lsp.server/test/unit/src/org/netbeans/modules/java/lsp/server/protocol/ServerTest.java
index e5edcc8..e891ddc 100644
---
a/java/java.lsp.server/test/unit/src/org/netbeans/modules/java/lsp/server/protocol/ServerTest.java
+++
b/java/java.lsp.server/test/unit/src/org/netbeans/modules/java/lsp/server/protocol/ServerTest.java
@@ -148,7 +148,6 @@ import
org.netbeans.modules.java.hints.infrastructure.JavaErrorProvider;
import org.netbeans.modules.java.source.BootClassPathUtil;
import org.netbeans.modules.parsing.impl.indexing.implspi.CacheFolderProvider;
import org.netbeans.spi.java.classpath.ClassPathProvider;
-import org.netbeans.spi.java.classpath.PathResourceImplementation;
import org.netbeans.spi.java.classpath.support.ClassPathSupport;
import org.netbeans.spi.java.queries.AnnotationProcessingQueryImplementation;
import org.netbeans.spi.lsp.ErrorProvider;
@@ -340,7 +339,7 @@ public class ServerTest extends NbTestCase {
server.getTextDocumentService().didChange(new
DidChangeTextDocumentParams(id, Arrays.asList(new
TextDocumentContentChangeEvent(new Range(new Position(0, closingBrace), new
Position(0, closingBrace)), 0, "public String c(Object o) {\nreturn o;\n}"))));
List<Diagnostic> diagnostics = assertDiags(diags, "Error:1:0-1:9");
//errors
assertDiags(diags, "Error:1:0-1:9");//hints
- List<Either<Command, CodeAction>> codeActions =
server.getTextDocumentService().codeAction(new CodeActionParams(id, new
Range(new Position(1, 0), new Position(1, 9)), new
CodeActionContext(Arrays.asList(diagnostics.get(0))))).get();
+ List<Either<Command, CodeAction>> codeActions =
server.getTextDocumentService().codeAction(new CodeActionParams(id, new
Range(new Position(1, 4), new Position(1, 4)), new
CodeActionContext(Arrays.asList(diagnostics.get(0))))).get();
String log = codeActions.toString();
assertTrue(log, codeActions.size() >= 2);
assertTrue(log, codeActions.get(0).isRight());
@@ -627,7 +626,7 @@ public class ServerTest extends NbTestCase {
List<Diagnostic> diagnostics = assertDiags(diags,
"Warning:1:7-1:19");//hints
VersionedTextDocumentIdentifier id = new
VersionedTextDocumentIdentifier(1);
id.setUri(toURI(src));
- List<Either<Command, CodeAction>> codeActions =
server.getTextDocumentService().codeAction(new CodeActionParams(id, new
Range(new Position(1, 7), new Position(1, 19)), new
CodeActionContext(Arrays.asList(diagnostics.get(0))))).get();
+ List<Either<Command, CodeAction>> codeActions =
server.getTextDocumentService().codeAction(new CodeActionParams(id, new
Range(new Position(1, 13), new Position(1, 13)), new
CodeActionContext(Arrays.asList(diagnostics.get(0))))).get();
String log = codeActions.toString();
assertTrue(log, codeActions.size() >= 1);
assertTrue(log, codeActions.get(0).isRight());
@@ -2014,7 +2013,6 @@ public class ServerTest extends NbTestCase {
}
VersionedTextDocumentIdentifier id = new
VersionedTextDocumentIdentifier(src.toURI().toString(), 1);
List<Either<Command, CodeAction>> codeActions =
server.getTextDocumentService().codeAction(new CodeActionParams(id, new
Range(new Position(2, 17), new Position(2, 17)), new
CodeActionContext(diags[0]))).get();
- assertTrue(codeActions.size() >= 1);
Optional<CodeAction> generateMehtod =
codeActions.stream()
.filter(Either::isRight)
@@ -2036,7 +2034,7 @@ public class ServerTest extends NbTestCase {
fileChanges.get(0).getRange());
assertEquals("\n" +
" private String convertToString(int value) {\n" +
- " throw new UnsupportedOperationException(\"Not
supported yet.\"); //To change body of generated methods, choose Tools |
Templates.\n" +
+ " throw new UnsupportedOperationException(\"Not
supported yet.\"); // Generated from
nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody\n" +
" }\n",
fileChanges.get(0).getNewText());
}
@@ -2100,8 +2098,7 @@ public class ServerTest extends NbTestCase {
}
}
VersionedTextDocumentIdentifier id = new
VersionedTextDocumentIdentifier(src.toURI().toString(), 1);
- List<Either<Command, CodeAction>> codeActions =
server.getTextDocumentService().codeAction(new CodeActionParams(id, new
Range(new Position(1, 14), new Position(2, 14)), new
CodeActionContext(diags[0]))).get();
- assertTrue(codeActions.size() >= 2);
+ List<Either<Command, CodeAction>> codeActions =
server.getTextDocumentService().codeAction(new CodeActionParams(id, new
Range(new Position(1, 14), new Position(1, 14)), new
CodeActionContext(diags[0]))).get();
Optional<CodeAction> generateClass =
codeActions.stream()
.filter(Either::isRight)
@@ -2212,7 +2209,7 @@ public class ServerTest extends NbTestCase {
assertEquals("\n" +
" @Override\n" +
" public void run() {\n" +
- " throw new UnsupportedOperationException(\"Not
supported yet.\"); //To change body of generated methods, choose Tools |
Templates.\n" +
+ " throw new UnsupportedOperationException(\"Not
supported yet.\"); // Generated from
nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody\n" +
" }\n",
fileChanges.get(0).getNewText());
}
@@ -2302,7 +2299,7 @@ public class ServerTest extends NbTestCase {
fileChanges.get(0).getRange());
assertEquals(" @Override\n" +
" public void run() {\n" +
- " throw new
UnsupportedOperationException(\"Not supported yet.\"); //To change body of
generated methods, choose Tools | Templates.\n" +
+ " throw new
UnsupportedOperationException(\"Not supported yet.\"); // Generated from
nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody\n" +
" }\n",
fileChanges.get(0).getNewText());
}
@@ -2390,7 +2387,7 @@ public class ServerTest extends NbTestCase {
fileChanges.get(0).getRange());
assertEquals(" @Override\n" +
" public void run() {\n" +
- " throw new
UnsupportedOperationException(\"Not supported yet.\"); //To change body of
generated methods, choose Tools | Templates.\n" +
+ " throw new
UnsupportedOperationException(\"Not supported yet.\"); // Generated from
nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody\n" +
" }\n",
fileChanges.get(0).getNewText());
}
@@ -3734,12 +3731,12 @@ public class ServerTest extends NbTestCase {
assertEquals("\n" +
" @Override\n" +
" protected void finalize() throws Throwable {\n" +
- " super.finalize(); //To change body of generated
methods, choose Tools | Templates.\n" +
+ " super.finalize(); // Generated from
nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/OverriddenMethodBody\n" +
" }\n" +
"\n" +
" @Override\n" +
" public String toString() {\n" +
- " return super.toString(); //To change body of
generated methods, choose Tools | Templates.\n" +
+ " return super.toString(); // Generated from
nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/OverriddenMethodBody\n" +
" }\n",
fileChanges.get(0).getNewText());
}
@@ -5172,7 +5169,7 @@ public class ServerTest extends NbTestCase {
codeActions.stream()
.filter(Either::isRight)
.map(Either::getRight)
- .filter(a ->
a.getTitle().startsWith(Bundle.DN_SurroundWith("do { ...")))
+ .filter(a ->
a.getTitle().startsWith(Bundle.DN_SurroundWith("do")))
.findAny();
assertTrue(surroundWith.isPresent());
Command command = surroundWith.get().getCommand();
diff --git a/java/java.lsp.server/vscode/src/testAdapter.ts
b/java/java.lsp.server/vscode/src/testAdapter.ts
index e28e5f7..26daaac 100644
--- a/java/java.lsp.server/vscode/src/testAdapter.ts
+++ b/java/java.lsp.server/vscode/src/testAdapter.ts
@@ -28,6 +28,7 @@ export class NbTestAdapter {
private readonly testController: TestController;
private disposables: { dispose(): void }[] = [];
private currentRun: TestRun | undefined;
+ private itemsToRun: Set<TestItem> | undefined;
constructor(client: Promise<LanguageClient>) {
this.testController =
tests.createTestController('apacheNetBeansController', 'Apache NetBeans');
@@ -52,6 +53,7 @@ export class NbTestAdapter {
async run(request: TestRunRequest, cancellation: CancellationToken):
Promise<void> {
cancellation.onCancellationRequested(() => this.cancel());
this.currentRun = this.testController.createTestRun(request);
+ this.itemsToRun = new Set();
if (request.include) {
const include = [...new Map(request.include.map(item => !item.uri
&& item.parent?.uri ? [item.parent.id, item.parent] : [item.id,
item])).values()];
for (let item of include) {
@@ -69,6 +71,8 @@ export class NbTestAdapter {
}
}
}
+ this.itemsToRun.forEach(item => this.set(item, 'skipped'));
+ this.itemsToRun = undefined;
this.currentRun.end();
this.currentRun = undefined;
}
@@ -77,13 +81,18 @@ export class NbTestAdapter {
if (this.currentRun) {
switch (state) {
case 'enqueued':
+ this.itemsToRun?.add(item);
+ this.currentRun.enqueued(item);
+ break;
case 'started':
case 'passed':
case 'skipped':
+ this.itemsToRun?.delete(item);
this.currentRun[state](item);
break;
case 'failed':
case 'errored':
+ this.itemsToRun?.delete(item);
this.currentRun[state](item, message || new
TestMessage(''));
break;
}
diff --git
a/java/refactoring.java/src/org/netbeans/modules/refactoring/java/plugins/MoveFileRefactoringPlugin.java
b/java/refactoring.java/src/org/netbeans/modules/refactoring/java/plugins/MoveFileRefactoringPlugin.java
index 31a53dd..faf4791 100644
---
a/java/refactoring.java/src/org/netbeans/modules/refactoring/java/plugins/MoveFileRefactoringPlugin.java
+++
b/java/refactoring.java/src/org/netbeans/modules/refactoring/java/plugins/MoveFileRefactoringPlugin.java
@@ -60,6 +60,8 @@ import org.openide.util.NbBundle;
"# {0} - The file not of java type.",
"ERR_NotJava=Selected element is not defined in a java file. {0}",
"ERR_CannotMovePublicIntoSamePackage=Cannot move public class to the same
package.",
+ "# {0} - Class name.",
+ "ERR_CannotMoveIntoItself=Cannot move {0} into itself.",
"ERR_NoTargetFound=Cannot find the target to move to.",
"# {0} - Class name.",
"ERR_ClassToMoveClashes=Class \"{0}\" already exists in the target
package.",
@@ -323,6 +325,9 @@ public class MoveFileRefactoringPlugin extends
JavaRefactoringPlugin {
ElementHandle elementHandle = target.getElementHandle();
assert elementHandle != null;
TypeElement targetType = (TypeElement)
elementHandle.resolve(javac);
+ if (targetType == resolveElement) {
+ return new Problem(true,
ERR_CannotMoveIntoItself(resolveElement.getSimpleName()));
+ }
List<? extends Element> enclosedElements =
targetType.getEnclosedElements();
for (Element element : enclosedElements) {
switch (element.getKind()) {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists