org.graalvm.polyglot.Value Java Examples
The following examples show how to use
org.graalvm.polyglot.Value.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HashemJavaInteropExceptionTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
@Test public void testGR7284() throws Exception { String sourceText = "bebin test(validator) {\n" + " bede validator.validateException();\n" + "}"; try (Context context = Context.newBuilder(HashemLanguage.ID).build()) { context.eval(Source.newBuilder(HashemLanguage.ID, sourceText, "Test").build()); Value test = context.getBindings(HashemLanguage.ID).getMember("test"); try { test.execute(new Validator()); fail("expected a PolyglotException but did not throw"); } catch (PolyglotException ex) { assertTrue("expected HostException", ex.isHostException()); assertThat(ex.asHostException(), instanceOf(NoSuchElementException.class)); assertNoJavaInteropStackFrames(ex); } } }
Example #2
Source File: HashemJavaInteropExceptionTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
@Test public void testGR7284GuestHostGuestHost() throws Exception { String sourceText = "bebin test(validator) {\n" + " bede validator.validateNested();\n" + "}"; try (Context context = Context.newBuilder(HashemLanguage.ID).build()) { context.eval(Source.newBuilder(HashemLanguage.ID, sourceText, "Test").build()); Value test = context.getBindings(HashemLanguage.ID).getMember("test"); try { test.execute(new Validator()); fail("expected a PolyglotException but did not throw"); } catch (PolyglotException ex) { assertTrue("expected HostException", ex.isHostException()); assertThat(ex.asHostException(), instanceOf(NoSuchElementException.class)); assertNoJavaInteropStackFrames(ex); } } }
Example #3
Source File: HashemExecutionListenerTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
@Test public void testFactorial() { // @formatter:off String characters = "fac(n) {" + " age (n <= 1) bood {" + " bede 1;" + " }" + " bede fac(n - 1) * n;" + "}"; // @formatter:on context.eval("hashemi", "bebin " + characters); Value factorial = context.getBindings("hashemi").getMember("fac"); ExecutionListener.newBuilder().onReturn(this::add).onEnter(this::add).// expressions(true).statements(true).roots(true).// collectExceptions(true).collectInputValues(true).collectReturnValue(true).// attach(context.getEngine()); expectedRootName = "fac"; assertEquals(0, events.size()); for (int i = 0; i < 10; i++) { testFactorial(characters, factorial); } }
Example #4
Source File: HashemExceptionTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
private void assertHostException(String source, String... expectedFrames) { boolean initialExecute = true; RuntimeException[] exception = new RuntimeException[1]; try { Value value = ctx.eval("hashemi", source); initialExecute = false; ProxyExecutable proxy = (args) -> { throw exception[0] = new RuntimeException(); }; value.execute(proxy); Assert.fail("Should not reach here."); } catch (PolyglotException e) { Assert.assertFalse(initialExecute); Assert.assertTrue(e.asHostException() == exception[0]); assertFrames(false, e, expectedFrames); } }
Example #5
Source File: DeviceTest.java From grcuda with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testCanSelectDevice() { try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) { Value devices = ctx.eval("grcuda", "getdevices()"); if (devices.getArraySize() > 1) { Value firstDevice = devices.getArrayElement(0); Value secondDevice = devices.getArrayElement(1); secondDevice.invokeMember("setCurrent"); assertFalse(firstDevice.invokeMember("isCurrent").asBoolean()); assertTrue(secondDevice.invokeMember("isCurrent").asBoolean()); firstDevice.invokeMember("setCurrent"); assertTrue(firstDevice.invokeMember("isCurrent").asBoolean()); assertFalse(secondDevice.invokeMember("isCurrent").asBoolean()); } else { // only one device available Value device = devices.getArrayElement(0); device.invokeMember("setCurrent"); assertTrue(device.invokeMember("isCurrent").asBoolean()); } } }
Example #6
Source File: DeviceArrayCopyFunctionTest.java From grcuda with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testDeviceArrayCopyFromDeviceArray() { final int numElements = 1000; try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) { Value createDeviceArray = ctx.eval("grcuda", "DeviceArray"); // create device array initialize its elements. Value sourceDeviceArray = createDeviceArray.execute("int", numElements); for (int i = 0; i < numElements; ++i) { sourceDeviceArray.setArrayElement(i, i + 1); } // create destination device array initialize its elements to zero. Value destinationDeviceArray = createDeviceArray.execute("int", numElements); for (int i = 0; i < numElements; ++i) { destinationDeviceArray.setArrayElement(i, 0); } destinationDeviceArray.invokeMember("copyFrom", sourceDeviceArray, numElements); // Verify content of device array for (int i = 0; i < numElements; ++i) { assertEquals(i + 1, destinationDeviceArray.getArrayElement(i).asInt()); } } }
Example #7
Source File: HashemExceptionTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
private void assertException(boolean failImmediately, String source, String... expectedFrames) { boolean initialExecute = true; try { Value value = ctx.eval("hashemi", source); initialExecute = false; if (failImmediately) { Assert.fail("Should not reach here."); } ProxyExecutable proxy = (args) -> args[0].execute(); value.execute(proxy); Assert.fail("Should not reach here."); } catch (PolyglotException e) { Assert.assertEquals(failImmediately, initialExecute); assertFrames(failImmediately, e, expectedFrames); } }
Example #8
Source File: DeviceArrayCopyFunctionTest.java From grcuda with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testDeviceArrayCopyFromOffheapMemory() { final int numElements = 1000; final int numBytesPerInt = 4; final int numBytes = numElements * numBytesPerInt; try (OffheapMemory hostMemory = new OffheapMemory(numBytes)) { // create off-heap host memory of integers: [1, 2, 3, 4, ..., 1000] LittleEndianNativeArrayView hostArray = hostMemory.getLittleEndianView(); for (int i = 0; i < numElements; ++i) { hostArray.setInt(i, i + 1); } try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) { // create DeviceArray and copy content from off-heap host memory into it Value createDeviceArray = ctx.eval("grcuda", "DeviceArray"); Value deviceArray = createDeviceArray.execute("int", numElements); deviceArray.invokeMember("copyFrom", hostMemory.getPointer(), numElements); // Verify content of device array for (int i = 0; i < numElements; ++i) { assertEquals(i + 1, deviceArray.getArrayElement(i).asInt()); } } } }
Example #9
Source File: HashemDebugDirectTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
@Test public void testNull() throws Throwable { final Source nullTest = createNull(); context.eval(nullTest); session.suspendNextExecution(); assertLocation("nullTest", 2, true, "res = doNull()", "res", UNASSIGNED); stepInto(1); assertLocation("nullTest", 3, true, "bede res", "res", "POOCH"); continueExecution(); Value value = context.getBindings("hashemi").getMember("nullTest").execute(); assertExecutedOK(); String val = value.toString(); assertNotNull(val); assertEquals("Hashemi displays null as POOCH", "POOCH", val); }
Example #10
Source File: DeviceArrayTest.java From grcuda with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void setElement(Value array, int index, Number value) { switch (dataTypeString) { case "char": array.setArrayElement(index, value.byteValue()); break; case "short": array.setArrayElement(index, value.shortValue()); break; case "int": array.setArrayElement(index, value.intValue()); break; case "long": array.setArrayElement(index, value.longValue()); break; case "float": array.setArrayElement(index, value.floatValue()); break; case "double": array.setArrayElement(index, value.doubleValue()); break; default: throw new RuntimeException("invalid type " + dataTypeString); } }
Example #11
Source File: HashemDebugDirectTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
@Test public void testBreakpoint() throws Throwable { final Source factorial = createFactorial(); session.install(Breakpoint.newBuilder(getSourceImpl(factorial)).lineIs(8).build()); context.eval(factorial); assertExecutedOK(); assertLocation("fac", 8, true, "bede 1", "n", "1", "nMinusOne", UNASSIGNED, "nMOFact", UNASSIGNED, "res", UNASSIGNED); continueExecution(); Value value = context.getBindings("hashemi").getMember("test").execute(); assertExecutedOK(); Assert.assertEquals("2\n", getOut()); Assert.assertTrue(value.isNumber()); int n = value.asInt(); assertEquals("Factorial computed OK", 2, n); }
Example #12
Source File: VmBridge.java From swim with Apache License 2.0 | 6 votes |
@Override public Object hostToGuest(Object hostValue) { final Object guestValue; if (hostValue instanceof Value || hostValue instanceof Proxy) { guestValue = hostValue; } else if (hostValue instanceof GuestWrapper) { guestValue = ((GuestWrapper) hostValue).unwrap(); } else { final HostType<? super Object> hostType = hostType(hostValue); if (hostType != null) { guestValue = hostTypedValueToGuestProxy(hostType, hostValue); } else if (hostValue instanceof Object[]) { guestValue = new VmBridgeArray(this, (Object[]) hostValue); } else { guestValue = hostValue; } } return guestValue; }
Example #13
Source File: HostMapSpec.java From swim with Apache License 2.0 | 6 votes |
@Test public void testUnspecializedMap() { try (Context context = Context.create()) { final JavaHostRuntime runtime = new JavaHostRuntime(); final VmBridge bridge = new VmBridge(runtime, "unknown"); runtime.addHostLibrary(JavaBase.LIBRARY); final Map<String, String> testMap = new HashMap<String, String>(); testMap.put("foo", "bar"); final Value bindings = context.getBindings("js"); bindings.putMember("testMap", bridge.hostToGuest(testMap)); assertNull(context.eval("js", "testMap.has").as(Object.class)); assertNotNull(context.eval("js", "testMap.containsKey").as(Object.class)); assertTrue(context.eval("js", "testMap.containsKey('foo')").asBoolean()); assertFalse(context.eval("js", "testMap.containsKey('bar')").asBoolean()); } }
Example #14
Source File: HashemJavaInteropTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
@Test public void sumPairs() { String scriptText = "bebin values(sum, k, v) {\n" + // " obj = jadid();\n" + // " obj.key = k;\n" + // " obj.value = v;\n" + // " bede sum.sum(obj);\n" + // "}\n"; // context.eval("hashemi", scriptText); Value fn = lookup("values"); Sum javaSum = new Sum(); Object sum = javaSum; Object ret1 = fn.execute(sum, "one", 1).asHostObject(); Object ret2 = fn.execute(sum, "two", 2).as(Object.class); Sum ret3 = fn.execute(sum, "three", 3).as(Sum.class); assertEquals(6, javaSum.sum); assertSame(ret1, ret2); assertSame(ret3, ret2); assertSame(sum, ret2); }
Example #15
Source File: HashemJavaInteropTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
@Test public void sumPairsInArray() { String scriptText = "bebin values(sum, arr) {\n" + // " sum.sumArray(arr);\n" + // "}\n"; // context.eval("hashemi", scriptText); Value fn = lookup("values"); Sum javaSum = new Sum(); PairImpl[] arr = { new PairImpl("one", 1), new PairImpl("two", 2), new PairImpl("three", 3), }; fn.execute(javaSum, arr); assertEquals(6, javaSum.sum); }
Example #16
Source File: VerbsManager.java From phoenicis with GNU Lesser General Public License v3.0 | 6 votes |
/** * Installs a Verb in a given container * * @param engineId ID of the engine which provides the Verb (e.g. "Wine") * @param container name of the container * @param verbId ID of the Verb * @param doneCallback callback executed after the script ran * @param errorCallback callback executed in case of an error */ public void installVerb(String engineId, String container, String verbId, Runnable doneCallback, Consumer<Exception> errorCallback) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); final String script = String.format("include(\"%s\");", verbId); interactiveScriptSession.eval(script, output -> { final Value verbClass = (Value) output; try { verbClass.invokeMember("install", container); } catch (ScriptException se) { errorCallback.accept(se); } doneCallback.run(); }, errorCallback); }
Example #17
Source File: HashemDebugDirectTest.java From mr-hashemi with Universal Permissive License v1.0 | 6 votes |
@Test public void testDebuggerBreakpoint() throws Throwable { final Source factorial = createFactorialWithDebugger(); context.eval(factorial); assertExecutedOK(); assertLocation("fac", 12, true, "debugger", "n", "2", "nMinusOne", "1", "nMOFact", "1", "res", UNASSIGNED); continueExecution(); Value value = context.getBindings("hashemi").getMember("test").execute(); assertExecutedOK(); Assert.assertEquals("2\n", getOut()); Assert.assertTrue(value.isNumber()); int n = value.asInt(); assertEquals("Factorial computed OK", 2, n); }
Example #18
Source File: GraalScriptRunner.java From citeproc-java with Apache License 2.0 | 5 votes |
@Override public <T> T callMethod(Object obj, String name, Class<T> resultType, Object... args) throws ScriptRunnerException { try { return convert(((Value)obj).getMember(name) .execute(convertArguments(args)), resultType); } catch (IOException | PolyglotException e) { throw new ScriptRunnerException("Could not call method", e); } }
Example #19
Source File: DeviceArrayFreeTest.java From grcuda with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testCanInvokeFreeDeviceArray() { try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) { // create DeviceArray Value createDeviceArray = ctx.eval("grcuda", "DeviceArray"); Value deviceArray = createDeviceArray.execute("int", 1000); assertTrue(deviceArray.canInvokeMember("free")); deviceArray.invokeMember("free"); // check that freed flag set assertTrue(deviceArray.hasMember("isMemoryFreed")); assertTrue(deviceArray.getMember("isMemoryFreed").asBoolean()); } }
Example #20
Source File: VmHostObjectSpec.java From swim with Apache License 2.0 | 5 votes |
@Test public void testGetMember() { try (Context context = Context.create()) { final JavaHostRuntime runtime = new JavaHostRuntime(); final VmBridge bridge = new VmBridge(runtime, "js"); runtime.addHostType(Foo.TYPE); final Value bindings = context.getBindings("js"); bindings.putMember("foo", bridge.hostToGuest(new Foo())); assertEquals(context.eval("js", "foo.bar").asString(), "BAR"); } }
Example #21
Source File: VmHostObjectSpec.java From swim with Apache License 2.0 | 5 votes |
@Test public void testInvokeMember() { try (Context context = Context.create()) { final JavaHostRuntime runtime = new JavaHostRuntime(); final VmBridge bridge = new VmBridge(runtime, "js"); runtime.addHostType(Foo.TYPE); final Value bindings = context.getBindings("js"); bindings.putMember("foo", bridge.hostToGuest(new Foo())); assertEquals(context.eval("js", "foo.baz()").asString(), "BAZ"); } }
Example #22
Source File: HashemTCKLanguageProvider.java From mr-hashemi with Universal Permissive License v1.0 | 5 votes |
private static Snippet.Builder createPostfixOperator( final Context context, final String operator, final String functionName, final TypeDescriptor type, final TypeDescriptor ltype) { final Value fnc = eval(context, String.format(PATTERN_POST_OP_FNC, functionName, operator), functionName); return Snippet.newBuilder(operator, fnc, type).parameterTypes(ltype); }
Example #23
Source File: SLApp.java From netbeans with Apache License 2.0 | 5 votes |
public static void main(String... args) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); Source src = Source.newBuilder("sl", "function main() {\n" + " x = 42;\n" + " println(x);\n" + " return x;\n" + "}\n"+ "function init() {\n"+ " obj = new();\n"+ " obj.fourtyTwo = main;\n"+ " return obj;\n"+ "}\n", "Meaning of world.sl").build(); Context context = Context.newBuilder().allowAllAccess(true).out(os).build(); Value result = context.eval(src); // LBREAKPOINT assertEquals("Expected result", 42L, result.asLong()); assertEquals("Expected output", "42\n", os.toString("UTF-8")); // dynamic generated interface Value init = context.getBindings("sl").getMember("init"); assertNotNull("init method found", init); Compute c = init.execute().as(Compute.class); // LBREAKPOINT Object result42 = c.fourtyTwo(); // LBREAKPOINT assertEquals("Expected result", 42L, result42); assertEquals("Expected output", "42\n42\n", os.toString("UTF-8")); }
Example #24
Source File: DeviceTest.java From grcuda with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testDeviceMemoryAllocationReducesReportedFreeMemory() { try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) { Value device = ctx.eval("grcuda", "getdevice(0)"); Value props = device.getMember("properties"); device.invokeMember("setCurrent"); long totalMemoryBefore = props.getMember("totalDeviceMemory").asLong(); long freeMemoryBefore = props.getMember("freeDeviceMemory").asLong(); assertTrue(freeMemoryBefore <= totalMemoryBefore); // allocate memory on device (unmanaged) long arraySizeBytes = freeMemoryBefore / 3; Value cudaMalloc = ctx.eval("grcuda", "cudaMalloc"); Value cudaFree = ctx.eval("grcuda", "cudaFree"); Value gpuPointer = null; try { gpuPointer = cudaMalloc.execute(arraySizeBytes); // After allocation total memory must be the same as before but // the free memory must be lower by at least the amount of allocated bytes. long totalMemoryAfter = props.getMember("totalDeviceMemory").asLong(); long freeMemoryAfter = props.getMember("freeDeviceMemory").asLong(); assertEquals(totalMemoryBefore, totalMemoryAfter); assertTrue(freeMemoryAfter <= (freeMemoryBefore - arraySizeBytes)); } finally { if (gpuPointer != null) { cudaFree.execute(gpuPointer); } } } }
Example #25
Source File: ApplicationInformationPanelSkin.java From phoenicis with GNU Lesser General Public License v3.0 | 5 votes |
/** * Install the given script * * @param script The script to be installed */ private void installScript(ScriptDTO script) { final StringBuilder executeBuilder = new StringBuilder(); executeBuilder.append(String.format("TYPE_ID=\"%s\";\n", script.getTypeId())); executeBuilder.append(String.format("CATEGORY_ID=\"%s\";\n", script.getCategoryId())); executeBuilder.append(String.format("APPLICATION_ID=\"%s\";\n", script.getApplicationId())); executeBuilder.append(String.format("SCRIPT_ID=\"%s\";\n", script.getId())); executeBuilder.append(script.getScript()); executeBuilder.append("\n"); getControl().getScriptInterpreter().createInteractiveSession() .eval(executeBuilder.toString(), result -> { Value installer = (Value) result; installer.as(Installer.class).go(); }, e -> Platform.runLater(() -> { // no exception if installation is cancelled if (!(e.getCause() instanceof InterruptedException)) { final ErrorDialog errorDialog = ErrorDialog.builder() .withMessage(tr("The script ended unexpectedly")) .withException(e) .build(); errorDialog.showAndWait(); } })); }
Example #26
Source File: HashemInteropObjectTest.java From mr-hashemi with Universal Permissive License v1.0 | 5 votes |
@Test public void testJadidForeign() { final Source src = Source.newBuilder("hashemi", "bebin getValue(type) {o = jadid(type); o.a = 10; bede o.value;}", "testObject.hashem").buildLiteral(); context.eval(src); Value getValue = context.getBindings("hashemi").getMember("getValue"); Value ret = getValue.execute(new TestType()); Assert.assertEquals(20, ret.asLong()); }
Example #27
Source File: HashemTCKLanguageProvider.java From mr-hashemi with Universal Permissive License v1.0 | 5 votes |
private static Snippet.Builder createBinaryOperator( final Context context, final String operator, final String functionName, final TypeDescriptor type, final TypeDescriptor ltype, final TypeDescriptor rtype) { final Value fnc = eval(context, String.format(PATTERN_BIN_OP_FNC, functionName, operator), functionName); return Snippet.newBuilder(operator, fnc, type).parameterTypes(ltype, rtype); }
Example #28
Source File: HashemJavaInteropTest.java From mr-hashemi with Universal Permissive License v1.0 | 5 votes |
@Test public void asFunctionWithArg() throws Exception { String scriptText = "bebin values(a, b) {\n" + // " bechap(\"Called with \" + a + \" and \" + b);\n" + // "}\n"; // context.eval("hashemi", scriptText); Value fn = lookup("values"); PassInValues valuesIn = fn.as(PassInValues.class); valuesIn.call("OK", "Fine"); assertEquals("Called with OK and Fine\n", toUnixString(os)); }
Example #29
Source File: MultiDimArrayTest.java From grcuda with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test(expected = ArrayIndexOutOfBoundsException.class) public void test2DimArrayOutOfBoundsOnWriteAccess() { try (Context context = Context.newBuilder().allowAllAccess(true).build()) { Value deviceArrayConstructor = context.eval("grcuda", "DeviceArray"); final int numDim1 = 19; final int numDim2 = 53; Value matrix = deviceArrayConstructor.execute("int", numDim1, numDim2); assertEquals(numDim1, matrix.getArraySize()); assertEquals(numDim2, matrix.getArrayElement(0).getArraySize()); // out-of-bounds write access matrix.getArrayElement(0).setArrayElement(53, 42); } }
Example #30
Source File: GraalEngine.java From netbeans with Apache License 2.0 | 5 votes |
private Value evalImpl(ScriptContext arg1, String src) throws ScriptException { try { return ((GraalContext) arg1).ctx().eval(id(), src); } catch (PolyglotException e) { throw new ScriptException(e); } }