Skip to content

Commit fadd95c

Browse files
gselzerclaude
andcommitted
Build Jedi's source from a ScriptDocument
The parameter preamble becomes ApposePythonDialect, and where the script runs (its environment's Python, its overlay) an EnvironmentContext. The preamble now lists imports first and task last. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 00de65d commit fadd95c

3 files changed

Lines changed: 194 additions & 115 deletions

File tree

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

Lines changed: 81 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,9 @@
3232
import java.io.File;
3333
import java.io.IOException;
3434
import java.io.InputStream;
35-
import java.math.BigDecimal;
36-
import java.math.BigInteger;
3735
import java.nio.charset.StandardCharsets;
3836
import java.util.ArrayList;
3937
import java.util.Arrays;
40-
import java.util.Collection;
4138
import java.util.Collections;
4239
import java.util.HashMap;
4340
import java.util.HashSet;
@@ -54,11 +51,8 @@
5451
import java.util.function.Function;
5552
import java.util.function.Supplier;
5653

57-
import net.imglib2.RandomAccessibleInterval;
58-
5954
import org.apposed.appose.Appose;
6055
import org.apposed.appose.Environment;
61-
import org.apposed.appose.NDArray;
6256
import org.apposed.appose.Service;
6357
import org.apposed.appose.util.Environments;
6458
import org.scijava.Context;
@@ -68,13 +62,17 @@
6862
import org.scijava.code.api.Completion;
6963
import org.scijava.code.api.CompletionRequest;
7064
import org.scijava.code.api.CompletionResult;
65+
import org.scijava.code.api.EnvironmentContext;
66+
import org.scijava.code.api.ScriptDialect;
67+
import org.scijava.code.api.ScriptDocument;
7168
import org.scijava.code.api.SignatureHelp;
7269
import org.scijava.code.api.SignatureHelp.Fit;
7370
import org.scijava.code.api.Signatures;
7471
import org.scijava.plugin.Plugin;
7572
import org.scijava.plugins.scripting.appose.python._internal.InlineMetadata;
7673
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorker;
7774
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorkerService;
75+
import org.scijava.plugins.scripting.appose.python.completion.ApposePythonDialect;
7876
import org.scijava.plugins.scripting.appose.python.completion.DependencyOverlays;
7977
import org.scijava.plugins.scripting.appose.python.completion.JediClient;
8078
import org.scijava.plugins.scripting.appose.python.completion.PythonSyntax;
@@ -150,6 +148,9 @@ protected boolean removeEldestEntry(
150148
*/
151149
private static final long OVERLAY_SETTLE = 1500;
152150

151+
/** How scripts see their parameters (as Python values) and {@code task}. */
152+
private static final ApposePythonDialect DIALECT = new ApposePythonDialect();
153+
153154
@Override
154155
public boolean supports(final ScriptLanguage language) {
155156
return language instanceof ApposePythonScriptLanguage;
@@ -165,10 +166,11 @@ public CompletionResult complete(final CompletionRequest request) {
165166
return CompletionResult.EMPTY;
166167
}
167168

168-
final Map<String, String> params = parameterTypes(text);
169-
final List<Completion> local = localCompletions(ctx, params);
170-
final CompletableFuture<List<Completion>> answer = jediCompletions(request,
171-
ctx, params);
169+
final JediClient client = jediClient();
170+
final ScriptDocument doc = document(request, client != null, false);
171+
final List<Completion> local = localCompletions(ctx, doc.parameters());
172+
final CompletableFuture<List<Completion>> answer = client == null ? null
173+
: jediCompletions(client, request, ctx, doc);
172174
if (answer == null) return merge(ctx, null, local);
173175

174176
// Use Jedi's answer if it is (almost) ready; otherwise answer without it
@@ -195,15 +197,14 @@ public void prepare(final CompletionRequest request) {
195197
// analyze the script against its environment, in the background.
196198
final JediClient client = jediClient();
197199
if (client == null) return;
198-
final String text = request.text();
199-
final String python = scriptPython(text, request.path());
200-
final String overlay = overlay(text, request.path(), python, true);
201-
final String source = preamble(parameterTypes(text)) + text;
202-
final int line = count(source, '\n') + 1;
203-
final int column = source.length() - source.lastIndexOf('\n') - 1;
204-
client.answer("prepare\n" + request.path() + "\n" + text,
205-
new JediClient.Query(source, line, column, request.path(), python, 0,
206-
overlay));
200+
final ScriptDocument doc = document(request, true, true);
201+
client.answer("prepare\n" + request.path() + "\n" + request.text(), query(
202+
doc, request.text().length(), request.path(), 0));
203+
}
204+
205+
@Override
206+
public ScriptDialect dialect() {
207+
return DIALECT;
207208
}
208209

209210
@Override
@@ -220,19 +221,12 @@ public SignatureHelp signatureHelp(final CompletionRequest request) {
220221
final JediClient client = jediClient();
221222
if (client == null) return SignatureHelp.NONE;
222223

223-
final String python = scriptPython(text, request.path());
224-
final String overlay = overlay(text, request.path(), python, false);
225-
final String preamble = preamble(parameterTypes(text));
226-
final String before = preamble + text.substring(0, caret);
227-
final int line = count(before, '\n') + 1;
228-
final int column = before.length() - before.lastIndexOf('\n') - 1;
229-
final JediClient.Query query = new JediClient.Query(preamble + text, line,
230-
column, request.path(), python, 0, overlay);
224+
final ScriptDocument doc = document(request, true, false);
225+
final JediClient.Query query = query(doc, caret, request.path(), 0);
231226
final int active = args.size() - 1;
232227
// NB: Where Jedi cannot tell the argument, count the commas.
233228
final CompletableFuture<SignatureHelp> help = client.signatures(
234-
"signatures\n" + python + "\n" + overlay + "\n" + request.path() +
235-
"\n" + before, query).handle((h, error) -> h == null ? null
229+
"signatures\n" + key(doc, caret, request.path()), query).handle((h, error) -> h == null ? null
236230
: new SignatureHelp(h.signatures(), h.activeParameter() >= 0 ? h
237231
.activeParameter() : active, open));
238232
try {
@@ -348,7 +342,7 @@ private static List<Completion> localCompletions(
348342
: p.getValue() + " (script parameter)").build());
349343
}
350344
if (matches("task", prefix)) out.add(Completion.builder("task").kind(
351-
Completion.Kind.VARIABLE).summary("appose.python_worker.Task").build());
345+
Completion.Kind.VARIABLE).summary(ApposePythonDialect.TASK_TYPE).build());
352346
for (final String name : PythonSyntax.BUILTINS) {
353347
if (matches(name, prefix)) out.add(Completion.builder(name).kind(
354348
Completion.Kind.OTHER).summary("builtin").build());
@@ -365,32 +359,70 @@ private static List<Completion> localCompletions(
365359
*
366360
* @return Jedi's answer, or pending answer; or null if Jedi is unavailable.
367361
*/
368-
private CompletableFuture<List<Completion>> jediCompletions(
369-
final CompletionRequest request, final PythonSyntax.Context ctx,
370-
final Map<String, String> params)
362+
private static CompletableFuture<List<Completion>> jediCompletions(
363+
final JediClient client, final CompletionRequest request,
364+
final PythonSyntax.Context ctx, final ScriptDocument doc)
371365
{
372-
final JediClient client = jediClient();
373-
if (client == null) return null;
374-
final String text = request.text();
375-
final String python = scriptPython(text, request.path());
376-
final String overlay = overlay(text, request.path(), python, false);
377-
378366
// Ask about the first character typed, if any: later keystrokes of the
379367
// same word then reuse the answer (filtered), while it stays short.
380368
final int caret = ctx.replaceStart + Math.min(1, ctx.prefix.length());
381-
final String preamble = preamble(params);
382-
final String before = preamble + text.substring(0, caret);
383-
final int line = count(before, '\n') + 1;
384-
final int column = before.length() - before.lastIndexOf('\n') - 1;
385369
// NB: Signatures are expensive, so ask for them only once a word is
386370
// begun, which narrows the completions down. Before that, functions are
387371
// offered by name.
388-
final JediClient.Query query = new JediClient.Query(preamble + text, line,
389-
column, request.path(), python, ctx.prefix.isEmpty() ? 0 : SIGNATURES,
390-
overlay);
391-
final String key = python + "\n" + overlay + "\n" + request.path() +
392-
"\n" + before;
393-
return client.answer(key, query);
372+
final JediClient.Query query = query(doc, caret, request.path(), ctx.prefix
373+
.isEmpty() ? 0 : SIGNATURES);
374+
return client.answer(key(doc, caret, request.path()), query);
375+
}
376+
377+
/**
378+
* Gets the script as plain Python, for Jedi: its parameters declared, and
379+
* (if asked) where it runs: its environment's Python, and its overlay.
380+
*
381+
* @param environment Whether to find where the script runs.
382+
* @param settled Whether the dependencies are known not to be changing.
383+
*/
384+
private ScriptDocument document(final CompletionRequest request,
385+
final boolean environment, final boolean settled)
386+
{
387+
final String text = request.text();
388+
EnvironmentContext env = null;
389+
if (environment) {
390+
final String python = scriptPython(text, request.path());
391+
final String overlay = overlay(text, request.path(), python, settled);
392+
env = new EnvironmentContext(python, overlay == null ? null
393+
: Collections.singletonList(overlay), null);
394+
}
395+
final CodeCompletionService service = service(
396+
CodeCompletionService.class);
397+
final Map<String, Class<?>> params = service == null ? Collections
398+
.emptyMap() : service.scriptParameters(text);
399+
return ScriptDocument.of(text, params, DIALECT, env);
400+
}
401+
402+
/** Asks Jedi about the given offset of the script. */
403+
private static JediClient.Query query(final ScriptDocument doc,
404+
final int offset, final String path, final int flags)
405+
{
406+
final String before = doc.text().substring(0, doc.map().toTransformed(
407+
offset));
408+
final int line = count(before, '\n') + 1;
409+
final int column = before.length() - before.lastIndexOf('\n') - 1;
410+
final EnvironmentContext env = doc.environment();
411+
final String overlay = env.searchPaths().isEmpty() ? null : env
412+
.searchPaths().get(0);
413+
return new JediClient.Query(doc.text(), line, column, path, env
414+
.interpreter(), flags, overlay);
415+
}
416+
417+
/** Identifies a question about the given offset, for reusing answers. */
418+
private static String key(final ScriptDocument doc, final int offset,
419+
final String path)
420+
{
421+
final EnvironmentContext env = doc.environment();
422+
final String overlay = env.searchPaths().isEmpty() ? null : env
423+
.searchPaths().get(0);
424+
return env.interpreter() + "\n" + overlay + "\n" + path + "\n" + doc
425+
.text().substring(0, doc.map().toTransformed(offset));
394426
}
395427

396428
/**
@@ -459,63 +491,6 @@ private static String installOverlay(final ResidentWorkerService workers,
459491
}
460492
}
461493

462-
/**
463-
* A line declaring the types of the script's parameters, for Jedi, e.g.
464-
* {@code import numpy; image: numpy.ndarray; sigma: float}.
465-
*/
466-
static String preamble(final Map<String, String> params) {
467-
final StringBuilder sb = new StringBuilder(
468-
"import appose.python_worker; task: appose.python_worker.Task");
469-
if (params.containsValue("numpy.ndarray")) sb.append("; import numpy");
470-
for (final Map.Entry<String, String> p : params.entrySet()) {
471-
if (p.getValue() == null) continue;
472-
sb.append("; ").append(p.getKey()).append(": ").append(p.getValue());
473-
}
474-
return sb.append('\n').toString();
475-
}
476-
477-
/**
478-
* Gets the script's parameters, with the Python types they have when the
479-
* script runs (see {@link ApposePythonScriptEngine#marshal}), or null types
480-
* if unknown.
481-
*/
482-
private Map<String, String> parameterTypes(final String text) {
483-
final Map<String, String> params = new LinkedHashMap<>();
484-
final Context context = getContext();
485-
final CodeCompletionService service = context == null ? null : context
486-
.getService(CodeCompletionService.class);
487-
if (service == null) return params;
488-
service.scriptParameters(text).forEach((name, type) -> params.put(name,
489-
pythonType(type)));
490-
return params;
491-
}
492-
493-
/** The Python type a Java value of the given type becomes in a script. */
494-
static String pythonType(final Class<?> type) {
495-
if (type == null) return null;
496-
if (RandomAccessibleInterval.class.isAssignableFrom(type) || NDArray.class
497-
.isAssignableFrom(type)) return "numpy.ndarray";
498-
if (type == boolean.class || type == Boolean.class) return "bool";
499-
if (type == int.class || type == long.class || type == short.class ||
500-
type == byte.class || type == Integer.class || type == Long.class ||
501-
type == Short.class || type == Byte.class || type == BigInteger.class)
502-
{
503-
return "int";
504-
}
505-
if (type == float.class || type == double.class || type == Float.class ||
506-
type == Double.class || type == BigDecimal.class) return "float";
507-
if (CharSequence.class.isAssignableFrom(type) || type == char.class ||
508-
type == Character.class || type.isEnum() || type == File.class)
509-
{
510-
return "str";
511-
}
512-
if (type.isArray() || Collection.class.isAssignableFrom(type)) {
513-
return "list";
514-
}
515-
if (Map.class.isAssignableFrom(type)) return "dict";
516-
return null;
517-
}
518-
519494
/**
520495
* Gets the Python executable of the script's environment, if it has been
521496
* built already: in this session (e.g. by running the script), or in an
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* #%L
3+
* Python scripting language plugin backed by Appose.
4+
* %%
5+
* Copyright (C) 2026 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.plugins.scripting.appose.python.completion;
31+
32+
import java.io.File;
33+
import java.math.BigDecimal;
34+
import java.math.BigInteger;
35+
import java.util.ArrayList;
36+
import java.util.Collection;
37+
import java.util.Collections;
38+
import java.util.List;
39+
import java.util.Map;
40+
41+
import net.imglib2.RandomAccessibleInterval;
42+
43+
import org.apposed.appose.NDArray;
44+
import org.scijava.code.api.ScriptDialect;
45+
46+
/**
47+
* How Python scripts run via Appose see their script parameters: as the
48+
* Python values the Java values become (see
49+
* {@code ApposePythonScriptEngine#marshal}), plus Appose's {@code task}.
50+
*
51+
* @author Gabriel Selzer
52+
*/
53+
public final class ApposePythonDialect implements ScriptDialect {
54+
55+
/** The type of the {@code task} variable scripts can use. */
56+
public static final String TASK_TYPE = "appose.python_worker.Task";
57+
58+
@Override
59+
public String runtimeType(final Class<?> type) {
60+
if (type == null) return null;
61+
if (RandomAccessibleInterval.class.isAssignableFrom(type) || NDArray.class
62+
.isAssignableFrom(type)) return "numpy.ndarray";
63+
if (type == boolean.class || type == Boolean.class) return "bool";
64+
if (type == int.class || type == long.class || type == short.class ||
65+
type == byte.class || type == Integer.class || type == Long.class ||
66+
type == Short.class || type == Byte.class || type == BigInteger.class)
67+
{
68+
return "int";
69+
}
70+
if (type == float.class || type == double.class || type == Float.class ||
71+
type == Double.class || type == BigDecimal.class) return "float";
72+
if (CharSequence.class.isAssignableFrom(type) || type == char.class ||
73+
type == Character.class || type.isEnum() || type == File.class)
74+
{
75+
return "str";
76+
}
77+
if (type.isArray() || Collection.class.isAssignableFrom(type)) {
78+
return "list";
79+
}
80+
if (Map.class.isAssignableFrom(type)) return "dict";
81+
return null;
82+
}
83+
84+
@Override
85+
public String declare(final String name, final String type) {
86+
return name + ": " + type;
87+
}
88+
89+
@Override
90+
public List<String> imports(final Collection<String> types) {
91+
final List<String> imports = new ArrayList<>();
92+
imports.add("import appose.python_worker");
93+
if (types.contains("numpy.ndarray")) imports.add("import numpy");
94+
return imports;
95+
}
96+
97+
@Override
98+
public List<String> extraDeclarations() {
99+
return Collections.singletonList(declare("task", TASK_TYPE));
100+
}
101+
}

0 commit comments

Comments
 (0)