Skip to content

Commit 105b768

Browse files
gselzerclaude
andcommitted
Serve plain Python: sessions declare the parameters
Jedi and the syntax-only server now read the text the session makes in ApposePythonDialect. The syntax server no longer reads #@ lines: it finds the parameters and task among the names declared, with the types they are annotated with. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dabdd81 commit 105b768

4 files changed

Lines changed: 96 additions & 79 deletions

File tree

‎src/main/java/org/scijava/plugins/scripting/appose/python/ApposePythonServerPlugin.java‎

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,13 @@
2929

3030
package org.scijava.plugins.scripting.appose.python;
3131

32-
import java.util.Collections;
33-
import java.util.Map;
34-
3532
import org.eclipse.lsp4j.TextDocumentItem;
3633
import org.eclipse.lsp4j.services.LanguageServer;
3734
import org.scijava.Priority;
3835
import org.scijava.code.lsp.Environment;
3936
import org.scijava.code.lsp.LanguageServerPlugin;
4037
import org.scijava.code.lsp.LanguageServerService;
41-
import org.scijava.code.lsp.script.ScriptDocument;
42-
import org.scijava.code.lsp.script.TransformingLanguageServer;
38+
import org.scijava.code.lsp.script.ScriptDialect;
4339
import org.scijava.plugin.Parameter;
4440
import org.scijava.plugin.Plugin;
4541
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorkerService;
@@ -56,8 +52,9 @@
5652
* script declares but its environment lacks are installed for completion only
5753
* (see
5854
* {@link org.scijava.plugins.scripting.appose.python.completion.DependencyOverlays}).
59-
* Jedi sees the script as plain Python, its parameters declared with the
60-
* types they have when it runs (e.g. images as NumPy arrays).
55+
* Both see the script as plain Python, its parameters declared with the
56+
* types they have when it runs (e.g. images as NumPy arrays; see
57+
* {@link #dialect()}).
6158
* <p>
6259
* Completion never builds a script's environment, and never disturbs its
6360
* worker.
@@ -86,9 +83,14 @@ public boolean supports(final ScriptLanguage language) {
8683
@Override
8784
public LanguageServer create(final Environment environment) {
8885
final boolean jedi = jediOffered();
89-
return new ApposePythonLanguageServer(new PythonSyntaxLanguageServer(
90-
servers), this::environment, jedi ? this::jedi : null,
91-
ApposePythonEnvironments.of(workers));
86+
return new ApposePythonLanguageServer(new PythonSyntaxLanguageServer(),
87+
this::environment, jedi ? this::jedi : null, ApposePythonEnvironments.of(
88+
workers));
89+
}
90+
91+
@Override
92+
public ScriptDialect dialect() {
93+
return PythonSyntaxLanguageServer.DIALECT;
9294
}
9395

9496
/** Whether jedi-language-server is offered. */
@@ -108,16 +110,7 @@ Environment environment(final TextDocumentItem document) {
108110

109111
/** Makes a jedi for scripts running in an environment. */
110112
private LanguageServer jedi(final Environment environment) {
111-
return new PythonCompletionServer(new TransformingLanguageServer(servers
112-
.launch("python", environment), text -> document(text, environment)),
113+
return new PythonCompletionServer(servers.launch("python", environment),
113114
SIGNATURES);
114115
}
115-
116-
/** The script as plain Python, for jedi. */
117-
ScriptDocument document(final String text, final Environment environment) {
118-
final Map<String, Class<?>> params = servers == null ? Collections
119-
.emptyMap() : servers.scriptParameters(text);
120-
return ScriptDocument.of(text, params, PythonSyntaxLanguageServer.DIALECT,
121-
environment);
122-
}
123116
}

‎src/main/java/org/scijava/plugins/scripting/appose/python/PythonSyntaxLanguageServer.java‎

Lines changed: 7 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,12 @@
3030
package org.scijava.plugins.scripting.appose.python;
3131

3232
import java.util.ArrayList;
33-
import java.util.Collections;
34-
import java.util.LinkedHashMap;
3533
import java.util.List;
3634
import java.util.Locale;
37-
import java.util.Map;
3835

3936
import org.eclipse.lsp4j.CompletionItem;
4037
import org.eclipse.lsp4j.CompletionItemKind;
4138
import org.eclipse.lsp4j.CompletionList;
42-
import org.scijava.code.lsp.LanguageServerService;
4339
import org.scijava.code.lsp.jvm.ScriptLanguageServer;
4440
import org.scijava.plugins.scripting.appose.python.completion.ApposePythonDialect;
4541
import org.scijava.plugins.scripting.appose.python.completion.PythonSyntax;
@@ -48,9 +44,9 @@
4844
/**
4945
* An in-process language server for Python scripts run via Appose, from the
5046
* syntax alone ({@link PythonSyntax}: tree-sitter): instantly, with no Python
51-
* needed, names in scope, the script's parameters, {@code task}, builtins and
52-
* keywords; and, after a dot, the names used after dots elsewhere in the
53-
* script. (A Python language server, e.g. jedi-language-server, knows more;
47+
* needed, names in scope (including the script's parameters and {@code task},
48+
* declared as {@link #DIALECT} says), builtins and keywords; and, after a dot,
49+
* the names used after dots elsewhere in the script. (A Python language server, e.g. jedi-language-server, knows more;
5450
* see {@link ApposePythonLanguageServer}.)
5551
*
5652
* @author Gabriel Selzer
@@ -59,12 +55,8 @@ public class PythonSyntaxLanguageServer extends ScriptLanguageServer {
5955

6056
static final ApposePythonDialect DIALECT = new ApposePythonDialect();
6157

62-
private final LanguageServerService servers;
63-
64-
/** @param servers Reads the scripts' parameters. */
65-
public PythonSyntaxLanguageServer(final LanguageServerService servers) {
58+
public PythonSyntaxLanguageServer() {
6659
super(null);
67-
this.servers = servers;
6860
}
6961

7062
@Override
@@ -75,20 +67,7 @@ protected CompletionList complete(final Document doc, final int caret) {
7567
{
7668
return list(doc, caret, caret, new ArrayList<>());
7769
}
78-
return list(doc, ctx.replaceStart, caret, localCompletions(ctx, parameters(
79-
doc.text())));
80-
}
81-
82-
/**
83-
* The script's parameters, with the Python types they have when the script
84-
* runs (null if unknown).
85-
*/
86-
private Map<String, String> parameters(final String text) {
87-
final Map<String, String> params = new LinkedHashMap<>();
88-
if (servers == null) return params;
89-
servers.scriptParameters(text).forEach((name, type) -> params.put(name,
90-
DIALECT.runtimeType(type)));
91-
return params;
70+
return list(doc, ctx.replaceStart, caret, localCompletions(ctx));
9271
}
9372

9473
private static CompletionItem item(final String name,
@@ -103,7 +82,7 @@ private static CompletionItem item(final String name,
10382

10483
/** Completions from the local (syntactic) analysis alone. */
10584
private static List<CompletionItem> localCompletions(
106-
final PythonSyntax.Context ctx, final Map<String, String> params)
85+
final PythonSyntax.Context ctx)
10786
{
10887
final List<CompletionItem> out = new ArrayList<>();
10988
final String prefix = ctx.prefix;
@@ -117,15 +96,8 @@ private static List<CompletionItem> localCompletions(
11796
if (ctx.kind != Kind.NAME) return out;
11897
for (final String name : ctx.names) {
11998
if (matches(name, prefix)) out.add(item(name,
120-
CompletionItemKind.Variable, null));
121-
}
122-
for (final Map.Entry<String, String> p : params.entrySet()) {
123-
if (matches(p.getKey(), prefix)) out.add(item(p.getKey(),
124-
CompletionItemKind.Variable, p.getValue() == null ? "Script parameter"
125-
: p.getValue() + " (script parameter)"));
99+
CompletionItemKind.Variable, ctx.types.get(name)));
126100
}
127-
if (matches("task", prefix)) out.add(item("task",
128-
CompletionItemKind.Variable, ApposePythonDialect.TASK_TYPE));
129101
for (final String name : PythonSyntax.BUILTINS) {
130102
if (matches(name, prefix)) out.add(item(name, CompletionItemKind.Function,
131103
"builtin"));

‎src/main/java/org/scijava/plugins/scripting/appose/python/completion/PythonSyntax.java‎

Lines changed: 50 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,10 @@
3434
import java.util.ArrayList;
3535
import java.util.Arrays;
3636
import java.util.Deque;
37+
import java.util.HashMap;
3738
import java.util.LinkedHashSet;
3839
import java.util.List;
40+
import java.util.Map;
3941
import java.util.Set;
4042
import java.util.regex.Matcher;
4143
import java.util.regex.Pattern;
@@ -91,18 +93,25 @@ public static final class Context {
9193
/** Names in scope at the caret, innermost first. */
9294
public final Set<String> names;
9395

96+
/**
97+
* The types names in scope are annotated with, as written (e.g.
98+
* {@code numpy.ndarray} for {@code image: numpy.ndarray}), by name.
99+
*/
100+
public final Map<String, String> types;
101+
94102
/** For {@link Kind#ATTRIBUTE}: attributes used on the same receiver. */
95103
public final Set<String> attributesUsed;
96104

97105
private Context(final Kind kind, final String prefix,
98106
final int replaceStart, final String receiver, final Set<String> names,
99-
final Set<String> attributesUsed)
107+
final Map<String, String> types, final Set<String> attributesUsed)
100108
{
101109
this.kind = kind;
102110
this.prefix = prefix;
103111
this.replaceStart = replaceStart;
104112
this.receiver = receiver;
105113
this.names = names;
114+
this.types = types;
106115
this.attributesUsed = attributesUsed;
107116
}
108117
}
@@ -177,18 +186,20 @@ else if (before.trim().endsWith(".") && !before.trim().endsWith("..")) {
177186
// Parse the script up to the caret, with the partial identifier replaced
178187
// by a placeholder, and any open brackets closed: a clean tree there.
179188
final String source = textBefore + CARET + closers;
180-
final Set<String> names = kind == Kind.NAME ? namesInScope(source,
181-
textBefore.length()) : new LinkedHashSet<>();
189+
final Set<String> names = new LinkedHashSet<>();
190+
final Map<String, String> types = new HashMap<>();
191+
if (kind == Kind.NAME) namesInScope(source, textBefore.length(), names,
192+
types);
182193
final Set<String> used = kind == Kind.ATTRIBUTE && receiver != null
183194
? attributesUsed(text, receiver, start) : new LinkedHashSet<>();
184-
return new Context(kind, prefix, start, receiver, names, used);
195+
return new Context(kind, prefix, start, receiver, names, types, used);
185196
}
186197

187198
// -- Helper methods --
188199

189200
private static Context none(final String prefix, final int start) {
190201
return new Context(Kind.NONE, prefix, start, null, new LinkedHashSet<>(),
191-
new LinkedHashSet<>());
202+
new HashMap<>(), new LinkedHashSet<>());
192203
}
193204

194205
/**
@@ -272,14 +283,16 @@ private static Set<String> attributesUsed(final String text,
272283
return used;
273284
}
274285

275-
/** Names in scope at the placeholder, which starts at {@code caret}. */
276-
private static Set<String> namesInScope(final String source,
277-
final int caret)
286+
/**
287+
* Finds the names in scope at the placeholder, which starts at
288+
* {@code caret}, and the types they are annotated with.
289+
*/
290+
private static void namesInScope(final String source, final int caret,
291+
final Set<String> names, final Map<String, String> types)
278292
{
279293
final byte[] bytes = source.getBytes(StandardCharsets.UTF_8);
280294
final int caretByte = source.substring(0, caret).getBytes(
281295
StandardCharsets.UTF_8).length;
282-
final Set<String> names = new LinkedHashSet<>();
283296
final TSParser parser = new TSParser();
284297
try {
285298
parser.setLanguage(new TreeSitterPython());
@@ -305,13 +318,13 @@ private static Set<String> namesInScope(final String source,
305318
if (type.endsWith("comprehension") || type.equals(
306319
"generator_expression"))
307320
{
308-
collectBindings(node, bytes, names, true);
321+
collectBindings(node, bytes, names, types, true);
309322
}
310323
else if (body != null && !body.isNull() && !type.equals("lambda")) {
311-
collectBindings(body, bytes, names, false);
324+
collectBindings(body, bytes, names, types, false);
312325
}
313326
}
314-
collectBindings(root, bytes, names, false);
327+
collectBindings(root, bytes, names, types, false);
315328
}
316329
catch (final RuntimeException | LinkageError exc) {
317330
// NB: Native parser unavailable or failed: no names, then.
@@ -320,15 +333,16 @@ else if (body != null && !body.isNull() && !type.equals("lambda")) {
320333
parser.close();
321334
}
322335
names.remove(CARET);
323-
return names;
324336
}
325337

326338
/**
327339
* Collects the names bound by statements within {@code node}, without
328-
* descending into nested scopes (whose own names are bound here, though).
340+
* descending into nested scopes (whose own names are bound here, though);
341+
* and the types annotated names are declared with.
329342
*/
330343
private static void collectBindings(final TSNode node, final byte[] bytes,
331-
final Set<String> names, final boolean comprehension)
344+
final Set<String> names, final Map<String, String> types,
345+
final boolean comprehension)
332346
{
333347
final int n = node.getNamedChildCount();
334348
for (int i = 0; i < n; i++) {
@@ -347,6 +361,9 @@ private static void collectBindings(final TSNode node, final byte[] bytes,
347361
if (!comprehension) continue; // NB: A nested scope.
348362
break;
349363
case "assignment":
364+
addType(child, bytes, types);
365+
addTargets(child.getChildByFieldName("left"), bytes, names);
366+
break;
350367
case "augmented_assignment":
351368
case "for_statement":
352369
case "for_in_clause":
@@ -366,10 +383,21 @@ private static void collectBindings(final TSNode node, final byte[] bytes,
366383
continue;
367384
default:
368385
}
369-
collectBindings(child, bytes, names, comprehension);
386+
collectBindings(child, bytes, names, types, comprehension);
370387
}
371388
}
372389

390+
/** Adds the type of an annotated assignment, e.g. {@code x: int = 1}. */
391+
private static void addType(final TSNode assignment, final byte[] bytes,
392+
final Map<String, String> types)
393+
{
394+
final TSNode left = assignment.getChildByFieldName("left");
395+
final TSNode type = assignment.getChildByFieldName("type");
396+
if (left == null || left.isNull() || !left.getType().equals(
397+
"identifier") || type == null || type.isNull()) return;
398+
types.putIfAbsent(text(left, bytes), text(type, bytes));
399+
}
400+
373401
/** Adds the names an import statement binds. */
374402
private static void addImported(final TSNode statement, final byte[] bytes,
375403
final Set<String> names, final boolean plainImport)
@@ -428,8 +456,12 @@ private static void addIdentifier(final TSNode node, final byte[] bytes,
428456
{
429457
if (node == null || node.isNull() || !node.getType().equals(
430458
"identifier")) return;
431-
names.add(new String(bytes, node.getStartByte(), node.getEndByte() - node
432-
.getStartByte(), StandardCharsets.UTF_8));
459+
names.add(text(node, bytes));
460+
}
461+
462+
private static String text(final TSNode node, final byte[] bytes) {
463+
return new String(bytes, node.getStartByte(), node.getEndByte() - node
464+
.getStartByte(), StandardCharsets.UTF_8);
433465
}
434466

435467
private static boolean isIdentifierPart(final char c) {

‎src/test/java/org/scijava/plugins/scripting/appose/python/ApposePythonServersTest.java‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import org.scijava.code.lsp.Environment;
5353
import org.scijava.code.lsp.LanguageServerPlugin;
5454
import org.scijava.code.lsp.ScriptSession;
55+
import org.scijava.code.lsp.script.ScriptDocument;
5556
import org.scijava.plugin.PluginService;
5657
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorkerService;
5758
import org.scijava.plugins.scripting.appose.python.completion.ApposePythonDialect;
@@ -115,6 +116,10 @@ public void testLocalCompletions() {
115116
assertTrue(complete(header + "x = si").contains("sigma"));
116117
assertTrue(complete(header + "pri").contains("print"));
117118
assertTrue(complete(header + "ta").contains("task"));
119+
// Declared with the types they have when the script runs.
120+
assertEquals("float", detail(header + "x = si", "sigma"));
121+
assertEquals("numpy.ndarray", detail(header + "x = ima", "image"));
122+
assertEquals("appose.python_worker.Task", detail(header + "ta", "task"));
118123
// Nothing on parameter lines, in strings or comments.
119124
assertTrue(complete("#@ String na").isEmpty());
120125
assertTrue(complete("s = 'pri").isEmpty());
@@ -124,9 +129,9 @@ public void testLocalCompletions() {
124129
public void testScriptAsPython() {
125130
final String code = "#@ net.imglib2.img.Img image\n#@ double sigma\n" +
126131
"image.sha";
127-
// The script's parameters are typed in a preamble, so the server knows
132+
// The script's parameters are typed in a preamble, so the servers know
128133
// them.
129-
assertTrue(plugin.document(code, Environment.NONE).text().startsWith(
134+
assertTrue(document(code).text().startsWith(
130135
"import appose.python_worker; import numpy; image: numpy.ndarray; " +
131136
"sigma: float; task: appose.python_worker.Task\n"));
132137
}
@@ -303,15 +308,30 @@ public void testServerOptions() {
303308

304309
// -- Helper methods --
305310

311+
/** The script as plain Python, as the plugin's servers see it. */
312+
private ScriptDocument document(final String code) {
313+
return ScriptDocument.of(code, context.service(LanguageServerService.class)
314+
.scriptParameters(code), plugin.dialect());
315+
}
316+
306317
/** Completes with the syntax-only server. */
307318
private List<String> complete(final String code) {
319+
return items(code).stream().map(CompletionItem::getLabel).collect(
320+
Collectors.toList());
321+
}
322+
323+
/** The detail of a completion with the syntax-only server, or null. */
324+
private String detail(final String code, final String label) {
325+
return items(code).stream().filter(i -> i.getLabel().equals(label))
326+
.findFirst().map(CompletionItem::getDetail).orElse(null);
327+
}
328+
329+
private List<CompletionItem> items(final String code) {
308330
try (ScriptSession session = ScriptSession.owning(
309-
new PythonSyntaxLanguageServer(context.service(
310-
LanguageServerService.class)), language))
331+
new PythonSyntaxLanguageServer(), language, this::document))
311332
{
312333
return session.completion(code, code.length()).get(10,
313-
TimeUnit.SECONDS).getItems().stream().map(CompletionItem::getLabel)
314-
.collect(Collectors.toList());
334+
TimeUnit.SECONDS).getItems();
315335
}
316336
catch (final Exception exc) {
317337
throw new RuntimeException(exc);

0 commit comments

Comments
 (0)