Skip to content

Commit 7e0363a

Browse files
gselzerclaude
andcommitted
code-lsp: keep server processes in a toolkit, not plugins
ServerProcessPlugin and the plugin publishing its processes are gone: a new exported package, org.scijava.code.lsp.server, holds what server plugins build on (ServerLauncher, ServerProcesses and RoutingLanguageServer), and plugins own the processes they start. So code-lsp-jedi serves "python" only, keeping jedi-language-server to itself; code-lsp-jython builds on "python". The servers' tests move here from the scripting repos, testing them on plain code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 69ec15b commit 7e0363a

31 files changed

Lines changed: 1050 additions & 357 deletions

‎code-lsp-groovy/src/test/java/org/scijava/code/lsp/groovy/GroovyLanguageServerTest.java‎

Lines changed: 328 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,275 @@
3030
package org.scijava.code.lsp.groovy;
3131

3232
import static org.junit.jupiter.api.Assertions.assertEquals;
33+
import static org.junit.jupiter.api.Assertions.assertFalse;
34+
import static org.junit.jupiter.api.Assertions.assertNull;
35+
import static org.junit.jupiter.api.Assertions.assertTrue;
3336

37+
import java.util.ArrayList;
38+
import java.util.Collections;
39+
import java.util.List;
40+
import java.util.concurrent.TimeUnit;
41+
import java.util.stream.Collectors;
42+
43+
import javax.script.ScriptContext;
44+
import javax.script.SimpleScriptContext;
45+
46+
import org.eclipse.lsp4j.CompletionItem;
47+
import org.eclipse.lsp4j.Diagnostic;
48+
import org.eclipse.lsp4j.SignatureHelp;
3449
import org.junit.jupiter.api.Test;
50+
import org.scijava.code.lsp.Environment;
51+
import org.scijava.code.lsp.ScriptSession;
52+
import org.scijava.code.lsp.jvm.ClassIndex;
3553

3654
/**
37-
* Tests {@link GroovyLanguageServer}'s pieces.
55+
* Tests {@link GroovyLanguageServer}: what it makes of plain Groovy, as its
56+
* clients send it.
3857
*
3958
* @author Gabriel Selzer
4059
*/
4160
public class GroovyLanguageServerTest {
4261

62+
@Test
63+
public void testMembersOfInferredTypes() {
64+
assertTrue(complete("def s = 'hello'\ns.toUpp").contains("toUpperCase"));
65+
// Types flow through method calls...
66+
assertTrue(complete("def x = new ArrayList()\n" +
67+
"def y = x.subList(0, 1)\ny.isEm").contains("isEmpty"));
68+
assertTrue(complete("'abc'.toUpperCase().trim().len").contains("length"));
69+
// ...and through closures.
70+
assertTrue(complete("[1, 2].collect { it * 2 }.isEm").contains(
71+
"isEmpty"));
72+
// Declared types count too.
73+
assertTrue(complete("List items = null\nitems.isEm").contains("isEmpty"));
74+
// Inherited members are included.
75+
assertTrue(complete("def x = new ArrayList()\nx.containsA").contains(
76+
"containsAll"));
77+
}
78+
79+
/**
80+
* Variables assigned without a declaration ({@code x = ...}) are not local
81+
* variables but script bindings. The static type checker sees as
82+
* dynamic (of unknown type) so {@link TypedAST} types them itself.
83+
*/
84+
@Test
85+
public void testMembersOfBindings() {
86+
// Variables assigned without a declaration are typed as assigned...
87+
assertTrue(complete("z = \"abc\"\nz.toU").contains("toUpperCase"));
88+
assertTrue(complete("z = new ArrayList()\ny = z.subList(0, 1)\ny.isEm")
89+
.contains("isEmpty"));
90+
// ...as last assigned.
91+
final List<String> reassigned = complete(
92+
"z = 'abc'\nz = new File('a')\nz.getN");
93+
assertTrue(reassigned.contains("getName"));
94+
// ...and offered with their type.
95+
final List<CompletionItem> items = items("zed = 'abc'\nx = ze");
96+
final CompletionItem zed = items.stream().filter(c -> "zed".equals(c
97+
.getLabel())).findFirst().orElse(null);
98+
assertTrue(zed != null, String.valueOf(labels(items)));
99+
assertEquals("java.lang.String zed", zed.getDetail());
100+
}
101+
102+
@Test
103+
public void testDiagnostics() {
104+
// Syntax errors, and unresolvable classes: errors, where they are.
105+
assertEquals(Collections.singletonList("Error@1:11-12 Unexpected input: '+'"),
106+
problems("sigma = 1.5\ndef x = (1 +\n"));
107+
assertEquals(Collections.singletonList(
108+
"Error@0:0-14 unable to resolve class foo.Bar"), problems(
109+
"import foo.Bar\nx = 1\n"));
110+
assertEquals(Collections.singletonList(
111+
"Error@0:0-9 unable to resolve class Foo"), problems("new Foo()\n"));
112+
// Members a known type lacks: warnings, also through calls and bindings.
113+
assertEquals(Collections.singletonList(
114+
"Warning@1:0-24 Cannot find matching method java.lang.String#fooBar()."),
115+
problems("def s = 'abc'\ns.toUpperCase().fooBar()\n"));
116+
assertEquals(Collections.singletonList(
117+
"Warning@1:0-10 Cannot find matching method java.lang.String#fooBar()."),
118+
problems("z = 'abc'\nz.fooBar()\n"));
119+
assertEquals(Collections.singletonList(
120+
"Warning@1:0-5 No such property: nme for class: java.io.File"), problems(
121+
"def f = new File('a')\nf.nme\n"));
122+
// Dynamic code, which Groovy resolves when the script runs: nothing.
123+
for (final String fine : new String[] { "x = 1\nprintln x\n",
124+
"def m = [:]\nm.foo = 1\nprintln m.foo\n",
125+
"def o = something()\no.foo()\n", "def c = { it * 2 }\nc(3)\n",
126+
"def x\nx = 'a'\nx.size()\n", "[1, 2].collect { it }.sum()\n",
127+
"println undefinedThing\n", "class A { def go() { bar() } }\n" })
128+
{
129+
assertEquals(Collections.emptyList(), problems(fine), fine);
130+
}
131+
}
132+
133+
@Test
134+
public void testCallablesAreSnippets() {
135+
final CompletionItem upper = items("def s = 'x'\ns.toUpp").stream().filter(
136+
c -> c.getLabelDetails() != null && "()".equals(c.getLabelDetails()
137+
.getDetail())).findFirst().orElse(null);
138+
assertTrue(upper != null);
139+
assertEquals("toUpperCase()", upper.getTextEdit().getLeft().getNewText());
140+
final CompletionItem locale = items("def s = 'x'\ns.toUpp").stream().filter(
141+
c -> "(java.util.Locale arg0)".equals(c.getLabelDetails().getDetail()) ||
142+
c.getLabelDetails().getDetail().startsWith("(java.util.Locale "))
143+
.findFirst().orElse(null);
144+
assertTrue(locale != null);
145+
assertTrue(locale.getTextEdit().getLeft().getNewText().startsWith(
146+
"toUpperCase(${1:"));
147+
assertEquals("java.lang.String", locale.getLabelDetails()
148+
.getDescription());
149+
}
150+
151+
@Test
152+
public void testStaticMembers() {
153+
final List<String> texts = complete("Math.ma");
154+
assertTrue(texts.contains("max"));
155+
// Only static members of a class.
156+
assertFalse(complete("Integer.intV").contains("intValue"));
157+
assertTrue(complete("Integer.parseI").contains("parseInt"));
158+
}
159+
160+
@Test
161+
public void testGroovyMethods() {
162+
// The GDK adds methods to Java classes.
163+
assertTrue(complete("[1, 2, 3].coll").contains("collect"));
164+
assertTrue(complete("def s = 'abc'\ns.rev").contains("reverse"));
165+
assertTrue(complete("new File('x').eachL").contains("eachLine"));
166+
final CompletionItem each = items("[1, 2, 3].eac").stream().filter(
167+
c -> c.getLabel().equals("each")).findFirst().orElse(null);
168+
assertTrue(each != null && each.getDetail().startsWith("GDK"));
169+
}
170+
171+
@Test
172+
public void testScriptClasses() {
173+
final List<String> texts = complete("class Foo {\n" + //
174+
" int bar\n" + //
175+
" String baz() { 'x' }\n" + //
176+
"}\n" + //
177+
"def f = new Foo()\n" + //
178+
"f.ba");
179+
assertTrue(texts.contains("bar"), texts.toString());
180+
assertTrue(texts.contains("baz"), texts.toString());
181+
}
182+
183+
@Test
184+
public void testVariableScopes() {
185+
assertTrue(complete("def greeting = 'hi'\ndef x = gree").contains(
186+
"greeting"));
187+
// Closure parameters are visible inside the closure...
188+
assertTrue(complete("[1].each { item ->\n ite").contains("item"));
189+
// ...but not variables declared in a closure that has ended.
190+
assertFalse(complete("[1].each { def inner = it }\ninn").contains(
191+
"inner"));
192+
// Nor variables declared after the caret.
193+
assertFalse(complete("def a = lat").contains("later"));
194+
// For loop variables are visible in the loop.
195+
assertTrue(complete("for (element in [1, 2]) {\n elem").contains(
196+
"element"));
197+
}
198+
199+
@Test
200+
public void testIncompleteCode() {
201+
// Unclosed brackets before the caret.
202+
assertTrue(complete("def s = 'x'\nif (true) {\n s.toUpp").contains(
203+
"toUpperCase"));
204+
assertTrue(complete("def s = 'x'\nprintln(s.toUpp").contains(
205+
"toUpperCase"));
206+
// Unresolvable classes do not prevent type inference.
207+
assertTrue(complete("def z = new NoSuchClass()\ndef s = 'x'\ns.toUpp")
208+
.contains("toUpperCase"));
209+
// A syntax error above the caret: the caret's line is still analyzed.
210+
assertTrue(complete("def a = (]\n'abc'.toUpp").contains("toUpperCase"));
211+
}
212+
213+
@Test
214+
public void testKeywords() {
215+
assertTrue(complete("ret").contains("return"));
216+
assertFalse(complete("def x = 1.").contains("return"));
217+
}
218+
219+
@Test
220+
public void testClassNamesWithAutoImport() {
221+
ClassIndex.ensureCache();
222+
final CompletionItem atomic = items("def a = new AtomicInt").stream()
223+
.filter(c -> c.getLabel().equals("AtomicInteger")).findFirst().orElse(
224+
null);
225+
assertTrue(atomic != null);
226+
assertEquals(1, atomic.getAdditionalTextEdits().size());
227+
assertEquals("import java.util.concurrent.atomic.AtomicInteger\n", atomic
228+
.getAdditionalTextEdits().get(0).getNewText());
229+
// Already imported (or imported by default): no edit.
230+
final CompletionItem list = items("def a = new ArrayLis").stream().filter(
231+
c -> c.getLabel().equals("ArrayList")).findFirst().orElse(null);
232+
assertTrue(list != null && list.getAdditionalTextEdits() == null);
233+
}
234+
235+
@Test
236+
public void testImports() {
237+
ClassIndex.ensureCache();
238+
assertTrue(complete("import java.util.concurrent.atomic.AtomicInt")
239+
.contains("java.util.concurrent.atomic.AtomicInteger"));
240+
assertTrue(complete("java.util.concurrent.atomic.AtomicInt").contains(
241+
"AtomicInteger"));
242+
}
243+
244+
@Test
245+
public void testStringsAndComments() {
246+
assertTrue(complete("def s = 'a.b.").isEmpty());
247+
assertTrue(complete("// s.toUpp").isEmpty());
248+
assertTrue(complete("/* x.").isEmpty());
249+
}
250+
251+
@Test
252+
public void testInterpreterBindings() {
253+
// Code typed into a running interpreter: its variables, by their values'
254+
// types.
255+
final ScriptContext live = new SimpleScriptContext();
256+
live.setAttribute("injected", new ArrayList<String>(),
257+
ScriptContext.ENGINE_SCOPE);
258+
final List<String> texts = labels(items(session(new Environment(null,
259+
Collections.emptyList(), live)), "injected.si"));
260+
assertTrue(texts.contains("size"), texts.toString());
261+
}
262+
263+
@Test
264+
public void testSignatureHelp() {
265+
// A decimal (a BigDecimal) fits the floating-point overloads, which come
266+
// first; the integral ones do not. The caret is in the second argument.
267+
final SignatureHelp max = help("Math.max(1.5, ");
268+
assertEquals(Integer.valueOf(1), max.getActiveParameter());
269+
assertEquals("[double, float, int, long]", describe(max));
270+
// An integer fits the integral overloads, and converts to the others.
271+
assertEquals("[int, long, double, float]", describe(help(
272+
"Math.max(1, 2")));
273+
// Nothing typed yet: all overloads.
274+
assertEquals(4, help("Math.max(").getSignatures().size());
275+
// Arguments' types come from the analysis, e.g. of variables.
276+
final SignatureHelp indexOf = help("def s = 'abc'\ndef c = 'b'\n" +
277+
"s.indexOf(c, ");
278+
assertEquals("java.lang.String", describe(indexOf).replaceAll(
279+
"^\\[([^,]*),.*", "$1"));
280+
// Constructors, and the script's own functions.
281+
assertTrue(describe(help("new StringBuilder(")).contains(
282+
"java.lang.String"));
283+
final SignatureHelp area = help("def area(int w, int h) { w * h }\n" +
284+
"area(3, ");
285+
assertEquals("[int]", describe(area));
286+
// The innermost call, and none outside calls.
287+
assertEquals(Integer.valueOf(0), help("Math.max(Math.abs(")
288+
.getActiveParameter());
289+
assertNull(help("def x = 1"));
290+
}
291+
292+
@Test
293+
public void testArgumentChoices() {
294+
// In a call's arguments: the variables fitting the parameter first.
295+
final List<CompletionItem> items = items(
296+
"def a = new ArrayList()\ndef s = 'x'\nCollections.sort(");
297+
assertEquals("a", items.get(0).getLabel());
298+
assertEquals(Boolean.TRUE, items.get(0).getPreselect());
299+
assertTrue(labels(items).contains("s"));
300+
}
301+
43302
@Test
44303
public void testImportOffset() {
45304
// Already imported: no import needed.
@@ -50,4 +309,72 @@ public void testImportOffset() {
50309
assertEquals(20, GroovyLanguageServer.importOffset("import java.io.File\n" +
51310
"x = 1\n", "java.util.concurrent.atomic.AtomicInteger"));
52311
}
312+
313+
// -- Helper methods --
314+
315+
/** A session about plain Groovy, with a server of its own. */
316+
private static ScriptSession session(final Environment env) {
317+
return ScriptSession.owning(new GroovyLanguageServer(env), null, "groovy",
318+
null);
319+
}
320+
321+
/** The problems found in a script, e.g. {@code Error@0:4-6 message}. */
322+
private static List<String> problems(final String code) {
323+
final List<Diagnostic> found;
324+
try (ScriptSession session = session(Environment.NONE)) {
325+
found = session.update(code).diagnostics(20_000);
326+
}
327+
return found.stream().map(d -> d.getSeverity() + "@" + d.getRange().getStart()
328+
.getLine() + ":" + d.getRange().getStart().getCharacter() + "-" + d
329+
.getRange().getEnd().getCharacter() + " " + d.getMessage().getLeft())
330+
.collect(Collectors.toList());
331+
}
332+
333+
private static SignatureHelp help(final String code) {
334+
try (ScriptSession session = session(Environment.NONE)) {
335+
return session.signatureHelp(code, code.length()).get(30,
336+
TimeUnit.SECONDS);
337+
}
338+
catch (final Exception exc) {
339+
throw new RuntimeException(exc);
340+
}
341+
}
342+
343+
/** Each signature's first parameter type, in order. */
344+
private static String describe(final SignatureHelp help) {
345+
return help.getSignatures().stream().map(s -> {
346+
final String first = s.getParameters().isEmpty() ? "()" : s
347+
.getParameters().get(0).getLabel().getLeft();
348+
final String type = first.contains(" ") ? first.substring(0, first
349+
.lastIndexOf(' ')) : first;
350+
return type;
351+
}).collect(Collectors.toList()).toString();
352+
}
353+
354+
private static List<CompletionItem> items(final String code) {
355+
return items(session(Environment.NONE), code);
356+
}
357+
358+
private static List<CompletionItem> items(final ScriptSession session,
359+
final String code)
360+
{
361+
try (ScriptSession s = session) {
362+
final List<CompletionItem> items = new ArrayList<>(s.completion(
363+
code, code.length()).get(30, TimeUnit.SECONDS).getItems());
364+
items.sort((a, b) -> a.getSortText().compareTo(b.getSortText()));
365+
return items;
366+
}
367+
catch (final Exception exc) {
368+
throw new RuntimeException(exc);
369+
}
370+
}
371+
372+
private static List<String> complete(final String code) {
373+
return labels(items(code));
374+
}
375+
376+
private static List<String> labels(final List<CompletionItem> items) {
377+
return items.stream().map(CompletionItem::getLabel).collect(Collectors
378+
.toList());
379+
}
53380
}

‎code-lsp-groovy/src/test/java/org/scijava/code/lsp/groovy/GroovyServerPluginTest.java‎

Lines changed: 0 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,12 @@
11
package org.scijava.code.lsp.groovy;
22

3-
import java.util.List;
4-
import java.util.concurrent.TimeUnit;
5-
import java.util.stream.Collectors;
6-
7-
import org.eclipse.lsp4j.CompletionItem;
8-
import org.eclipse.lsp4j.CompletionParams;
9-
import org.eclipse.lsp4j.DidOpenTextDocumentParams;
10-
import org.eclipse.lsp4j.InitializeParams;
11-
import org.eclipse.lsp4j.TextDocumentIdentifier;
12-
import org.eclipse.lsp4j.TextDocumentItem;
133
import org.eclipse.lsp4j.services.LanguageServer;
144
import org.junit.jupiter.api.AfterEach;
155
import org.junit.jupiter.api.BeforeEach;
166
import org.junit.jupiter.api.Test;
177
import org.scijava.Context;
188
import org.scijava.code.lsp.Environment;
199
import org.scijava.code.lsp.LanguageServerService;
20-
import org.scijava.code.lsp.Positions;
2110

2211
import static org.junit.jupiter.api.Assertions.assertTrue;
2312

@@ -55,21 +44,5 @@ public void testServerLaunch() {
5544
);
5645
assertTrue(server instanceof GroovyLanguageServer);
5746
}
58-
59-
/** Plain Groovy, as the server's clients send it. */
60-
@Test
61-
public void testCompletion() throws Exception {
62-
LanguageServer server = servers.launch("groovy", Environment.NONE);
63-
server.initialize(new InitializeParams()).get();
64-
String code = "def s = 'hello'\ns.toUpp";
65-
server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(
66-
new TextDocumentItem("untitled:/a.groovy", "groovy", 1, code)));
67-
List<String> labels = server.getTextDocumentService().completion(
68-
new CompletionParams(new TextDocumentIdentifier("untitled:/a.groovy"),
69-
Positions.position(code, code.length()))).get(30, TimeUnit.SECONDS)
70-
.getRight().getItems().stream().map(CompletionItem::getLabel)
71-
.collect(Collectors.toList());
72-
assertTrue(labels.contains("toUpperCase"), labels.toString());
73-
}
7447
}
7548

0 commit comments

Comments
 (0)