Skip to content

Commit f53787e

Browse files
gselzerclaude
andcommitted
code-lsp: do not complete names only the declarations import
The declarations a session adds are real code: imports of the parameters' types bind names (e.g. numpy) the script does not. A dialect now says which name each import binds (ScriptDialect#imported); unless the script mentions it, the session leaves completions of it out (see ScriptDocument#added). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f1dd82f commit f53787e

5 files changed

Lines changed: 85 additions & 7 deletions

File tree

‎code-lsp/src/main/java/org/scijava/code/lsp/ScriptSession.java‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,8 @@
9393
* the server), the session shows the server each script as plain code of its
9494
* language (see {@link ScriptDocument}), and maps positions both ways.
9595
* Whatever the server says about the lines the transformation added is left
96-
* out.
96+
* out, as are completions of names only those lines bind (see
97+
* {@link ScriptDocument#added()}).
9798
* </p>
9899
* <p>
99100
* A session owns its server: it is the server's client, initializes it, and
@@ -376,12 +377,16 @@ private void newVersion() {
376377
if (nextDiagnostics.isDone()) nextDiagnostics = new CompletableFuture<>();
377378
}
378379

379-
/** Maps completions' edits back, leaving out those in the added lines. */
380+
/**
381+
* Maps completions' edits back, leaving out those in the added lines, and
382+
* those of names only the added lines bind.
383+
*/
380384
private static CompletionList back(final ScriptDocument doc,
381385
final CompletionList list)
382386
{
383387
final List<CompletionItem> items = new ArrayList<>();
384388
for (final CompletionItem item : list.getItems()) {
389+
if (doc.added().contains(leadingName(item.getLabel()))) continue;
385390
if (item.getTextEdit() != null) {
386391
if (item.getTextEdit().isLeft()) {
387392
final TextEdit e = item.getTextEdit().getLeft();
@@ -411,6 +416,17 @@ private static CompletionList back(final ScriptDocument doc,
411416
return new CompletionList(list.isIncomplete(), items);
412417
}
413418

419+
/**
420+
* The name a completion's label starts with, e.g. {@code java} for
421+
* {@code java.lang} and {@code max} for {@code max(a, b)}.
422+
*/
423+
private static String leadingName(final String label) {
424+
int end = 0;
425+
while (end < label.length() && (Character.isLetterOrDigit(label.charAt(
426+
end)) || label.charAt(end) == '_')) end++;
427+
return label.substring(0, end);
428+
}
429+
414430
/** Maps problems back, leaving out those in the added lines. */
415431
private static List<Diagnostic> back(final ScriptDocument doc,
416432
final List<Diagnostic> diagnostics)

‎code-lsp/src/main/java/org/scijava/code/lsp/script/ScriptDialect.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,16 @@ default List<String> imports(final Collection<String> types) {
7575
return Collections.emptyList();
7676
}
7777

78+
/**
79+
* Gets the name one of the {@link #imports} binds, e.g. {@code numpy} for
80+
* {@code import numpy}; or null if none. Unless the script itself mentions
81+
* it, the name is the declarations' alone: it is not completed (see
82+
* {@link ScriptDocument#added()}). The default binds none.
83+
*/
84+
default String imported(final String statement) {
85+
return null;
86+
}
87+
7888
/**
7989
* Gets declarations of other variables scripts can use, e.g. Appose's
8090
* {@code task}. The default declares none.

‎code-lsp/src/main/java/org/scijava/code/lsp/script/ScriptDocument.java‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
import java.util.List;
3737
import java.util.Map;
3838
import java.util.Set;
39+
import java.util.regex.Pattern;
3940

4041
import org.eclipse.lsp4j.Position;
4142
import org.eclipse.lsp4j.Range;
@@ -65,19 +66,23 @@ public final class ScriptDocument {
6566
/** Number of characters prepended. */
6667
private final int headerLength;
6768
private final Map<String, String> parameters;
69+
private final Set<String> added;
6870

6971
private ScriptDocument(final String original, final String text,
70-
final int headerLength, final Map<String, String> parameters)
72+
final int headerLength, final Map<String, String> parameters,
73+
final Set<String> added)
7174
{
7275
this.original = original;
7376
this.text = text;
7477
this.headerLength = headerLength;
7578
this.parameters = Collections.unmodifiableMap(parameters);
79+
this.added = Collections.unmodifiableSet(added);
7680
}
7781

7882
/** A script as it is: nothing declared, nothing blanked. */
7983
public static ScriptDocument of(final String script) {
80-
return new ScriptDocument(script, script, 0, Collections.emptyMap());
84+
return new ScriptDocument(script, script, 0, Collections.emptyMap(),
85+
Collections.emptySet());
8186
}
8287

8388
/**
@@ -104,13 +109,28 @@ public static ScriptDocument of(final String script,
104109
declarations.addAll(dialect.extraDeclarations());
105110
final Set<String> used = new LinkedHashSet<>(types.values());
106111
used.remove(null);
107-
final List<String> statements = new ArrayList<>(dialect.imports(used));
112+
final List<String> imports = dialect.imports(used);
113+
final Set<String> added = new LinkedHashSet<>();
114+
for (final String statement : imports) {
115+
final String name = dialect.imported(statement);
116+
if (name != null && !mentions(script, name)) added.add(name);
117+
}
118+
final List<String> statements = new ArrayList<>(imports);
108119
statements.addAll(declarations);
109120
final String header = statements.isEmpty() ? "" : String.join(dialect
110121
.separator(), statements) + "\n";
111122

112123
return new ScriptDocument(script, header + blank(script, dialect),
113-
header.length(), types);
124+
header.length(), types, added);
125+
}
126+
127+
/**
128+
* Names only the declarations bind, e.g. modules imported to declare the
129+
* parameters' types, which the script does not mention (see
130+
* {@link ScriptDialect#imported}): for completion to leave out.
131+
*/
132+
public Set<String> added() {
133+
return added;
114134
}
115135

116136
/** The script, as given. */
@@ -171,6 +191,12 @@ public Map<String, String> parameters() {
171191

172192
// -- Helper methods --
173193

194+
/** Whether the script mentions a name, e.g. to import it itself. */
195+
private static boolean mentions(final String script, final String name) {
196+
return Pattern.compile("(?<![\\w.])" + Pattern.quote(name) + "(?!\\w)")
197+
.matcher(script).find();
198+
}
199+
174200
/** Replaces the characters of the lines to blank with spaces. */
175201
private static String blank(final String script, final ScriptDialect dialect) {
176202
final StringBuilder sb = new StringBuilder(script);

‎code-lsp/src/test/java/org/scijava/code/lsp/impl/LanguageServersTest.java‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
import java.io.File;
3939
import java.util.ArrayList;
4040
import java.util.Arrays;
41+
import java.util.Collection;
4142
import java.util.Collections;
4243
import java.util.List;
4344
import java.util.Map;
@@ -283,9 +284,12 @@ public void testTransforming() throws Exception {
283284
final CompletionList list = session.completion(script, script.length())
284285
.get(10, TimeUnit.SECONDS);
285286
// The server sees plain code, in its plugin's dialect.
286-
assertEquals("open 1 sigma: double\n" + script, server.events.get(1));
287+
assertEquals("open 1 import mass; sigma: double\n" + script, server.events
288+
.get(1));
287289
// Asked one line down; its edits mapped back up.
288290
assertEquals(new Position(2, 4), server.asked.get(0));
291+
// Names only the declarations import are not completed.
292+
assertEquals(Collections.singletonList("max"), labels(list));
289293
assertEquals(new Range(new Position(1, 2), new Position(1, 4)), list
290294
.getItems().get(0).getTextEdit().getLeft().getRange());
291295
// Problems mapped back; those in the added line left out.
@@ -448,6 +452,17 @@ public String runtimeType(final Class<?> type) {
448452
public String declare(final String name, final String type) {
449453
return name + ": " + type;
450454
}
455+
456+
@Override
457+
public List<String> imports(final Collection<String> types) {
458+
return types.isEmpty() ? Collections.emptyList() : Collections
459+
.singletonList("import mass");
460+
}
461+
462+
@Override
463+
public String imported(final String statement) {
464+
return statement.substring("import ".length());
465+
}
451466
};
452467
}
453468
}

‎code-lsp/src/test/java/org/scijava/code/lsp/script/ScriptDocumentTest.java‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,11 @@ public List<String> imports(final Collection<String> types) {
7777
return Arrays.asList(modules.toArray(new String[0]));
7878
}
7979

80+
@Override
81+
public String imported(final String statement) {
82+
return statement.substring("import ".length());
83+
}
84+
8085
@Override
8186
public List<String> extraDeclarations() {
8287
return Collections.singletonList("task: object");
@@ -123,6 +128,12 @@ public void testDeclarations() {
123128
.keySet().toArray()));
124129
assertNull(doc.parameters().get("n"));
125130
assertEquals("numpy.ndarray", doc.parameters().get("a"));
131+
// The module is the declarations' alone, unless the script mentions it.
132+
assertEquals(Collections.singleton("numpy"), doc.added());
133+
assertTrue(ScriptDocument.of("import numpy as np\n" + script, params("a",
134+
double[].class), PYTHON).added().isEmpty());
135+
assertTrue(ScriptDocument.of(script + "\nnumpyish = 1", params("a",
136+
double[].class), PYTHON).added().contains("numpy"));
126137
}
127138

128139
@Test

0 commit comments

Comments
 (0)