8081015: Allow conversion of native arrays to Queue and Collection
authorattila
Tue, 26 May 2015 14:37:14 +0200
changeset 30831 f733f1de0166
parent 30830 9d3a0827accd
child 30832 9553298028ef
8081015: Allow conversion of native arrays to Queue and Collection Reviewed-by: hannesw, lagergren, sundar
nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java
nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/JSType.java
nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java
nashorn/test/src/jdk/nashorn/internal/runtime/test/JDK_8081015_Test.java
nashorn/test/src/jdk/nashorn/test/models/JDK_8081015_TestModel.java
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java	Tue May 26 13:49:45 2015 +0530
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java	Tue May 26 14:37:14 2015 +0200
@@ -27,11 +27,13 @@
 
 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
+
 import java.lang.invoke.MethodHandles;
 import java.lang.reflect.Array;
 import java.util.Collection;
 import java.util.Deque;
 import java.util.List;
+import java.util.Queue;
 import jdk.internal.dynalink.beans.StaticClass;
 import jdk.internal.dynalink.support.TypeUtilities;
 import jdk.nashorn.api.scripting.JSObject;
@@ -337,7 +339,8 @@
 
     /**
      * Given a script object and a Java type, converts the script object into the desired Java type. Currently it
-     * performs shallow creation of Java arrays, as well as wrapping of objects in Lists and Dequeues. Example:
+     * performs shallow creation of Java arrays, as well as wrapping of objects in Lists, Dequeues, Queues,
+     * and Collections. Example:
      * <pre>
      * var anArray = [1, "13", false]
      * var javaIntArray = Java.to(anArray, "int[]")
@@ -351,9 +354,10 @@
      * object to create. Can not be null. If undefined, a "default" conversion is presumed (allowing the argument to be
      * omitted).
      * @return a Java object whose value corresponds to the original script object's value. Specifically, for array
-     * target types, returns a Java array of the same type with contents converted to the array's component type. Does
-     * not recursively convert for multidimensional arrays. For {@link List} or {@link Deque}, returns a live wrapper
-     * around the object, see {@link ListAdapter} for details. Returns null if obj is null.
+     * target types, returns a Java array of the same type with contents converted to the array's component type.
+     * Converts recursively when the target type is multidimensional array. For {@link List}, {@link Deque},
+     * {@link Queue}, or {@link Collection}, returns a live wrapper around the object, see {@link ListAdapter} for
+     * details. Returns null if obj is null.
      * @throws ClassNotFoundException if the class described by objType is not found
      */
     @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
@@ -383,7 +387,7 @@
             return JSType.toJavaArray(obj, targetClass.getComponentType());
         }
 
-        if(targetClass == List.class || targetClass == Deque.class) {
+        if (targetClass == List.class || targetClass == Deque.class || targetClass == Queue.class || targetClass == Collection.class) {
             return ListAdapter.create(obj);
         }
 
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/JSType.java	Tue May 26 13:49:45 2015 +0530
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/JSType.java	Tue May 26 14:37:14 2015 +0200
@@ -34,7 +34,6 @@
 import java.lang.reflect.Array;
 import java.util.Arrays;
 import java.util.Collections;
-import java.util.Deque;
 import java.util.List;
 import jdk.internal.dynalink.beans.StaticClass;
 import jdk.nashorn.api.scripting.JSObject;
@@ -201,12 +200,6 @@
     /** Method handle to convert a JS Object to a Java array. */
     public static final Call TO_JAVA_ARRAY = staticCall(JSTYPE_LOOKUP, JSType.class, "toJavaArray", Object.class, Object.class, Class.class);
 
-    /** Method handle to convert a JS Object to a Java List. */
-    public static final Call TO_JAVA_LIST = staticCall(JSTYPE_LOOKUP, JSType.class, "toJavaList", List.class, Object.class);
-
-    /** Method handle to convert a JS Object to a Java deque. */
-    public static final Call TO_JAVA_DEQUE = staticCall(JSTYPE_LOOKUP, JSType.class, "toJavaDeque", Deque.class, Object.class);
-
     /** Method handle for void returns. */
     public static final Call VOID_RETURN = staticCall(JSTYPE_LOOKUP, JSType.class, "voidReturn", void.class);
 
@@ -1351,24 +1344,6 @@
     }
 
     /**
-     * Converts a JavaScript object to a Java List. See {@link ListAdapter} for details.
-     * @param obj the object to convert. Can be any array-like object.
-     * @return a List that is live-backed by the JavaScript object.
-     */
-    public static List<?> toJavaList(final Object obj) {
-        return ListAdapter.create(obj);
-    }
-
-    /**
-     * Converts a JavaScript object to a Java Deque. See {@link ListAdapter} for details.
-     * @param obj the object to convert. Can be any array-like object.
-     * @return a Deque that is live-backed by the JavaScript object.
-     */
-    public static Deque<?> toJavaDeque(final Object obj) {
-        return ListAdapter.create(obj);
-    }
-
-    /**
      * Check if an object is null or undefined
      *
      * @param obj object to check
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java	Tue May 26 13:49:45 2015 +0530
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java	Tue May 26 14:37:14 2015 +0200
@@ -29,13 +29,15 @@
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
-import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
 import java.lang.reflect.Modifier;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.util.Collection;
 import java.util.Deque;
 import java.util.List;
 import java.util.Map;
+import java.util.Queue;
 import javax.script.Bindings;
 import jdk.internal.dynalink.CallSiteDescriptor;
 import jdk.internal.dynalink.linker.ConversionComparator;
@@ -47,11 +49,13 @@
 import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
 import jdk.internal.dynalink.support.Guards;
 import jdk.internal.dynalink.support.LinkerServicesImpl;
+import jdk.internal.dynalink.support.Lookup;
 import jdk.nashorn.api.scripting.JSObject;
 import jdk.nashorn.api.scripting.ScriptObjectMirror;
 import jdk.nashorn.api.scripting.ScriptUtils;
 import jdk.nashorn.internal.objects.NativeArray;
 import jdk.nashorn.internal.runtime.JSType;
+import jdk.nashorn.internal.runtime.ListAdapter;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.Undefined;
@@ -167,7 +171,7 @@
         return null;
     }
 
-    private static Lookup getCurrentLookup() {
+    private static java.lang.invoke.MethodHandles.Lookup getCurrentLookup() {
         final LinkRequest currentRequest = AccessController.doPrivileged(new PrivilegedAction<LinkRequest>() {
             @Override
             public LinkRequest run() {
@@ -179,12 +183,12 @@
 
     /**
      * Returns a guarded invocation that converts from a source type that is NativeArray to a Java array or List or
-     * Deque type.
+     * Queue or Deque or Collection type.
      * @param sourceType the source type (presumably NativeArray a superclass of it)
-     * @param targetType the target type (presumably an array type, or List or Deque)
+     * @param targetType the target type (presumably an array type, or List or Queue, or Deque, or Collection)
      * @return a guarded invocation that converts from the source type to the target type. null is returned if
      * either the source type is neither NativeArray, nor a superclass of it, or if the target type is not an array
-     * type, List, or Deque.
+     * type, List, Queue, Deque, or Collection.
      */
     private static GuardedInvocation getArrayConverter(final Class<?> sourceType, final Class<?> targetType) {
         final boolean isSourceTypeNativeArray = sourceType == NativeArray.class;
@@ -195,12 +199,14 @@
             final MethodHandle guard = isSourceTypeGeneric ? IS_NATIVE_ARRAY : null;
             if(targetType.isArray()) {
                 return new GuardedInvocation(ARRAY_CONVERTERS.get(targetType), guard);
-            }
-            if(targetType == List.class) {
-                return new GuardedInvocation(JSType.TO_JAVA_LIST.methodHandle(), guard);
-            }
-            if(targetType == Deque.class) {
-                return new GuardedInvocation(JSType.TO_JAVA_DEQUE.methodHandle(), guard);
+            } else if(targetType == List.class) {
+                return new GuardedInvocation(TO_LIST, guard);
+            } else if(targetType == Deque.class) {
+                return new GuardedInvocation(TO_DEQUE, guard);
+            } else if(targetType == Queue.class) {
+                return new GuardedInvocation(TO_QUEUE, guard);
+            } else if(targetType == Collection.class) {
+                return new GuardedInvocation(TO_COLLECTION, guard);
             }
         }
         return null;
@@ -286,6 +292,23 @@
     private static final MethodHandle IS_NASHORN_OR_UNDEFINED_TYPE = findOwnMH("isNashornTypeOrUndefined", Boolean.TYPE, Object.class);
     private static final MethodHandle CREATE_MIRROR = findOwnMH("createMirror", Object.class, Object.class);
 
+    private static final MethodHandle TO_COLLECTION;
+    private static final MethodHandle TO_DEQUE;
+    private static final MethodHandle TO_LIST;
+    private static final MethodHandle TO_QUEUE;
+    static {
+        final MethodHandle listAdapterCreate = new Lookup(MethodHandles.lookup()).findStatic(
+                ListAdapter.class, "create", MethodType.methodType(ListAdapter.class, Object.class));
+        TO_COLLECTION = asReturning(listAdapterCreate, Collection.class);
+        TO_DEQUE = asReturning(listAdapterCreate, Deque.class);
+        TO_LIST = asReturning(listAdapterCreate, List.class);
+        TO_QUEUE = asReturning(listAdapterCreate, Queue.class);
+    }
+
+    private static MethodHandle asReturning(final MethodHandle mh, final Class<?> nrtype) {
+        return mh.asType(mh.type().changeReturnType(nrtype));
+    }
+
     @SuppressWarnings("unused")
     private static boolean isNashornTypeOrUndefined(final Object obj) {
         return obj instanceof ScriptObject || obj instanceof Undefined;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/src/jdk/nashorn/internal/runtime/test/JDK_8081015_Test.java	Tue May 26 14:37:14 2015 +0200
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.nashorn.internal.runtime.test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNull;
+
+import jdk.nashorn.test.models.JDK_8081015_TestModel;
+
+import java.util.Collection;
+import java.util.Queue;
+import javax.script.ScriptEngine;
+import javax.script.ScriptException;
+import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
+import org.testng.annotations.Test;
+
+/**
+ * @bug 8081015
+ * @summary Test that native arrays get converted to {@link Queue} and {@link Collection}.
+ */
+public class JDK_8081015_Test {
+    @Test
+    public void testConvertToCollection() throws ScriptException {
+        test("receiveCollection");
+    }
+
+    @Test
+    public void testConvertToDeque() throws ScriptException {
+        test("receiveDeque");
+    }
+
+    @Test
+    public void testConvertToList() throws ScriptException {
+        test("receiveList");
+    }
+
+    @Test
+    public void testConvertToQueue() throws ScriptException {
+        test("receiveQueue");
+    }
+
+    private void test(final String methodName) throws ScriptException {
+        final ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine();
+        final JDK_8081015_TestModel model = new JDK_8081015_TestModel();
+        engine.put("test", model);
+
+        assertNull(model.getLastInvoked());
+        engine.eval("test." + methodName + "([1, 2, 3.3, 'foo'])");
+        assertEquals(model.getLastInvoked(), methodName );
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/src/jdk/nashorn/test/models/JDK_8081015_TestModel.java	Tue May 26 14:37:14 2015 +0200
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.nashorn.test.models;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+
+import java.util.Collection;
+import java.util.Deque;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Queue;
+
+@SuppressWarnings("javadoc")
+public class JDK_8081015_TestModel {
+    private String lastInvoked;
+
+    public void receiveCollection(final Collection<Object> c) {
+        lastInvoked = "receiveCollection";
+        walkCollection(c);
+    }
+
+    public void receiveDeque(final Deque<Object> d) {
+        lastInvoked = "receiveDeque";
+        walkCollection(d);
+    }
+
+    public void receiveList(final List<Object> l) {
+        lastInvoked = "receiveList";
+        walkCollection(l);
+    }
+
+    public void receiveQueue(final Queue<Object> q) {
+        lastInvoked = "receiveQueue";
+        walkCollection(q);
+    }
+
+    public String getLastInvoked() {
+        return lastInvoked;
+    }
+
+    private static void walkCollection(final Collection<Object> c) {
+        final Iterator<Object> it = c.iterator();
+        assertEquals(it.next(), Integer.valueOf(1));
+        assertEquals(it.next(), Integer.valueOf(2));
+        assertEquals(it.next(), Double.valueOf(3.3));
+        assertEquals(it.next(), "foo");
+        assertFalse(it.hasNext());
+    }
+}