You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2026/09/26 18:01:02 UTC
(groovy) branch GROOVY-12411 updated: GROOVY-12411: Tighten groovy-lsp and cover the feature paths
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch GROOVY-12411
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/GROOVY-12411 by this push:
new b996beb644 GROOVY-12411: Tighten groovy-lsp and cover the feature paths
b996beb644 is described below
commit b996beb6446d2117987039cd20c7bc81adb6dc3c
Author: Daniel Sun <su...@apache.org>
AuthorDate: Sun Sep 27 02:28:29 2026 +0900
GROOVY-12411: Tighten groovy-lsp and cover the feature paths
Rename configuration keys that shadowed record components, remove unused
folding helpers and an unused call-hierarchy parameter, and simplify
hover, import fixes, and Groovydoc markdown. Exercise those paths from
the tests that already own each feature.
Assisted-by: Grok 4.7
---
.../groovy/lsp/internal/LanguageServerContext.java | 1 +
.../lsp/internal/compile/CompilerSettings.java | 22 +-
.../lsp/internal/engine/GroovyLanguageEngine.java | 2 +-
.../lsp/internal/feature/CodeActionService.java | 55 +-
.../lsp/internal/feature/FoldingService.java | 42 --
.../lsp/internal/feature/HierarchyService.java | 5 +-
.../groovy/lsp/internal/feature/HoverService.java | 4 +-
.../lsp/internal/util/GroovydocMarkdown.java | 20 +-
.../groovy/lsp/GroovyLanguageServerTest.groovy | 84 ++-
.../lsp/internal/compile/AstQueryTest.groovy | 143 ++++
.../lsp/internal/compile/CompilerSafetyTest.groovy | 247 +++++++
.../lsp/internal/compile/ImportSupportTest.groovy | 102 +++
.../internal/compile/WorkspaceLayoutTest.groovy | 80 +++
.../diagnostic/DiagnosticConverterTest.groovy | 58 ++
.../engine/GroovyLanguageEngineTest.groovy | 123 ++++
.../feature/ConservativeNavigationTest.groovy | 251 +++++++
.../lsp/internal/feature/DocumentSymbolTest.groovy | 152 +++++
.../lsp/internal/feature/JdtInspiredTest.groovy | 435 ++++++++++++
.../internal/feature/LanguageQualityTest.groovy | 272 ++++++++
.../lsp/internal/feature/MetalsInspiredTest.groovy | 477 +++++++++++++
.../lsp/internal/feature/MethodBindingTest.groovy | 386 +++++++++++
.../internal/feature/NavigationIdentityTest.groovy | 746 +++++++++++++++++++++
.../internal/feature/SupportServicesTest.groovy | 464 +++++++++++++
.../lsp/internal/feature/TypeInferenceTest.groovy | 64 ++
.../lsp/internal/position/PositionsTest.groovy | 40 ++
.../internal/protocol/ProtocolCoverageTest.groovy | 38 ++
.../lsp/internal/util/GroovyKeywordsTest.groovy | 8 +
.../internal/util/GroovySourceTokensTest.groovy | 11 +
.../lsp/internal/util/GroovydocMarkdownTest.groovy | 9 +
.../groovy/lsp/internal/util/NameHumpsTest.groovy | 8 +
.../groovy/lsp/internal/util/UrisTest.groovy | 7 +
31 files changed, 4261 insertions(+), 95 deletions(-)
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/LanguageServerContext.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/LanguageServerContext.java
index 42da0ceb16..17ffd531f1 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/LanguageServerContext.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/LanguageServerContext.java
@@ -94,6 +94,7 @@ public final class LanguageServerContext {
* Creates a session.
*/
public LanguageServerContext() {
+ // Fields are initialized at declaration; the constructor exists so tests can build a session directly.
}
/**
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/CompilerSettings.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/CompilerSettings.java
index ea7c52c1aa..81f1889878 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/CompilerSettings.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/CompilerSettings.java
@@ -42,12 +42,12 @@ import java.util.Set;
public record CompilerSettings(List<String> classpath, List<String> sourcePaths, int throughPhase,
boolean grapeEnabled, boolean astTestEnabled, Map<String, String> extra) {
- private static final String CLASSPATH = "classpath";
- private static final String SOURCE_PATHS = "sourcePaths";
- private static final String GRAPE_ENABLED = "grapeEnabled";
- private static final String AST_TEST_ENABLED = "astTestEnabled";
+ private static final String KEY_CLASSPATH = "classpath";
+ private static final String KEY_SOURCE_PATHS = "sourcePaths";
+ private static final String KEY_GRAPE_ENABLED = "grapeEnabled";
+ private static final String KEY_AST_TEST_ENABLED = "astTestEnabled";
private static final Set<String> CLIENT_KEYS = Set.of(
- CLASSPATH, SOURCE_PATHS, GRAPE_ENABLED, AST_TEST_ENABLED);
+ KEY_CLASSPATH, KEY_SOURCE_PATHS, KEY_GRAPE_ENABLED, KEY_AST_TEST_ENABLED);
/**
* Creates settings with the supplied classpath and source paths.
@@ -128,12 +128,12 @@ public record CompilerSettings(List<String> classpath, List<String> sourcePaths,
if (map == null || map.isEmpty()) {
return base;
}
- List<String> classpath = stringList(map.get(CLASSPATH));
- List<String> sourcePaths = stringList(map.get(SOURCE_PATHS));
- boolean grape = map.containsKey(GRAPE_ENABLED)
- ? Boolean.TRUE.equals(map.get(GRAPE_ENABLED)) : base.isGrapeEnabled();
- boolean astTest = map.containsKey(AST_TEST_ENABLED)
- ? Boolean.TRUE.equals(map.get(AST_TEST_ENABLED)) : base.isAstTestEnabled();
+ List<String> classpath = stringList(map.get(KEY_CLASSPATH));
+ List<String> sourcePaths = stringList(map.get(KEY_SOURCE_PATHS));
+ boolean grape = map.containsKey(KEY_GRAPE_ENABLED)
+ ? Boolean.TRUE.equals(map.get(KEY_GRAPE_ENABLED)) : base.isGrapeEnabled();
+ boolean astTest = map.containsKey(KEY_AST_TEST_ENABLED)
+ ? Boolean.TRUE.equals(map.get(KEY_AST_TEST_ENABLED)) : base.isAstTestEnabled();
return new CompilerSettings(
classpath.isEmpty() ? base.getClasspath() : classpath,
sourcePaths.isEmpty() ? base.getSourcePaths() : sourcePaths,
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngine.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngine.java
index a9370cefa5..f03ff71bf6 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngine.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngine.java
@@ -318,7 +318,7 @@ public final class GroovyLanguageEngine implements AutoCloseable {
int to = Math.max(from, endLine + SNIPPET_CONTEXT_LINES);
StringBuilder builder = new StringBuilder();
for (int line = from; line <= to; line++) {
- if (builder.length() > 0) {
+ if (!builder.isEmpty()) {
builder.append('\n');
}
builder.append(Positions.lineText(text, line + 1));
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/CodeActionService.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/CodeActionService.java
index 7d6d319aab..2435441661 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/CodeActionService.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/CodeActionService.java
@@ -571,31 +571,44 @@ public final class CodeActionService {
organize.setCommand(new Command("Organize imports", "groovy.lsp.organizeImports",
List.of(document.getUri().toString())));
actions.add(Either.forRight(organize));
- if (diagnostics != null) {
- for (Diagnostic diagnostic : diagnostics) {
- String message = DiagnosticConverter.diagnosticMessage(diagnostic);
- String className = unresolvedClassName(message);
- if (className == null) {
- continue;
- }
- for (TypeIndex.TypeHit hit : importCandidates(className, snapshot)) {
- List<TextEdit> edits = ImportSupport.addImport(compiled, hit.name(), encoding);
- if (edits.isEmpty()) {
- continue;
- }
- CodeAction action = new CodeAction("Add import for " + hit.name());
- action.setKind(CodeActionKind.QuickFix);
- action.setDiagnostics(List.of(diagnostic));
- action.setEdit(new WorkspaceEdit(Map.of(document.getUri().toString(), edits)));
- actions.add(Either.forRight(action));
- }
- }
- }
+ addAmbiguousImportFixes(actions, document, compiled, snapshot, diagnostics, encoding);
addUnambiguousImports(actions, compiled, snapshot, diagnostics, encoding);
actions.addAll(contribute(document, snapshot, diagnostics, range, encoding, folders, sourcePaths));
return actions;
}
+ private static void addAmbiguousImportFixes(final List<Either<Command, CodeAction>> actions,
+ final TextDocument document, final CompiledDocument compiled,
+ final CompilationSnapshot snapshot, final List<Diagnostic> diagnostics,
+ final PositionEncoding encoding) {
+ if (diagnostics == null) {
+ return;
+ }
+ for (Diagnostic diagnostic : diagnostics) {
+ String className = unresolvedClassName(DiagnosticConverter.diagnosticMessage(diagnostic));
+ if (className == null) {
+ continue;
+ }
+ for (TypeIndex.TypeHit hit : importCandidates(className, snapshot)) {
+ addImportFix(actions, document, compiled, encoding, diagnostic, hit);
+ }
+ }
+ }
+
+ private static void addImportFix(final List<Either<Command, CodeAction>> actions, final TextDocument document,
+ final CompiledDocument compiled, final PositionEncoding encoding,
+ final Diagnostic diagnostic, final TypeIndex.TypeHit hit) {
+ List<TextEdit> edits = ImportSupport.addImport(compiled, hit.name(), encoding);
+ if (edits.isEmpty()) {
+ return;
+ }
+ CodeAction action = new CodeAction("Add import for " + hit.name());
+ action.setKind(CodeActionKind.QuickFix);
+ action.setDiagnostics(List.of(diagnostic));
+ action.setEdit(new WorkspaceEdit(Map.of(document.getUri().toString(), edits)));
+ actions.add(Either.forRight(action));
+ }
+
public List<TextEdit> organizeImports(final CompiledDocument document, final PositionEncoding encoding) {
if (document == null || document.getModule() == null) {
return List.of();
@@ -660,7 +673,7 @@ public final class CodeActionService {
if (from > to) {
from = to;
}
- if (slice.length() > 0) {
+ if (!slice.isEmpty()) {
slice.append('\n');
}
slice.append(row, from, to);
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/FoldingService.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/FoldingService.java
index f235445a23..4c44713e77 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/FoldingService.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/FoldingService.java
@@ -30,8 +30,6 @@ import org.codehaus.groovy.ast.ImportNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.eclipse.lsp4j.FoldingRange;
import org.eclipse.lsp4j.FoldingRangeKind;
-import org.eclipse.lsp4j.Position;
-import org.eclipse.lsp4j.Range;
import java.util.ArrayList;
import java.util.List;
@@ -61,20 +59,6 @@ public final class FoldingService {
return ranges;
}
- private static Range earlier(final Range current, final Range candidate) {
- if (current == null || comparePosition(candidate.getStart(), current.getStart()) < 0) {
- return candidate;
- }
- return current;
- }
-
- private static Range later(final Range current, final Range candidate) {
- if (current == null || comparePosition(candidate.getEnd(), current.getEnd()) > 0) {
- return candidate;
- }
- return current;
- }
-
private static void addCommentFolds(final String text, final List<FoldingRange> ranges) {
int blockStart = -1;
String[] lines = text.split("\n", -1);
@@ -153,30 +137,4 @@ public final class FoldingService {
}
}
- private static int comparePosition(final Position left, final Position right) {
- if (left.getLine() != right.getLine()) {
- return Integer.compare(left.getLine(), right.getLine());
- }
- return Integer.compare(left.getCharacter(), right.getCharacter());
- }
-
- private static String slice(final String text, final Range first, final Range last) {
- String[] lines = text.split("\n", -1);
- int startLine = first.getStart().getLine();
- int endLine = last.getEnd().getLine();
- if (startLine < 0 || endLine >= lines.length || startLine > endLine) {
- return "";
- }
- StringBuilder slice = new StringBuilder();
- for (int line = startLine; line <= endLine; line++) {
- String row = lines[line];
- int from = line == startLine ? Math.min(Math.max(first.getStart().getCharacter(), 0), row.length()) : 0;
- int to = line == endLine ? Math.min(Math.max(last.getEnd().getCharacter(), 0), row.length()) : row.length();
- if (from > to) {
- from = to;
- }
- slice.append(line > startLine ? "\n" : "").append(row, from, to);
- }
- return slice.toString();
- }
}
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/HierarchyService.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/HierarchyService.java
index f475cdb509..5cadbe4adb 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/HierarchyService.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/HierarchyService.java
@@ -78,7 +78,7 @@ public final class HierarchyService {
}
Map<String, Incoming> grouped = new LinkedHashMap<>();
for (CompiledDocument document : snapshot.documents()) {
- collectIncomingCalls(grouped, document, method, snapshot, encoding);
+ collectIncomingCalls(grouped, document, method, encoding);
}
List<CallHierarchyIncomingCall> result = new ArrayList<>();
for (Incoming incoming : grouped.values()) {
@@ -193,8 +193,7 @@ public final class HierarchyService {
}
private static void collectIncomingCalls(final Map<String, Incoming> grouped, final CompiledDocument document,
- final MethodNode method, final CompilationSnapshot snapshot,
- final PositionEncoding encoding) {
+ final MethodNode method, final PositionEncoding encoding) {
if (document.getModule() == null) {
return;
}
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/HoverService.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/HoverService.java
index 425033ecbd..c7dece41c8 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/HoverService.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/feature/HoverService.java
@@ -66,8 +66,8 @@ public final class HoverService {
Hover hover = new Hover(new MarkupContent(MarkupKind.MARKDOWN, markdown));
CompiledDocument compiled = snapshot == null ? null : snapshot.get(document);
ModuleNode module = compiled == null ? null : compiled.getModule();
- ASTNode node = module == null || document == null ? null : AstQuery.nodeAt(module, document, position, encoding);
- if (node != null && document != null) {
+ ASTNode node = module == null ? null : AstQuery.nodeAt(module, document, position, encoding);
+ if (node != null) {
hover.setRange(Positions.toIdentifierRange(node, document.getText(), encoding));
}
return hover;
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovydocMarkdown.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovydocMarkdown.java
index 88a330a6a4..c7e4aa8d4b 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovydocMarkdown.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovydocMarkdown.java
@@ -80,7 +80,7 @@ public final class GroovydocMarkdown {
line = line.substring(1);
}
}
- if (builder.length() > 0) {
+ if (!builder.isEmpty()) {
builder.append('\n');
}
builder.append(line);
@@ -101,12 +101,8 @@ public final class GroovydocMarkdown {
int from = 0;
while (from < text.length()) {
int start = text.indexOf(open, from);
- if (start < 0) {
- builder.append(text, from, text.length());
- break;
- }
- int end = text.indexOf('}', start + open.length());
- if (end < 0) {
+ int end = start < 0 ? -1 : text.indexOf('}', start + open.length());
+ if (start < 0 || end < 0) {
builder.append(text, from, text.length());
break;
}
@@ -122,12 +118,8 @@ public final class GroovydocMarkdown {
int from = 0;
while (from < text.length()) {
int start = text.indexOf(open, from);
- if (start < 0) {
- builder.append(text, from, text.length());
- break;
- }
- int end = text.indexOf('}', start + open.length());
- if (end < 0) {
+ int end = start < 0 ? -1 : text.indexOf('}', start + open.length());
+ if (start < 0 || end < 0) {
builder.append(text, from, text.length());
break;
}
@@ -207,7 +199,7 @@ public final class GroovydocMarkdown {
} else if (line.startsWith("@see ")) {
line = "**@see** " + line.substring("@see ".length());
}
- if (builder.length() > 0) {
+ if (!builder.isEmpty()) {
builder.append('\n');
}
builder.append(line);
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/GroovyLanguageServerTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/GroovyLanguageServerTest.groovy
index d4cea7e85f..56ddaca26c 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/GroovyLanguageServerTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/GroovyLanguageServerTest.groovy
@@ -18,9 +18,9 @@
*/
package org.apache.groovy.lsp
+import org.apache.groovy.lsp.internal.LanguageServerContext
import org.apache.groovy.lsp.internal.LspFixture
import org.apache.groovy.lsp.internal.compile.CompilerSettings
-import org.eclipse.lsp4j.ClientCapabilities
import org.eclipse.lsp4j.CompletionParams
import org.eclipse.lsp4j.DefinitionParams
import org.eclipse.lsp4j.DidChangeTextDocumentParams
@@ -40,9 +40,24 @@ import org.eclipse.lsp4j.RenameParams
import org.eclipse.lsp4j.TextDocumentContentChangeEvent
import org.eclipse.lsp4j.TextDocumentIdentifier
import org.eclipse.lsp4j.VersionedTextDocumentIdentifier
+import org.eclipse.lsp4j.ClientCapabilities
+import org.eclipse.lsp4j.MessageActionItem
+import org.eclipse.lsp4j.MessageParams
+import org.eclipse.lsp4j.ProgressParams
+import org.eclipse.lsp4j.PublishDiagnosticsParams
+import org.eclipse.lsp4j.ShowMessageRequestParams
+import org.eclipse.lsp4j.TextDocumentItem
+import org.eclipse.lsp4j.services.LanguageClient
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.io.PrintStream
+import java.nio.charset.StandardCharsets
+import java.nio.file.Files
+import java.util.concurrent.CompletableFuture
+
final class GroovyLanguageServerTest {
private LspFixture fixture
@@ -218,4 +233,71 @@ final class GroovyLanguageServerTest {
fixture.server.exit()
fixture = null
}
+
+ @Test
+ void progressEndSurvivesAClientThatRejectsNotifications() {
+ def context = new LanguageServerContext()
+ try {
+ def window = new WindowClientCapabilities()
+ window.workDoneProgress = true
+ def capabilities = new ClientCapabilities()
+ capabilities.window = window
+ context.clientCapabilities = capabilities
+ context.client = new ThrowingProgressClient()
+ def uri = Files.createTempFile('groovy-lsp-progress', '.groovy').toUri().toString()
+ context.documents.open(new TextDocumentItem(uri, 'groovy', 1, 'class Progress {}\n'))
+ assert context.recompile() != null
+ } finally {
+ context.close()
+ }
+ }
+
+ @Test
+ void launcherHelpAndVersionPrintWithoutExiting() {
+ def original = System.out
+ def buffer = new ByteArrayOutputStream()
+ System.setOut(new PrintStream(buffer, true, StandardCharsets.UTF_8))
+ try {
+ GroovyLanguageServerLauncher.main(['--help'] as String[])
+ GroovyLanguageServerLauncher.main(['-h'] as String[])
+ GroovyLanguageServerLauncher.main(['--version'] as String[])
+ GroovyLanguageServerLauncher.main(['-v'] as String[])
+ } finally {
+ System.setOut(original)
+ }
+ def text = buffer.toString(StandardCharsets.UTF_8)
+ assert text.contains('groovylsp')
+ assert text.contains('groovy-lsp')
+ def code = GroovyLanguageServerLauncher.run(new ByteArrayInputStream(new byte[0]), new ByteArrayOutputStream(), false)
+ assert code == null || code == 0
+ }
+
+ private static final class ThrowingProgressClient implements LanguageClient {
+
+ @Override
+ void telemetryEvent(Object object) {
+ }
+
+ @Override
+ void publishDiagnostics(PublishDiagnosticsParams diagnostics) {
+ }
+
+ @Override
+ void showMessage(MessageParams messageParams) {
+ }
+
+ @Override
+ CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams requestParams) {
+ return CompletableFuture.completedFuture(null)
+ }
+
+ @Override
+ void logMessage(MessageParams message) {
+ }
+
+ @Override
+ void notifyProgress(ProgressParams params) {
+ throw new IllegalStateException('progress failed')
+ }
+ }
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/AstQueryTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/AstQueryTest.groovy
new file mode 100644
index 0000000000..e0ca6fc6e9
--- /dev/null
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/AstQueryTest.groovy
@@ -0,0 +1,143 @@
+/*
+ * 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.apache.groovy.lsp.internal.compile
+
+import org.codehaus.groovy.ast.ModuleNode
+import java.nio.file.Path
+import org.eclipse.lsp4j.Position
+import org.codehaus.groovy.ast.expr.AttributeExpression
+import org.apache.groovy.lsp.internal.workspace.TextDocument
+import org.codehaus.groovy.control.SourceUnit
+import org.apache.groovy.lsp.internal.position.PositionEncoding
+import org.junit.jupiter.api.Test
+import org.codehaus.groovy.ast.InnerClassNode
+import org.codehaus.groovy.ast.expr.ConstantExpression
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.ASTNode
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.FieldNode
+import org.junit.jupiter.api.io.TempDir
+
+final class AstQueryTest {
+
+ @TempDir
+ Path folder
+
+
+ @Test
+ void astQueryCoversImportsParametersFieldsAndAttributeNames() {
+ def source = '''\
+ package demo.cov
+
+ import java.util.ArrayList
+ import java.io.*
+ import static java.lang.Math.PI
+ import static java.lang.System.*
+
+ class Outer {
+ private int secret
+ int visible
+ class Inner {
+ def nested() { 1 }
+ }
+ def use(ArrayList items) {
+ def closure = { int x -> x }
+ for (int i = 0; i < items.size(); i++) {
+ i
+ }
+ for (int idx, val in items) {
+ idx
+ }
+ try {
+ this.@secret
+ } catch (Exception caught) {
+ caught
+ }
+ PI
+ }
+ }
+ '''.stripIndent()
+ def compiled = compile(source)
+ def module = compiled.module
+ assert module.package != null
+ assert module.classes.any { it instanceof InnerClassNode }
+
+ def script = new ClassNode('ExtraScript', 0, ClassHelper.OBJECT_TYPE)
+ script.script = true
+ script.lineNumber = 0
+ module.addClass(script)
+
+ assert AstQuery.nodeAt(module, 1, 1) != null
+ def declarations = AstQuery.declarations(module)
+ assert declarations.any { it.is(module.package) }
+ assert declarations.any { it instanceof FieldNode && it.name == 'secret' }
+
+ def pkg = module.package
+ assert AstQuery.containing(module, pkg.lineNumber, pkg.columnNumber).any { it.is(pkg) }
+ def imp = module.imports[0]
+ assert AstQuery.containing(module, imp.lineNumber, imp.columnNumber).any { it.is(imp) }
+
+ def attributes = []
+ AstQuery.walk(module, { node, ctx ->
+ if (node instanceof AttributeExpression) {
+ attributes << node
+ }
+ })
+ assert !attributes.isEmpty()
+ def property = attributes[0].property
+ assert property.lineNumber > 0
+ assert AstQuery.nodeAt(module, property.lineNumber, property.columnNumber) instanceof AttributeExpression
+ def lift = AstQuery.getDeclaredMethod('liftNameLeaf', ASTNode, ASTNode)
+ lift.accessible = true
+ def liftedName = new ConstantExpression('secret')
+ def lifted = new AttributeExpression(new VariableExpression('this'), liftedName)
+ assert lift.invoke(null, liftedName, lifted).is(lifted)
+
+ def document = compiled.toTextDocument()
+ assert AstQuery.enclosingCall(module, document, new Position(0, 0), PositionEncoding.UTF16) != null ||
+ document.text.contains('use')
+ assert AstQuery.nodeAt(module, (TextDocument) null, new Position(0, 0), PositionEncoding.UTF16) == null
+ assert AstQuery.enclosingCall(module, document, null, PositionEncoding.UTF16) == null
+ }
+
+ @Test
+ void astQueryNullGuards() {
+ assert AstQuery.containing(null, 1, 1).isEmpty()
+ assert AstQuery.enclosingMethod(null, 1, 1) == null
+ AstQuery.walk((ModuleNode) null, { node, ctx -> })
+ AstQuery.walk(new ModuleNode((SourceUnit) null), null)
+ AstQuery.walk((ASTNode) null, { node, ctx -> })
+ AstQuery.walk(new ASTNode(), null)
+
+ def script = compile('println 1\n')
+ assert AstQuery.declarations(script.module) != null
+ }
+
+ private CompiledDocument compile(String text) {
+ def compiler = new GroovyCompiler()
+ try {
+ def uri = folder.resolve("Cov${System.nanoTime()}.groovy").toUri()
+ return compiler.compile([new TextDocument(uri, 'groovy', 1, text)], [],
+ CompilerSettings.defaults(), AstQueryTest.classLoader).get(uri)
+ } finally {
+ compiler.close()
+ }
+ }
+}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/CompilerSafetyTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/CompilerSafetyTest.groovy
index 9fb30754c3..61daf81fa8 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/CompilerSafetyTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/CompilerSafetyTest.groovy
@@ -18,6 +18,20 @@
*/
package org.apache.groovy.lsp.internal.compile
+import com.sun.source.tree.CompilationUnitTree
+import com.sun.source.util.JavacTask
+import com.sun.source.util.Trees
+import groovy.lang.GroovyClassLoader
+import java.lang.reflect.InvocationHandler
+import java.lang.reflect.Proxy
+import java.nio.file.Path
+import javax.tools.JavaFileObject
+import javax.tools.ToolProvider
+import org.codehaus.groovy.control.CompilationUnit
+import javax.tools.Diagnostic
+import org.junit.jupiter.api.Assumptions
+import org.junit.jupiter.api.io.TempDir
+
import org.apache.groovy.lsp.internal.diagnostic.DiagnosticConverter
import org.apache.groovy.lsp.internal.position.PositionEncoding
import org.apache.groovy.lsp.internal.workspace.TextDocument
@@ -33,6 +47,11 @@ import org.junit.jupiter.api.Test
import java.nio.file.Files
final class CompilerSafetyTest {
+ private static final Object HOME = new Object()
+
+ @TempDir
+ Path folder
+
@Test
void astTestClosureDoesNotRunWhenDisabled() {
@@ -120,4 +139,232 @@ final class CompilerSafetyTest {
assert fingerprint.contains(live.fileName.toString())
assert fingerprint.contains(missing.fileName.toString())
}
+ @Test
+ void compilerNullInputsUnreadableFilesAndBadSourceNames() {
+ def compiler = new GroovyCompiler()
+ try {
+ def empty = compiler.compile(null, null, CompilerSettings.defaults(), CompilerSafetyTest.classLoader)
+ assert empty.documents().isEmpty()
+
+ def groovy = folder.resolve('Hidden.groovy')
+ def java = folder.resolve('Hidden.java')
+ Files.writeString(groovy, 'class Hidden {}\n')
+ Files.writeString(java, 'public class HiddenJava {}\n')
+ groovy.toFile().setReadable(false, false)
+ java.toFile().setReadable(false, false)
+ try {
+ def snapshot = compiler.compile([], [groovy, java], CompilerSettings.defaults(), CompilerSafetyTest.classLoader)
+ assert snapshot.get(groovy.toUri()) == null
+ assert snapshot.get(java.toUri()) == null
+ } finally {
+ groovy.toFile().setReadable(true, false)
+ java.toFile().setReadable(true, false)
+ }
+ } finally {
+ compiler.close()
+ }
+
+ def addCompiled = GroovyCompiler.getDeclaredMethod('addCompiled', Map, Map, Map, SourceUnit)
+ addCompiled.accessible = true
+ def config = new CompilerConfiguration()
+ def unit = new SourceUnit('not a uri', 'class A {}', config, null, new ErrorCollector(config))
+ def compiled = new LinkedHashMap()
+ addCompiled.invoke(null, compiled, [:], [:], unit)
+ assert compiled.isEmpty()
+ }
+
+ @Test
+ void compilerJointOutputFailureCloseAndLoaderKey() {
+ def homeFile = folder.resolve('not-a-directory')
+ Files.writeString(homeFile, 'x')
+ def java = folder.resolve('Plain.java')
+ Files.writeString(java, 'public class Plain {}\n')
+ withHome(homeFile) {
+ def compiler = new GroovyCompiler()
+ try {
+ def snapshot = compiler.compile(
+ [new TextDocument(folder.resolve('G.groovy').toUri(), 'groovy', 1, 'class G {}')],
+ [java], CompilerSettings.defaults(), CompilerSafetyTest.classLoader)
+ assert snapshot.get(folder.resolve('G.groovy').toUri()) != null
+ } finally {
+ compiler.close()
+ }
+ }
+
+ def throwing = new GroovyCompiler()
+ try {
+ def groovyField = GroovyCompiler.getDeclaredField('groovyLoader')
+ def classpathField = GroovyCompiler.getDeclaredField('classpathLoader')
+ groovyField.accessible = true
+ classpathField.accessible = true
+ groovyField.set(throwing, new GroovyClassLoader(CompilerSafetyTest.classLoader) {
+ @Override
+ void close() throws IOException {
+ throw new IOException('groovy loader')
+ }
+ })
+ classpathField.set(throwing, new URLClassLoader(new URL[0], CompilerSafetyTest.classLoader) {
+ @Override
+ void close() throws IOException {
+ throw new IOException('url loader')
+ }
+ })
+ } finally {
+ throwing.close()
+ }
+
+ def keyType = Class.forName('org.apache.groovy.lsp.internal.compile.GroovyCompiler$LoaderKey')
+ def ctor = keyType.getDeclaredConstructor(List, List, Map, boolean, boolean, ClassLoader)
+ ctor.accessible = true
+ def key = ctor.newInstance([], [], [:], false, false, CompilerSafetyTest.classLoader)
+ assert key.equals(key)
+ assert !key.equals('nope')
+ assert !key.equals(null)
+ }
+
+ @Test
+ void symlinkJavaDiagnosticStillPublishes() {
+ assumeJavac()
+ def real = folder.resolve('real')
+ Files.createDirectories(real)
+ def target = real.resolve('Widget.java')
+ Files.writeString(target, 'public class Widget { int x = ; }\n')
+ def link = folder.resolve('Widget.java')
+ Files.createSymbolicLink(link, target)
+ def compiler = new GroovyCompiler()
+ try {
+ def snapshot = compiler.compile(
+ [new TextDocument(folder.resolve('Use.groovy').toUri(), 'groovy', 1, 'class Use {}')],
+ [link], CompilerSettings.defaults(), CompilerSafetyTest.classLoader)
+ assert snapshot.documents().any { it.javaMessages }
+ } finally {
+ compiler.close()
+ }
+ }
+
+ @Test
+ void javaSymbolIndexPackageAnonymousAndStubUnits() {
+ assumeJavac()
+ def java = folder.resolve('Host.java')
+ Files.writeString(java, '''\
+ package demo;
+ public class Host {
+ public void run() {
+ Runnable r = new Runnable() {
+ public void run() {}
+ };
+ }
+ }
+ '''.stripIndent())
+ def compiler = new GroovyCompiler()
+ try {
+ def snapshot = compiler.compile(
+ [new TextDocument(folder.resolve('Call.groovy').toUri(), 'groovy', 1, 'class Call {}')],
+ [java], CompilerSettings.defaults(), CompilerSafetyTest.classLoader)
+ assert snapshot.javaSymbols().type('demo.Host') != null
+ } finally {
+ compiler.close()
+ }
+
+ def javac = ToolProvider.systemJavaCompiler
+ javac.getStandardFileManager(null, null, null).withCloseable { manager ->
+ def task = javac.getTask(null, manager, null, null, null, List.of()) as JavacTask
+ def trees = Trees.instance(task)
+ def missing = Proxy.newProxyInstance(CompilationUnitTree.classLoader, [CompilationUnitTree] as Class[],
+ { proxy, method, args -> method.name == 'getSourceFile' ? null : null } as InvocationHandler)
+ assert JavaSymbolIndex.of(trees, [missing as CompilationUnitTree]).types().isEmpty()
+ def file = Proxy.newProxyInstance(JavaFileObject.classLoader, [JavaFileObject] as Class[],
+ { proxy, method, args -> method.name == 'toUri' ? null : null } as InvocationHandler) as JavaFileObject
+ def noUri = Proxy.newProxyInstance(CompilationUnitTree.classLoader, [CompilationUnitTree] as Class[],
+ { proxy, method, args -> method.name == 'getSourceFile' ? file : null } as InvocationHandler)
+ assert JavaSymbolIndex.of(trees, [noUri as CompilationUnitTree]).types().isEmpty()
+ }
+
+ def anon = folder.resolve('Anon.java')
+ Files.writeString(anon, '''\
+ package demo;
+ public class Anon {
+ public void run() {
+ new Runnable() { public void run() {} };
+ }
+ }
+ '''.stripIndent())
+ ToolProvider.systemJavaCompiler.getStandardFileManager(null, null, null).withCloseable { manager ->
+ def files = manager.getJavaFileObjects(anon.toFile())
+ def task = ToolProvider.systemJavaCompiler.getTask(null, manager, null, ['--release', '17'], null, files) as JavacTask
+ def units = []
+ task.parse().each { units << it }
+ def indexed = JavaSymbolIndex.of(Trees.instance(task), units)
+ assert indexed.type('demo.Anon') != null
+ def other = ToolProvider.systemJavaCompiler.getTask(null, manager, null, ['--release', '17'], null, List.of()) as JavacTask
+ def shifted = JavaSymbolIndex.of(Trees.instance(other), units)
+ assert shifted.types()
+ }
+ }
+
+ @Test
+ void lspJavaCompilerNullFilesNotesAndUnboundedPositions() {
+ assumeJavac()
+ def compiler = new LspJavaCompiler(Map.of())
+ compiler.compile(null, new CompilationUnit())
+ assert compiler.messages().isEmpty()
+
+ def diagnosticUri = LspJavaCompiler.getDeclaredMethod('diagnosticUri', Diagnostic)
+ diagnosticUri.accessible = true
+ assert diagnosticUri.invoke(null, javacDiagnostic(Diagnostic.Kind.NOTE, null)) == null
+ assert diagnosticUri.invoke(null, javacDiagnostic(Diagnostic.Kind.ERROR, null)) == null
+
+ def bounded = LspJavaCompiler.getDeclaredMethod('bounded', long)
+ bounded.accessible = true
+ assert bounded.invoke(null, -1L) == 1
+ assert bounded.invoke(null, 0L) == 1
+ assert bounded.invoke(null, Integer.MAX_VALUE + 1L) == 1
+ assert bounded.invoke(null, 4L) == 4
+ }
+
+ private CompiledDocument compile(String text) {
+ def compiler = new GroovyCompiler()
+ try {
+ def uri = folder.resolve("Cov${System.nanoTime()}.groovy").toUri()
+ return compiler.compile([new TextDocument(uri, 'groovy', 1, text)], [],
+ CompilerSettings.defaults(), CompilerSafetyTest.classLoader).get(uri)
+ } finally {
+ compiler.close()
+ }
+ }
+
+ private static void withHome(Path home, Closure work) {
+ synchronized (HOME) {
+ def previous = System.getProperty('user.home')
+ System.setProperty('user.home', home.toString())
+ try {
+ work.call()
+ } finally {
+ System.setProperty('user.home', previous)
+ }
+ }
+ }
+
+ private static void assumeJavac() {
+ Assumptions.assumeTrue(ToolProvider.systemJavaCompiler != null, 'jdk.compiler is required')
+ }
+
+ private static Diagnostic javacDiagnostic(Diagnostic.Kind kind, JavaFileObject source) {
+ return (Diagnostic) Proxy.newProxyInstance(Diagnostic.classLoader,
+ [Diagnostic] as Class[], { proxy, method, args ->
+ switch (method.name) {
+ case 'getKind': return kind
+ case 'getSource': return source
+ case 'getLineNumber': return -1L
+ case 'getColumnNumber': return -1L
+ case 'getPosition': return -1L
+ case 'getStartPosition': return -1L
+ case 'getEndPosition': return -1L
+ case 'getCode': return null
+ case 'getMessage': return 'note'
+ default: return null
+ }
+ } as InvocationHandler)
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/ImportSupportTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/ImportSupportTest.groovy
new file mode 100644
index 0000000000..77441d490b
--- /dev/null
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/ImportSupportTest.groovy
@@ -0,0 +1,102 @@
+/*
+ * 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.apache.groovy.lsp.internal.compile
+
+import org.codehaus.groovy.ast.ModuleNode
+import java.nio.file.Path
+import org.apache.groovy.lsp.internal.workspace.TextDocument
+import org.codehaus.groovy.ast.ImportNode
+import org.codehaus.groovy.control.SourceUnit
+import org.apache.groovy.lsp.internal.position.PositionEncoding
+import org.codehaus.groovy.ast.PackageNode
+import org.junit.jupiter.api.Test
+import org.codehaus.groovy.ast.ClassHelper
+import org.junit.jupiter.api.io.TempDir
+
+final class ImportSupportTest {
+
+ @TempDir
+ Path folder
+
+
+ @Test
+ void importSupportCoversAliasesStarsAndUnpositionedRanges() {
+ def plain = new ModuleNode((SourceUnit) null)
+ plain.addImport('List', ClassHelper.make('java.util.List'))
+ assert ImportSupport.needsImport(plain, 'com.example.Other')
+ assert ImportSupport.importedName(new ImportNode(ClassHelper.make('java.lang.Math'), 'PI', 'Pie')) == 'Pie'
+ assert ImportSupport.importedName(new ImportNode('java.util.')) == null
+
+ def compiled = compile('class Holder {}\n')
+ assert ImportSupport.addImport(compiled, 'java.lang.String', PositionEncoding.UTF16).isEmpty()
+
+ def module = new ModuleNode((SourceUnit) null)
+ module.setPackage(new PackageNode('demo'))
+ def text = '\nimport com.example.Widget as Alias\nclass C {}\n'
+ module.addImport('Alias', ClassHelper.make('com.example.Widget'))
+ module.addImport('Missing', ClassHelper.make('org.missing.Thing'))
+ def blank = new ImportNode(ClassHelper.make('org.blank.Type'), 'Blank') {
+ @Override
+ String getText() {
+ return ''
+ }
+ }
+ assert blank.getText().isEmpty()
+ def uri = URI.create('file:///tmp/coverage-import.groovy')
+ def document = new CompiledDocument(uri, 1, text, module, null, null)
+ def rangeOf = ImportSupport.getDeclaredMethod('rangeOf', ImportNode, CompiledDocument, PositionEncoding)
+ rangeOf.accessible = true
+ assert rangeOf.invoke(null, blank, document, PositionEncoding.UTF16) == null
+ assert ImportSupport.unusedDiagnostics(document, PositionEncoding.UTF16).size() == 1
+ assert ImportSupport.removeUnused(document, PositionEncoding.UTF16).size() == 1
+
+ def positioned = new ModuleNode((SourceUnit) null)
+ positioned.setPackage(new PackageNode('demo'))
+ positioned.addImport('List', ClassHelper.make('java.util.List'))
+ def added = positioned.imports[0]
+ added.lineNumber = 2
+ added.columnNumber = 1
+ added.lastLineNumber = 2
+ added.lastColumnNumber = 24
+ def withPackage = new CompiledDocument(uri, 1, '\nimport java.util.List\nclass C {}\n', positioned, null, null)
+ def insert = ImportSupport.insertPosition(withPackage, PositionEncoding.UTF16)
+ assert insert.line == 1
+ assert insert.character == 0
+
+ def star = new ImportNode('java.util.')
+ def field = ImportNode.getDeclaredField('packageName')
+ field.accessible = true
+ field.set(star, null)
+ assert star.packageName == null
+ def starred = new ModuleNode((SourceUnit) null)
+ starred.starImports.add(star)
+ assert ImportSupport.needsImport(starred, 'com.example.Foo')
+ }
+
+ private CompiledDocument compile(String text) {
+ def compiler = new GroovyCompiler()
+ try {
+ def uri = folder.resolve("Cov${System.nanoTime()}.groovy").toUri()
+ return compiler.compile([new TextDocument(uri, 'groovy', 1, text)], [],
+ CompilerSettings.defaults(), ImportSupportTest.classLoader).get(uri)
+ } finally {
+ compiler.close()
+ }
+ }
+}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/WorkspaceLayoutTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/WorkspaceLayoutTest.groovy
index a69b3fd250..127f3c0cb3 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/WorkspaceLayoutTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/compile/WorkspaceLayoutTest.groovy
@@ -18,6 +18,13 @@
*/
package org.apache.groovy.lsp.internal.compile
+import java.nio.file.Path
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.ModuleNode
+import org.codehaus.groovy.control.SourceUnit
+import org.junit.jupiter.api.io.TempDir
+
import org.apache.groovy.lsp.internal.position.PositionEncoding
import org.apache.groovy.lsp.internal.workspace.TextDocument
import org.junit.jupiter.api.Test
@@ -26,6 +33,10 @@ import java.nio.file.Files
final class WorkspaceLayoutTest {
+ @TempDir
+ Path folder
+
+
@Test
void conventionalSourceRootsWinOverWorkspaceRoot() {
def root = Files.createTempDirectory('groovy-lsp-layout')
@@ -138,4 +149,73 @@ final class WorkspaceLayoutTest {
assert edits[0].newText.contains('import org.other.Foo')
compiler.close()
}
+ @Test
+ void snapshotTypeIndexPackageGuessAndWorkspaceEdges() {
+ def oneArg = new CompilationSnapshot(Map.of())
+ assert oneArg.javaSymbols() == JavaSymbolIndex.EMPTY
+ assert oneArg.types() != null
+ assert oneArg.types().is(oneArg.types())
+
+ def script = new ClassNode('Scripty', 0, ClassHelper.OBJECT_TYPE)
+ script.script = true
+ script.lineNumber = 0
+ def alpha = new ClassNode('Alpha', 0, ClassHelper.OBJECT_TYPE)
+ alpha.lineNumber = 1
+ def alpine = new ClassNode('Alpine', 0, ClassHelper.OBJECT_TYPE)
+ alpine.lineNumber = 1
+ def module = new ModuleNode((SourceUnit) null)
+ module.addClass(script)
+ module.addClass(alpha)
+ module.addClass(alpine)
+ def uri = URI.create('file:///tmp/coverage-types.groovy')
+ def typed = new CompilationSnapshot([(uri): new CompiledDocument(uri, 1, 'class Alpha {}', module, null, null)])
+ def types = TypeIndex.of(typed)
+ assert types.byName('Scripty') == null
+ assert types.matchingPrefix('Al', 1).size() == 1
+
+ assert PackageGuess.fromUri(URI.create('file:///'), [URI.create('file:///')], []) == ''
+ assert PackageGuess.fromUri(URI.create('file:///tmp/%00bad.groovy'), [URI.create('file:///tmp')], []) == ''
+ def loose = folder.resolve('Loose.groovy')
+ Files.writeString(loose, 'class Loose {}')
+ assert PackageGuess.fromUri(loose.toUri(), [URI.create('https://example.test/')], []) == ''
+ assert PackageGuess.fromUri(loose.toUri(), [folder.toUri()], []) == ''
+
+ def lib = folder.resolve('lib')
+ Files.createDirectories(lib)
+ assert lib.toFile().setReadable(false, false)
+ assert lib.toFile().setExecutable(false, false)
+ try {
+ assert WorkspaceLayout.classpathJars(folder).isEmpty()
+ } finally {
+ lib.toFile().setReadable(true, false)
+ lib.toFile().setExecutable(true, false)
+ }
+ def inferred = WorkspaceLayout.withInferred(CompilerSettings.defaults(),
+ [null, URI.create('https://example.test/root')])
+ assert inferred.classpath.isEmpty()
+
+ def blocked = folder.resolve('blocked')
+ Files.createDirectories(blocked)
+ assert blocked.toFile().setReadable(false, false)
+ assert blocked.toFile().setExecutable(false, false)
+ try {
+ assert new WorkspaceScanner().scan([blocked.toUri()], []).isEmpty()
+ } finally {
+ blocked.toFile().setReadable(true, false)
+ blocked.toFile().setExecutable(true, false)
+ }
+
+ def first = folder.resolve('cap-a')
+ def second = folder.resolve('cap-b')
+ Files.createDirectories(first)
+ Files.createDirectories(second)
+ for (int i = 0; i < 4000; i++) {
+ Files.createFile(first.resolve("F${i}.groovy"))
+ }
+ Files.writeString(second.resolve('Z.groovy'), 'class Z {}')
+ def found = new WorkspaceScanner().scan([first.toUri(), second.toUri()], [])
+ assert found.size() == 4000
+ assert found.every { it.fileName.toString() != 'Z.groovy' }
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/diagnostic/DiagnosticConverterTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/diagnostic/DiagnosticConverterTest.groovy
index a05b14d7fd..eb600b2814 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/diagnostic/DiagnosticConverterTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/diagnostic/DiagnosticConverterTest.groovy
@@ -18,6 +18,14 @@
*/
package org.apache.groovy.lsp.internal.diagnostic
+import org.codehaus.groovy.control.messages.Diagnostic as GroovyDiagnostic
+import org.codehaus.groovy.control.messages.Message
+import org.eclipse.lsp4j.Diagnostic
+import org.eclipse.lsp4j.MarkupContent
+import org.eclipse.lsp4j.Position
+import org.eclipse.lsp4j.Range
+import org.eclipse.lsp4j.jsonrpc.messages.Either
+
import org.apache.groovy.lsp.internal.compile.CompiledDocument
import org.apache.groovy.lsp.internal.position.PositionEncoding
import org.codehaus.groovy.control.CompilerConfiguration
@@ -83,4 +91,54 @@ final class DiagnosticConverterTest {
def diagnostic = new DiagnosticConverter().toDiagnostic(message, '', PositionEncoding.UTF16, DiagnosticSeverity.Error)
assert diagnostic.range != null
}
+ @Test
+ void diagnosticMessagesAndSmallUtilities() {
+ def uri = URI.create('file:///tmp/coverage-diag.groovy')
+ def config = new CompilerConfiguration()
+ def source = new SourceUnit(uri.toString(), 'class A {}', config, null, new ErrorCollector(config))
+ def collector = new ErrorCollector(config)
+ collector.addErrorAndContinue(new Message() {
+ @Override
+ void write(PrintWriter writer, Janitor janitor) {
+ }
+
+ @Override
+ GroovyDiagnostic toDiagnostic() {
+ throw new IllegalStateException('no diagnostic')
+ }
+ })
+ int[] calls = [0]
+ collector.addErrorAndContinue(new Message() {
+ @Override
+ void write(PrintWriter writer, Janitor janitor) {
+ }
+
+ @Override
+ GroovyDiagnostic toDiagnostic() {
+ if (calls[0]++ == 0) {
+ return new GroovyDiagnostic(uri.toString(), 1, 1, 'first')
+ }
+ throw new IllegalStateException('second')
+ }
+ })
+ collector.addErrorAndContinue(new SimpleMessage('orphan', null))
+ def document = new CompiledDocument(uri, 4, 'class A {}', null, source, collector)
+ assert document.version == 4
+ def diagnostics = new DiagnosticConverter().convert(document, PositionEncoding.UTF16)
+ assert diagnostics.size() == 1
+ assert !DiagnosticConverter.diagnosticMessage(diagnostics[0]).contains('first')
+ assert DiagnosticConverter.diagnosticMessage(null) == null
+ assert DiagnosticConverter.diagnosticMessage(new Diagnostic()) == null
+
+ def markup = new Diagnostic(new Range(new Position(0, 0), new Position(0, 1)), 'temp')
+ markup.setMessage(new MarkupContent('markdown', 'rendered'))
+ assert DiagnosticConverter.diagnosticMessage(markup) == 'rendered'
+ def ctor = Either.getDeclaredConstructor(Object, Object)
+ ctor.accessible = true
+ def empty = ctor.newInstance(null, null)
+ def neither = new Diagnostic()
+ neither.setMessage(empty)
+ assert DiagnosticConverter.diagnosticMessage(neither).contains('Either')
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngineTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngineTest.groovy
index fc896e58ea..43cf784e6f 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngineTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngineTest.groovy
@@ -18,11 +18,22 @@
*/
package org.apache.groovy.lsp.internal.engine
+import org.apache.groovy.lsp.internal.LanguageServerContext
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.eclipse.lsp4j.MessageActionItem
+import org.eclipse.lsp4j.MessageParams
+import org.eclipse.lsp4j.PublishDiagnosticsParams
+import org.eclipse.lsp4j.Range
+import org.eclipse.lsp4j.ShowMessageRequestParams
+import org.eclipse.lsp4j.WorkspaceSymbol
+import org.eclipse.lsp4j.services.LanguageClient
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import java.nio.file.Files
import java.nio.file.Path
+import java.nio.file.attribute.PosixFilePermissions
+import java.util.concurrent.CompletableFuture
final class GroovyLanguageEngineTest {
@@ -80,4 +91,116 @@ final class GroovyLanguageEngineTest {
}
assert nil
}
+
+ @Test
+ void diagnosticsAndImplementationsUseTheSuppliedContext() {
+ def context = new LanguageServerContext()
+ engine = new GroovyLanguageEngine(context)
+ assert engine.context().is(context)
+ def dir = Files.createTempDirectory('groovy-lsp-engine')
+ def broken = dir.resolve('Broken.groovy')
+ Files.writeString(broken, 'class Broken { def x = }\n')
+ def hits = engine.diagnostics(broken)
+ assert !hits.isEmpty()
+ assert hits[0].message()
+ assert hits[0].severity()
+ def explicit = new GroovyLanguageEngine.Hit(hits[0].uri(), 0, 0, 0, 0, 'm', 'Error')
+ assert explicit.message() == 'm'
+
+ def face = dir.resolve('Face.groovy')
+ Files.writeString(face, '''\
+ interface Face {
+ def run()
+ }
+ class Impl implements Face {
+ def run() {}
+ }
+ '''.stripIndent())
+ engine.open(face)
+ def lines = Files.readString(face).readLines()
+ def line = lines.findIndexOf { it.contains('def run()') && !it.contains('class') }
+ def character = lines[line].indexOf('run')
+ def sites = engine.implementations(face, line, character)
+ assert !sites.isEmpty()
+ assert sites[0].snippet().contains('run')
+ }
+
+ @Test
+ void openRejectsAnUnreadableFileAndAClearedBuffer() {
+ def context = new LanguageServerContext()
+ engine = new GroovyLanguageEngine(context)
+ def hidden = Files.createTempFile('groovy-lsp-hidden', '.groovy')
+ Files.writeString(hidden, 'class Hidden {}\n')
+ Files.setPosixFilePermissions(hidden, PosixFilePermissions.fromString('---------'))
+ def failed = false
+ try {
+ engine.open(hidden)
+ } catch (IllegalArgumentException ex) {
+ failed = ex.message.contains('unreadable') && ex.cause instanceof IOException
+ } finally {
+ Files.setPosixFilePermissions(hidden, PosixFilePermissions.fromString('rw-r--r--'))
+ Files.deleteIfExists(hidden)
+ }
+ assert failed
+
+ context.client = new ClearingClient(context)
+ def path = Files.createTempFile('groovy-lsp-clear', '.groovy')
+ Files.writeString(path, 'class Clear {}\n')
+ def missing = false
+ try {
+ engine.describe(path, 0, 0)
+ } catch (IllegalStateException ex) {
+ missing = ex.message.contains('not compiled')
+ } finally {
+ Files.deleteIfExists(path)
+ }
+ assert missing
+ }
+
+ @Test
+ void sitesWithoutBuffersAndSymbolsWithoutLocations() {
+ engine = new GroovyLanguageEngine()
+ def toSite = GroovyLanguageEngine.getDeclaredMethod('toSite', URI, Range)
+ toSite.accessible = true
+ def site = toSite.invoke(engine, URI.create('file:///coverage/missing.groovy'), null) as GroovyLanguageEngine.Site
+ assert site.snippet() == ''
+
+ def toSymbol = GroovyLanguageEngine.getDeclaredMethod('toSymbol', WorkspaceSymbol)
+ toSymbol.accessible = true
+ def symbol = toSymbol.invoke(engine, new WorkspaceSymbol()) as GroovyLanguageEngine.Symbol
+ assert symbol.location().uri() == URI.create('file:///')
+ assert symbol.kind() == 'Object'
+ }
+
+ private static final class ClearingClient implements LanguageClient {
+
+ private final LanguageServerContext context
+
+ private ClearingClient(LanguageServerContext context) {
+ this.context = context
+ }
+
+ @Override
+ void telemetryEvent(Object object) {
+ }
+
+ @Override
+ void publishDiagnostics(PublishDiagnosticsParams diagnostics) {
+ context.documents.clear()
+ context.snapshot = CompilationSnapshot.EMPTY
+ }
+
+ @Override
+ void showMessage(MessageParams messageParams) {
+ }
+
+ @Override
+ CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams requestParams) {
+ return CompletableFuture.completedFuture(null)
+ }
+
+ @Override
+ void logMessage(MessageParams message) {
+ }
+ }
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/ConservativeNavigationTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/ConservativeNavigationTest.groovy
index add387ac16..5604d016fe 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/ConservativeNavigationTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/ConservativeNavigationTest.groovy
@@ -18,6 +18,24 @@
*/
package org.apache.groovy.lsp.internal.feature
+import java.lang.reflect.Modifier
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.apache.groovy.lsp.internal.compile.CompiledDocument
+import org.apache.groovy.lsp.internal.compile.Identifiers
+import org.apache.groovy.lsp.internal.position.Positions
+import org.codehaus.groovy.ast.ASTNode
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.CompileUnit
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.ModuleNode
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
+import org.codehaus.groovy.ast.stmt.EmptyStatement
+import org.codehaus.groovy.ast.stmt.ExpressionStatement
+import org.eclipse.lsp4j.FileRename
+import org.eclipse.lsp4j.InlayHint
+import org.eclipse.lsp4j.WorkspaceEdit
+
import org.apache.groovy.lsp.internal.LspFixture
import org.apache.groovy.lsp.internal.compile.AstQuery
import org.apache.groovy.lsp.internal.compile.CompilerSettings
@@ -45,6 +63,9 @@ import org.junit.jupiter.api.Test
final class ConservativeNavigationTest {
+ private static final PositionEncoding ENC = PositionEncoding.UTF16
+
+
private LspFixture fixture
@AfterEach
@@ -267,4 +288,234 @@ final class ConservativeNavigationTest {
new Position(2, col), new ReferenceContext(true))).get()
assert refs == null || refs.size() <= 1
}
+ @Test
+ void renameGuardsFileMovesAndIdentifierParts() {
+ assert !RenameService.isIdentifier('a-b')
+ assert RenameService.isIdentifier('ok_Name')
+ def rename = new RenameService()
+ def uri = open('Hello.groovy', 'class Hello {\n class Inner {}\n}\n')
+ def doc = compiled(uri)
+ def snap = snapshot()
+ def buffer = doc.toTextDocument()
+ def hello = typeNamed(doc, 'Hello')
+ def renamed = uri.replace('Hello.groovy', 'World.groovy')
+
+ assert rename.willRenameFiles(null, snap, ENC).changes.isEmpty()
+ assert rename.willRenameFiles([], null, ENC).changes.isEmpty()
+ assert newTexts(rename.willRenameFiles([null, new FileRename(uri, renamed)], snap, ENC)).contains('World')
+ assert rename.willRenameFiles([new FileRename()], snap, ENC).changes.isEmpty()
+ assert rename.willRenameFiles([new FileRename(uri, uri.substring(0, uri.lastIndexOf('.')) + '.txt')], snap, ENC).changes.isEmpty()
+ assert rename.willRenameFiles([new FileRename(uri, uri.replace('Hello.groovy', '1World.groovy'))], snap, ENC).changes.isEmpty()
+ def slash = uri.lastIndexOf('/')
+ def parent = uri.substring(0, slash)
+ def elsewhere = parent.substring(0, parent.lastIndexOf('/') + 1) + 'elsewhere/World.groovy'
+ assert rename.willRenameFiles([new FileRename(uri, elsewhere)], snap, ENC).changes.isEmpty()
+ def missing = uri.replace('Hello.groovy', 'Missing.groovy')
+ assert rename.willRenameFiles([new FileRename(missing, uri.replace('Hello.groovy', 'Other.groovy'))], snap, ENC).changes.isEmpty()
+ assert rename.willRenameFiles([new FileRename('mailto:Hello.groovy', 'mailto:World.groovy')], snap, ENC).changes.isEmpty()
+ assert rename.willRenameFiles([new FileRename('Hello.groovy', 'World.groovy')], snap, ENC).changes.isEmpty()
+ assert rename.rename(null, snap, at(doc.text, 'Hello'), 'World', ENC).changes.isEmpty()
+ assert rename.rename(buffer, snap, at(doc.text, 'Hello'), ' ', ENC).changes.isEmpty()
+ assert rename.rename(buffer, snap, at(doc.text, 'Hello'), 'a-b', ENC).changes.isEmpty()
+
+ def decoy = new ClassNode('Hello', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ decoy.script = true
+ decoy.lineNumber = 1
+ decoy.columnNumber = 1
+ decoy.lastLineNumber = 1
+ decoy.lastColumnNumber = 2
+ decoy.module = doc.module
+ def invisible = new ClassNode('Skip', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ invisible.lineNumber = -1
+ invisible.module = doc.module
+ doc.module.classes.add(decoy)
+ doc.module.classes.add(invisible)
+ assert newTexts(rename.willRenameFiles([new FileRename(uri, renamed)], snap, ENC)).contains('World')
+
+ def dup = new ClassNode('Hello', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ dup.lineNumber = 1
+ dup.columnNumber = 1
+ dup.lastLineNumber = 1
+ dup.lastColumnNumber = 2
+ dup.module = doc.module
+ doc.module.classes.add(dup)
+ assert rename.willRenameFiles([new FileRename(uri, renamed)], snap, ENC).changes.isEmpty()
+ doc.module.classes.remove(dup)
+
+ hello.columnNumber = 1
+ hello.lastColumnNumber = 2
+ hello.lastLineNumber = hello.lineNumber
+ assert rename.willRenameFiles([new FileRename(uri, renamed)], snap, ENC).changes.isEmpty()
+ }
+
+ @Test
+ void renameRefusesCallCoveringClassNameAndSkipsFileRename() {
+ def src = 'class Hello {}\n'
+ def uri = open('Hello.groovy', src)
+ def doc = compiled(uri)
+ def type = typeNamed(doc, 'Hello')
+ def rename = new RenameService()
+ def renamed = uri.replace('Hello.groovy', 'World.groovy')
+ assert newTexts(rename.willRenameFiles([new FileRename(uri, renamed)], snapshot(), ENC)).contains('World')
+
+ int start = doc.text.indexOf('Hello') + 1
+ int end = start + 'Hello'.length()
+ def call = new MethodCallExpression(new VariableExpression('this'), 'Hello', MethodCallExpression.NO_ARGUMENTS)
+ place(call, 1, start, end)
+ place(call.method, 1, start, end)
+ def touch = new MethodNode('touch', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY,
+ ClassNode.EMPTY_ARRAY, new ExpressionStatement(call))
+ place(touch, 1, 1, doc.text.length())
+ type.addMethod(touch)
+ assert AstQuery.nodeAt(doc.module, doc.toTextDocument(), at(doc.text, 'Hello'), ENC) instanceof MethodCallExpression
+ assert rename.willRenameFiles([new FileRename(uri, renamed)], snapshot(), ENC).changes.isEmpty()
+
+ def txt = open('Hello.txt', 'class Hello {}\n')
+ def txtDoc = compiled(txt)
+ def txtEdit = rename.rename(txtDoc.toTextDocument(), snapshot(), at(txtDoc.text, 'Hello'), 'World', ENC)
+ assert newTexts(txtEdit).contains('World')
+ assert txtEdit.documentChanges == null
+
+ def other = open('Other.groovy', 'class Hello {}\n')
+ def otherDoc = compiled(other)
+ def otherEdit = rename.rename(otherDoc.toTextDocument(), snapshot(), at(otherDoc.text, 'Hello'), 'World', ENC)
+ assert newTexts(otherEdit).contains('World')
+ assert otherEdit.documentChanges == null
+
+ def relative = URI.create('Hello.groovy')
+ def relativeType = new ClassNode('Hello', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ place(relativeType, 1, 1, src.length())
+ def relativeDoc = handCompiled(relative, src, relativeType)
+ def relativeSnap = new CompilationSnapshot([(relative): relativeDoc])
+ def relativeEdit = rename.rename(relativeDoc.toTextDocument(), relativeSnap, at(src, 'Hello'), 'World', ENC)
+ assert newTexts(relativeEdit).contains('World')
+ assert relativeEdit.documentChanges == null
+ }
+
+ @Test
+ void prepareRenameRejectsNamelessAndUnlocatedNodes() {
+ def text = 'class Holder {\n}\n'
+ def uri = URI.create('file:///Holder.groovy')
+ def type = new ClassNode('Holder', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ place(type, 1, 1, text.length())
+ def nameless = new MethodNode(null, Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY,
+ ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ place(nameless, 1, 1, 5)
+ type.addMethod(nameless)
+ def missing = new MethodNode('missing', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY,
+ ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ place(missing, 2, 1, 2)
+ type.addMethod(missing)
+ def doc = handCompiled(uri, text, type)
+ def snap = new CompilationSnapshot([(uri): doc])
+ def buffer = doc.toTextDocument()
+ assert AstQuery.nodeAt(doc.module, buffer, new Position(0, 0), ENC).is(nameless)
+ assert Identifiers.nameOf(nameless) == null
+ assert new RenameService().prepareRename(buffer, snap, new Position(0, 0), ENC) == null
+ assert AstQuery.nodeAt(doc.module, buffer, new Position(1, 0), ENC).is(missing)
+ assert Positions.toIdentifierRange(missing, text, ENC) == null
+ assert new RenameService().prepareRename(buffer, snap, new Position(1, 0), ENC) == null
+ }
+
+ @Test
+ void inlayHintsSkipSyntheticUnresolvedAndMatchingNames() {
+ def src = '''\
+ class Box {
+ def early() {
+ def count = "x"
+ }
+ static int add(int left, int right) { left + right }
+ static int sum(int $skip, int right) { $skip + right }
+ int plain() { sum(1, 2) }
+ int same(int left) { add(left, 2) }
+ def dyn(def item) { item }
+ def later() { 1 }
+ }
+ '''.stripIndent()
+ def uri = open('Box.groovy', src)
+ def doc = compiled(uri)
+ def box = typeNamed(doc, 'Box')
+ def service = new InlayHintService()
+ def labels = service.inlayHints(doc, null, ENC, snapshot()).collect { hintLabel(it) }
+ assert labels.any { it.contains('String') || it.contains('GString') } : labels
+ assert labels.any { it == 'right:' } : labels
+ assert labels.every { it != 'left:' && it != '$skip:' && !it.startsWith('Object') } : labels
+
+ def laterLine = doc.text.readLines().findIndexOf { it.contains('later') }
+ def restricted = service.inlayHints(doc, new Range(new Position(laterLine, 0), new Position(laterLine, 1)), ENC, snapshot())
+ assert restricted.every { it.position.line >= laterLine }
+ assert restricted.every { !(hintLabel(it).contains('String') || hintLabel(it).contains('GString') || hintLabel(it) == 'right:') }
+ def staticNames = []
+ AstQuery.walk(box) { node, ctx ->
+ if (node instanceof StaticMethodCallExpression) {
+ staticNames << node.method
+ }
+ }
+ assert staticNames.containsAll(['sum', 'add']) : staticNames
+ }
+
+ private String open(String path, String text) {
+ if (fixture == null) {
+ fixture = new LspFixture()
+ }
+ fixture.open(path, text)
+ }
+
+ private CompilationSnapshot snapshot() {
+ fixture.server.context.snapshot
+ }
+
+ private CompiledDocument compiled(String uri) {
+ def doc = snapshot().get(uri)
+ assert doc?.module != null
+ doc
+ }
+
+ private static ClassNode typeNamed(CompiledDocument doc, String simple) {
+ def found = doc.module.classes.find { it.nameWithoutPackage == simple && !it.name.contains('$') }
+ assert found != null : doc.module.classes*.name
+ found
+ }
+
+ private static CompiledDocument handCompiled(URI uri, String text, ClassNode type) {
+ def module = new ModuleNode((CompileUnit) null)
+ module.addClass(type)
+ new CompiledDocument(uri, 1, text, module, null, null)
+ }
+
+ private static void place(ASTNode node, int line, int column, int lastColumn) {
+ node.lineNumber = line
+ node.columnNumber = column
+ node.lastLineNumber = line
+ node.lastColumnNumber = lastColumn
+ }
+
+ private static Position at(String text, String token) {
+ int index = text.indexOf(token)
+ assert index >= 0 : token
+ int line = 0
+ int column = 0
+ for (int i = 0; i < index; i++) {
+ if (text.charAt(i) == '\n') {
+ line += 1
+ column = 0
+ } else {
+ column += 1
+ }
+ }
+ new Position(line, column)
+ }
+
+ private static List<String> newTexts(WorkspaceEdit edit) {
+ if (edit?.changes == null) {
+ return []
+ }
+ edit.changes.values().flatten().collect { it.newText as String }
+ }
+
+ private static String hintLabel(InlayHint hint) {
+ def label = hint.getLabel()
+ label.isLeft() ? label.getLeft() : String.valueOf(label.getRight())
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/DocumentSymbolTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/DocumentSymbolTest.groovy
new file mode 100644
index 0000000000..98d8360f2a
--- /dev/null
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/DocumentSymbolTest.groovy
@@ -0,0 +1,152 @@
+/*
+ * 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.apache.groovy.lsp.internal.feature
+
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.apache.groovy.lsp.internal.LspFixture
+import org.eclipse.lsp4j.SymbolKind
+import org.objectweb.asm.Opcodes
+import org.codehaus.groovy.ast.Parameter
+import java.lang.reflect.Modifier
+import org.junit.jupiter.api.AfterEach
+import org.apache.groovy.lsp.internal.position.PositionEncoding
+import org.apache.groovy.lsp.internal.compile.AstQuery
+import org.junit.jupiter.api.Test
+import org.codehaus.groovy.ast.ConstructorNode
+import org.codehaus.groovy.ast.ASTNode
+import org.codehaus.groovy.ast.ClassHelper
+import org.apache.groovy.lsp.internal.compile.CompiledDocument
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.stmt.EmptyStatement
+import org.codehaus.groovy.ast.FieldNode
+
+final class DocumentSymbolTest {
+ private static final PositionEncoding ENC = PositionEncoding.UTF16
+
+
+ private LspFixture fixture
+
+ @AfterEach
+ void tearDown() {
+ fixture?.close()
+ }
+
+
+ @Test
+ void symbolsSkipUnresolvedRangesAndReportKinds() {
+ def symbols = new SymbolService()
+ assert symbols.documentSymbols(null, ENC).isEmpty()
+ assert symbols.documentSymbols(new CompiledDocument(URI.create('file:///none.groovy'), 1, '', null, null, null), ENC).isEmpty()
+ assert symbols.workspaceSymbols(null, 'Named', ENC).isEmpty()
+ assert symbols.documentSymbolInformation(null, ENC).isEmpty()
+ assert SymbolService.kindOf(new ClassNode('Color', Opcodes.ACC_ENUM | Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE)) == SymbolKind.Enum
+ assert SymbolService.kindOf(new ConstructorNode(Modifier.PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new EmptyStatement())) == SymbolKind.Constructor
+ assert SymbolService.kindOf(new FieldNode('f', 0, ClassHelper.int_TYPE, ClassHelper.OBJECT_TYPE, null)) == SymbolKind.Field
+ assert SymbolService.kindOf(new Parameter(ClassHelper.int_TYPE, 'p')) == SymbolKind.Variable
+
+ def src = '''\
+ import java.util.List
+ class Named {
+ String title
+ def foo() { title }
+ }
+ '''.stripIndent()
+ def uri = open('Named.groovy', src)
+ def doc = compiled(uri)
+ def type = typeNamed(doc, 'Named')
+ def field = ensureField(doc, type, 'title')
+ def top = symbols.documentSymbols(doc, ENC)
+ assert top*.name == ['Named']
+ assert top[0].children.any { it.name == 'title' && it.kind == SymbolKind.Field }
+ def info = symbols.documentSymbolInformation(doc, ENC)
+ assert info*.name.containsAll(['Named', 'title', 'foo'])
+ assert info.size() < AstQuery.declarations(doc.module).size()
+ def extra = plus(snapshot(), new CompiledDocument(URI.create('file:///null-module.groovy'), 1, '', null, null, null))
+ assert symbols.workspaceSymbols(extra, 'Named', ENC)*.name.contains('Named')
+
+ field.lineNumber = 0
+ type.properties.findAll { it.name == 'title' }.each { it.lineNumber = 0 }
+ assert symbols.workspaceSymbols(snapshot(), 'title', ENC).isEmpty()
+ assert symbols.workspaceSymbols(snapshot(), 'foo', ENC)*.name.contains('foo')
+ def children = symbols.documentSymbols(doc, ENC)[0].children*.name
+ assert !children.contains('title')
+ assert children.contains('foo')
+ }
+
+ private String open(String path, String text) {
+ if (fixture == null) {
+ fixture = new LspFixture()
+ }
+ fixture.open(path, text)
+ }
+
+ private CompilationSnapshot snapshot() {
+ fixture.server.context.snapshot
+ }
+
+ private CompiledDocument compiled(String uri) {
+ def doc = snapshot().get(uri)
+ assert doc?.module != null
+ doc
+ }
+
+ private static ClassNode typeNamed(CompiledDocument doc, String simple) {
+ def found = doc.module.classes.find { it.nameWithoutPackage == simple && !it.name.contains('$') }
+ assert found != null : doc.module.classes*.name
+ found
+ }
+
+ private static CompilationSnapshot plus(CompilationSnapshot base, CompiledDocument... extra) {
+ def map = new LinkedHashMap<URI, CompiledDocument>()
+ if (base != null) {
+ for (CompiledDocument doc : base.documents()) {
+ if (doc.uri != null) {
+ map.put(doc.uri, doc)
+ }
+ }
+ }
+ for (CompiledDocument doc : extra) {
+ def key = doc.uri != null ? doc.uri : URI.create('file:///synthetic-' + System.identityHashCode(doc) + '.groovy')
+ map.put(key, doc)
+ }
+ new CompilationSnapshot(map)
+ }
+
+ private static void place(ASTNode node, int line, int column, int lastColumn) {
+ node.lineNumber = line
+ node.columnNumber = column
+ node.lastLineNumber = line
+ node.lastColumnNumber = lastColumn
+ }
+
+ private static FieldNode ensureField(CompiledDocument doc, ClassNode type, String name) {
+ def existing = type.fields.find { it.name == name && !it.synthetic }
+ if (existing != null) {
+ return existing
+ }
+ def lines = doc.text.readLines()
+ int line = lines.findIndexOf { it.contains(name) }
+ assert line >= 0 : name
+ int column = lines[line].indexOf(name)
+ def field = new FieldNode(name, Modifier.PRIVATE, ClassHelper.STRING_TYPE, type, null)
+ place(field, line + 1, column + 1, column + 1 + name.length())
+ type.addField(field)
+ field
+ }
+}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/JdtInspiredTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/JdtInspiredTest.groovy
index 5c9152435d..f4bff1ff83 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/JdtInspiredTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/JdtInspiredTest.groovy
@@ -18,6 +18,31 @@
*/
package org.apache.groovy.lsp.internal.feature
+import java.lang.reflect.Modifier
+import org.apache.groovy.lsp.internal.compile.AstQuery
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.apache.groovy.lsp.internal.compile.CompiledDocument
+import org.apache.groovy.lsp.internal.position.PositionEncoding
+import org.apache.groovy.lsp.internal.position.Positions
+import org.apache.groovy.lsp.internal.util.GroovydocMarkdown
+import org.apache.groovy.lsp.internal.workspace.TextDocument
+import org.codehaus.groovy.ast.ASTNode
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.ConstructorNode
+import org.codehaus.groovy.ast.FieldNode
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.Parameter
+import org.codehaus.groovy.ast.PropertyNode
+import org.codehaus.groovy.ast.expr.ConstantExpression
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.expr.PropertyExpression
+import org.codehaus.groovy.ast.expr.TupleExpression
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.stmt.EmptyStatement
+import org.codehaus.groovy.transform.stc.StaticTypesMarker
+import org.objectweb.asm.Opcodes
+
import org.apache.groovy.lsp.internal.LspFixture
import org.eclipse.lsp4j.CodeActionContext
import org.eclipse.lsp4j.CodeActionParams
@@ -32,6 +57,10 @@ import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
final class JdtInspiredTest {
+ private static final PositionEncoding UTF16 = PositionEncoding.UTF16
+
+ private static final PositionEncoding ENC = PositionEncoding.UTF16
+
private LspFixture fixture
@@ -158,4 +187,410 @@ final class JdtInspiredTest {
assert action != null
action.getRight().edit.changes.values().flatten()[0].newText
}
+ @Test
+ void sourceGenerationFiltersCapitalizeAndUnpositionedInsert() {
+ assert SourceGeneration.instanceFields(null).isEmpty()
+ assert SourceGeneration.capitalize(null) == ''
+ assert SourceGeneration.capitalize('') == ''
+ assert SourceGeneration.capitalize('widget') == 'Widget'
+
+ def owner = new ClassNode('demo.Filtered', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ def kept = field(owner, 'kept', Modifier.PRIVATE, ClassHelper.STRING_TYPE, 2)
+ owner.addField(kept)
+ def stat = field(owner, 'STAT', Modifier.STATIC, ClassHelper.int_TYPE, 3)
+ owner.addField(stat)
+ def hidden = field(owner, 'hidden', Modifier.PRIVATE, ClassHelper.OBJECT_TYPE, 4)
+ hidden.synthetic = true
+ owner.addField(hidden)
+ def meta = field(owner, 'metaClass', Modifier.PRIVATE, ClassHelper.OBJECT_TYPE, 5)
+ owner.addField(meta)
+ owner.addField(field(owner, 'nolines', Modifier.PRIVATE, ClassHelper.STRING_TYPE, -1))
+
+ def ghost = new PropertyNode('ghost', Modifier.PUBLIC, ClassHelper.STRING_TYPE, owner, null, null, null)
+ ghost.field = null
+ owner.getProperties().add(ghost)
+ def staticProp = new PropertyNode('COUNT', Modifier.STATIC | Modifier.PUBLIC, ClassHelper.int_TYPE, owner, null, null, null)
+ owner.getProperties().add(staticProp)
+ def syntheticProp = new PropertyNode('syn', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, owner, null, null, null)
+ syntheticProp.synthetic = true
+ owner.getProperties().add(syntheticProp)
+ def metaProp = new PropertyNode('metaClass', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, owner, null, null, null)
+ owner.getProperties().add(metaProp)
+ assert SourceGeneration.instanceFields(owner)*.name == ['kept']
+
+ def bare = new ClassNode('Bare', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ bare.addField(field(bare, 'name', Modifier.PRIVATE, ClassHelper.STRING_TYPE, 1))
+ def bareDoc = new CompiledDocument(URI.create('file:///Bare.groovy'), 1, 'class Bare {\n}\n', null, null, null)
+ assert SourceGeneration.beforeClose(bare, bareDoc, ENC) == null
+ assert SourceGeneration.toStringMethod(bare, bareDoc, ENC).isEmpty()
+ assert SourceGeneration.overrideAnnotations(null, bareDoc, ENC).isEmpty()
+
+ def text = 'class Bare {\n int a\n\n'
+ def open = new ClassNode('Bare', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ open.lineNumber = 1
+ open.columnNumber = 1
+ open.lastLineNumber = 3
+ open.lastColumnNumber = 1
+ def openDoc = new CompiledDocument(URI.create('file:///Bare.groovy'), 1, text, null, null, null)
+ def end = Positions.toRange(open, text, ENC).end
+ def insert = SourceGeneration.beforeClose(open, openDoc, ENC)
+ assert insert.line == end.line
+ assert insert.character == end.character
+
+ def noInterfaces = new ClassNode('Lonely', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ noInterfaces.setInterfaces(null)
+ def run = new MethodNode('run', Modifier.PUBLIC, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY,
+ ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ run.lineNumber = 1
+ run.columnNumber = 1
+ run.lastLineNumber = 1
+ run.lastColumnNumber = 4
+ noInterfaces.addMethod(run)
+ assert SourceGeneration.overrideAnnotations(noInterfaces, bareDoc, ENC).isEmpty()
+ }
+
+ @Test
+ void sourceGenerationEditsAndOverrideAnnotations() {
+ def src = '''\
+ class Pair {
+ String left
+ String right
+ }
+ class HasString {
+ String name
+ String toString() { name }
+ }
+ class HasEquals {
+ String name
+ boolean equals(Object o) { false }
+ }
+ class HasCtor {
+ String name
+ HasCtor(String name) { this.name = name }
+ }
+ class Parent {
+ void run() {}
+ void ping() {}
+ }
+ class Child extends Parent {
+ @Deprecated
+ void run() {}
+ @Override
+ void ping() {}
+ }
+ interface Face {
+ void run()
+ }
+ class Impl implements Face {
+ void run() {}
+ }
+ '''.stripIndent()
+ def uri = open('Gen.groovy', src)
+ def doc = compiled(uri)
+ def pair = typeNamed(doc, 'Pair')
+ def toString = SourceGeneration.toStringMethod(pair, doc, ENC)
+ assert toString.size() == 1
+ assert toString[0].newText.contains('left: ${left}, right: ${right}')
+ def equals = SourceGeneration.equalsAndHashCode(pair, doc, ENC)
+ assert equals.size() == 1
+ assert equals[0].newText.contains('left == other.left && right == other.right')
+ assert equals[0].newText.contains('Objects.hash(left, right)')
+ assert SourceGeneration.toStringMethod(typeNamed(doc, 'HasString'), doc, ENC).isEmpty()
+ assert SourceGeneration.equalsAndHashCode(typeNamed(doc, 'HasEquals'), doc, ENC).isEmpty()
+ assert SourceGeneration.constructor(typeNamed(doc, 'HasCtor'), doc, ENC).isEmpty()
+
+ def generatedCtor = SourceGeneration.constructor(pair, doc, ENC)
+ if (generatedCtor.isEmpty()) {
+ pair.declaredConstructors.clear()
+ def synthetic = new ConstructorNode(Modifier.PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ synthetic.synthetic = true
+ pair.addConstructor(synthetic)
+ generatedCtor = SourceGeneration.constructor(pair, doc, ENC)
+ }
+ assert generatedCtor.size() == 1
+ assert generatedCtor[0].newText.contains('String left, String right')
+ assert generatedCtor[0].newText.contains('this.left = left')
+
+ def lines = doc.text.readLines()
+ def childEdits = SourceGeneration.overrideAnnotations(typeNamed(doc, 'Child'), doc, ENC)
+ assert childEdits
+ assert childEdits.every { it.newText.contains('@Override') }
+ assert childEdits.any { lines[it.range.start.line].contains('run') }
+ assert childEdits.every { !lines[it.range.start.line].contains('ping') }
+
+ def impl = typeNamed(doc, 'Impl')
+ def implEdits = SourceGeneration.overrideAnnotations(impl, doc, ENC)
+ assert implEdits.any { it.newText.contains('@Override') && lines[it.range.start.line].contains('run') }
+ def run = impl.methods.find { it.name == 'run' && !it.synthetic }
+ run.columnNumber = 1
+ run.lastColumnNumber = 2
+ run.lastLineNumber = run.lineNumber
+ assert SourceGeneration.overrideAnnotations(impl, doc, ENC).isEmpty()
+ }
+
+ @Test
+ void codeLensSkipsFieldsAndUnlocatedNames() {
+ def src = '''\
+ class Hello {
+ String name
+ def foo() { foo() }
+ }
+ '''.stripIndent()
+ def uri = open('Hello.groovy', src)
+ def doc = compiled(uri)
+ ensureField(doc, typeNamed(doc, 'Hello'), 'name')
+ def service = new CodeLensService()
+ def decls = AstQuery.declarations(doc.module)
+ assert decls.any { it instanceof PropertyNode }
+ def lenses = service.codeLenses(doc, snapshot(), ENC)
+ assert lenses.size() == decls.count { it instanceof ClassNode || it instanceof MethodNode }
+ assert lenses.every { it.command.title.contains('reference') }
+
+ def hello = typeNamed(doc, 'Hello')
+ hello.columnNumber = 1
+ hello.lastColumnNumber = 2
+ hello.lastLineNumber = hello.lineNumber
+ def after = service.codeLenses(doc, snapshot(), ENC)
+ assert lenses.any { it.range.start.line == 0 }
+ assert after.size() == lenses.size() - 1
+ assert after.every { it.range.start.line != 0 }
+ }
+
+ private String open(String path, String text) {
+ if (fixture == null) {
+ fixture = new LspFixture()
+ }
+ fixture.open(path, text)
+ }
+
+ private CompilationSnapshot snapshot() {
+ fixture.server.context.snapshot
+ }
+
+ private CompiledDocument compiled(String uri) {
+ def doc = snapshot().get(uri)
+ assert doc?.module != null
+ doc
+ }
+
+ private static ClassNode typeNamed(CompiledDocument doc, String simple) {
+ def found = doc.module.classes.find { it.nameWithoutPackage == simple && !it.name.contains('$') }
+ assert found != null : doc.module.classes*.name
+ found
+ }
+
+ private static FieldNode field(ClassNode owner, String name, int modifiers, ClassNode type, int line) {
+ def node = new FieldNode(name, modifiers, type, owner, null)
+ node.lineNumber = line
+ node.columnNumber = 1
+ node.lastLineNumber = line
+ node.lastColumnNumber = 2
+ node
+ }
+
+ private static FieldNode ensureField(CompiledDocument doc, ClassNode type, String name) {
+ def existing = type.fields.find { it.name == name && !it.synthetic }
+ if (existing != null) {
+ return existing
+ }
+ def lines = doc.text.readLines()
+ int line = lines.findIndexOf { it.contains(name) }
+ assert line >= 0 : name
+ int column = lines[line].indexOf(name)
+ def field = new FieldNode(name, Modifier.PRIVATE, ClassHelper.STRING_TYPE, type, null)
+ place(field, line + 1, column + 1, column + 1 + name.length())
+ type.addField(field)
+ field
+ }
+
+ private static void place(ASTNode node, int line, int column, int lastColumn) {
+ node.lineNumber = line
+ node.columnNumber = column
+ node.lastLineNumber = line
+ node.lastColumnNumber = lastColumn
+ }
+
+ @Test
+ void sourceGenerationHoverAndInference() {
+ fixture = new LspFixture()
+ def text = '''\
+ /**
+ * Documented API.
+ * @param name who
+ * @return a label
+ */
+ interface Face {
+ void ping()
+ void run(String name, int count)
+ Object value()
+ }
+ class Impl implements Face {
+ String left
+ String right
+ private String hidden
+ void ping() { ping() }
+ void run(String name, int count) { left }
+ Object value() { 'v' }
+ def local(def label) {
+ def item = 'z'
+ /*xdef*/ def other = 1
+ this.@left
+ String
+ }
+ }
+ enum Hue { RED }
+ record Rec(String name) {}
+ class Plain {
+ private String secret
+ String a
+ String b
+ }
+ class HasCtor {
+ String a
+ HasCtor(String a) { this.a = a }
+ String toString() { a }
+ boolean equals(Object o) { true }
+ }
+ '''.stripIndent()
+ def uri = fixture.open('Sample.groovy', text)
+ def snapshot = fixture.server.context.snapshot
+ def compiled = snapshot.get(uri)
+ def module = compiled.module
+ def impl = module.classes.find { it.name == 'Impl' }
+ def face = module.classes.find { it.name == 'Face' }
+ def hue = module.classes.find { it.name == 'Hue' }
+ def rec = module.classes.find { it.name == 'Rec' }
+ def plain = module.classes.find { it.name == 'Plain' }
+ def hasCtor = module.classes.find { it.name == 'HasCtor' }
+ def run = impl.methods.find { it.name == 'run' && it.lineNumber > 0 }
+
+ assert SourceGeneration.instanceFields(null).isEmpty()
+ assert SourceGeneration.capitalize(null) == ''
+ assert SourceGeneration.capitalize('') == ''
+ assert SourceGeneration.capitalize('über').startsWith('Ü')
+ assert SourceGeneration.toStringMethod(hasCtor, compiled, UTF16).isEmpty()
+ assert SourceGeneration.equalsAndHashCode(hasCtor, compiled, UTF16).isEmpty()
+ assert SourceGeneration.constructor(hasCtor, compiled, UTF16).isEmpty()
+ assert SourceGeneration.overrideAnnotations(null, compiled, UTF16).isEmpty()
+ def unpositioned = new ClassNode('X', 0, ClassHelper.OBJECT_TYPE)
+ assert SourceGeneration.beforeClose(unpositioned, compiled, UTF16) == null
+
+ def accessors = SourceGeneration.accessors(plain, compiled, UTF16)
+ assert accessors[0].newText.contains('getSecret')
+ assert accessors[0].newText.contains('setSecret')
+ def generated = SourceGeneration.toStringMethod(plain, compiled, UTF16)[0].newText
+ assert generated.contains('a: ${a}, b: ${b}')
+ def equals = SourceGeneration.equalsAndHashCode(plain, compiled, UTF16)[0].newText
+ assert equals.contains('a == other.a && b == other.b')
+ assert equals.contains('Objects.hash(secret, a, b)')
+ def ctor = SourceGeneration.constructor(impl, compiled, UTF16)[0].newText
+ assert ctor.contains('String left, String right')
+ def overrides = SourceGeneration.overrideAnnotations(impl, compiled, UTF16)
+ assert overrides.any { it.newText.contains('@Override') }
+
+ def empty = module.classes.find { it.name == 'Hue' }
+ assert SourceGeneration.equalsAndHashCode(new ClassNode('pkg.Empty', Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE), compiled, UTF16).isEmpty() || empty != null
+
+ def hover = new HoverService()
+ assert hover.markdown(null, snapshot, new Position(0, 0), UTF16) == ''
+ assert hover.hover(null, snapshot, new Position(0, 0), UTF16) == null
+ assert HoverService.render(face).contains('interface ')
+ assert HoverService.render(hue).contains('enum ')
+ assert HoverService.render(rec).contains('record ')
+ assert HoverService.render(impl).contains('class ')
+ assert HoverService.render(run).contains(', ')
+ def noOwner = new MethodNode('ping', 0, ClassHelper.VOID_TYPE,
+ [new Parameter(ClassHelper.STRING_TYPE, 'a'), new Parameter(ClassHelper.int_TYPE, 'b')] as Parameter[],
+ ClassNode.EMPTY_ARRAY, null)
+ assert HoverService.render(noOwner).contains(', ')
+ assert !HoverService.render(noOwner).contains('.')
+ def field = impl.fields.find { it.name == 'left' }
+ assert HoverService.render(field).contains('left')
+ def property = impl.properties.find { it.name == 'left' }
+ assert HoverService.render(property).contains('left')
+ assert HoverService.render(run.parameters[0]).contains('name')
+ def dynamicProperty = new PropertyExpression(new VariableExpression('obj'), new VariableExpression('dyn'))
+ assert HoverService.render(dynamicProperty).contains('?')
+ def targeted = new MethodCallExpression(new VariableExpression('this'), 'run', new TupleExpression())
+ targeted.methodTarget = run
+ assert HoverService.render(targeted).contains('run')
+ def loose = new MethodCallExpression(new VariableExpression('this'), 'run', new TupleExpression())
+ assert HoverService.render(loose).contains('run(...)')
+ def imp = module.imports.find { it.className?.contains('Object') } ?: module.imports[0]
+ if (imp != null) {
+ assert HoverService.render(imp).contains('import')
+ }
+ assert HoverService.render(new ConstantExpression('z')).contains('z')
+ assert HoverService.render(new ASTNode()) == null
+
+ def document = compiled.toTextDocument()
+ def faceHover = hover.hover(document, snapshot, caret(text, 'Face'), UTF16)
+ assert faceHover.contents.getRight().value.contains('Documented API')
+ def itemHover = hover.hover(document, snapshot, caret(text, 'item'), UTF16)
+ assert itemHover.contents.getRight().value.contains('_inferred_')
+
+ def looseDoc = new TextDocument(URI.create('file:///loose.groovy'), 'groovy', 1, 'Hello')
+ def looseHover = hover.hover(looseDoc, CompilationSnapshot.EMPTY, new Position(0, 'Hello'.length()), UTF16)
+ assert looseHover.contents.getRight().value.contains('Hello')
+ assert looseHover.range == null
+
+ assert TypeInference.of((FieldNode) null) == null
+ assert TypeInference.of((Parameter) null) == null
+ assert TypeInference.of((VariableExpression) null, null) == null
+ assert !TypeInference.usedInitializer((FieldNode) null)
+ assert !TypeInference.usedInitializer((VariableExpression) null, module)
+ def marked = new FieldNode('name', 0, ClassHelper.DYNAMIC_TYPE, ClassHelper.OBJECT_TYPE, new ConstantExpression('hi'))
+ marked.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, 'nope')
+ marked.putNodeMetaData(StaticTypesMarker.DECLARATION_INFERRED_TYPE, ClassHelper.STRING_TYPE)
+ assert TypeInference.of(marked).name == 'java.lang.String'
+ def fromInit = new FieldNode('n', 0, ClassHelper.DYNAMIC_TYPE, ClassHelper.OBJECT_TYPE, new ConstantExpression('hi'))
+ assert TypeInference.of(fromInit) != null
+ def typed = new FieldNode('s', 0, ClassHelper.STRING_TYPE, ClassHelper.OBJECT_TYPE, null)
+ assert !TypeInference.usedInitializer(typed)
+ def parameter = new Parameter(ClassHelper.OBJECT_TYPE, 'p')
+ parameter.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, ClassHelper.Integer_TYPE)
+ assert TypeInference.of(parameter).name == 'java.lang.Integer'
+ def viaField = new VariableExpression('v', ClassHelper.DYNAMIC_TYPE)
+ viaField.accessedVariable = fromInit
+ assert TypeInference.of(viaField, null) != null
+
+ def markdown = GroovydocMarkdown.format('''\
+ /**
+ * See {@link java.lang.String#length() size} and {@link #member(int a)}.
+ * {@link pkg.Type} {@link Type}
+ * {@link java.lang.String#length()
+ * <b>bold</b><br><dangling
+ * @param name the name
+ * @return the value
+ * @throws IllegalStateException when broken
+ * @exception IOException also
+ * @see java.lang.String#length()
+ * @see java.util.List
+ */
+ '''.stripIndent())
+ assert markdown.contains('**@param** `name`')
+ assert markdown.contains('**@throws** `IllegalStateException`')
+ assert markdown.contains('**@exception** `IOException`')
+ assert markdown.contains('**@see**')
+ assert markdown.contains('String.length')
+ assert markdown.contains('**bold**')
+ assert GroovydocMarkdown.format('@param only') == '**@param** `only`'
+ }
+
+ private static Position caret(String text, String token) {
+ int idx = text.indexOf(token)
+ assert idx >= 0 : token
+ int line = 0
+ int character = 0
+ for (int i = 0; i < idx; i++) {
+ if (text.charAt(i) == '\n') {
+ line++
+ character = 0
+ } else {
+ character++
+ }
+ }
+ new Position(line, character)
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/LanguageQualityTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/LanguageQualityTest.groovy
index 02b285ad1d..a3dc5c4ba5 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/LanguageQualityTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/LanguageQualityTest.groovy
@@ -18,6 +18,32 @@
*/
package org.apache.groovy.lsp.internal.feature
+import groovy.lang.groovydoc.Groovydoc
+import groovy.lang.groovydoc.GroovydocHolder
+import java.lang.reflect.Modifier
+import java.nio.file.Path
+import org.apache.groovy.lsp.internal.compile.AstQuery
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.apache.groovy.lsp.internal.compile.CompiledDocument
+import org.apache.groovy.lsp.internal.compile.GroovyCompiler
+import org.apache.groovy.lsp.internal.position.PositionEncoding
+import org.apache.groovy.lsp.internal.util.Uris
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.ModuleNode
+import org.codehaus.groovy.ast.Parameter
+import org.codehaus.groovy.ast.PropertyNode
+import org.codehaus.groovy.ast.expr.MapExpression
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
+import org.codehaus.groovy.ast.expr.TupleExpression
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.stmt.EmptyStatement
+import org.codehaus.groovy.control.SourceUnit
+import org.eclipse.lsp4j.CompletionItemKind
+import static org.objectweb.asm.Opcodes.ACC_PUBLIC
+
import org.apache.groovy.lsp.internal.LspFixture
import org.apache.groovy.lsp.internal.LanguageServerContext
import org.apache.groovy.lsp.internal.compile.CompilerSettings
@@ -40,6 +66,10 @@ import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
final class LanguageQualityTest {
+ private static final PositionEncoding UTF16 = PositionEncoding.UTF16
+
+ private static final PositionEncoding ENC = PositionEncoding.UTF16
+
private LspFixture fixture
@@ -233,4 +263,246 @@ final class LanguageQualityTest {
def labels = result.getRight().items*.label
assert !('each' in labels)
}
+ @Test
+ void completionResolvesDocsAndGdkWithoutModule() {
+ def gdk = new TextDocument(fileUri('file:///tmp/cov-gdk.groovy'), 'groovy', 1, 'foo.ea')
+ def gdkItems = new CompletionService().complete(gdk, null, new Position(0, 6), UTF16).items
+ assert gdkItems.any { it.label == 'each' && it.detail == 'GDK' }
+
+ def uri = fileUri('file:///tmp/cov-docs.groovy')
+ def snap = compileOf(uri, 'class Hello {}\n')
+ def hello = snap.get(uri).module.classes.find { it.nameWithoutPackage == 'Hello' }
+ hello.putNodeMetaData(GroovydocHolder.DOC_COMMENT, new Groovydoc('Hello type docs.', hello))
+ def typeItem = new CompletionItem('Hello')
+ typeItem.data = [k: 't', n: 'Hello']
+ def typeResolved = new CompletionService().resolve(typeItem, snap)
+ assert typeResolved.documentation.getRight().value.contains('Hello type docs')
+
+ def owner = new ClassNode('demo.Hello', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def method = owner.addMethod('foo', ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ method.lineNumber = 2
+ method.putNodeMetaData(GroovydocHolder.DOC_COMMENT, new Groovydoc('Does the thing.', method))
+ def module = new ModuleNode((SourceUnit) null)
+ module.addClass(owner)
+ def methodUri = fileUri('file:///tmp/cov-method-doc.groovy')
+ def methodSnap = snapshot(new CompiledDocument(methodUri, 1, 'class Hello { def foo() {} }\n', module, null, null))
+ def methodItem = new CompletionItem('foo')
+ methodItem.data = [k: 'm', n: 'foo', o: 'demo.Hello', d: '']
+ def methodResolved = new CompletionService().resolve(methodItem, methodSnap)
+ assert methodResolved.documentation.getRight().value.contains('Does the thing')
+
+ def blank = new CompletionItem('x')
+ blank.data = 'nope'
+ assert new CompletionService().resolve(blank, methodSnap).documentation == null
+ def emptyData = new CompletionItem('x')
+ emptyData.data = [k: null]
+ assert new CompletionService().resolve(emptyData, methodSnap).documentation == null
+ }
+
+ @Test
+ void completionMembersNamedArgumentsAndOverrides() {
+ fixture = new LspFixture()
+ def src = '''\
+ enum Color { RED }
+ interface Face {
+ void run()
+ // face-caret
+ }
+ interface Named { String name() }
+ class Hello implements Named {
+ String name
+ int years
+ Hello(String name, int age) {}
+ static void go(String name, int age) {}
+ void foo(String name) {}
+ def bar(String left, int right) {
+ zzz
+ ri
+ Co
+ Hello.na
+ go(xx, ag)
+ new Hello(yy, ag)
+ foo(name: 1)
+ }
+ }
+ '''.stripIndent()
+ def uri = fixture.open('Hello.groovy', src)
+ def doc = fixture.server.context.documentFor(uri)
+ def snap = fixture.server.context.snapshot
+ def module = snap.get(uri).module
+ assert walked(module, StaticMethodCallExpression) { it.method == 'go' }
+ def foo = null
+ AstQuery.walk(module) { node, ctx ->
+ if (node instanceof MethodCallExpression && node.methodAsString == 'foo') {
+ foo = node
+ }
+ }
+ assert foo != null
+ assert foo.arguments instanceof TupleExpression
+ assert foo.arguments.expressions.any { it instanceof MapExpression }
+ assert MethodBinding.resolveMethod(foo, snap)?.name == 'foo'
+
+ def service = new CompletionService()
+ def faceLine = src.readLines().findIndexOf { it.contains('face-caret') }
+ def faceItems = service.complete(doc, snap, new Position(faceLine, 0), UTF16).items
+ assert faceItems.every { it.detail == null || !it.detail.startsWith('override') }
+
+ def zzz = itemsAt(service, doc, snap, src, 'zzz')
+ assert zzz.every { it.detail == null || !it.detail.startsWith('override') }
+
+ def locals = itemsAt(service, doc, snap, src, 'ri')
+ assert locals.any { it.label == 'right' && it.kind == CompletionItemKind.Variable }
+ assert locals.every { it.label != 'left' }
+
+ def enums = itemsAt(service, doc, snap, src, 'Co')
+ assert enums.any { it.label == 'Color' && it.kind == CompletionItemKind.Enum }
+
+ def helloType = module.classes.find { it.nameWithoutPackage == 'Hello' }
+ helloType.addField('other', ACC_PUBLIC, ClassHelper.int_TYPE, null)
+ helloType.addField('nameTag', ACC_PUBLIC, ClassHelper.STRING_TYPE, null)
+ def fields = itemsAt(service, doc, snap, src, 'Hello.na')
+ assert fields.any { it.label == 'nameTag' && it.kind == CompletionItemKind.Field }
+
+ def staticNamed = itemsAt(service, doc, snap, src, 'go(xx, ag')
+ assert staticNamed.any { it.label == 'age' && it.detail == 'named argument' }
+ assert staticNamed.every { it.detail != 'named argument' || it.label != 'name' }
+
+ def ctorNamed = itemsAt(service, doc, snap, src, 'new Hello(yy, ag')
+ assert ctorNamed.any { it.label == 'age' && it.detail == 'named argument' }
+
+ def used = itemsAt(service, doc, snap, src, 'foo(name: 1')
+ assert used.every { it.detail != 'named argument' }
+ }
+
+ private CompilationSnapshot compileOf(URI uri, String text) {
+ compileOf([new TextDocument(uri, 'groovy', 1, text)])
+ }
+
+ private CompilationSnapshot compileOf(List<TextDocument> documents) {
+ def compiler = new GroovyCompiler()
+ try {
+ return compiler.compile(documents, [], CompilerSettings.defaults(), getClass().classLoader)
+ } finally {
+ compiler.close()
+ }
+ }
+
+ private static CompilationSnapshot snapshot(CompiledDocument... documents) {
+ def map = [:]
+ documents.each { map[it.uri] = it }
+ new CompilationSnapshot(map)
+ }
+
+ private static URI fileUri(String path) {
+ Uris.normalize(URI.create(path))
+ }
+
+ private static URI fileUri(Path path) {
+ Uris.normalize(path.toUri())
+ }
+
+ private static List itemsAt(CompletionService service, TextDocument document, CompilationSnapshot snapshot,
+ String text, String token) {
+ def lines = text.readLines()
+ int line = -1
+ for (int i = lines.size() - 1; i >= 0; i--) {
+ if (lines[i].contains(token)) {
+ line = i
+ break
+ }
+ }
+ assert line >= 0
+ int column = lines[line].indexOf(token) + token.length() - 1
+ service.complete(document, snapshot, new Position(line, column), UTF16).items
+ }
+
+ private static boolean walked(module, Class type, Closure predicate) {
+ boolean[] found = [false]
+ AstQuery.walk(module) { node, ctx ->
+ if (type.isInstance(node) && predicate(node)) {
+ found[0] = true
+ }
+ }
+ found[0]
+ }
+
+ @Test
+ void hoverMarkdownForRecordsPropertiesTargetsAndIdentifiers() {
+ def hover = new HoverService()
+ assert hover.hover(null, null, new Position(0, 0), ENC) == null
+ assert hover.markdown(null, null, new Position(0, 0), ENC) == ''
+
+ def blank = new TextDocument(URI.create('file:///blank.groovy'), 'groovy', 1, ' \n')
+ def blankDoc = new CompiledDocument(blank.uri, 1, blank.text, null, null, null)
+ def blankSnap = new CompilationSnapshot([(blank.uri): blankDoc])
+ assert hover.markdown(blank, blankSnap, new Position(0, 1), ENC) == ''
+ assert hover.hover(blank, blankSnap, new Position(0, 1), ENC) == null
+
+ def recordType = ClassHelper.make('java.lang.Record')
+ def rec = new ClassNode('Point', Modifier.PUBLIC, recordType)
+ assert rec.record
+ def recordMarkdown = HoverService.render(rec)
+ assert recordMarkdown.contains('record')
+ assert recordMarkdown.contains('Point')
+
+ def owner = new ClassNode('Box', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ def property = new PropertyNode('title', Modifier.PUBLIC, ClassHelper.STRING_TYPE, owner, null, null, null)
+ def propertyMarkdown = HoverService.render(property)
+ assert propertyMarkdown.contains('String')
+ assert propertyMarkdown.contains('title')
+
+ def params = [new Parameter(ClassHelper.STRING_TYPE, 'left'), new Parameter(ClassHelper.int_TYPE, 'right')] as Parameter[]
+ def method = new MethodNode('join', Modifier.PUBLIC, ClassHelper.STRING_TYPE, params, ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ method.declaringClass = new ClassNode('Util', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ def call = new MethodCallExpression(new VariableExpression('this'), 'join', MethodCallExpression.NO_ARGUMENTS)
+ call.methodTarget = method
+ def callMarkdown = HoverService.render(call)
+ assert callMarkdown.contains('Util.join')
+ assert callMarkdown.contains('String left, int right')
+
+ def widgetUri = open('Widget.groovy', 'class Widget {}\n')
+ def note = new TextDocument(URI.create('file:///note.groovy'), 'groovy', 1, 'Widget\n')
+ def noteDoc = new CompiledDocument(note.uri, 1, note.text, null, null, null)
+ def snap = plus(snapshot(), noteDoc)
+ assert snap.types().uniqueBySimpleName('Widget') != null
+ def markdown = hover.markdown(note, snap, new Position(0, 'Widget'.length()), ENC)
+ assert markdown.startsWith('```groovy')
+ assert markdown.contains(snap.types().uniqueBySimpleName('Widget').name())
+ assert compiled(widgetUri).module != null
+ }
+
+ private String open(String path, String text) {
+ if (fixture == null) {
+ fixture = new LspFixture()
+ }
+ fixture.open(path, text)
+ }
+
+ private CompilationSnapshot snapshot() {
+ fixture.server.context.snapshot
+ }
+
+ private CompiledDocument compiled(String uri) {
+ def doc = snapshot().get(uri)
+ assert doc?.module != null
+ doc
+ }
+
+ private static CompilationSnapshot plus(CompilationSnapshot base, CompiledDocument... extra) {
+ def map = new LinkedHashMap<URI, CompiledDocument>()
+ if (base != null) {
+ for (CompiledDocument doc : base.documents()) {
+ if (doc.uri != null) {
+ map.put(doc.uri, doc)
+ }
+ }
+ }
+ for (CompiledDocument doc : extra) {
+ def key = doc.uri != null ? doc.uri : URI.create('file:///synthetic-' + System.identityHashCode(doc) + '.groovy')
+ map.put(key, doc)
+ }
+ new CompilationSnapshot(map)
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/MetalsInspiredTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/MetalsInspiredTest.groovy
index a22f17b072..1a806152ee 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/MetalsInspiredTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/MetalsInspiredTest.groovy
@@ -18,6 +18,37 @@
*/
package org.apache.groovy.lsp.internal.feature
+import java.nio.file.Path
+import org.apache.groovy.lsp.internal.compile.AstQuery
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.apache.groovy.lsp.internal.compile.CompiledDocument
+import org.apache.groovy.lsp.internal.util.Uris
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.ModuleNode
+import org.codehaus.groovy.ast.PackageNode
+import org.codehaus.groovy.ast.Parameter
+import org.codehaus.groovy.ast.expr.ArgumentListExpression
+import org.codehaus.groovy.ast.expr.ConstantExpression
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression
+import org.codehaus.groovy.ast.expr.MapEntryExpression
+import org.codehaus.groovy.ast.expr.MapExpression
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
+import org.codehaus.groovy.ast.expr.TupleExpression
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.stmt.BlockStatement
+import org.codehaus.groovy.ast.stmt.EmptyStatement
+import org.codehaus.groovy.ast.stmt.ExpressionStatement
+import org.codehaus.groovy.control.SourceUnit
+import org.junit.jupiter.api.io.TempDir
+import static org.objectweb.asm.Opcodes.ACC_ABSTRACT
+import static org.objectweb.asm.Opcodes.ACC_INTERFACE
+import static org.objectweb.asm.Opcodes.ACC_PUBLIC
+import static org.objectweb.asm.Opcodes.ACC_STATIC
+import static org.objectweb.asm.Opcodes.ACC_SYNTHETIC
+
import org.apache.groovy.lsp.internal.LspFixture
import org.apache.groovy.lsp.internal.diagnostic.DiagnosticConverter
import org.apache.groovy.lsp.internal.compile.CompilerSettings
@@ -46,6 +77,8 @@ import org.junit.jupiter.api.Test
import java.nio.file.Files
final class MetalsInspiredTest {
+ private static final PositionEncoding UTF16 = PositionEncoding.UTF16
+
private LspFixture fixture
@@ -328,4 +361,448 @@ final class MetalsInspiredTest {
new CodeActionContext([widget, gadget]))).get()
assert actions.any { it.getRight().title == 'Add all unambiguous imports' }
}
+ @Test
+ void contributeWithoutSnapshotIsEmpty() {
+ def document = new TextDocument(fileUri('file:///tmp/cov-none.groovy'), 'groovy', 1, 'class Use {}\n')
+ assert new CodeActionService().contribute(document, null, [], null, UTF16, [], []).isEmpty()
+ def actions = new CodeActionService().collect(document, null, [unresolved('demo.Widget')], null, UTF16, [], [])
+ assert titles(actions) == ['Organize imports']
+ assert CodeActionService.unresolvedClassName(null) == null
+ assert CodeActionService.unresolvedClassName('unable to resolve class demo.Widget') == 'demo.Widget'
+ }
+
+ @Test
+ void packageActionInsertsOrReplaces(@TempDir Path folder) {
+ def root = folder.resolve('src/main/groovy/com/acme')
+ Files.createDirectories(root)
+ def bare = root.resolve('Hello.groovy')
+ def bareUri = fileUri(bare)
+ def bareSnap = compileOf(bareUri, 'class Hello {}\n')
+ def inserted = new CodeActionService().contribute(bareSnap.get(bareUri).toTextDocument(), bareSnap, [],
+ null, UTF16, [folder.toUri()], [])
+ def add = inserted.find { it.isRight() && it.getRight().title == 'Add package com.acme' }
+ assert add != null
+ assert editText(add) == 'package com.acme\n\n'
+
+ def wrong = root.resolve('Wrong.groovy')
+ def wrongUri = fileUri(wrong)
+ def wrongSnap = compileOf(wrongUri, 'package wrong\nclass Hello {}\n')
+ def replaced = new CodeActionService().contribute(wrongSnap.get(wrongUri).toTextDocument(), wrongSnap, [],
+ null, UTF16, [folder.toUri()], [])
+ def fix = replaced.find { it.isRight() && it.getRight().title == 'Add package com.acme' }
+ assert fix != null
+ assert editText(fix) == 'package com.acme'
+
+ def otherUri = fileUri(root.resolve('Other.groovy'))
+ def module = new ModuleNode((SourceUnit) null)
+ module.setPackage(new PackageNode('wrong'))
+ def hello = new ClassNode('Hello', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ hello.lineNumber = 2
+ hello.columnNumber = 1
+ hello.lastLineNumber = 2
+ hello.lastColumnNumber = 12
+ module.addClass(hello)
+ def compiled = new CompiledDocument(otherUri, 1, 'package wrong\nclass Hello {}\n', module, null, null)
+ def skipped = new CodeActionService().contribute(compiled.toTextDocument(), snapshot(compiled), [],
+ null, UTF16, [folder.toUri()], [])
+ assert titles(skipped).every { !it.startsWith('Add package') }
+ }
+
+ @Test
+ void inferredTypeSkipsUnresolvedAndEmbeddedDef() {
+ def uri = fileUri('file:///tmp/cov-infer.groovy')
+ def src = '''\
+ class Hello {
+ def bare
+ def bar() {
+ String typed = "x"
+ def loose
+ }
+ }
+ '''.stripIndent()
+ def snap = compileOf(uri, src)
+ def actions = new CodeActionService().contribute(snap.get(uri).toTextDocument(), snap, [], null, UTF16, [], [])
+ assert titles(actions).every { !it.startsWith('Insert inferred type') }
+
+ def owner = new ClassNode('Hello', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def field = owner.addField('name', ACC_PUBLIC, ClassHelper.STRING_TYPE, null)
+ field.lineNumber = 1
+ field.columnNumber = 1
+ field.lastLineNumber = 1
+ field.lastColumnNumber = 5
+ def module = new ModuleNode((SourceUnit) null)
+ module.addClass(owner)
+ def text = 'name defdef\n'
+ def compiled = new CompiledDocument(fileUri('file:///tmp/cov-defdef.groovy'), 1, text, module, null, null)
+ def embedded = new CodeActionService().contribute(compiled.toTextDocument(), snapshot(compiled), [],
+ null, UTF16, [], [])
+ assert titles(embedded).every { !it.startsWith('Insert inferred type') }
+ }
+
+ @Test
+ void namedArgumentsCoverStaticConstructorAndGuards() {
+ def uri = fileUri('file:///tmp/cov-named.groovy')
+ def src = '''\
+ class Hello {
+ Hello(String name) {}
+ static void go(String name) {}
+ void foo(String name) {}
+ void bar() {
+ go("a")
+ new Hello("b")
+ foo(name: "a")
+ }
+ }
+ '''.stripIndent()
+ def snap = compileOf(uri, src)
+ def calls = []
+ AstQuery.walk(snap.get(uri).module) { node, ctx ->
+ if (node instanceof MethodCallExpression || node instanceof StaticMethodCallExpression
+ || node instanceof ConstructorCallExpression) {
+ calls << node
+ }
+ }
+ def foo = calls.find { it instanceof MethodCallExpression && it.methodAsString == 'foo' }
+ assert foo != null
+ assert foo.arguments instanceof TupleExpression
+ assert foo.arguments.expressions.any { it instanceof MapExpression }
+ assert MethodBinding.resolveMethod(foo, snap)?.name == 'foo'
+ assert calls.any { it instanceof StaticMethodCallExpression && it.method == 'go' }
+ assert calls.any { it instanceof ConstructorCallExpression }
+ def actions = new CodeActionService().contribute(snap.get(uri).toTextDocument(), snap, [], null, UTF16, [], [])
+ def named = actions.findAll { it.isRight() && it.getRight().title == 'Convert to named arguments' }
+ assert named.size() == 2
+ assert named.every { editText(it).contains('name:') }
+
+ def guarded = guardedNamedCalls()
+ def guardedActions = new CodeActionService().contribute(guarded.toTextDocument(), snapshot(guarded), [],
+ null, UTF16, [], [])
+ def converted = guardedActions.findAll { it.isRight() && it.getRight().title == 'Convert to named arguments' }
+ assert converted.size() == 1
+ assert editText(converted[0]) == 'name: '
+ }
+
+ @Test
+ void createClassUsesSimpleNameAtEndWithoutNewline() {
+ def text = 'class Use {}'
+ def uri = fileUri('file:///tmp/cov-create.groovy')
+ def module = new ModuleNode((SourceUnit) null)
+ def type = new ClassNode('Use', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ type.lineNumber = 1
+ type.columnNumber = 7
+ type.lastLineNumber = 1
+ type.lastColumnNumber = 10
+ module.addClass(type)
+ def compiled = new CompiledDocument(uri, 1, text, module, null, null)
+ def actions = new CodeActionService().contribute(compiled.toTextDocument(), snapshot(compiled),
+ [unresolved('widget'), unresolved('com.acme.Widget')], null, UTF16, [], [])
+ def creates = titles(actions).findAll { it.startsWith('Create class') }
+ assert creates == ['Create class Widget']
+ def created = actions.find { it.isRight() && it.getRight().title == 'Create class Widget' }
+ assert editText(created).contains('class Widget')
+ assert created.getRight().edit.changes.values().collectMany { it }[0].range.start.line == 0
+ assert created.getRight().edit.changes.values().collectMany { it }[0].range.start.character == text.length()
+ }
+
+ @Test
+ void abstractMembersFilterSyntheticGroovyObjectAndBodies() {
+ def snippets = new MethodNode('run', ACC_PUBLIC, ClassHelper.int_TYPE,
+ [new Parameter(ClassHelper.STRING_TYPE, 'name'), new Parameter(ClassHelper.int_TYPE, 'age')] as Parameter[],
+ ClassNode.EMPTY_ARRAY, null)
+ def snippet = CodeActionService.overrideSnippet(snippets)
+ assert snippet.contains('int run(')
+ assert snippet.contains('String name, int age')
+ def objectMethod = new MethodNode('box', ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ assert CodeActionService.overrideSnippet(objectMethod).startsWith('@Override\ndef box(')
+ def voidMethod = new MethodNode('go', ACC_PUBLIC, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ assert CodeActionService.overrideSnippet(voidMethod).contains('void go(')
+
+ def groovyObject = new ClassNode('groovy.lang.GroovyObject', ACC_INTERFACE | ACC_ABSTRACT, ClassHelper.OBJECT_TYPE)
+ groovyObject.addMethod('ping', ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ def host = new ClassNode('Host', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ host.addInterface(groovyObject)
+ assert host.abstractMethods.any { it.name == 'ping' && it.declaringClass.name == 'groovy.lang.GroovyObject' }
+ assert CodeActionService.missingAbstracts(host).every { it.name != 'ping' }
+
+ def box = new ClassNode('Box', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def hidden = box.addMethod('hidden', ACC_PUBLIC | ACC_ABSTRACT | ACC_SYNTHETIC, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ hidden.synthetic = true
+ assert box.abstractMethods.any { it.name == 'hidden' }
+ assert CodeActionService.missingAbstracts(box).every { it.name != 'hidden' }
+
+ def face = new ClassNode('Face', ACC_INTERFACE | ACC_ABSTRACT, ClassHelper.OBJECT_TYPE)
+ face.addMethod('run', ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ def body = new ClassNode('Body', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ body.addInterface(face)
+ body.addMethod('run', ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ assert body.abstractMethods.any { it.name == 'run' && it.abstract }
+ assert CodeActionService.missingAbstracts(body).every { it.declaringClass?.name != 'Face' }
+
+ def pending = new ClassNode('Pending', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ pending.addInterface(face)
+ assert CodeActionService.missingAbstracts(pending)
+ def module = new ModuleNode((SourceUnit) null)
+ module.addClass(face)
+ module.addClass(pending)
+ def compiled = new CompiledDocument(fileUri('file:///tmp/cov-pending.groovy'), 1, 'class Pending {}\n',
+ module, null, null)
+ def actions = new CodeActionService().contribute(compiled.toTextDocument(), snapshot(compiled), [],
+ new Range(new Position(0, 0), new Position(0, 4)), UTF16, [], [])
+ assert titles(actions).every { it != 'Implement abstract methods' }
+ }
+
+ @Test
+ void organizeImportsSortsAndRejectsBadSpans() {
+ def uri = fileUri('file:///tmp/cov-imports.groovy')
+ def src = '''\
+ import java.util.concurrent.ConcurrentHashMap
+ import java.util.ArrayList
+ class Hello {}
+ '''.stripIndent()
+ def snap = compileOf(uri, src)
+ def sorted = new CodeActionService().collect(snap.get(uri).toTextDocument(), snap, null, null, UTF16, [], [])
+ def organize = sorted.find { it.isRight() && it.getRight().title == 'Organize imports' }
+ assert organize.getRight().edit != null
+ def edited = editText(organize)
+ assert edited.indexOf('import java.util.ArrayList') < edited.indexOf('import java.util.concurrent.ConcurrentHashMap')
+ assert titles(sorted).every { !it.startsWith('Add import') }
+ assert titles(sorted).every { !it.startsWith('Create class') }
+
+ def service = new CodeActionService()
+ assert service.organizeImports(null, UTF16).isEmpty()
+ def noModule = new CompiledDocument(fileUri('file:///tmp/cov-nomodule.groovy'), 1, 'import java.util.List\n',
+ null, null, null)
+ assert service.organizeImports(noModule, UTF16).isEmpty()
+
+ def unpositioned = importDocument(fileUri('file:///tmp/cov-unpos.groovy'), 'import java.util.List\n', -1, 1, -1, 1)
+ assert service.organizeImports(unpositioned, UTF16).isEmpty()
+
+ def beyond = importDocument(fileUri('file:///tmp/cov-beyond.groovy'), 'import java.util.List\n', 40, 1, 40, 5)
+ assert service.organizeImports(beyond, UTF16)[0].newText.contains('import java.util.List')
+
+ def inverted = importDocument(fileUri('file:///tmp/cov-invert.groovy'), 'import java.util.List\n', 1, 10, 1, 3)
+ assert service.organizeImports(inverted, UTF16)[0].newText.contains('import java.util.List')
+ }
+
+ @Test
+ void importFixesUseQualifiedNamesAndSkipSamePackage() {
+ def widgetUri = fileUri('file:///tmp/cov-demo-widget.groovy')
+ def sameUri = fileUri('file:///tmp/cov-demo-use.groovy')
+ def otherUri = fileUri('file:///tmp/cov-other-use.groovy')
+ def snap = compileOf([
+ new TextDocument(widgetUri, 'groovy', 1, 'package demo\nclass Widget {}\n'),
+ new TextDocument(sameUri, 'groovy', 1, 'package demo\nclass Use {}\n'),
+ new TextDocument(otherUri, 'groovy', 1, 'package other\nclass Use {}\n')
+ ])
+ assert snap.types().bySimpleName('Widget').size() == 1
+ def service = new CodeActionService()
+ def same = service.collect(snap.get(sameUri).toTextDocument(), snap, [unresolved('Widget')],
+ null, UTF16, [], [])
+ assert titles(same).every { it != 'Add import for demo.Widget' }
+ def qualified = service.collect(snap.get(otherUri).toTextDocument(), snap, [unresolved('demo.Widget')],
+ null, UTF16, [], [])
+ assert titles(qualified).contains('Add import for demo.Widget')
+ }
+
+ private static CompiledDocument guardedNamedCalls() {
+ def owner = new ClassNode('Hello', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def name = new Parameter(ClassHelper.STRING_TYPE, 'name')
+ def dollar = new Parameter(ClassHelper.STRING_TYPE, '$name')
+ owner.addMethod('go', ACC_PUBLIC | ACC_STATIC, ClassHelper.VOID_TYPE, [name] as Parameter[],
+ ClassNode.EMPTY_ARRAY, null)
+ def hidden = owner.addMethod('hidden', ACC_PUBLIC, ClassHelper.VOID_TYPE, [dollar] as Parameter[],
+ ClassNode.EMPTY_ARRAY, null)
+ def plain = owner.addMethod('plain', ACC_PUBLIC, ClassHelper.VOID_TYPE, [name] as Parameter[],
+ ClassNode.EMPTY_ARRAY, null)
+ def shown = owner.addMethod('shown', ACC_PUBLIC, ClassHelper.VOID_TYPE, [name] as Parameter[],
+ ClassNode.EMPTY_ARRAY, null)
+ def mapCall = new StaticMethodCallExpression(owner, 'go', new MapExpression([
+ new MapEntryExpression(new ConstantExpression('name'), new ConstantExpression('a'))
+ ]))
+ def dollarCall = new MethodCallExpression(new VariableExpression('this'), 'hidden',
+ new ArgumentListExpression(new ConstantExpression('a')))
+ dollarCall.methodTarget = hidden
+ def plainCall = new MethodCallExpression(new VariableExpression('this'), 'plain',
+ new ArgumentListExpression(new ConstantExpression('a')))
+ plainCall.methodTarget = plain
+ def arg = new ConstantExpression('a')
+ arg.lineNumber = 1
+ arg.columnNumber = 8
+ arg.lastLineNumber = 1
+ arg.lastColumnNumber = 2
+ def inverted = new MethodCallExpression(new VariableExpression('this'), 'shown',
+ new ArgumentListExpression(arg))
+ inverted.methodTarget = shown
+ def block = new BlockStatement()
+ block.addStatement(new ExpressionStatement(mapCall))
+ block.addStatement(new ExpressionStatement(dollarCall))
+ block.addStatement(new ExpressionStatement(plainCall))
+ block.addStatement(new ExpressionStatement(inverted))
+ owner.addMethod('bar', ACC_PUBLIC, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, block)
+ def module = new ModuleNode((SourceUnit) null)
+ module.addClass(owner)
+ new CompiledDocument(fileUri('file:///tmp/cov-guard.groovy'), 1, 'abcdefghijklmnop', module, null, null)
+ }
+
+ private static CompiledDocument importDocument(URI uri, String text, int line, int column, int lastLine, int lastColumn) {
+ def module = new ModuleNode((SourceUnit) null)
+ module.addImport('List', ClassHelper.LIST_TYPE)
+ def imp = module.imports[0]
+ imp.lineNumber = line
+ imp.columnNumber = column
+ imp.lastLineNumber = lastLine
+ imp.lastColumnNumber = lastColumn
+ def type = new ClassNode('Hello', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ type.lineNumber = 1
+ module.addClass(type)
+ new CompiledDocument(uri, 1, text, module, null, null)
+ }
+
+ private CompilationSnapshot compileOf(URI uri, String text) {
+ compileOf([new TextDocument(uri, 'groovy', 1, text)])
+ }
+
+ private CompilationSnapshot compileOf(List<TextDocument> documents) {
+ def compiler = new GroovyCompiler()
+ try {
+ return compiler.compile(documents, [], CompilerSettings.defaults(), getClass().classLoader)
+ } finally {
+ compiler.close()
+ }
+ }
+
+ private static CompilationSnapshot snapshot(CompiledDocument... documents) {
+ def map = [:]
+ documents.each { map[it.uri] = it }
+ new CompilationSnapshot(map)
+ }
+
+ private static URI fileUri(String path) {
+ Uris.normalize(URI.create(path))
+ }
+
+ private static URI fileUri(Path path) {
+ Uris.normalize(path.toUri())
+ }
+
+ private static Diagnostic unresolved(String name) {
+ def diagnostic = new Diagnostic()
+ diagnostic.range = new Range(new Position(0, 0), new Position(0, 1))
+ diagnostic.message = Either.forLeft('unable to resolve class ' + name)
+ diagnostic
+ }
+
+ private static List<String> titles(List actions) {
+ actions.findAll { it.isRight() }.collect { it.getRight().title }
+ }
+
+ private static String editText(def action) {
+ action.getRight().edit.changes.values().collectMany { it }[0].newText
+ }
+
+ @Test
+ void codeActionsForPackageNamedArgsAndGeneration(@TempDir Path folder) {
+ def root = folder.resolve('workspace')
+ def src = root.resolve('src/main/groovy/com/acme')
+ Files.createDirectories(src)
+ def source = '''\
+ class Hello {
+ private String hidden
+ String left
+ String right
+ void ping(String name, int count) {}
+ void use() {
+ ping('a', 1)
+ new Hello('a', 'b')
+ Hello.util(1, 2)
+ }
+ static void util(int left, int right) { }
+ Hello(String left, String right) {
+ this.left = left
+ }
+ }
+ '''.stripIndent()
+ def file = src.resolve('Hello.groovy')
+ Files.writeString(file, 'package com.other\n' + source)
+ fixture = new LspFixture()
+ fixture.server.context.addWorkspaceFolder(root.toUri())
+ def uri = fixture.open(file.toString(), 'package com.other\n' + source)
+ def snapshot = fixture.server.context.snapshot
+ def compiled = snapshot.get(uri)
+ def service = new CodeActionService()
+ def actions = service.collect(compiled.toTextDocument(), snapshot, null,
+ new Range(new Position(0, 0), new Position(30, 0)), UTF16,
+ fixture.server.context.workspaceFolders(), [])
+ assert actions.any { it.isRight() && it.getRight().title.contains('com.acme') }
+ assert actions.any { it.isRight() && it.getRight().title == 'Generate getters and setters' }
+ assert actions.any { it.isRight() && it.getRight().title.startsWith('Convert to named arguments') }
+
+ def missingPackage = src.resolve('Bare.groovy')
+ def bare = 'class Bare {}\n'
+ Files.writeString(missingPackage, bare)
+ def bareUri = fixture.open(missingPackage.toString(), bare)
+ def bareActions = service.collect(fixture.server.context.snapshot.get(bareUri).toTextDocument(),
+ fixture.server.context.snapshot, [],
+ new Range(new Position(0, 0), new Position(1, 1)), UTF16,
+ fixture.server.context.workspaceFolders(), [])
+ assert bareActions.any { it.isRight() && it.getRight().title == 'Add package com.acme' }
+
+ def unsorted = '''\
+ import static java.lang.Math.PI
+ import java.util.Map
+ import java.util.List
+ class Sorted {
+ List a
+ Map b
+ def n = PI
+ }
+ '''.stripIndent()
+ def unsortedUri = fixture.open('Sorted.groovy', unsorted)
+ def unsortedDoc = fixture.server.context.snapshot.get(unsortedUri)
+ def organized = service.organizeImports(unsortedDoc, UTF16)
+ assert organized
+ assert organized[0].newText.indexOf('import java.util.List') < organized[0].newText.indexOf('import static')
+ def sorted = '''\
+ import java.util.List
+ import java.util.Map
+ import static java.lang.Math.PI
+ class Already {
+ List a
+ Map b
+ def n = PI
+ }
+ '''.stripIndent()
+ def sortedUri = fixture.open('Already.groovy', sorted)
+ assert service.organizeImports(fixture.server.context.snapshot.get(sortedUri), UTF16).isEmpty()
+ assert service.organizeImports(null, UTF16).isEmpty()
+ assert CodeActionService.unresolvedClassName(null) == null
+ assert CodeActionService.unresolvedClassName('nope') == null
+ assert CodeActionService.unresolvedClassName('unable to resolve class com.acme.Widget') == 'com.acme.Widget'
+
+ def lower = new Diagnostic(new Range(new Position(0, 0), new Position(0, 1)), 'unable to resolve class widget')
+ def dotted = new Diagnostic(new Range(new Position(0, 0), new Position(0, 1)), 'unable to resolve class com.acme.Widget')
+ def created = service.collect(compiled.toTextDocument(), snapshot, [lower, dotted],
+ new Range(new Position(0, 0), new Position(1, 1)), UTF16, [], [])
+ assert !created.any { it.isRight() && it.getRight().title == 'Create class widget' }
+ assert created.any { it.isRight() && it.getRight().title == 'Create class Widget' }
+
+ def emptyUri = fixture.open('Empty.groovy', '')
+ def emptyDoc = fixture.server.context.snapshot.get(emptyUri)
+ if (emptyDoc != null) {
+ def onEmpty = service.collect(emptyDoc.toTextDocument(), fixture.server.context.snapshot,
+ [dotted], new Range(new Position(0, 0), new Position(0, 0)), UTF16, [], [])
+ assert onEmpty.any { it.isRight() && it.getRight().title == 'Create class Widget' }
+ }
+
+ def params = new CodeActionParams(new TextDocumentIdentifier(uri),
+ new Range(new Position(0, 0), new Position(2, 1)), new CodeActionContext([]))
+ assert fixture.server.textDocumentService.codeAction(params).get() != null
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/MethodBindingTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/MethodBindingTest.groovy
new file mode 100644
index 0000000000..4b8fe52cd8
--- /dev/null
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/MethodBindingTest.groovy
@@ -0,0 +1,386 @@
+/*
+ * 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.apache.groovy.lsp.internal.feature
+
+import org.codehaus.groovy.ast.ModuleNode
+import java.nio.file.Path
+import org.codehaus.groovy.ast.expr.ClassExpression
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.codehaus.groovy.ast.expr.MapExpression
+import org.apache.groovy.lsp.internal.LspFixture
+import static org.objectweb.asm.Opcodes.ACC_PUBLIC
+import org.codehaus.groovy.ast.Parameter
+import org.objectweb.asm.Opcodes
+import org.codehaus.groovy.ast.expr.ArgumentListExpression
+import org.junit.jupiter.api.AfterEach
+import org.codehaus.groovy.ast.expr.TupleExpression
+import static org.objectweb.asm.Opcodes.ACC_STATIC
+import org.codehaus.groovy.control.SourceUnit
+import org.codehaus.groovy.ast.expr.PropertyExpression
+import static org.objectweb.asm.Opcodes.ACC_INTERFACE
+import org.junit.jupiter.api.Test
+import static org.objectweb.asm.Opcodes.ACC_ABSTRACT
+import static org.objectweb.asm.Opcodes.ACC_SYNTHETIC
+import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
+import org.codehaus.groovy.ast.expr.ConstantExpression
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.ConstructorNode
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression
+import org.apache.groovy.lsp.internal.compile.CompiledDocument
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.stmt.EmptyStatement
+import org.apache.groovy.lsp.internal.util.Uris
+
+final class MethodBindingTest {
+
+ private LspFixture fixture
+
+ @AfterEach
+ void tearDown() {
+ fixture?.close()
+ }
+
+
+ @Test
+ void methodBindingResolvesTargetsPropertiesAndArity() {
+ def target = new MethodNode('foo', ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ def call = new MethodCallExpression(new VariableExpression('this'), 'foo', new ArgumentListExpression())
+ call.methodTarget = target
+ assert MethodBinding.resolveMethodCandidates(call, null) == [target]
+ assert MethodBinding.methodAt(call, null).is(target)
+
+ def owner = new ClassNode('Hello', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def go = owner.addMethod('go', ACC_PUBLIC | ACC_STATIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ def stat = new StaticMethodCallExpression(owner, 'go', new ArgumentListExpression())
+ assert MethodBinding.methodAt(stat, null).is(go)
+ assert MethodBinding.methodAt(new VariableExpression('x'), null) == null
+
+ def field = owner.addField('name', ACC_PUBLIC, ClassHelper.STRING_TYPE, null)
+ def property = new PropertyExpression(new ClassExpression(owner), 'name')
+ assert MethodBinding.resolveProperty(property).is(field)
+ assert MethodBinding.resolveProperty(new PropertyExpression(new ClassExpression(owner), 'absent')) == null
+
+ assert MethodBinding.resolveConstructorCandidates(null).isEmpty()
+ def anon = new ConstructorCallExpression(owner, ArgumentListExpression.EMPTY_ARGUMENTS)
+ anon.usingAnonymousInnerClass = true
+ assert MethodBinding.resolveConstructorCandidates(anon).isEmpty()
+ assert MethodBinding.resolveConstructorCandidates(
+ new ConstructorCallExpression(ClassHelper.OBJECT_TYPE, ArgumentListExpression.EMPTY_ARGUMENTS)).isEmpty()
+
+ def box = new ClassNode('Box', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def synthetic = box.addConstructor(ACC_PUBLIC | ACC_SYNTHETIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ synthetic.synthetic = true
+ def real = box.addConstructor(ACC_PUBLIC, [new Parameter(ClassHelper.STRING_TYPE, 's')] as Parameter[],
+ ClassNode.EMPTY_ARRAY, null)
+ def ctor = new ConstructorCallExpression(box, new ArgumentListExpression(new ConstantExpression('a')))
+ assert MethodBinding.resolveConstructor(ctor).is(real)
+ }
+
+ @Test
+ void methodBindingWalksHierarchyLookupAndEnclosingClass() {
+ assert MethodBinding.superOf(null) == null
+ def orphan = new MethodNode('x', ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ assert orphan.declaringClass == null
+ assert MethodBinding.superOf(orphan) == null
+
+ def base = new ClassNode('Base', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def child = new ClassNode('Child', ACC_PUBLIC, base)
+ def only = child.addMethod('only', ACC_PUBLIC, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ assert MethodBinding.superOf(only) == null
+
+ def face = new ClassNode('Face', ACC_INTERFACE | ACC_ABSTRACT, ClassHelper.OBJECT_TYPE)
+ def ping = face.addMethod('ping', ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ def direct = new ClassNode('Direct', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ direct.addInterface(face)
+ def directPing = direct.addMethod('ping', ACC_PUBLIC, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ assert MethodBinding.superOf(directPing).is(ping)
+
+ def top = new ClassNode('Top', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ top.addInterface(face)
+ def mid = new ClassNode('Mid', ACC_PUBLIC, top)
+ def grand = new ClassNode('Grand', ACC_PUBLIC, mid)
+ def grandPing = grand.addMethod('ping', ACC_PUBLIC, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ assert MethodBinding.superOf(grandPing).is(ping)
+
+ def parent = new ClassNode('Parent', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def derived = new ClassNode('Derived', ACC_PUBLIC, parent)
+ def further = new ClassNode('Further', ACC_PUBLIC, derived)
+ assert MethodBinding.sameOrDerived(derived, parent)
+ assert MethodBinding.sameOrDerived(further, ClassHelper.OBJECT_TYPE)
+ assert !MethodBinding.sameOrDerived(null, parent)
+ assert MethodBinding.overloads((ClassNode) null, 'foo').isEmpty()
+ assert MethodBinding.overloads(ClassHelper.STRING_TYPE, (String) null).isEmpty()
+
+ face.lineNumber = 1
+ def impl = new ClassNode('Impl', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ impl.addInterface(face)
+ impl.lineNumber = 2
+ def ghost = new ClassNode('Ghost', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def module = new ModuleNode((SourceUnit) null)
+ module.addClass(face)
+ module.addClass(impl)
+ module.addClass(ghost)
+ def implUri = fileUri('file:///tmp/cov-impl.groovy')
+ def emptyUri = fileUri('file:///tmp/cov-emptymod.groovy')
+ def snap = snapshot(
+ new CompiledDocument(emptyUri, 1, '', null, null, null),
+ new CompiledDocument(implUri, 1, 'class Impl implements Face {}', module, null, null))
+ assert MethodBinding.implementations(face, snap).contains(impl)
+ assert MethodBinding.methodImplementations(ping, snap).isEmpty()
+
+ def holder = new ClassNode('demo.Holder', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def foo = holder.addMethod('foo', ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ foo.lineNumber = 2
+ def holderModule = new ModuleNode((SourceUnit) null)
+ holderModule.addClass(holder)
+ def holderUri = fileUri('file:///tmp/cov-holder.groovy')
+ def lookup = snapshot(
+ new CompiledDocument(emptyUri, 1, '', null, null, null),
+ new CompiledDocument(holderUri, 1, 'class Holder { def foo() {} }', holderModule, null, null))
+ assert MethodBinding.findMethod(null, 'demo.Holder', 'foo', null) == null
+ assert MethodBinding.findMethod(lookup, 'demo.Holder', null, null) == null
+ assert MethodBinding.findMethod(lookup, 'demo.Missing', 'foo', null) == null
+ assert MethodBinding.findMethod(lookup, 'demo.Holder', 'foo', '').is(foo)
+
+ def loose = new MethodCallExpression(new VariableExpression('missing'), 'nope', new ArgumentListExpression())
+ assert MethodBinding.resolveMethodCandidates(loose, null).isEmpty()
+ assert MethodBinding.resolveMethodCandidates(loose, lookup).isEmpty()
+ }
+
+ private static CompilationSnapshot snapshot(CompiledDocument... documents) {
+ def map = [:]
+ documents.each { map[it.uri] = it }
+ new CompilationSnapshot(map)
+ }
+
+ private static URI fileUri(String path) {
+ Uris.normalize(URI.create(path))
+ }
+
+ private static URI fileUri(Path path) {
+ Uris.normalize(path.toUri())
+ }
+
+ @Test
+ void callSitesNamedNullAndBareArgument() {
+ def named = new MapExpression()
+ assert CallSites.hasNamedArgs(named)
+ assert CallSites.argumentExpressions(named) == [named]
+
+ assert CallSites.argumentExpressions(null).isEmpty()
+ assert !CallSites.hasNamedArgs(null)
+
+ def literal = new ConstantExpression(1)
+ assert !CallSites.hasNamedArgs(literal)
+ assert CallSites.argumentExpressions(literal) == [literal]
+
+ def tuple = new TupleExpression(new ConstantExpression(2))
+ assert !CallSites.hasNamedArgs(tuple)
+ assert CallSites.argumentExpressions(tuple)*.value == [2]
+ }
+
+ @Test
+ void methodBindingCoversTargetsOverridesAndCalls() {
+ fixture = new LspFixture()
+ fixture.open('Types.groovy', '''\
+ interface I { void ping(String s) }
+ class Base implements I { void ping(String s) {} }
+ class Child extends Base {
+ void ping(String s) { ping('x') }
+ static void util(int n) { util(n) }
+ }
+ '''.stripIndent())
+ def snapshot = fixture.server.context.snapshot
+ def child = snapshot.types().byName('Child')
+ assert child != null
+ def module = snapshot.documents().find { it.module?.classes?.any { it.name == 'Child' } }.module
+ def childNode = module.classes.find { it.name == 'Child' }
+ def baseNode = module.classes.find { it.name == 'Base' }
+ def ping = childNode.methods.find { it.name == 'ping' && it.lineNumber > 0 }
+ assert ping != null
+ def iface = baseNode.interfaces ? baseNode.interfaces[0] : baseNode
+ def impls = MethodBinding.implementations(iface, snapshot)
+ assert impls.any { it.name == 'Base' || it.name == 'Child' }
+ assert MethodBinding.methodImplementations(ping, snapshot) != null
+ assert MethodBinding.superOf(ping) != null
+ assert MethodBinding.superOf(null) == null
+ assert MethodBinding.methodAt(ping, snapshot).is(ping)
+ assert MethodBinding.methodAt(new VariableExpression('x'), snapshot) == null
+ assert MethodBinding.findMethod(null, 'Child', 'ping', null) == null
+ assert MethodBinding.findMethod(snapshot, 'Child', 'ping', ping.typeDescriptor)?.name == 'ping'
+ assert MethodBinding.findMethod(snapshot, null, 'util', '')?.name == 'util'
+ assert MethodBinding.overloads((ClassNode) null, 'ping').isEmpty()
+ assert !MethodBinding.overloads(childNode, 'util').isEmpty()
+ def call = new MethodCallExpression(new VariableExpression('this'), 'ping', new TupleExpression())
+ call.methodTarget = ping
+ assert MethodBinding.resolveMethodCandidates(call, snapshot) == [ping]
+ assert MethodBinding.resolveMethodCandidates(new VariableExpression('x'), snapshot).isEmpty()
+ assert MethodBinding.overloads((MethodCallExpression) null, snapshot).isEmpty()
+ assert MethodBinding.argumentCount(null) == 0
+ assert MethodBinding.argumentCount(new VariableExpression('x')) == 1
+ assert MethodBinding.argumentCount(new TupleExpression([new VariableExpression('a')])) == 1
+ assert !MethodBinding.sameType(null, ClassHelper.OBJECT_TYPE)
+ assert MethodBinding.sameOrDerived(ClassHelper.STRING_TYPE, ClassHelper.OBJECT_TYPE)
+ def ctor = new ConstructorCallExpression(ClassHelper.OBJECT_TYPE, new TupleExpression())
+ ctor.usingAnonymousInnerClass = true
+ assert MethodBinding.resolveConstructorCandidates(ctor).isEmpty()
+ assert MethodBinding.resolveConstructor(null) == null
+ def field = childNode.addField('label', 0, ClassHelper.STRING_TYPE, null)
+ field.synthetic = false
+ def property = new PropertyExpression(new VariableExpression('this', childNode), 'label')
+ assert MethodBinding.resolveProperty(property)?.name == 'label'
+ assert MethodBinding.resolveProperty(null) == null
+ def stat = new StaticMethodCallExpression(childNode, 'util', new TupleExpression())
+ def util = childNode.methods.find { it.name == 'util' && it.lineNumber > 0 }
+ assert MethodBinding.staticCallMatches(stat, util)
+ def param = new Parameter(ClassHelper.STRING_TYPE, 'n')
+ param.lineNumber = 1
+ def local = new VariableExpression('n')
+ local.accessedVariable = param
+ assert MethodBinding.isRenameSafe(local, snapshot)
+ }
+
+ @Test
+ void callSitesCoverNamedNullAndSingleArguments() {
+ def named = new TupleExpression([new MapExpression()])
+ assert CallSites.hasNamedArgs(named)
+ assert CallSites.argumentExpressions(null).isEmpty()
+ def single = new VariableExpression('x')
+ assert CallSites.argumentExpressions(single) == [single]
+ assert !CallSites.hasNamedArgs(single)
+ }
+
+ @Test
+ void methodBindingEdges() {
+ fixture = new LspFixture()
+ def text = '''\
+ interface Top { void ping() }
+ interface Mid extends Top {}
+ class Impl implements Mid {
+ void ping() { ping() }
+ static void util(int n) { util(n) }
+ }
+ class Child extends Impl {}
+ class Solo { void solo() {} }
+ class A {}
+ class B extends A {}
+ class C extends B {}
+ '''.stripIndent()
+ fixture.open('Types.groovy', text)
+ def snapshot = fixture.server.context.snapshot
+ def module = snapshot.documents().find { it.module?.classes?.any { it.name == 'Impl' } }.module
+ def impl = module.classes.find { it.name == 'Impl' }
+ def child = module.classes.find { it.name == 'Child' }
+ def solo = module.classes.find { it.name == 'Solo' }
+ def top = module.classes.find { it.name == 'Top' }
+ def typeC = module.classes.find { it.name == 'C' }
+ def typeA = module.classes.find { it.name == 'A' }
+ def ping = impl.methods.find { it.name == 'ping' && it.lineNumber > 0 }
+ def soloMethod = solo.methods.find { it.name == 'solo' && it.lineNumber > 0 }
+ def topPing = top.methods.find { it.name == 'ping' }
+
+ assert MethodBinding.superOf(ping)?.declaringClass?.name == 'Top'
+ assert MethodBinding.superOf(soloMethod) == null
+ assert MethodBinding.superOf(null) == null
+ def orphan = new MethodNode('x', 0, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ assert MethodBinding.methodImplementations(orphan, snapshot).isEmpty()
+ assert MethodBinding.methodImplementations(topPing, snapshot).any { it.declaringClass.name == 'Impl' }
+ assert MethodBinding.implementations(impl, snapshot).any { it.name == 'Child' }
+
+ def blank = new CompiledDocument(URI.create('file:///blank.groovy'), 1, '', null, null, null)
+ def mixed = new CompilationSnapshot(snapshot.documents().collectEntries { [(it.uri): it] } + [(blank.uri): blank])
+ assert MethodBinding.implementations(impl, mixed).any { it.name == 'Child' }
+ assert MethodBinding.findMethod(mixed, 'Nope', 'ping', null) == null
+
+ def unresolved = new ClassNode('Missing', 0, ClassHelper.OBJECT_TYPE)
+ def ctor = new ConstructorCallExpression(unresolved, new TupleExpression())
+ assert MethodBinding.resolveConstructorCandidates(ctor).isEmpty()
+ assert MethodBinding.resolveConstructor(ctor) == null
+ assert MethodBinding.resolveProperty(null) == null
+ def dynamicProp = new PropertyExpression(new VariableExpression('obj'), new VariableExpression('dyn'))
+ assert MethodBinding.resolveProperty(dynamicProp) == null
+
+ def staticCall = new StaticMethodCallExpression(impl, 'util', new ArgumentListExpression(new ConstantExpression(1)))
+ assert MethodBinding.methodAt(staticCall, snapshot)?.name == 'util'
+ def instanceCall = new MethodCallExpression(new VariableExpression('this'), 'ping', new TupleExpression())
+ instanceCall.implicitThis = true
+ instanceCall.methodTarget = ping
+ assert MethodBinding.methodAt(instanceCall, snapshot).is(ping)
+ assert MethodBinding.resolveMethodCandidates(instanceCall, snapshot) == [ping]
+ assert MethodBinding.methodAt(new ConstantExpression(1), snapshot) == null
+ assert MethodBinding.callMatches(instanceCall, ping, null)
+ assert !MethodBinding.callMatches(null, ping, null)
+ assert !MethodBinding.staticCallMatches(null, ping)
+ assert !MethodBinding.staticCallMatches(staticCall, ping)
+ assert MethodBinding.staticCallMatches(staticCall, impl.methods.find { it.name == 'util' && it.lineNumber > 0 })
+ assert !MethodBinding.receiverMatchesOwner(new VariableExpression('x'), '')
+ assert !MethodBinding.receiverMatchesOwner(null, 'Impl')
+
+ def implicit = new MethodCallExpression(new VariableExpression('this'), 'absent', new TupleExpression())
+ implicit.implicitThis = true
+ assert MethodBinding.overloads(implicit, null).isEmpty()
+ assert MethodBinding.overloads(implicit, mixed).isEmpty()
+ assert MethodBinding.overloads(impl, null).isEmpty()
+ assert MethodBinding.overloads((MethodCallExpression) null, snapshot).isEmpty()
+ assert !MethodBinding.sameType(null, impl)
+ assert MethodBinding.sameOrDerived(null, ClassHelper.OBJECT_TYPE) == false
+ assert MethodBinding.sameOrDerived(child, impl)
+ assert MethodBinding.sameOrDerived(typeC, typeA)
+ assert MethodBinding.argumentCount(null) == 0
+ assert MethodBinding.argumentCount(new ConstantExpression(1)) == 1
+
+ def grand = new ClassNode('pkg.Grand', Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def parent = new ClassNode('pkg.Parent', Opcodes.ACC_PUBLIC, grand)
+ def kid = new ClassNode('pkg.Kid', Opcodes.ACC_PUBLIC, parent)
+ grand.addMethod(new MethodNode('ping', Opcodes.ACC_PUBLIC, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE))
+ def same = new MethodNode('ping', Opcodes.ACC_PUBLIC, ClassHelper.VOID_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE)
+ parent.addMethod(same)
+ same.declaringClass = kid
+ assert MethodBinding.superOf(same)?.declaringClass?.name == 'pkg.Grand'
+
+ def synthetic = new ConstructorNode(Opcodes.ACC_PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE)
+ synthetic.synthetic = true
+ def host = new ClassNode('pkg.Host', Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ host.addConstructor(synthetic)
+ assert MethodBinding.resolveConstructorCandidates(new ConstructorCallExpression(host, new TupleExpression())).isEmpty()
+ def real = new ConstructorNode(Opcodes.ACC_PUBLIC,
+ [new Parameter(ClassHelper.STRING_TYPE, 'name')] as Parameter[], ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE)
+ host.addConstructor(real)
+ def args = new ArgumentListExpression(new ConstantExpression('a'))
+ assert MethodBinding.resolveConstructor(new ConstructorCallExpression(host, args))?.parameters?.length == 1
+
+ assert !MethodBinding.isRenameSafe(new ConstantExpression(1), snapshot)
+ def unsafe = new MethodCallExpression(new VariableExpression('this'), 'ping', new TupleExpression())
+ assert !MethodBinding.isRenameSafe(unsafe, snapshot)
+ assert MethodBinding.isRenameSafe(staticCall, snapshot)
+ }
+}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/NavigationIdentityTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/NavigationIdentityTest.groovy
index 79916b7a64..3977b0bff1 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/NavigationIdentityTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/NavigationIdentityTest.groovy
@@ -18,6 +18,48 @@
*/
package org.apache.groovy.lsp.internal.feature
+import java.lang.reflect.Modifier
+import java.nio.file.Files
+import java.nio.file.Path
+import javax.tools.ToolProvider
+import org.apache.groovy.lsp.internal.compile.AstQuery
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.apache.groovy.lsp.internal.compile.CompiledDocument
+import org.apache.groovy.lsp.internal.compile.CompilerSettings
+import org.apache.groovy.lsp.internal.compile.GroovyCompiler
+import org.apache.groovy.lsp.internal.position.PositionEncoding
+import org.apache.groovy.lsp.internal.position.Positions
+import org.apache.groovy.lsp.internal.util.Uris
+import org.apache.groovy.lsp.internal.workspace.TextDocument
+import org.codehaus.groovy.ast.ASTNode
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.CompileUnit
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.ModuleNode
+import org.codehaus.groovy.ast.Parameter
+import org.codehaus.groovy.ast.expr.ClassExpression
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression
+import org.codehaus.groovy.ast.expr.DeclarationExpression
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.expr.PropertyExpression
+import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.stmt.EmptyStatement
+import org.codehaus.groovy.ast.stmt.ExpressionStatement
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.SourceUnit
+import org.eclipse.lsp4j.CallHierarchyItem
+import org.eclipse.lsp4j.CompletionItem
+import org.eclipse.lsp4j.FileRename
+import org.eclipse.lsp4j.Range
+import org.eclipse.lsp4j.RenameFile
+import org.eclipse.lsp4j.SymbolKind
+import org.eclipse.lsp4j.TypeHierarchyItem
+import org.junit.jupiter.api.Assumptions
+import org.junit.jupiter.api.io.TempDir
+import static org.objectweb.asm.Opcodes.ACC_PUBLIC
+
import org.apache.groovy.lsp.internal.LspFixture
import org.eclipse.lsp4j.CallHierarchyIncomingCallsParams
import org.eclipse.lsp4j.CallHierarchyOutgoingCallsParams
@@ -42,6 +84,10 @@ import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
final class NavigationIdentityTest {
+ private static final PositionEncoding UTF16 = PositionEncoding.UTF16
+
+ private static final PositionEncoding ENC = PositionEncoding.UTF16
+
private LspFixture fixture
@@ -216,4 +262,704 @@ final class NavigationIdentityTest {
assert fixture.server.context.snapshot.documents().size() == 1
assert fixture.server.context.snapshot.get(uri) != null
}
+ @Test
+ void navigationUsesClassExpressionSuperAndBadUris() {
+ def text = '''\
+ class Hello implements Runnable {
+ void run() {}
+ def values() {
+ def (a, b) = [1, 2]
+ String
+ }
+ }
+ class Blank {
+ }
+ '''.stripIndent() + '\n'
+ def uri = fileUri('file:///tmp/cov-nav.groovy')
+ def snap = compileOf(uri, text)
+ def compiled = snap.get(uri)
+ def doc = compiled.toTextDocument()
+ def nav = new NavigationService()
+ def module = compiled.module
+ def hello = module.classes.find { it.nameWithoutPackage == 'Hello' }
+ def run = hello.methods.find { it.name == 'run' && !it.synthetic && it.lineNumber > 0 }
+ def values = hello.methods.find { it.name == 'values' && !it.synthetic && it.lineNumber > 0 }
+ assert MethodBinding.superOf(run)?.name == 'run'
+ def runPos = caretOn(text, run.lineNumber, 'run')
+ assert AstQuery.nodeAt(module, doc, runPos, UTF16) instanceof MethodNode
+ assert nav.superMethod(doc, snap, runPos, UTF16).isEmpty()
+ assert MethodBinding.superOf(values) == null
+ assert nav.superMethod(doc, snap, caretOn(text, values.lineNumber, 'values'), UTF16).isEmpty()
+
+ def classExprs = []
+ def decls = []
+ AstQuery.walk(module) { node, ctx ->
+ if (node instanceof ClassExpression) {
+ classExprs << node
+ }
+ if (node instanceof DeclarationExpression && node.multipleAssignmentDeclaration) {
+ decls << node
+ }
+ }
+ assert classExprs
+ def classPos = positionOf(text, classExprs[0])
+ assert AstQuery.nodeAt(module, doc, classPos, UTF16) instanceof ClassExpression
+ assert nav.definition(doc, snap, classPos, UTF16).isEmpty()
+ assert decls
+ def declPos = positionOf(text, decls[0])
+ assert AstQuery.nodeAt(module, doc, declPos, UTF16) instanceof DeclarationExpression
+ assert nav.definition(doc, snap, declPos, UTF16).isEmpty()
+
+ def trailing = new Position(text.readLines().size() - 1, 0)
+ assert AstQuery.nodeAt(module, doc, trailing, UTF16) == null
+ assert nav.definition(doc, snap, trailing, UTF16).isEmpty()
+ assert nav.definition(null, null, null, UTF16).isEmpty()
+ assert nav.superMethod(null, CompilationSnapshot.EMPTY, new Position(0, 0), UTF16).isEmpty()
+
+ def config = new CompilerConfiguration()
+ def bad = new SourceUnit('::::', 'class A {}', config, null, null)
+ def badModule = new ModuleNode(bad)
+ def type = new ClassNode('A', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ badModule.addClass(type)
+ def fallback = URI.create('file:///fallback.groovy')
+ assert NavigationService.uriOf(type, fallback, CompilationSnapshot.EMPTY, null) == fallback
+ def method = new MethodNode('m', ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+ assert NavigationService.uriOf(method, fallback, null, new ModuleNode(bad)) == fallback
+
+ def other = new ClassNode('Other', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ other.lineNumber = 1
+ def otherModule = new ModuleNode((SourceUnit) null)
+ otherModule.addClass(other)
+ def wanted = new ClassNode('Wanted', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def located = NavigationService.uriOf(wanted, fallback, snapshot(
+ new CompiledDocument(fileUri('file:///tmp/cov-nav-empty.groovy'), 1, '', null, null, null),
+ new CompiledDocument(fileUri('file:///tmp/cov-nav-other.groovy'), 1, 'class Other {}', otherModule, null, null)
+ ), null)
+ assert located == fallback
+ }
+
+ @Test
+ void navigationJumpsToJavaFieldAndComment(@TempDir Path folder) {
+ Assumptions.assumeTrue(ToolProvider.systemJavaCompiler != null, 'jdk.compiler is required')
+ fixture = new LspFixture()
+ fixture.open(folder.resolve('Widget.java').toString(), '''\
+ public class Widget {
+ public String id;
+ public String name() { return id; }
+ }
+ '''.stripIndent(), 'java')
+ def uri = fixture.open(folder.resolve('Use.groovy').toString(), '''\
+ class Use {
+ def run(Widget widget) {
+ widget.id
+ }
+ }
+ // Widget
+ '''.stripIndent())
+ def doc = fixture.server.context.documentFor(uri)
+ def snap = fixture.server.context.snapshot
+ def widgetTypes = snap.javaSymbols().typesNamed('Widget')
+ assert widgetTypes
+ def nav = fixture.server.features().navigation()
+ def lines = doc.text.readLines()
+ def idLine = lines.findIndexOf { it.contains('widget.id') }
+ def idColumn = lines[idLine].indexOf('.id') + 1
+ PropertyExpression idProperty = null
+ AstQuery.walk(snap.get(uri).module) { node, ctx ->
+ if (node instanceof PropertyExpression && node.propertyAsString == 'id') {
+ idProperty = node
+ }
+ }
+ assert idProperty != null
+ def widgetType = new ClassNode('Widget', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ def idField = widgetType.addField('id', ACC_PUBLIC, ClassHelper.STRING_TYPE, null)
+ def object = new VariableExpression('widget', widgetType)
+ object.setSourcePosition(idProperty.objectExpression)
+ idProperty.objectExpression = object
+ assert MethodBinding.resolveProperty(idProperty).is(idField)
+ assert idField.lineNumber <= 0
+ def fieldLinks = nav.definition(doc, snap, new Position(idLine, idColumn), UTF16)
+ assert fieldLinks.isEmpty() || fieldLinks.every { it.targetUri.endsWith('Widget.java') }
+ def commentLine = lines.findIndexOf { it.contains('// Widget') }
+ def commentColumn = lines[commentLine].indexOf('Widget')
+ def commentPos = new Position(commentLine, commentColumn)
+ assert AstQuery.nodeAt(snap.get(uri).module, doc, commentPos, UTF16) == null
+ def commentLinks = nav.definition(doc, snap, commentPos, UTF16)
+ assert commentLinks
+ assert commentLinks[0].targetUri.endsWith('Widget.java')
+ }
+
+ private CompilationSnapshot compileOf(URI uri, String text) {
+ compileOf([new TextDocument(uri, 'groovy', 1, text)])
+ }
+
+ private CompilationSnapshot compileOf(List<TextDocument> documents) {
+ def compiler = new GroovyCompiler()
+ try {
+ return compiler.compile(documents, [], CompilerSettings.defaults(), getClass().classLoader)
+ } finally {
+ compiler.close()
+ }
+ }
+
+ private static CompilationSnapshot snapshot(CompiledDocument... documents) {
+ def map = [:]
+ documents.each { map[it.uri] = it }
+ new CompilationSnapshot(map)
+ }
+
+ private static URI fileUri(String path) {
+ Uris.normalize(URI.create(path))
+ }
+
+ private static URI fileUri(Path path) {
+ Uris.normalize(path.toUri())
+ }
+
+ private static Position caretOn(String text, int groovyLine, String token) {
+ def line = text.readLines()[groovyLine - 1]
+ new Position(groovyLine - 1, line.indexOf(token))
+ }
+
+ private static Position positionOf(String text, node) {
+ def line = Positions.lineText(text, node.lineNumber)
+ Positions.toLsp(node.lineNumber, Math.max(node.columnNumber, 1), line, UTF16)
+ }
+
+ @Test
+ void hierarchyCallsTypesAndGuards() {
+ def src = '''\
+ interface Face {
+ String tag()
+ }
+ class Base {
+ String tag() { 'base' }
+ }
+ class Alpha {
+ }
+ class Beta extends Alpha {
+ }
+ class Child extends Base implements Face {
+ static String stat(String value) { value }
+ Child() {}
+ String tag() { 'child' }
+ String onlyPing() { stat('x') }
+ String use() {
+ helper()
+ stat('x')
+ onlyPing()
+ new Child()
+ }
+ }
+ '''.stripIndent()
+ def uri = open('Hierarchy.groovy', src)
+ def doc = compiled(uri)
+ def snap = snapshot()
+ def buffer = doc.toTextDocument()
+ def hierarchy = new HierarchyService()
+ def child = typeNamed(doc, 'Child')
+ def onlyPing = child.methods.find { it.name == 'onlyPing' && !it.synthetic }
+ def stat = child.methods.find { it.name == 'stat' && !it.synthetic }
+ def use = child.methods.find { it.name == 'use' && !it.synthetic }
+ def text = doc.text
+
+ assert hierarchy.prepareTypeHierarchy(buffer, snap, at(text, 'onlyPing'), ENC).isEmpty()
+ def childItem = hierarchy.prepareTypeHierarchy(buffer, snap, nameIn(text, 'class Child'), ENC)
+ assert childItem*.name == ['Child']
+ def supers = hierarchy.supertypes(childItem[0], snap, ENC)*.name
+ assert supers.contains('Base')
+ assert supers.contains('Face')
+ assert !supers.contains('Object')
+
+ def betaItem = hierarchy.prepareTypeHierarchy(buffer, snap, nameIn(text, 'class Beta'), ENC)[0]
+ assert hierarchy.supertypes(betaItem, snap, ENC)*.name == ['Alpha']
+
+ def missing = new TypeHierarchyItem('Missing', SymbolKind.Class, uri, SymbolService.emptyRange(), SymbolService.emptyRange())
+ missing.data = [name: 'missing.Missing']
+ assert hierarchy.supertypes(missing, snap, ENC).isEmpty()
+ def nullOnly = new CompiledDocument(URI.create('file:///null-module.groovy'), 1, '', null, null, null)
+ def nullSnap = new CompilationSnapshot([(nullOnly.uri): nullOnly])
+ assert hierarchy.supertypes(childItem[0], nullSnap, ENC).isEmpty()
+
+ def pingItem = hierarchy.prepareCallHierarchy(buffer, snap, at(text, 'onlyPing'), ENC)
+ assert pingItem*.name == ['onlyPing']
+ def statItem = hierarchy.prepareCallHierarchy(buffer, snap, at(text, 'stat'), ENC)
+ assert statItem*.name == ['stat']
+ def useItem = hierarchy.prepareCallHierarchy(buffer, snap, at(text, 'use()'), ENC)[0]
+ assert hierarchy.incomingCalls(pingItem[0], snap, ENC)*.from.name == ['use']
+ assert hierarchy.incomingCalls(statItem[0], snap, ENC)*.from.name.contains('use')
+ def staticCalls = []
+ AstQuery.walk(use) { node, ctx ->
+ if (node instanceof StaticMethodCallExpression) {
+ staticCalls << node.method
+ }
+ }
+ assert staticCalls.contains('stat')
+
+ def helper = new MethodNode('helper', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY,
+ ClassNode.EMPTY_ARRAY, new EmptyStatement())
+ def external = new ClassNode('ext.Util', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ external.addMethod(helper)
+ helper.lineNumber = 4
+ helper.columnNumber = 5
+ helper.lastLineNumber = 4
+ helper.lastColumnNumber = 11
+ def helperCall = callsNamed(use, 'helper')[0]
+ helperCall.methodTarget = helper
+ def ctorCalls = []
+ AstQuery.walk(use) { node, ctx ->
+ if (node instanceof ConstructorCallExpression) {
+ ctorCalls << node
+ }
+ }
+ assert ctorCalls
+ def userCtor = child.declaredConstructors.find { !it.synthetic && it.lineNumber > 0 }
+ if (userCtor != null) {
+ child.declaredConstructors.remove(userCtor)
+ child.declaredConstructors.add(0, userCtor)
+ }
+
+ def outgoing = hierarchy.outgoingCalls(useItem, snap, ENC)*.to.name
+ assert outgoing.contains('stat')
+ assert outgoing.contains('onlyPing')
+ assert !outgoing.contains('helper')
+ assert !outgoing.contains('<init>')
+
+ def bare = new CallHierarchyItem(pingItem[0].name, pingItem[0].kind, pingItem[0].uri, pingItem[0].range, pingItem[0].selectionRange)
+ assert hierarchy.incomingCalls(bare, snap, ENC)*.from.name.contains('use')
+ def broken = new CallHierarchyItem(useItem.name, useItem.kind, useItem.uri, useItem.range, useItem.selectionRange)
+ broken.data = useItem.data
+ broken.uri = '%'
+ assert hierarchy.outgoingCalls(broken, snap, ENC)*.to.name.contains('stat')
+
+ def caller = callerOf(onlyPing)
+ def extra = plus(snap, nullOnly, caller)
+ def withCaller = hierarchy.incomingCalls(pingItem[0], extra, ENC)
+ assert withCaller*.from.name.contains('use')
+ assert withCaller.every { it.from.uri }
+
+ def pingCall = callsNamed(use, 'onlyPing')[0]
+ pingCall.lineNumber = -1
+ pingCall.lastLineNumber = -1
+ pingCall.method.lineNumber = -1
+ pingCall.method.lastLineNumber = -1
+ def after = hierarchy.outgoingCalls(useItem, snap, ENC)*.to.name
+ assert after.contains('stat')
+ assert !after.contains('onlyPing')
+ assert hierarchy.incomingCalls(pingItem[0], snap, ENC).isEmpty()
+
+ child.interfaces?.each { it.lineNumber = 0 }
+ def withoutFace = hierarchy.supertypes(childItem[0], snap, ENC)*.name
+ assert withoutFace.contains('Base')
+ assert !withoutFace.contains('Face') : child.interfaces.collect { [it.name, it.lineNumber] }
+ def base = child.superClass
+ base.setName('NotInSource')
+ def hiddenBase = hierarchy.supertypes(childItem[0], snap, ENC)*.name
+ assert !hiddenBase.contains('Base')
+ assert !hiddenBase.contains('NotInSource')
+ def externalType = new ClassNode('ext.External', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ externalType.lineNumber = 1
+ externalType.columnNumber = 1
+ externalType.lastLineNumber = 1
+ externalType.lastColumnNumber = 8
+ child.superClass = externalType
+ assert hierarchy.supertypes(childItem[0], snap, ENC).isEmpty()
+ }
+
+ @Test
+ void documentLinksWorkspaceStarAndNonFileTargets() {
+ def widgetUri = open('demo/Widget.groovy', '''\
+ package demo
+ class Widget {}
+ '''.stripIndent())
+ def useUri = open('demo/Use.groovy', '''\
+ package demo
+ import demo.Widget
+ import java.util.*
+ class Use {
+ Widget item
+ }
+ '''.stripIndent())
+ def use = compiled(useUri)
+ def widget = compiled(widgetUri)
+ def links = new DocumentLinkService().documentLinks(use, snapshot(), ENC)
+ assert links*.target == [widget.uri.toString()]
+
+ use.module.addImport('Ghost', ClassHelper.make('demo.Ghost'))
+ assert use.module.imports[-1].lineNumber <= 0
+ assert new DocumentLinkService().documentLinks(use, snapshot(), ENC)*.target == [widget.uri.toString()]
+
+ def nullModule = new CompiledDocument(URI.create('file:///null-module.groovy'), 1, '', null, null, null)
+ def skipped = new DocumentLinkService().documentLinks(use, new CompilationSnapshot([(nullModule.uri): nullModule]), ENC)
+ assert skipped.size() == 1
+ assert skipped[0].target.endsWith('demo/Widget.groovy')
+ assert skipped[0].target != widget.uri.toString()
+
+ def unresolved = new DocumentLinkService().documentLinks(use, null, ENC)
+ assert unresolved.size() == 1
+ assert unresolved[0].target.endsWith('demo/Widget.groovy')
+
+ def http = importDocument(URI.create('http://example.com/A.groovy'), 'import demo.Missing\n', 'demo.Missing')
+ assert new DocumentLinkService().documentLinks(http, CompilationSnapshot.EMPTY, ENC).isEmpty()
+ def root = importDocument(URI.create('file:///'), 'import demo.Missing\n', 'demo.Missing')
+ assert new DocumentLinkService().documentLinks(root, CompilationSnapshot.EMPTY, ENC).isEmpty()
+ }
+
+ @Test
+ void symbolIdentityClassExpressionAndNullNode() {
+ def expr = new ClassExpression(ClassHelper.STRING_TYPE)
+ def identity = SymbolIdentity.of(expr, CompilationSnapshot.EMPTY)
+ assert identity.kind() == SymbolIdentity.Kind.TYPE
+ assert identity.name() == 'String'
+ assert identity.refersTo(new ClassExpression(ClassHelper.STRING_TYPE), null)
+ assert !identity.refersTo(new ClassExpression(ClassHelper.Integer_TYPE), null)
+ assert !identity.refersTo(null, null)
+ }
+
+ private String open(String path, String text) {
+ if (fixture == null) {
+ fixture = new LspFixture()
+ }
+ fixture.open(path, text)
+ }
+
+ private CompilationSnapshot snapshot() {
+ fixture.server.context.snapshot
+ }
+
+ private CompiledDocument compiled(String uri) {
+ def doc = snapshot().get(uri)
+ assert doc?.module != null
+ doc
+ }
+
+ private static ClassNode typeNamed(CompiledDocument doc, String simple) {
+ def found = doc.module.classes.find { it.nameWithoutPackage == simple && !it.name.contains('$') }
+ assert found != null : doc.module.classes*.name
+ found
+ }
+
+ private static CompiledDocument importDocument(URI uri, String text, String className) {
+ def module = new ModuleNode((CompileUnit) null)
+ module.addImport(className.substring(className.lastIndexOf('.') + 1), ClassHelper.make(className))
+ def imp = module.imports[0]
+ place(imp, 1, 1, text.length())
+ new CompiledDocument(uri, 1, text, module, null, null)
+ }
+
+ private static CompilationSnapshot plus(CompilationSnapshot base, CompiledDocument... extra) {
+ def map = new LinkedHashMap<URI, CompiledDocument>()
+ if (base != null) {
+ for (CompiledDocument doc : base.documents()) {
+ if (doc.uri != null) {
+ map.put(doc.uri, doc)
+ }
+ }
+ }
+ for (CompiledDocument doc : extra) {
+ def key = doc.uri != null ? doc.uri : URI.create('file:///synthetic-' + System.identityHashCode(doc) + '.groovy')
+ map.put(key, doc)
+ }
+ new CompilationSnapshot(map)
+ }
+
+ private static CompiledDocument callerOf(MethodNode target) {
+ def text = target.name + '()\n'
+ def call = new MethodCallExpression(new VariableExpression('this'), target.name, MethodCallExpression.NO_ARGUMENTS)
+ call.methodTarget = target
+ call.implicitThis = true
+ place(call, 1, 1, 1 + target.name.length())
+ place(call.method, 1, 1, 1 + target.name.length())
+ def caller = new MethodNode('caller', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY,
+ ClassNode.EMPTY_ARRAY, new ExpressionStatement(call))
+ place(caller, 1, 1, text.length())
+ def type = new ClassNode('Caller', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ place(type, 1, 1, text.length())
+ type.addMethod(caller)
+ def module = new ModuleNode((CompileUnit) null)
+ module.addClass(type)
+ new CompiledDocument(null, 1, text, module, null, null)
+ }
+
+ private static List<MethodCallExpression> callsNamed(MethodNode method, String name) {
+ def found = []
+ AstQuery.walk(method.code) { node, ctx ->
+ if (node instanceof MethodCallExpression && node.methodAsString == name) {
+ found << node
+ }
+ }
+ assert found : name
+ found
+ }
+
+ private static Position nameIn(String text, String declaration) {
+ def position = at(text, declaration)
+ int space = declaration.lastIndexOf(' ')
+ position.character += space + 1
+ position
+ }
+
+ private static Position at(String text, String token) {
+ int index = text.indexOf(token)
+ assert index >= 0 : token
+ int line = 0
+ int column = 0
+ for (int i = 0; i < index; i++) {
+ if (text.charAt(i) == '\n') {
+ line += 1
+ column = 0
+ } else {
+ column += 1
+ }
+ }
+ new Position(line, column)
+ }
+
+ @Test
+ void completionNavigationRenameAndHierarchy(@TempDir Path folder) {
+ fixture = new LspFixture()
+ def widgetA = folder.resolve('a')
+ def widgetB = folder.resolve('b')
+ Files.createDirectories(widgetA)
+ Files.createDirectories(widgetB)
+ def alpha = '''\
+ package a
+ class Alpha {}
+ '''.stripIndent()
+ def beta = '''\
+ package b
+ class Beta {}
+ '''.stripIndent()
+ def widget1 = '''\
+ package a
+ class Widget {}
+ '''.stripIndent()
+ def widget2 = '''\
+ package b
+ class Widget {}
+ '''.stripIndent()
+ fixture.open(widgetA.resolve('Alpha.groovy').toString(), alpha)
+ fixture.open(widgetB.resolve('Beta.groovy').toString(), beta)
+ fixture.open(widgetA.resolve('Widget.groovy').toString(), widget1)
+ fixture.open(widgetB.resolve('Widget.groovy').toString(), widget2)
+ def use = '''\
+ class Use {
+ Alpha a
+ Beta b
+ Widget w
+ }
+ '''.stripIndent()
+ def useUri = fixture.open(folder.resolve('Use.groovy').toString(), use)
+ def snapshot = fixture.server.context.snapshot
+ def useDoc = snapshot.get(useUri)
+ def diagnostics = fixture.publishedDiagnostics().findAll {
+ it.message != null && it.message.isLeft() && it.message.getLeft().toLowerCase().contains('unable to resolve class')
+ }
+ def actions = new CodeActionService().collect(useDoc.toTextDocument(), snapshot, diagnostics,
+ new Range(new Position(0, 0), new Position(5, 0)), UTF16, [], [])
+ assert actions.any { it.isRight() && it.getRight().title.startsWith('Add import for a.Alpha') }
+ assert actions.any { it.isRight() && it.getRight().title == 'Add all unambiguous imports' }
+ assert actions.any { it.isRight() && (it.getRight().title.startsWith('Add import for a.Widget') || it.getRight().title.startsWith('Add import for b.Widget')) }
+
+ def completion = new CompletionService()
+ def gdkDoc = new TextDocument(URI.create('file:///gdk.groovy'), 'groovy', 1, 'foo.each')
+ def gdk = completion.complete(gdkDoc, CompilationSnapshot.EMPTY, new Position(0, 8), UTF16)
+ assert gdk.items.any { it.detail == 'GDK' }
+ assert completion.complete(null, snapshot, new Position(0, 0), UTF16).items.any { it.kind.toString() == 'Keyword' }
+ assert CompletionService.prefixAt(null, null, UTF16) == ''
+ assert !CompletionService.isMemberAccess(null, null, UTF16)
+ assert CompletionService.prefixAt(gdkDoc, new Position(0, 80), UTF16).contains('each')
+ assert CompletionService.stringMap('nope').isEmpty()
+ assert CompletionService.stringMap(null).isEmpty()
+ assert CompletionService.stringMap([k: null, n: 'A']) == [n: 'A']
+ assert completion.resolve(null, snapshot) == null
+ def bare = new CompletionItem('x')
+ assert completion.resolve(bare, null).is(bare)
+
+ def boxText = '''\
+ /**
+ * A box.
+ */
+ class Box {
+ String name
+ static void ping(String name, int count) {}
+ /**
+ * Builds a box.
+ */
+ Box(String name, int count) { this.name = name }
+ void use() {
+ ping(name: 'a', )
+ Box.ping( )
+ new Box( )
+ }
+ }
+ interface Work { void run(String name, int count) }
+ class Job implements Work {
+ void run(String name, int count) {}
+ }
+ enum Hue { RED }
+ '''.stripIndent()
+ def boxUri = fixture.open('Box.groovy', boxText)
+ def boxCompiled = fixture.server.context.snapshot.get(boxUri)
+ assert boxCompiled.module != null : boxCompiled.errors
+ def boxDoc = boxCompiled.toTextDocument()
+ def member = afterLast(boxText, 'Box.')
+ def inside = completion.complete(boxDoc, fixture.server.context.snapshot, member, UTF16)
+ assert inside.items != null
+ assert CompletionService.isMemberAccess(boxDoc, member, UTF16)
+ def named = completion.complete(boxDoc, fixture.server.context.snapshot, after(boxText, "ping(name: 'a', "), UTF16)
+ assert named.items.any { it.kind.toString() == 'Keyword' }
+ def hueLine = boxText.readLines().findIndexOf { it.contains('enum Hue') }
+ def hueColumn = boxText.readLines()[hueLine].indexOf('Hue') + 2
+ def typeItems = completion.complete(boxDoc, fixture.server.context.snapshot, new Position(hueLine, hueColumn), UTF16)
+ assert typeItems.items.any { it.label == 'Hue' && it.kind.toString() == 'Enum' }
+ def boxType = boxCompiled.module.classes.find { it.name == 'Box' }
+ def ping = boxType.methods.find { it.name == 'ping' && it.lineNumber > 0 }
+ def item = new CompletionItem('ping')
+ item.data = [k: 'm', n: 'ping', o: ping.declaringClass.name, d: ping.typeDescriptor]
+ def resolved = completion.resolve(item, fixture.server.context.snapshot)
+ assert resolved.documentation == null || resolved.documentation.getRight().value != null
+ def typeItem = new CompletionItem('Box')
+ typeItem.data = [k: 't', n: boxType.name]
+ def resolvedType = completion.resolve(typeItem, fixture.server.context.snapshot)
+ assert resolvedType.documentation.getRight().value.contains('A box')
+
+ def hello = folder.resolve('Hello.groovy')
+ def helloText = '''\
+ class Hello {
+ Hello field
+ void run() { new Hello() }
+ static void util(int n) { util(1) }
+ }
+ '''.stripIndent()
+ def helloUri = fixture.open(hello.toString(), helloText)
+ def helloSnapshot = fixture.server.context.snapshot
+ def helloDoc = helloSnapshot.get(helloUri).toTextDocument()
+ def navigation = new NavigationService()
+ def classPos = caret(helloText, 'class Hello')
+ assert navigation.declaration(helloDoc, helloSnapshot, classPos, UTF16)
+ assert navigation.implementation(helloDoc, helloSnapshot, classPos, UTF16) != null
+ assert navigation.superMethod(helloDoc, helloSnapshot, caret(helloText, 'void run'), UTF16).isEmpty()
+ assert navigation.references(null, helloSnapshot, classPos, UTF16, true).isEmpty()
+ def multi = '''\
+ class Multi {
+ def split() {
+ def (left, right) = [1, 2]
+ left
+ }
+ }
+ '''.stripIndent()
+ def multiUri = fixture.open('Multi.groovy', multi)
+ def multiDoc = fixture.server.context.snapshot.get(multiUri).toTextDocument()
+ assert navigation.definition(multiDoc, fixture.server.context.snapshot, caret(multi, 'def (left'), UTF16) != null
+
+ def rename = new RenameService()
+ assert rename.prepareRename(null, helloSnapshot, classPos, UTF16) == null
+ assert rename.rename(helloDoc, helloSnapshot, classPos, ' ', UTF16).changes.isEmpty()
+ def renamed = rename.rename(helloDoc, helloSnapshot, caret(helloText, 'class Hello'), 'Greeting', UTF16)
+ assert renamed.documentChanges.any { it.isRight() && it.getRight() instanceof RenameFile }
+ assert rename.willRenameFiles(null, helloSnapshot, UTF16).changes != null
+ assert rename.willRenameFiles([null], helloSnapshot, UTF16).changes.isEmpty()
+ def javaRename = new FileRename(helloUri, helloUri.replace('.groovy', '.java'))
+ assert rename.willRenameFiles([javaRename], helloSnapshot, UTF16).changes.isEmpty()
+ def otherDir = new FileRename(helloUri, URI.create('file:///elsewhere/Greeting.groovy').toString())
+ assert rename.willRenameFiles([otherDir], helloSnapshot, UTF16).changes.isEmpty()
+ def badName = new FileRename(helloUri, helloUri.replace('Hello.groovy', '1Bad.groovy'))
+ assert rename.willRenameFiles([badName], helloSnapshot, UTF16).changes.isEmpty()
+ def good = new FileRename(helloUri, helloUri.replace('Hello.groovy', 'Greeting.groovy'))
+ def moved = rename.willRenameFiles([good], helloSnapshot, UTF16)
+ assert moved.changes.values().flatten().any { it.newText == 'Greeting' }
+ assert RenameService.isIdentifier('Name')
+ assert !RenameService.isIdentifier(null)
+ assert !RenameService.isIdentifier('')
+ assert !RenameService.isIdentifier('1a')
+ assert !RenameService.isIdentifier('a-b')
+
+ def hierarchy = new HierarchyService()
+ def prepared = hierarchy.prepareTypeHierarchy(helloDoc, helloSnapshot, caret(helloText, 'class Hello'), UTF16)
+ assert prepared
+ assert hierarchy.supertypes(prepared[0], helloSnapshot, UTF16) != null
+ assert hierarchy.subtypes(prepared[0], helloSnapshot, UTF16) != null
+ assert hierarchy.incomingCalls(null, helloSnapshot, UTF16).isEmpty()
+ assert hierarchy.prepareTypeHierarchy(null, helloSnapshot, classPos, UTF16).isEmpty()
+ def callItems = fixture.server.textDocumentService.prepareCallHierarchy(
+ new CallHierarchyPrepareParams(new TextDocumentIdentifier(helloUri),
+ caret(helloText, 'void util'))).get()
+ if (callItems) {
+ assert hierarchy.incomingCalls(callItems[0], helloSnapshot, UTF16) != null
+ assert hierarchy.outgoingCalls(callItems[0], helloSnapshot, UTF16) != null
+ }
+ def bad = new CallHierarchyItem('util', SymbolKind.Method, ':::',
+ new Range(new Position(0, 0), new Position(0, 1)),
+ new Range(new Position(0, 0), new Position(0, 1)))
+ bad.data = [:]
+ assert hierarchy.outgoingCalls(bad, helloSnapshot, UTF16)*.to.name.contains('util')
+
+ AstQuery.walk(helloSnapshot.get(helloUri).module) { node, ctx ->
+ def identity = SymbolIdentity.of(node, helloSnapshot)
+ if (identity != null) {
+ assert identity.refersTo(node, ctx) || !identity.refersTo(null, ctx)
+ }
+ SymbolIdentity.keyOf(node)
+ }
+ assert !SymbolIdentity.isResolvedType(null)
+ assert !SymbolIdentity.isResolvedType(ClassHelper.OBJECT_TYPE)
+ assert SymbolIdentity.isResolvedType(ClassHelper.STRING_TYPE)
+ assert SymbolService.kindOf(new Parameter(ClassHelper.STRING_TYPE, 'p')) == SymbolKind.Variable
+ assert SymbolService.kindOf(hueNode(boxCompiled)) == SymbolKind.Enum
+ assert new SymbolService().workspaceSymbols(null, 'Box', UTF16).isEmpty()
+ assert new SymbolService().documentSymbols(null, UTF16).isEmpty()
+ assert new SymbolService().documentSymbolInformation(boxCompiled, UTF16).any { it.name == 'Box' }
+ }
+
+ private static ClassNode hueNode(CompiledDocument document) {
+ document.module.classes.find { it.name == 'Hue' }
+ }
+
+ private static Position caret(String text, String token) {
+ int idx = text.indexOf(token)
+ assert idx >= 0 : token
+ int line = 0
+ int character = 0
+ for (int i = 0; i < idx; i++) {
+ if (text.charAt(i) == '\n') {
+ line++
+ character = 0
+ } else {
+ character++
+ }
+ }
+ new Position(line, character)
+ }
+
+ private static Position after(String text, String token) {
+ def position = caret(text, token)
+ new Position(position.line, position.character + token.length())
+ }
+
+ private static Position afterLast(String text, String token) {
+ int idx = text.lastIndexOf(token)
+ assert idx >= 0 : token
+ int line = 0
+ int character = 0
+ int end = idx + token.length()
+ for (int i = 0; i < end; i++) {
+ if (text.charAt(i) == '\n') {
+ line++
+ character = 0
+ } else {
+ character++
+ }
+ }
+ new Position(line, character)
+ }
+
+ private static void place(ASTNode node, int line, int column, int lastColumn) {
+ node.lineNumber = line
+ node.columnNumber = column
+ node.lastLineNumber = line
+ node.lastColumnNumber = lastColumn
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/SupportServicesTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/SupportServicesTest.groovy
index b6a42d691d..d1669e8573 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/SupportServicesTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/SupportServicesTest.groovy
@@ -18,6 +18,27 @@
*/
package org.apache.groovy.lsp.internal.feature
+import java.nio.file.Path
+import org.apache.groovy.lsp.internal.compile.AstQuery
+import org.apache.groovy.lsp.internal.compile.CompilationSnapshot
+import org.apache.groovy.lsp.internal.compile.CompilerSettings
+import org.apache.groovy.lsp.internal.compile.GroovyCompiler
+import org.apache.groovy.lsp.internal.util.Uris
+import org.codehaus.groovy.ast.AnnotationNode
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.CompileUnit
+import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.ModuleNode
+import org.codehaus.groovy.ast.Parameter
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.expr.PropertyExpression
+import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
+import org.codehaus.groovy.ast.expr.TupleExpression
+import org.codehaus.groovy.control.SourceUnit
+import org.eclipse.lsp4j.FoldingRangeKind
+import static org.objectweb.asm.Opcodes.ACC_PUBLIC
+
import org.apache.groovy.lsp.internal.LspFixture
import org.apache.groovy.lsp.internal.compile.CompiledDocument
import org.apache.groovy.lsp.internal.compile.WorkspaceScanner
@@ -50,6 +71,10 @@ import org.junit.jupiter.api.Test
import java.nio.file.Files
final class SupportServicesTest {
+ private static final PositionEncoding UTF16 = PositionEncoding.UTF16
+
+ private static final PositionEncoding ENC = PositionEncoding.UTF16
+
private LspFixture fixture
@@ -288,4 +313,443 @@ final class SupportServicesTest {
new FormattingOptions(4, false), new Position(1, 0), '\n')).get()
assert edits[0].newText.contains('\t') || edits[0].newText.isEmpty()
}
+ @Test
+ void semanticTokensCoverKindsModifiersAndRanges() {
+ def uri = fileUri('file:///tmp/cov-tokens.groovy')
+ def src = '''\
+ package demo
+ import java.util.List
+ @java.lang.SuppressWarnings('unused')
+ interface Face {
+ void run()
+ }
+ @java.lang.Deprecated
+ enum Hue {
+ RED
+ }
+ class Hello {
+ @java.lang.Deprecated
+ static String label
+ def foo(String item) {
+ this.label
+ go('x')
+ }
+ static void go(String item) {}
+ }
+ '''.stripIndent()
+ def snap = compileOf(uri, src)
+ def module = snap.get(uri).module
+ def face = module.classes.find { it.nameWithoutPackage == 'Face' }
+ def hue = module.classes.find { it.nameWithoutPackage == 'Hue' }
+ assert face.annotations.any { it.classNode?.name == 'java.lang.SuppressWarnings' }
+ assert hue.annotations.any { it.classNode?.name == 'java.lang.Deprecated' }
+ assert walked(module, StaticMethodCallExpression) { it.method == 'go' }
+ assert walked(module, PropertyExpression) { it.propertyAsString == 'label' }
+ def hello = module.classes.find { it.nameWithoutPackage == 'Hello' }
+ hello.addSyntheticMethod('hidden', ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
+ Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
+
+ def service = new SemanticTokensService()
+ def full = decode(service.semanticTokens(snap.get(uri), UTF16).data)
+ assert full.any { it.type == token('interface') }
+ assert full.any { it.type == token('enum') && (it.mod & 4) != 0 }
+ assert full.any { it.type == token('property') && (it.mod & 2) != 0 }
+ assert full.any { it.type == token('method') }
+ def ranged = decode(service.semanticTokens(snap.get(uri), UTF16,
+ new Range(new Position(0, 0), new Position(0, 4))).data)
+ assert ranged
+ assert ranged.every { it.line == 0 }
+ assert full.any { it.line > 0 }
+
+ def bare = new NullAnnotations()
+ bare.lineNumber = 1
+ bare.columnNumber = 7
+ bare.lastLineNumber = 1
+ bare.lastColumnNumber = 12
+ def bareModule = new ModuleNode((SourceUnit) null)
+ bareModule.addClass(bare)
+ def bareDoc = new CompiledDocument(fileUri('file:///tmp/cov-bare-token.groovy'), 1, 'class Hello {}',
+ bareModule, null, null)
+ def bareTokens = decode(service.semanticTokens(bareDoc, UTF16).data)
+ assert bareTokens.any { it.type == token('class') && it.mod == 1 }
+
+ def one = new CompiledDocument(fileUri('file:///tmp/cov-one.groovy'), 1, 'def', null, null, null)
+ assert service.semanticTokens(one, UTF16).data.size() == 5
+ def empty = new CompiledDocument(fileUri('file:///tmp/cov-empty-text.groovy'), 1, '', null, null, null)
+ assert service.semanticTokens(empty, UTF16).data.isEmpty()
+ }
+
+ private CompilationSnapshot compileOf(URI uri, String text) {
+ compileOf([new TextDocument(uri, 'groovy', 1, text)])
+ }
+
+ private CompilationSnapshot compileOf(List<TextDocument> documents) {
+ def compiler = new GroovyCompiler()
+ try {
+ return compiler.compile(documents, [], CompilerSettings.defaults(), getClass().classLoader)
+ } finally {
+ compiler.close()
+ }
+ }
+
+ private static URI fileUri(String path) {
+ Uris.normalize(URI.create(path))
+ }
+
+ private static URI fileUri(Path path) {
+ Uris.normalize(path.toUri())
+ }
+
+ private static boolean walked(module, Class type, Closure predicate) {
+ boolean[] found = [false]
+ AstQuery.walk(module) { node, ctx ->
+ if (type.isInstance(node) && predicate(node)) {
+ found[0] = true
+ }
+ }
+ found[0]
+ }
+
+ private static int token(String name) {
+ SemanticTokensService.TOKEN_TYPES.indexOf(name)
+ }
+
+ private static List<Map> decode(List<Integer> data) {
+ int line = 0
+ int col = 0
+ def out = []
+ for (int i = 0; i < data.size(); i += 5) {
+ line += data[i]
+ col = data[i] == 0 ? col + data[i + 1] : data[i + 1]
+ out << [line: line, start: col, length: data[i + 2], type: data[i + 3], mod: data[i + 4]]
+ }
+ out
+ }
+
+ private static final class NullAnnotations extends ClassNode {
+ private boolean reported
+
+ NullAnnotations() {
+ super('Hello', ACC_PUBLIC, ClassHelper.OBJECT_TYPE)
+ }
+
+ @Override
+ List<AnnotationNode> getAnnotations() {
+ if (!reported) {
+ reported = true
+ return null
+ }
+ Collections.emptyList()
+ }
+ }
+
+ @Test
+ void signatureHelpActiveParameterAndEmptyOverloads() {
+ def src = '''\
+ class Sig {
+ void zero() {}
+ void two(int a, int b) {}
+ void show() {
+ missing(1)
+ zero( )
+ two(1, 2 )
+ }
+ }
+ '''.stripIndent()
+ def uri = open('Sig.groovy', src)
+ def doc = compiled(uri)
+ def buffer = doc.toTextDocument()
+ def service = new SignatureHelpService()
+ def orphan = new TextDocument(URI.create('file:///missing.groovy'), 'groovy', 1, doc.text)
+ assert service.signatureHelp(orphan, snapshot(), at(doc.text, 'class'), ENC).signatures.isEmpty()
+ assert service.signatureHelp(buffer, snapshot(), at(doc.text, 'missing('), ENC).signatures.isEmpty()
+ assert service.signatureHelp(buffer, snapshot(), at(doc.text, 'class'), ENC).signatures.isEmpty()
+
+ def zeroPos = at(doc.text, 'zero( )')
+ zeroPos.character += 'zero('.length()
+ def zeroHelp = service.signatureHelp(buffer, snapshot(), zeroPos, ENC)
+ assert zeroHelp.signatures*.label.any { it.contains('zero()') }
+ assert zeroHelp.activeParameter == 0
+
+ def twoCall = callsNamed(typeNamed(doc, 'Sig').methods.find { it.name == 'show' }, 'two')[0]
+ def args = twoCall.arguments
+ assert args instanceof TupleExpression
+ def first = args.expressions[0]
+ int savedLine = first.lineNumber
+ def mid = new Position(first.lastLineNumber - 1, first.lastColumnNumber)
+ assert AstQuery.enclosingCall(doc.module, buffer, mid, ENC).is(twoCall)
+ assert service.signatureHelp(buffer, snapshot(), mid, ENC).activeParameter == 1
+ first.lineNumber = -1
+ assert service.signatureHelp(buffer, snapshot(), mid, ENC).activeParameter == 0
+ first.lineNumber = savedLine
+
+ def last = args.expressions[-1]
+ def afterLast = new Position(last.lastLineNumber - 1, last.lastColumnNumber)
+ assert AstQuery.enclosingCall(doc.module, buffer, afterLast, ENC).is(twoCall)
+ def afterHelp = service.signatureHelp(buffer, snapshot(), afterLast, ENC)
+ assert afterHelp.activeParameter == 1
+ assert afterHelp.signatures[afterHelp.activeSignature].label.contains('int a, int b')
+ }
+
+ @Test
+ void formattingRangeNewlineAndOutdentGuards() {
+ def formatting = new FormattingService()
+ def ready = 'class C {\n def ready\n}\n'
+ def readyDoc = new TextDocument(URI.create('file:///C.groovy'), 'groovy', 1, ready)
+ assert formatting.format(readyDoc, new Range(new Position(5, 0), new Position(1, 0)), 4, true, ENC).isEmpty()
+ assert formatting.format(readyDoc, new Range(new Position(1, 0), new Position(1, 12)), 4, true, ENC).isEmpty()
+
+ def bare = new TextDocument(URI.create('file:///C.groovy'), 'groovy', 1, 'class C {\n}')
+ def full = formatting.format(bare, null, 4, true, ENC)
+ assert full.size() == 1
+ assert full[0].newText.endsWith('\n')
+ assert full[0].newText.contains('class C')
+
+ def ended = new TextDocument(URI.create('file:///C.groovy'), 'groovy', 1, 'class C {\n}')
+ assert formatting.onTypeFormat(ended, new Position(5, 0), '}', 4, true, ENC).isEmpty()
+ def identifier = new TextDocument(URI.create('file:///C.groovy'), 'groovy', 1, 'class C {\n x}\n')
+ int brace = identifier.text.readLines()[1].indexOf('}') + 1
+ assert formatting.onTypeFormat(identifier, new Position(1, brace), '}', 4, true, ENC).isEmpty()
+ assert formatting.onTypeFormat(null, new Position(0, 0), '\n', 4, true, ENC).isEmpty()
+ assert formatting.onTypeFormat(readyDoc, new Position(0, 0), null, 4, true, ENC).isEmpty()
+ assert formatting.onTypeFormat(readyDoc, new Position(-1, 0), '\n', 4, true, ENC).isEmpty()
+ }
+
+ @Test
+ void foldingRegionsImportsAndEmptyText() {
+ def src = '''\
+ import java.util.List
+ import java.util.Map
+ // #region basket
+ class Folded {
+ def foo() { 1 }
+ }
+ // #endregion
+ // plain note
+ '''.stripIndent()
+ def uri = open('Folded.groovy', src)
+ def doc = compiled(uri)
+ doc.module.addStarImport('ghost.')
+ def ghost = doc.module.starImports[-1]
+ ghost.lineNumber = -1
+ def folds = new FoldingService().folding(doc)
+ def regions = folds.findAll { it.kind == FoldingRangeKind.Region }
+ assert regions.size() == 1
+ assert regions[0].startLine == doc.text.readLines().findIndexOf { it.contains('#region') }
+ def imports = folds.findAll { it.kind == FoldingRangeKind.Imports }
+ assert imports.size() == 1
+ assert imports[0].startLine == 0
+
+ def emptyModule = new ModuleNode((CompileUnit) null)
+ def empty = new CompiledDocument(URI.create('file:///empty.groovy'), 1, '', emptyModule, null, null)
+ assert new FoldingService().folding(empty).isEmpty()
+ }
+
+ private String open(String path, String text) {
+ if (fixture == null) {
+ fixture = new LspFixture()
+ }
+ fixture.open(path, text)
+ }
+
+ private CompilationSnapshot snapshot() {
+ fixture.server.context.snapshot
+ }
+
+ private CompiledDocument compiled(String uri) {
+ def doc = snapshot().get(uri)
+ assert doc?.module != null
+ doc
+ }
+
+ private static ClassNode typeNamed(CompiledDocument doc, String simple) {
+ def found = doc.module.classes.find { it.nameWithoutPackage == simple && !it.name.contains('$') }
+ assert found != null : doc.module.classes*.name
+ found
+ }
+
+ private static List<MethodCallExpression> callsNamed(MethodNode method, String name) {
+ def found = []
+ AstQuery.walk(method.code) { node, ctx ->
+ if (node instanceof MethodCallExpression && node.methodAsString == name) {
+ found << node
+ }
+ }
+ assert found : name
+ found
+ }
+
+ private static Position at(String text, String token) {
+ int index = text.indexOf(token)
+ assert index >= 0 : token
+ int line = 0
+ int column = 0
+ for (int i = 0; i < index; i++) {
+ if (text.charAt(i) == '\n') {
+ line += 1
+ column = 0
+ } else {
+ column += 1
+ }
+ }
+ new Position(line, column)
+ }
+
+ @Test
+ void signatureInlaySemanticFormatAndLinks() {
+ fixture = new LspFixture()
+ def text = '''\
+ package demo
+ import java.util.Map
+ import static java.lang.Math.PI
+ import java.util.List
+ import java.util.*
+ @Deprecated
+ class Box {
+ @Deprecated
+ static String CONST = 'x'
+ String name
+ static void ping(String name, int count) {}
+ Box(String name, int count) { this.name = name }
+ void use(def label) {
+ def item = 'z'
+ def name = 'a'
+ ping(name, 1)
+ ping(name: 'a', count: 1)
+ Box.ping('b', 2)
+ new Box('a', 1)
+ ping('a', 1)
+ List
+ PI
+ CONST.length()
+ }
+ }
+ interface Named { String name() }
+ enum Hue { RED }
+ '''.stripIndent()
+ def uri = fixture.open('Box.groovy', text)
+ def snapshot = fixture.server.context.snapshot
+ def compiled = snapshot.get(uri)
+ def document = compiled.toTextDocument()
+ def help = new SignatureHelpService()
+ assert help.signatureHelp(null, snapshot, new Position(0, 0), UTF16).signatures.isEmpty()
+ def outside = help.signatureHelp(document, snapshot, caret(text, 'class'), UTF16)
+ assert outside.signatures.isEmpty()
+ def staticHelp = help.signatureHelp(document, snapshot, after(text, 'Box.ping('), UTF16)
+ assert staticHelp.signatures.any { it.label.contains('ping') }
+ def ctorHelp = help.signatureHelp(document, snapshot, after(text, 'new Box('), UTF16)
+ assert ctorHelp.signatures.any { it.label.contains('<init>') }
+ def tooMany = help.signatureHelp(document, snapshot, after(text, "ping('a', 1"), UTF16)
+ assert tooMany.signatures.any { it.label.startsWith('ping') }
+ assert tooMany.activeParameter >= 0
+
+ def inlays = new InlayHintService()
+ assert inlays.inlayHints(null, null, UTF16).isEmpty()
+ def hints = inlays.inlayHints(compiled, null, UTF16, snapshot)
+ assert hints.any { it.kind.toString().contains('Parameter') || (it.label.isLeft() && it.label.getLeft().contains(':')) }
+ def skipped = inlays.inlayHints(compiled, new Range(new Position(200, 0), new Position(200, 1)), UTF16, snapshot)
+ assert skipped.size() <= hints.size()
+
+ def tokens = new SemanticTokensService().semanticTokens(compiled, UTF16)
+ def kinds = tokenTypes(tokens.data)
+ assert SemanticTokensService.TOKEN_TYPES.indexOf('interface') in kinds
+ assert SemanticTokensService.TOKEN_TYPES.indexOf('enum') in kinds
+ assert SemanticTokensService.TOKEN_TYPES.indexOf('method') in kinds
+ assert tokenModifiers(tokens.data).any { (it & 2) != 0 }
+ assert tokenModifiers(tokens.data).any { (it & 4) != 0 }
+ def ranged = new SemanticTokensService().semanticTokens(compiled, UTF16,
+ new Range(new Position(0, 0), new Position(0, 1)))
+ assert ranged.data != null
+
+ def formatting = new FormattingService()
+ def messy = new TextDocument(URI.create('file:///T.groovy'), 'groovy', 1, 'class T {\n def a=1\n}')
+ def formatted = formatting.format(messy, null, 4, true, UTF16)
+ assert formatted[0].newText.endsWith('\n')
+ def tidy = new TextDocument(messy.uri, 'groovy', 2, formatted[0].newText)
+ assert formatting.format(tidy, null, 4, true, UTF16).isEmpty()
+ assert formatting.format(messy, new Range(new Position(5, 0), new Position(1, 0)), 4, true, UTF16).isEmpty()
+ assert formatting.onTypeFormat(null, new Position(0, 0), '\n', 4, true).isEmpty()
+ assert formatting.onTypeFormat(messy, new Position(0, 0), null, 4, true).isEmpty()
+ assert formatting.onTypeFormat(messy, new Position(-1, 0), '\n', 4, true).isEmpty()
+ assert formatting.onTypeFormat(messy, new Position(0, 0), 'x', 4, true).isEmpty()
+ def tabbed = new TextDocument(URI.create('file:///Tab.groovy'), 'groovy', 1, 'class T {\n\tdef a = 1\n}\n')
+ assert formatting.format(tabbed, null, 4, false, UTF16) != null
+ def closer = new TextDocument(URI.create('file:///C.groovy'), 'groovy', 1, 'class T {\n}')
+ assert formatting.onTypeFormat(closer, new Position(20, 1), '}', 4, true).isEmpty()
+ def frozen = new TextDocument(URI.create('file:///F.groovy'), 'groovy', 1, "class F {\n def s = '''\n keep\n'''\n}\n")
+ def frozenEdits = formatting.format(frozen, null, 4, true, UTF16)
+ if (frozenEdits) {
+ assert frozenEdits[0].newText.contains('keep')
+ }
+
+ def folds = new FoldingService().folding(compiled)
+ assert folds.any { it.kind == 'imports' }
+ def regions = '''\
+ // #region demo
+ class Regioned {
+ }
+ // #endregion
+ /* one */
+ /*
+ block
+ */
+ '''.stripIndent()
+ def regionUri = fixture.open('Regioned.groovy', regions)
+ def regionDoc = snapshotOf(regionUri)
+ assert new FoldingService().folding(regionDoc).any { it.kind == 'region' }
+ assert new FoldingService().folding(new CompiledDocument(URI.create('file:///e.groovy'), 1, '', null, null, null)).isEmpty()
+
+ def lenses = new CodeLensService().codeLenses(compiled, snapshot, UTF16)
+ assert lenses.any { it.command.title.contains('reference') }
+ assert new CodeLensService().codeLenses(null, snapshot, UTF16).isEmpty()
+
+ def selection = new SelectionRangeService().selectionRanges(document, snapshot, [new Position(400, 0)], UTF16)
+ assert selection[0].range.start.line == 400
+
+ def links = new DocumentLinkService().documentLinks(compiled, snapshot, UTF16)
+ assert links != null
+ assert new DocumentLinkService().documentLinks(null, snapshot, UTF16).isEmpty()
+ }
+
+ private CompiledDocument snapshotOf(String uri) {
+ fixture.server.context.snapshot.get(uri)
+ }
+
+ private static List<Integer> tokenTypes(List<Integer> data) {
+ def types = []
+ for (int i = 0; i + 4 < data.size(); i += 5) {
+ types << data[i + 3]
+ }
+ types
+ }
+
+ private static List<Integer> tokenModifiers(List<Integer> data) {
+ def modifiers = []
+ for (int i = 0; i + 4 < data.size(); i += 5) {
+ modifiers << data[i + 4]
+ }
+ modifiers
+ }
+
+ private static Position caret(String text, String token) {
+ int idx = text.indexOf(token)
+ assert idx >= 0 : token
+ int line = 0
+ int character = 0
+ for (int i = 0; i < idx; i++) {
+ if (text.charAt(i) == '\n') {
+ line++
+ character = 0
+ } else {
+ character++
+ }
+ }
+ new Position(line, character)
+ }
+
+ private static Position after(String text, String token) {
+ def position = caret(text, token)
+ new Position(position.line, position.character + token.length())
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/TypeInferenceTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/TypeInferenceTest.groovy
new file mode 100644
index 0000000000..bcd3ed273f
--- /dev/null
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/TypeInferenceTest.groovy
@@ -0,0 +1,64 @@
+/*
+ * 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.apache.groovy.lsp.internal.feature
+
+import java.lang.reflect.Modifier
+import org.junit.jupiter.api.Test
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.FieldNode
+import org.codehaus.groovy.transform.stc.StaticTypesMarker
+
+final class TypeInferenceTest {
+
+ @Test
+ void typeInferenceMarkersFieldsAndInitializers() {
+ def owner = new ClassNode('demo.Infer', Modifier.PUBLIC, ClassHelper.OBJECT_TYPE)
+ def marked = field(owner, 'n', 0, ClassHelper.OBJECT_TYPE, 1)
+ marked.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, ClassHelper.STRING_TYPE)
+ assert TypeInference.of(marked).name == 'java.lang.String'
+
+ def typed = new VariableExpression('s', ClassHelper.STRING_TYPE)
+ assert !typed.dynamicTyped
+ assert TypeInference.of(typed, null).name == 'java.lang.String'
+
+ def count = field(owner, 'count', 0, ClassHelper.dynamicType(), 2)
+ count.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, ClassHelper.STRING_TYPE)
+ def dynamic = new VariableExpression('count')
+ dynamic.accessedVariable = count
+ assert dynamic.dynamicTyped
+ assert TypeInference.of(dynamic, null).name == 'java.lang.String'
+
+ def concrete = field(owner, 'name', 0, ClassHelper.STRING_TYPE, 3)
+ assert !TypeInference.usedInitializer(concrete)
+
+ def uninit = field(owner, 'pending', 0, ClassHelper.dynamicType(), 4)
+ assert ClassHelper.isDynamicTyped(TypeInference.of(uninit))
+ }
+
+ private static FieldNode field(ClassNode owner, String name, int modifiers, ClassNode type, int line) {
+ def node = new FieldNode(name, modifiers, type, owner, null)
+ node.lineNumber = line
+ node.columnNumber = 1
+ node.lastLineNumber = line
+ node.lastColumnNumber = 2
+ node
+ }
+}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/position/PositionsTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/position/PositionsTest.groovy
index 2dcc737f87..b2c5ddf0be 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/position/PositionsTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/position/PositionsTest.groovy
@@ -18,6 +18,9 @@
*/
package org.apache.groovy.lsp.internal.position
+import org.codehaus.groovy.ast.expr.AttributeExpression
+import org.codehaus.groovy.ast.expr.ConstantExpression
+
import org.codehaus.groovy.ast.ASTNode
import org.codehaus.groovy.ast.ClassHelper
import org.codehaus.groovy.ast.ClassNode
@@ -160,4 +163,41 @@ final class PositionsTest {
assert PositionEncoding.fromProtocol(null) == null
assert PositionEncoding.UTF16.protocolName() == 'utf-16'
}
+ @Test
+ void attributeIdentifierRangeAndPositionEdges() {
+ def name = new ConstantExpression('secret')
+ def attribute = new AttributeExpression(new VariableExpression('this'), name)
+ assert Positions.toIdentifierRange(attribute, 'this.@secret', PositionEncoding.UTF16) == null
+
+ def negative = new ASTNode()
+ negative.lineNumber = 1
+ negative.columnNumber = -5
+ negative.lastLineNumber = 1
+ negative.lastColumnNumber = 2
+ def positive = new ASTNode()
+ positive.lineNumber = 1
+ positive.columnNumber = 1
+ positive.lastLineNumber = 1
+ positive.lastColumnNumber = 2
+ assert Positions.innerScore(negative) != Positions.innerScore(positive)
+
+ def hello = new ClassNode('Hello', 0, ClassHelper.OBJECT_TYPE)
+ hello.lineNumber = 1
+ hello.columnNumber = 1
+ hello.lastLineNumber = 1
+ hello.lastColumnNumber = 20
+ assert Positions.findIdentifier(hello, 'class xHello', PositionEncoding.UTF16) == null
+
+ def index = Positions.getDeclaredMethod('indexOfIdentifier', int[], String, int, int)
+ index.accessible = true
+ assert index.invoke(null, new int[0], '', 0, 0) == -1
+
+ String emoji = 'a🥤b'
+ assert Positions.characterToGroovyColumn(emoji, 2, PositionEncoding.UTF16) == 2
+ assert Positions.characterToGroovyColumn('©', 1, PositionEncoding.UTF8) == 1
+ assert Positions.characterToGroovyColumn('©', 2, PositionEncoding.UTF8) == 2
+ assert Positions.characterToGroovyColumn('€', 1, PositionEncoding.UTF8) == 1
+ assert Positions.characterToGroovyColumn('€', 3, PositionEncoding.UTF8) == 2
+ }
+
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/protocol/ProtocolCoverageTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/protocol/ProtocolCoverageTest.groovy
index 4289330d9b..c0cc5c581f 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/protocol/ProtocolCoverageTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/protocol/ProtocolCoverageTest.groovy
@@ -21,7 +21,11 @@ package org.apache.groovy.lsp.internal.protocol
import org.apache.groovy.lsp.GroovyLanguageServerLauncher
import org.apache.groovy.lsp.internal.LspFixture
import org.apache.groovy.lsp.internal.util.Uris
+import org.apache.groovy.lsp.internal.LanguageServerContext
+import org.apache.groovy.lsp.internal.feature.LanguageFeatures
+import org.eclipse.lsp4j.CodeAction
import org.eclipse.lsp4j.CodeActionContext
+import org.eclipse.lsp4j.Command
import org.eclipse.lsp4j.CodeActionParams
import org.eclipse.lsp4j.CompletionParams
import org.eclipse.lsp4j.DeclarationParams
@@ -62,6 +66,7 @@ import org.eclipse.lsp4j.TypeHierarchySubtypesParams
import org.eclipse.lsp4j.TypeHierarchySupertypesParams
import org.eclipse.lsp4j.WorkspaceFolder
import org.eclipse.lsp4j.WorkspaceFoldersChangeEvent
+import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
@@ -223,4 +228,37 @@ final class ProtocolCoverageTest {
thread.join(2000)
}
}
+
+ @Test
+ void workspaceFolderChangesAndCommandsTolerateMissingDocuments() {
+ def context = new LanguageServerContext()
+ try {
+ def workspace = new GroovyWorkspaceService(context, new LanguageFeatures())
+ workspace.didChangeWorkspaceFolders(new DidChangeWorkspaceFoldersParams())
+ def added = new WorkspaceFoldersChangeEvent([null, new WorkspaceFolder()], [])
+ workspace.didChangeWorkspaceFolders(new DidChangeWorkspaceFoldersParams(added))
+ def bare = new WorkspaceFoldersChangeEvent()
+ def addedField = WorkspaceFoldersChangeEvent.getDeclaredField('added')
+ def removedField = WorkspaceFoldersChangeEvent.getDeclaredField('removed')
+ addedField.accessible = true
+ removedField.accessible = true
+ addedField.set(bare, null)
+ removedField.set(bare, null)
+ workspace.didChangeWorkspaceFolders(new DidChangeWorkspaceFoldersParams(bare))
+
+ def missing = workspace.executeCommand(new ExecuteCommandParams(
+ 'groovy.lsp.showReferences', ['file:///groovy-lsp-missing.groovy', 1, 2])).get()
+ assert missing instanceof List
+ assert missing.isEmpty()
+ def superCall = workspace.executeCommand(new ExecuteCommandParams(
+ 'groovy.lsp.gotoSuperMethod', ['file:///groovy-lsp-missing.groovy', 'x', 'y'])).get()
+ assert superCall instanceof List
+ assert superCall.isEmpty()
+
+ def actions = [null, Either.forLeft(new Command('title', 'cmd')), Either.forRight(new CodeAction('bare'))]
+ assert GroovyTextDocumentService.filterByOnly(actions, ['refactor']).isEmpty()
+ } finally {
+ context.close()
+ }
+ }
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovyKeywordsTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovyKeywordsTest.groovy
index f21fc64a46..d0902c9948 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovyKeywordsTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovyKeywordsTest.groovy
@@ -45,4 +45,12 @@ final class GroovyKeywordsTest {
assert GroovyKeywords.KEYWORDS.containsAll(GroovyKeywords.MODIFIERS)
assert GroovyKeywords.MODIFIERS == GroovyKeywords.MODIFIERS.toSorted()
}
+
+ @Test
+ void wordKeywordsRejectPunctuation() {
+ def word = GroovyKeywords.getDeclaredMethod('isWordKeyword', String)
+ word.accessible = true
+ assert word.invoke(null, 'a!') == false
+ assert word.invoke(null, 'non-sealed') == true
+ }
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovySourceTokensTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovySourceTokensTest.groovy
index 6f953def81..e4b15547b2 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovySourceTokensTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovySourceTokensTest.groovy
@@ -52,4 +52,15 @@ final class GroovySourceTokensTest {
assert !GroovySourceTokens.isStructuralRbrace('/* block } */', '/* block } */'.indexOf('}'))
assert !GroovySourceTokens.isStructuralRbrace("def c = '}'", "def c = '}'".indexOf('}'))
}
+
+ @Test
+ void shebangAndBrokenNumericLiteralProduceNoCoveringToken() {
+ def skipped = '#!only\nclass C {}'
+ assert !GroovySourceTokens.tokenize(skipped).isEmpty()
+ assert GroovySourceTokens.covering(skipped, 0) == null
+ assert GroovySourceTokens.tokenize('#!only').isEmpty()
+ assert GroovySourceTokens.covering('#!only', 1) == null
+ assert GroovySourceTokens.tokenize('1_').isEmpty()
+ assert GroovySourceTokens.covering('1_', 0) == null
+ }
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovydocMarkdownTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovydocMarkdownTest.groovy
index 75376505e3..df45db4ff6 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovydocMarkdownTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovydocMarkdownTest.groovy
@@ -49,4 +49,13 @@ final class GroovydocMarkdownTest {
assert GroovydocMarkdown.format('{@literal *}').contains('*')
assert GroovydocMarkdown.format('plain <unknown>tag</unknown>').contains('plain tag')
}
+
+ @Test
+ void formatsBareTagsAndUnclosedMarkup() {
+ assert GroovydocMarkdown.format('{@link java.lang.String#foo bar}').contains('java.lang.String.foo')
+ assert GroovydocMarkdown.format('{@link java.lang.String}').contains('`String`')
+ assert GroovydocMarkdown.format('keep <unclosed').contains('<unclosed')
+ assert GroovydocMarkdown.format('@exception Only').contains('**@exception** `Only`')
+ assert GroovydocMarkdown.format('@param name').contains('**@param** `name`')
+ }
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/NameHumpsTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/NameHumpsTest.groovy
index 6c8b9e58c6..53ae06e4a7 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/NameHumpsTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/NameHumpsTest.groovy
@@ -38,4 +38,12 @@ final class NameHumpsTest {
assert NameHumps.splitHumps('') == []
assert NameHumps.splitHumps(null) == []
}
+
+ @Test
+ void mismatchedHumpDoesNotMatch() {
+ assert !NameHumps.matches('Aqz', 'Abstract')
+ def hump = NameHumps.getDeclaredMethod('humpMatches', String, String)
+ hump.accessible = true
+ assert hump.invoke(null, '', 'Abstract') == false
+ }
}
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/UrisTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/UrisTest.groovy
index 6fb711c506..8bf1977d14 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/UrisTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/UrisTest.groovy
@@ -65,4 +65,11 @@ final class UrisTest {
Uris.normalize(URI.create('file:///C:/Users/me/Hello.groovy'))
assert Uris.fileName(URI.create('foo:bar')) == 'bar'
}
+
+ @Test
+ void fileNameAndSeparatorGuardEmptyInput() {
+ assert Uris.fileName(new URI(null, null, null)) == ''
+ assert Uris.lastSeparator(null) == -1
+ assert Uris.lastSeparator('') == -1
+ }
}