3232import java .io .File ;
3333import java .io .IOException ;
3434import java .io .InputStream ;
35- import java .math .BigDecimal ;
36- import java .math .BigInteger ;
3735import java .nio .charset .StandardCharsets ;
3836import java .util .ArrayList ;
3937import java .util .Arrays ;
40- import java .util .Collection ;
4138import java .util .Collections ;
4239import java .util .HashMap ;
4340import java .util .HashSet ;
5451import java .util .function .Function ;
5552import java .util .function .Supplier ;
5653
57- import net .imglib2 .RandomAccessibleInterval ;
58-
5954import org .apposed .appose .Appose ;
6055import org .apposed .appose .Environment ;
61- import org .apposed .appose .NDArray ;
6256import org .apposed .appose .Service ;
6357import org .apposed .appose .util .Environments ;
6458import org .scijava .Context ;
6862import org .scijava .code .api .Completion ;
6963import org .scijava .code .api .CompletionRequest ;
7064import 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 ;
7168import org .scijava .code .api .SignatureHelp ;
7269import org .scijava .code .api .SignatureHelp .Fit ;
7370import org .scijava .code .api .Signatures ;
7471import org .scijava .plugin .Plugin ;
7572import org .scijava .plugins .scripting .appose .python ._internal .InlineMetadata ;
7673import org .scijava .plugins .scripting .appose .python ._internal .ResidentWorker ;
7774import org .scijava .plugins .scripting .appose .python ._internal .ResidentWorkerService ;
75+ import org .scijava .plugins .scripting .appose .python .completion .ApposePythonDialect ;
7876import org .scijava .plugins .scripting .appose .python .completion .DependencyOverlays ;
7977import org .scijava .plugins .scripting .appose .python .completion .JediClient ;
8078import 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
0 commit comments