8
org.scijava.plugins.scripting.jython
+ false
+
+
+ 2.101.0
+ 0.1.0
+ 0.1.0
+
+ 2.14.0
+
+ 11
bsd_2
SciJava developers.
@@ -99,6 +114,18 @@
org.scijava
scijava-common
+
+ org.scijava
+ scijava-lsp
+ ${scijava-lsp.version}
+
+
+ org.scijava
+ scijava-lsp-jython
+ ${scijava-lsp-jython.version}
+
+ test
+
@@ -113,4 +140,40 @@
test
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+
+
+ org.scijava
+ scijava-common
+ ${scijava-common.version}
+
+
+
+
+
+ default-testCompile
+
+ false
+
+
+
+
+
+
+
diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java
new file mode 100644
index 0000000..df15f9e
--- /dev/null
+++ b/src/main/java/module-info.java
@@ -0,0 +1,45 @@
+/*
+ * #%L
+ * JSR-223-compliant Jython scripting language plugin.
+ * %%
+ * Copyright (C) 2008 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+module org.scijava.plugins.scripting.jython {
+ exports org.scijava.plugins.scripting.jython;
+ exports org.scijava.plugins.scripting.jython.completion;
+
+ // NB: SciJava instantiates @Plugin classes reflectively.
+ opens org.scijava.plugins.scripting.jython to org.scijava;
+ opens org.scijava.plugins.scripting.jython.completion to org.scijava;
+
+ requires transitive java.scripting;
+ requires transitive org.scijava;
+ requires transitive org.scijava.lsp;
+ requires org.python.jython2;
+
+ provides javax.script.ScriptEngineFactory with
+ org.scijava.plugins.scripting.jython.JythonScriptLanguage;
+}
diff --git a/src/main/java/org/scijava/plugins/scripting/jython/JythonScriptLanguage.java b/src/main/java/org/scijava/plugins/scripting/jython/JythonScriptLanguage.java
index 8fe493a..e6a86b3 100644
--- a/src/main/java/org/scijava/plugins/scripting/jython/JythonScriptLanguage.java
+++ b/src/main/java/org/scijava/plugins/scripting/jython/JythonScriptLanguage.java
@@ -2,7 +2,7 @@
* #%L
* JSR-223-compliant Jython scripting language plugin.
* %%
- * Copyright (C) 2008 - 2023 SciJava developers.
+ * Copyright (C) 2008 - 2026 SciJava developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
diff --git a/src/main/java/org/scijava/plugins/scripting/jython/completion/JythonDialect.java b/src/main/java/org/scijava/plugins/scripting/jython/completion/JythonDialect.java
new file mode 100644
index 0000000..07b43c3
--- /dev/null
+++ b/src/main/java/org/scijava/plugins/scripting/jython/completion/JythonDialect.java
@@ -0,0 +1,248 @@
+/*-
+ * #%L
+ * JSR-223-compliant Jython scripting language plugin.
+ * %%
+ * Copyright (C) 2008 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+package org.scijava.plugins.scripting.jython.completion;
+
+import java.lang.reflect.Modifier;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.python.core.PyFunction;
+import org.python.core.PyJavaType;
+import org.python.core.PyModule;
+import org.python.core.PyObject;
+import org.scijava.lsp.ScriptDialect;
+import org.scijava.plugin.Plugin;
+import org.scijava.plugins.scripting.jython.JythonScriptLanguage;
+import org.scijava.script.ScriptLanguage;
+
+/**
+ * Describes how to turn Jython scripts into plain Jython code. Scripts see
+ * their parameters as the Python values Jython converts them to (e.g.
+ * {@code str} for strings, {@code int} for integers, {@code array.array} for
+ * arrays), or else as the Java objects themselves (e.g.
+ * {@code net.imglib2.img.Img}).
+ *
+ * Each is declared as an instance of its type, in code both Jython's own
+ * analysis (Python 2) and a Python language server knowing the Java packages
+ * from stubs (see scijava-lsp-jython) read: e.g.
+ * {@code import net.imglib2.img; image = net.imglib2.img.Img(); name = str()}.
+ *
+ *
+ * A live interpreter's variables are declared by their values, where those
+ * say more: its imported Java classes as the classes themselves, its modules
+ * imported again, its functions as functions, and its other Python values as
+ * instances of their builtin types.
+ *
+ *
+ * @author Gabriel Selzer
+ */
+@Plugin(type = ScriptDialect.class, name = "Jython")
+public class JythonDialect implements ScriptDialect {
+
+ /** Names Python reserves, which cannot be declared. */
+ private static final Set KEYWORDS = new HashSet<>(Arrays.asList(
+ "False", "None", "True", "and", "as", "assert", "async", "await", "break",
+ "class", "continue", "def", "del", "elif", "else", "except", "exec",
+ "finally", "for", "from", "global", "if", "import", "in", "is", "lambda",
+ "nonlocal", "not", "or", "pass", "print", "raise", "return", "try",
+ "while", "with", "yield"));
+
+ @Override
+ public boolean supports(final ScriptLanguage language) {
+ return language instanceof JythonScriptLanguage;
+ }
+
+ @Override
+ public String outputLanguage() {
+ return "jython";
+ }
+
+ @Override
+ public Header header(final Map variables) {
+ // Declare each variable, for type reasoning
+ final List types = new ArrayList<>();
+ final List declarations = new ArrayList<>();
+ variables.forEach((name, v) -> {
+ // NB: Names Python reserves cannot be declared.
+ if (!KEYWORDS.contains(name)) declarations.add(declaration(name, v,
+ types));
+ });
+ // And import the packages of those types, before the declarations
+ final List code = new ArrayList<>();
+ final Set hidden = new TreeSet<>();
+ for (final String p : packages(types)) {
+ code.add("import " + p);
+ // NB: "import a.b" binds a.
+ hidden.add(p.split("\\.")[0]);
+ }
+ code.addAll(declarations);
+ // Combine into a Header
+ return new Header(String.join("; ", code), hidden);
+ }
+
+ /**
+ * Declares a variable: by its value, if known (e.g. a live interpreter's
+ * imported Java class, as the class itself), or else as an instance of its
+ * type.
+ *
+ * @param types Where to note the types the declaration refers to (see
+ * {@link #packages}).
+ */
+ static String declaration(final String name, final Variable v,
+ final List types)
+ {
+ final Object value = v.value().orElse(null);
+ // A Java class (e.g. after "from java.util import ArrayList"): itself
+ final Class> c = value instanceof PyJavaType ? ((PyJavaType) value)
+ .getProxyType() : value instanceof Class ? (Class>) value : null;
+ if (c != null) {
+ if (!isNamed(c)) return name + " = " + any(types);
+ types.add(c.getName());
+ return name + " = " + c.getName().replace('$', '.');
+ }
+ // A Python module (e.g. after "import os"): imported again
+ if (value instanceof PyModule) {
+ final PyObject module = ((PyModule) value).__findattr__("__name__");
+ if (module != null && module.toString().matches("[\\w.]+")) {
+ return "import " + module + " as " + name;
+ }
+ }
+ // A function (e.g. after "def f(): ...")
+ if (value instanceof PyFunction) {
+ return name + " = lambda *args, **kwargs: None";
+ }
+ // Another Python value (e.g. a dict): an instance of its builtin type
+ if (value instanceof PyObject) {
+ final String builtin = pythonType(((PyObject) value).getType()
+ .getName());
+ return name + " = " + (builtin != null ? builtin + "()" : any(types));
+ }
+ // A Java value, or a script parameter: an instance of its type
+ final String t = parameterType(v.type());
+ types.add(t);
+ return name + " = " + t.replace('$', '.') + "()";
+ }
+
+ /**
+ * A value of any type (noting the module that says so), for variables
+ * without a type to declare.
+ */
+ private static String any(final List types) {
+ types.add("typing.Any");
+ return "typing.cast(typing.Any, None)";
+ }
+
+ /**
+ * The Python 3 type of a Python 2 builtin one (as the Python server knows
+ * Python 3's), e.g. {@code str} for {@code unicode}; or null if not a
+ * builtin one.
+ */
+ private static String pythonType(final String type) {
+ switch (type) {
+ case "int":
+ case "long":
+ return "int";
+ case "unicode":
+ return "str";
+ case "bool":
+ case "float":
+ case "str":
+ case "list":
+ case "dict":
+ case "tuple":
+ case "set":
+ return type;
+ default:
+ return null;
+ }
+ }
+
+ /** Whether code can refer to a class by its name. */
+ private static boolean isNamed(final Class> c) {
+ if (c.isPrimitive() || c.isArray() || c.isAnonymousClass() || c
+ .isLocalClass() || c.getName().indexOf('.') < 0) return false;
+ for (Class> t = c; t != null; t = t.getEnclosingClass()) {
+ if (!Modifier.isPublic(t.getModifiers())) return false;
+ }
+ return true;
+ }
+
+ /**
+ * @param type the Java type (of a SciJava Script parameter) declared in the
+ * script
+ * @return the type of the object given to the script by Jython: a Python
+ * type for the values Jython converts (e.g. {@code str}), or else
+ * the Java type itself
+ */
+ static String parameterType(final Class> type) {
+ final Class> t = boxed(type);
+ // NB: As Jython converts them (Py.java2py).
+ if (t == String.class || t == Character.class) return "str";
+ if (t == Integer.class || t == Long.class || t == Short.class ||
+ t == Byte.class || t == BigInteger.class) return "int";
+ if (t == Double.class || t == Float.class) return "float";
+ if (t == Boolean.class) return "bool";
+ if (t.isArray()) return "array.array";
+ return t.getName();
+ }
+
+ /**
+ * The packages or modules of the given types that a declaration refers to
+ * (none for builtins, e.g. {@code str}).
+ */
+ static Set packages(final Collection types) {
+ final Set packages = new TreeSet<>();
+ for (final String t : types) {
+ if (t.lastIndexOf('.') > 0) packages.add(t.substring(0, t.lastIndexOf(
+ '.')));
+ }
+ return packages;
+ }
+
+ /** Maps primitive types to their wrappers. */
+ private static Class> boxed(final Class> type) {
+ if (!type.isPrimitive()) return type;
+ if (type == int.class) return Integer.class;
+ if (type == long.class) return Long.class;
+ if (type == double.class) return Double.class;
+ if (type == float.class) return Float.class;
+ if (type == boolean.class) return Boolean.class;
+ if (type == char.class) return Character.class;
+ if (type == short.class) return Short.class;
+ if (type == byte.class) return Byte.class;
+ return Object.class; // void
+ }
+}
diff --git a/src/test/java/org/scijava/plugins/scripting/jython/JythonTest.java b/src/test/java/org/scijava/plugins/scripting/jython/JythonTest.java
index 60b5877..0e120ca 100644
--- a/src/test/java/org/scijava/plugins/scripting/jython/JythonTest.java
+++ b/src/test/java/org/scijava/plugins/scripting/jython/JythonTest.java
@@ -2,7 +2,7 @@
* #%L
* JSR-223-compliant Jython scripting language plugin.
* %%
- * Copyright (C) 2008 - 2023 SciJava developers.
+ * Copyright (C) 2008 - 2026 SciJava developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
diff --git a/src/test/java/org/scijava/plugins/scripting/jython/completion/JythonDialectTest.java b/src/test/java/org/scijava/plugins/scripting/jython/completion/JythonDialectTest.java
new file mode 100644
index 0000000..bfc5711
--- /dev/null
+++ b/src/test/java/org/scijava/plugins/scripting/jython/completion/JythonDialectTest.java
@@ -0,0 +1,183 @@
+/*-
+ * #%L
+ * JSR-223-compliant Jython scripting language plugin.
+ * %%
+ * Copyright (C) 2008 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+package org.scijava.plugins.scripting.jython.completion;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+
+import org.eclipse.lsp4j.CompletionItem;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.scijava.Context;
+import org.scijava.lsp.LanguageServerService;
+import org.python.jsr223.PyScriptEngineFactory;
+import org.scijava.lsp.ScriptDialect.Header;
+import org.scijava.lsp.ScriptSession;
+import org.scijava.log.LogLevel;
+import org.scijava.log.LogService;
+import org.scijava.script.ScriptLanguage;
+import org.scijava.script.ScriptService;
+
+/**
+ * Tests {@link JythonDialect}: Jython scripts, as plain Jython for
+ * scijava-lsp-jython's server (which its own tests test).
+ *
+ * @author Gabriel Selzer
+ */
+public class JythonDialectTest {
+
+ private Context context;
+ private ScriptLanguage jython;
+
+ @Before
+ public void setUp() {
+ context = new Context(ScriptService.class, LanguageServerService.class);
+ jython = context.service(ScriptService.class).getLanguageByName("Jython");
+ }
+
+ @After
+ public void tearDown() {
+ context.dispose();
+ }
+
+ @Test
+ public void testSupports() {
+ // JythonDialect supports JythonScriptLanguage
+ final JythonDialect dialect = new JythonDialect();
+ assertTrue(dialect.supports(jython));
+ // JythonLanguageServer supports JythonDialect's output
+ assertTrue(context.service(LanguageServerService.class).supports(dialect.outputLanguage()));
+ }
+
+ @Test
+ public void testParameterType() {
+ // Ensure Java primitives are converted to Python primitives
+ assertEquals("str", JythonDialect.parameterType(String.class));
+ assertEquals("int", JythonDialect.parameterType(int.class));
+ assertEquals("int", JythonDialect.parameterType(Long.class));
+ assertEquals("float", JythonDialect.parameterType(double.class));
+ assertEquals("bool", JythonDialect.parameterType(boolean.class));
+ assertEquals("array.array", JythonDialect.parameterType(
+ double[].class));
+ // Ensure Java classes stay the same
+ assertEquals("java.math.BigDecimal", JythonDialect.parameterType(
+ java.math.BigDecimal.class));
+ }
+
+ @Test
+ public void testScriptParameters() {
+ // Note: NoSuchType is deliberately unresolvable; silence the resulting
+ // warnings (with stack traces) that the parameter parser logs for it.
+ context.service(LogService.class).setLevel(LogLevel.ERROR);
+ final String scijavaScriptPrefix = //
+ "#@ String (label=\"Please enter your name\") name\n" + //
+ "#@output String greeting\n" + //
+ "#@ java.util.Map$Entry entry\n" + //
+ "#@ double[] values\n" + //
+ "#@ NoSuchType mystery\n";
+ // Ensure script parameter names can be autocompleted
+ assertTrue(complete(scijavaScriptPrefix + "x = na").contains("name"));
+ assertTrue(complete(scijavaScriptPrefix + "myst").contains("mystery"));
+ // Primitive script parameters have the members of their JYTHON types...
+ final List nameMembers = complete(scijavaScriptPrefix + "name.upp");
+ assertTrue("expected upper among " + nameMembers, nameMembers.contains(
+ "upper"));
+ // ...but NOT the members of their JAVA types
+ assertTrue(complete(scijavaScriptPrefix + "name.toUpp").isEmpty());
+ // Outputs are known too, even before the script assigns them.
+ assertTrue(complete(scijavaScriptPrefix + "greeting.st").contains("strip"));
+ // Other Java objects are instances of their classes, nested ones included.
+ assertTrue(complete(scijavaScriptPrefix + "entry.getK").contains("getKey"));
+ // Java arrays are Python arrays.
+ assertTrue(complete(scijavaScriptPrefix + "values.app").contains("append"));
+ // Modules imported only to declare those are not completed.
+ // TODO: Also check "j" (for java), once scijava-lsp ignores #@ lines
+ // when deciding whether the script mentions a name.
+ assertFalse(complete(scijavaScriptPrefix + "arr").contains("array"));
+ }
+
+
+ /**
+ * Tests that bindings in an {@link org.scijava.lsp.Environment} make it into the
+ * {@link Header}.
+ */
+ @Test
+ public void testInterpreterBindings() throws Exception {
+ // Derive a ScriptContext with some bindings
+ final ScriptEngine engine = new PyScriptEngineFactory().getScriptEngine();
+ engine.put("injected", new java.util.ArrayList());
+ engine.eval("from java.util import Collections\n" + //
+ "import os.path as osp\n" + //
+ "def helper(): pass\n" + //
+ "pairs = {1: 2}\n");
+ final ScriptContext live = engine.getContext();
+ // Pass that ScriptContext to completion and ensure it can be used.
+ // A Java object offers its instance members.
+ assertTrue(complete("injected.si", live).contains("size"));
+ // An imported Java class offers its static members.
+ assertTrue(complete("Collections.emptyL", live).contains("emptyList"));
+ // A module bound under another name is the module itself.
+ assertTrue(complete("osp.joi", live).contains("join"));
+ // A function is known by name.
+ assertTrue(complete("x = hel", live).contains("helper"));
+ // A Python value is an instance of its builtin type.
+ assertTrue(complete("pairs.ke", live).contains("keys"));
+ }
+
+ // -- Helper methods --
+
+ private List complete(final String code) {
+ return complete(code, null);
+ }
+
+ /** Completions at the end of the code, typed into the given interpreter. */
+ private List complete(final String code, final ScriptContext live) {
+ final LanguageServerService servers = context.service(
+ LanguageServerService.class);
+ try (ScriptSession session = live == null ? new ScriptSession(servers,
+ jython) : new ScriptSession(servers, jython, live))
+ {
+ return session.completion(code, code.length()).get(30, TimeUnit.SECONDS)
+ .getItems().stream().map(CompletionItem::getLabel).collect(Collectors
+ .toList());
+ }
+ catch (final Exception exc) {
+ throw new RuntimeException(exc);
+ }
+ }
+}